Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(list): custom template columns and cached PR numbers in the picker (#3073)
Maximilian Roosa7e29f79c71d
diff --git a/dev/config.example.toml b/dev/config.example.tomlindex e5acc688b..0d877ab28 100644--- a/dev/config.example.toml+++ b/dev/config.example.toml@@ -102,6 +102,33 @@# task-timeout-ms = 0 # Kill individual git commands after N ms; 0 disables# timeout-ms = 0 # Wall-clock budget for the entire collect phase; 0 disables#+# #### Custom columns [experimental]+#+# Custom columns add per-branch context to the `wt list` table. Each+# `[list.custom-columns]` entry is a column: the key is the header, the template+# renders each row's cell.+#+# [list.custom-columns.Ticket]+# template = "{{ vars.ticket }}" # Required; the result is the cell text+# width = 20 # Optional max display width (default: 40)+# priority = 9 # Optional drop order when the terminal narrows;+# # lower = kept longer (default: 9, the URL band)+#+# Templates may reference `{{ branch }}`, `{{ worktree_path }}`,+# `{{ worktree_name }}` (empty for branch-only rows), and `{{ vars.* }}` —+# per-branch values stored with+# `wt config state vars set` (https://worktrunk.dev/config/#wt-config-state-vars).+# All standard filters work (`sanitize`, `hash_port`, `codename`, …). A row+# where the template renders empty (e.g. a branch without the vars key) shows an+# empty cell; a column that is empty for every row is dropped from the table.+# `wt list --format json` includes the rendered values under `columns`.+#+# A `Note` column showing free-form descriptions, set per branch with+# `wt config state vars set note "Bug fix for production fire"`:+#+# [list.custom-columns.Note]+# template = "{{ vars.note }}"+## ### Commit## Shared by `wt step commit`, `wt step squash`, and `wt merge`.diff --git a/docs/content/config.md b/docs/content/config.mdindex 6adb939e4..f2c35eda8 100644--- a/docs/content/config.md+++ b/docs/content/config.md@@ -190,6 +190,39 @@ task-timeout-ms = 0 # Kill individual git commands after N ms; 0 disablestimeout-ms = 0 # Wall-clock budget for the entire collect phase; 0 disables```+#### Custom columns++<span class="badge-experimental"></span>++Custom columns add per-branch context to the `wt list` table. Each+`[list.custom-columns]` entry is a column: the key is the header, the template+renders each row's cell.++```toml+[list.custom-columns.Ticket]+template = "{{ vars.ticket }}" # Required; the result is the cell text+width = 20 # Optional max display width (default: 40)+priority = 9 # Optional drop order when the terminal narrows;+ # lower = kept longer (default: 9, the URL band)+```++Templates may reference `{{ branch }}`, `{{ worktree_path }}`,+`{{ worktree_name }}` (empty for branch-only rows), and `{{ vars.* }}` —+per-branch values stored with+[`wt config state vars set`](@/config.md#wt-config-state-vars).+All standard filters work (`sanitize`, `hash_port`, `codename`, …). A row+where the template renders empty (e.g. a branch without the vars key) shows an+empty cell; a column that is empty for every row is dropped from the table.+`wt list --format json` includes the rendered values under `columns`.++A `Note` column showing free-form descriptions, set per branch with+`wt config state vars set note "Bug fix for production fire"`:++```toml+[list.custom-columns.Note]+template = "{{ vars.note }}"+```+### CommitShared by `wt step commit`, `wt step squash`, and `wt merge`.diff --git a/docs/content/list.md b/docs/content/list.mdindex ca37f8882..243a2844d 100644--- a/docs/content/list.md+++ b/docs/content/list.md@@ -84,6 +84,7 @@ Output as JSON for scripting:| CI | PR/MR number colored by pipeline status; `--full` only || Path | Worktree directory || URL | Dev server URL from project config; dimmed if port is not listening |+| *(custom)* | User-defined [custom columns](#custom-columns) from `[list.custom-columns]` user config <span class="badge-experimental"></span> || Commit | Short hash (8 chars) || Age | Time since last commit || Message | Last commit message (truncated) |@@ -128,6 +129,19 @@ CI cells are clickable links to the PR or pipeline page, and appear dimmed whenReuses the [`commit.generation`](@/config.md#commit) command — the same LLM that generates commit messages. Enable with `summary = true` in `[list]` config; requires `--full`. Results are cached until the branch's diff changes.+### Custom columns++<span class="badge-experimental"></span>++Each `[list.custom-columns]` entry in user config adds a column: the key is the header, the template renders each row's cell. Templates can reference per-branch `{{ vars.* }}` stored with [`wt config state vars set`](@/config.md#wt-config-state-vars) — useful for tracking what each of many (often agent-driven) branches is for:++```toml+[list.custom-columns.Ticket]+template = "{{ vars.ticket }}"+```++A column that renders empty for every row is dropped from the table. Templates, widths, and drop priority: [custom columns config](@/config.md#custom-columns).+## Status symbolsThe Status column has multiple subcolumns. Within each, only the first matching symbol is shown (listed in priority order):@@ -203,6 +217,7 @@ Query structured data with `--format=json`:| `statusline` | string | Pre-formatted status with ANSI colors || `symbols` | string | Raw status symbols without colors (e.g., `"!?↓"`) || `vars` | object | Per-branch variables from [`wt config state vars`](@/config.md#wt-config-state-vars) (absent when empty) |+| `columns` | object | Rendered [custom column](#custom-columns) values keyed by header; empty cells omitted (absent when none configured) |### Commit objectdiff --git a/docs/content/switch.md b/docs/content/switch.mdindex 30f1ec82d..b1eb3ab34 100644--- a/docs/content/switch.md+++ b/docs/content/switch.md@@ -58,6 +58,8 @@ Shortcuts also apply to `--base`. For a fork PR/MR, the head commit is fetched aWhen called without arguments, `wt switch` opens an interactive picker to browse and select worktrees with live preview.+The CI column shows cached PR/MR status when earlier runs (`wt list --full`, the statusline) have fetched it — the picker never fetches CI status itself. An entry whose branch has moved or whose TTL has passed keeps its PR/MR number, dimmed.+<figure class="demo"><picture><source srcset="/assets/docs/dark/wt-switch-picker.gif" media="(prefers-color-scheme: dark)">diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.mdindex c194c2b10..80af549de 100644--- a/skills/worktrunk/reference/config.md+++ b/skills/worktrunk/reference/config.md@@ -189,6 +189,37 @@ task-timeout-ms = 0 # Kill individual git commands after N ms; 0 disablestimeout-ms = 0 # Wall-clock budget for the entire collect phase; 0 disables```+#### Custom columns [experimental]++Custom columns add per-branch context to the `wt list` table. Each+`[list.custom-columns]` entry is a column: the key is the header, the template+renders each row's cell.++```toml+[list.custom-columns.Ticket]+template = "{{ vars.ticket }}" # Required; the result is the cell text+width = 20 # Optional max display width (default: 40)+priority = 9 # Optional drop order when the terminal narrows;+ # lower = kept longer (default: 9, the URL band)+```++Templates may reference `{{ branch }}`, `{{ worktree_path }}`,+`{{ worktree_name }}` (empty for branch-only rows), and `{{ vars.* }}` —+per-branch values stored with+[`wt config state vars set`](https://worktrunk.dev/config/#wt-config-state-vars).+All standard filters work (`sanitize`, `hash_port`, `codename`, …). A row+where the template renders empty (e.g. a branch without the vars key) shows an+empty cell; a column that is empty for every row is dropped from the table.+`wt list --format json` includes the rendered values under `columns`.++A `Note` column showing free-form descriptions, set per branch with+`wt config state vars set note "Bug fix for production fire"`:++```toml+[list.custom-columns.Note]+template = "{{ vars.note }}"+```+### CommitShared by `wt step commit`, `wt step squash`, and `wt merge`.diff --git a/skills/worktrunk/reference/list.md b/skills/worktrunk/reference/list.mdindex 86ba092f4..586fdfdd9 100644--- a/skills/worktrunk/reference/list.md+++ b/skills/worktrunk/reference/list.md@@ -73,6 +73,7 @@ $ wt list --format=json| CI | PR/MR number colored by pipeline status; `--full` only || Path | Worktree directory || URL | Dev server URL from project config; dimmed if port is not listening |+| *(custom)* | User-defined [custom columns](#custom-columns) from `[list.custom-columns]` user config [experimental] || Commit | Short hash (8 chars) || Age | Time since last commit || Message | Last commit message (truncated) |@@ -115,6 +116,17 @@ CI cells are clickable links to the PR or pipeline page, and appear dimmed whenReuses the [`commit.generation`](https://worktrunk.dev/config/#commit) command — the same LLM that generates commit messages. Enable with `summary = true` in `[list]` config; requires `--full`. Results are cached until the branch's diff changes.+### Custom columns [experimental]++Each `[list.custom-columns]` entry in user config adds a column: the key is the header, the template renders each row's cell. Templates can reference per-branch `{{ vars.* }}` stored with [`wt config state vars set`](https://worktrunk.dev/config/#wt-config-state-vars) — useful for tracking what each of many (often agent-driven) branches is for:++```toml+[list.custom-columns.Ticket]+template = "{{ vars.ticket }}"+```++A column that renders empty for every row is dropped from the table. Templates, widths, and drop priority: [custom columns config](https://worktrunk.dev/config/#custom-columns).+## Status symbolsThe Status column has multiple subcolumns. Within each, only the first matching symbol is shown (listed in priority order):@@ -214,6 +226,7 @@ $ wt list --format=json --full | jq '.[] | select(.ci.stale) | .branch'| `statusline` | string | Pre-formatted status with ANSI colors || `symbols` | string | Raw status symbols without colors (e.g., `"!?↓"`) || `vars` | object | Per-branch variables from [`wt config state vars`](https://worktrunk.dev/config/#wt-config-state-vars) (absent when empty) |+| `columns` | object | Rendered [custom column](#custom-columns) values keyed by header; empty cells omitted (absent when none configured) |### Commit objectdiff --git a/skills/worktrunk/reference/switch.md b/skills/worktrunk/reference/switch.mdindex 84d7fc776..da04bac69 100644--- a/skills/worktrunk/reference/switch.md+++ b/skills/worktrunk/reference/switch.md@@ -61,6 +61,8 @@ Shortcuts also apply to `--base`. For a fork PR/MR, the head commit is fetched aWhen called without arguments, `wt switch` opens an interactive picker to browse and select worktrees with live preview.+The CI column shows cached PR/MR status when earlier runs (`wt list --full`, the statusline) have fetched it — the picker never fetches CI status itself. An entry whose branch has moved or whose TTL has passed keeps its PR/MR number, dimmed.+**Keybindings:**| Key | Action |diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex db10fc762..5f2830e12 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -625,6 +625,8 @@ Shortcuts also apply to `--base`. For a fork PR/MR, the head commit is fetched aWhen called without arguments, `wt switch` opens an interactive picker to browse and select worktrees with live preview.+The CI column shows cached PR/MR status when earlier runs (`wt list --full`, the statusline) have fetched it — the picker never fetches CI status itself. An entry whose branch has moved or whose TTL has passed keeps its PR/MR number, dimmed.+<!-- demo: wt-switch-picker.gif 1600x800 -->**Keybindings:**@@ -771,6 +773,7 @@ $ wt list --format=json| CI | PR/MR number colored by pipeline status; `--full` only || Path | Worktree directory || URL | Dev server URL from project config; dimmed if port is not listening |+| *(custom)* | User-defined [custom columns](#custom-columns) from `[list.custom-columns]` user config [experimental] || Commit | Short hash (8 chars) || Age | Time since last commit || Message | Last commit message (truncated) |@@ -813,6 +816,17 @@ CI cells are clickable links to the PR or pipeline page, and appear dimmed whenReuses the [`commit.generation`](@/config.md#commit) command — the same LLM that generates commit messages. Enable with `summary = true` in `[list]` config; requires `--full`. Results are cached until the branch's diff changes.+### Custom columns [experimental]++Each `[list.custom-columns]` entry in user config adds a column: the key is the header, the template renders each row's cell. Templates can reference per-branch `{{ vars.* }}` stored with [`wt config state vars set`](@/config.md#wt-config-state-vars) — useful for tracking what each of many (often agent-driven) branches is for:++```toml+[list.custom-columns.Ticket]+template = "{{ vars.ticket }}"+```++A column that renders empty for every row is dropped from the table. Templates, widths, and drop priority: [custom columns config](@/config.md#custom-columns).+## Status symbolsThe Status column has multiple subcolumns. Within each, only the first matching symbol is shown (listed in priority order):@@ -912,6 +926,7 @@ $ wt list --format=json --full | jq '.[] | select(.ci.stale) | .branch'| `statusline` | string | Pre-formatted status with ANSI colors || `symbols` | string | Raw status symbols without colors (e.g., `"!?↓"`) || `vars` | object | Per-branch variables from [`wt config state vars`](@/config.md#wt-config-state-vars) (absent when empty) |+| `columns` | object | Rendered [custom column](#custom-columns) values keyed by header; empty cells omitted (absent when none configured) |### Commit object@@ -1821,6 +1836,37 @@ task-timeout-ms = 0 # Kill individual git commands after N ms; 0 disablestimeout-ms = 0 # Wall-clock budget for the entire collect phase; 0 disables```+#### Custom columns [experimental]++Custom columns add per-branch context to the `wt list` table. Each+`[list.custom-columns]` entry is a column: the key is the header, the template+renders each row's cell.++```toml+[list.custom-columns.Ticket]+template = "{{ vars.ticket }}" # Required; the result is the cell text+width = 20 # Optional max display width (default: 40)+priority = 9 # Optional drop order when the terminal narrows;+ # lower = kept longer (default: 9, the URL band)+```++Templates may reference `{{ branch }}`, `{{ worktree_path }}`,+`{{ worktree_name }}` (empty for branch-only rows), and `{{ vars.* }}` —+per-branch values stored with+[`wt config state vars set`](@/config.md#wt-config-state-vars).+All standard filters work (`sanitize`, `hash_port`, `codename`, …). A row+where the template renders empty (e.g. a branch without the vars key) shows an+empty cell; a column that is empty for every row is dropped from the table.+`wt list --format json` includes the rendered values under `columns`.++A `Note` column showing free-form descriptions, set per branch with+`wt config state vars set note "Bug fix for production fire"`:++```toml+[list.custom-columns.Note]+template = "{{ vars.note }}"+```+### CommitShared by `wt step commit`, `wt step squash`, and `wt merge`.diff --git a/src/commands/list/CLAUDE.md b/src/commands/list/CLAUDE.mdindex 236f850b8..935d4311d 100644--- a/src/commands/list/CLAUDE.md+++ b/src/commands/list/CLAUDE.md@@ -37,10 +37,13 @@ Results update cells progressively as they complete.## Adding New FeaturesDefault: defer to post-skeleton. Only add a pre-skeleton operation when the-skeleton literally cannot render without the data — column sizing is the one-current exception (the CI column reads its cached width hint pre-skeleton; see-the `collect/mod.rs` docstring inventory). Template expansion and other file-I/O wait; new columns can render a placeholder until data arrives.+skeleton literally cannot render without the data. Current exceptions, all+small local reads: column sizing (the CI column's cached width hint), custom+`[list.custom-columns]` expansion (values come from the in-memory config snapshot and+must be measured for layout), and the picker's cache-only CI fill (the CiStatus+task is skipped there, so the cache read is the column's entire data source).+Template expansion and other file I/O wait; new columns can render a+placeholder until data arrives.## Benchmarking Skeleton Timediff --git a/src/commands/list/ci_status/cache.rs b/src/commands/list/ci_status/cache.rsindex e2d90b51c..923aab04f 100644--- a/src/commands/list/ci_status/cache.rs+++ b/src/commands/list/ci_status/cache.rs@@ -123,6 +123,12 @@ impl CachedCiStatus {cache::cache_dir(repo, KIND)}+ /// Whether any CI status has ever been cached in this repo (the+ /// directory is created on first write and never removed by reads).+ pub(super) fn cache_dir_exists(repo: &Repository) -> bool {+ Self::cache_dir(repo).is_dir()+ }+/// Get the cache file path for a branch.fn cache_file(repo: &Repository, branch: &str) -> PathBuf {let safe_branch = sanitize_for_filename(branch);diff --git a/src/commands/list/ci_status/mod.rs b/src/commands/list/ci_status/mod.rsindex 7a6c83756..4f4a3dd47 100644--- a/src/commands/list/ci_status/mod.rs+++ b/src/commands/list/ci_status/mod.rs@@ -594,9 +594,74 @@ impl PrStatus {}}+/// Fill `pr_status` on items from the CI cache without touching the network.+///+/// The interactive picker skips the `CiStatus` task — fetching would put+/// network latency inside a synchronous TUI — but cached results are local+/// data. A valid entry (HEAD unchanged, within TTL) is used as-is. An+/// expired entry that names a PR/MR is kept with `is_stale` set: a PR/MR+/// number is stable per branch *identity*, so it still identifies the PR+/// even when the pipeline color may be outdated, and `is_stale` renders it+/// dimmed like the existing unpushed-changes treatment. (Deleting a branch+/// and reusing its name can leave the old PR's number showing dimmed until+/// the next fetching surface — `wt list --full`, the statusline — rewrites+/// the entry; the picker accepts that brief skew rather than fetching.) An+/// expired entry without a number is dropped — a stale dot conveys nothing+/// but the outdated color.+///+/// `item.branch` is the cache key for every row shape: local worktrees and+/// branches cache under the bare name, remote rows under `origin/...` —+/// the same `full_name` the `CiStatus` task writes.+///+/// Returns whether any row gained a status; the caller allocates the CI+/// column only in that case. The cache read is the column's complete data+/// source — no task will fill cells in later — so when the column will+/// render, every remaining row resolves to "checked, nothing to show"+/// (blank) rather than staying in the pending-placeholder state.+pub(crate) fn populate_from_cache(repo: &Repository, items: &mut [super::model::ListItem]) -> bool {+ // Common never-fetched case (no `wt list --full`/statusline run yet):+ // skip the per-row file probes entirely.+ if !CachedCiStatus::cache_dir_exists(repo) {+ return false;+ }+ let Ok(repo_path) = repo.current_worktree().root() else {+ return false;+ };+ let now_secs = epoch_now();+ let mut any = false;+ for item in items.iter_mut() {+ let Some(branch) = item.branch.as_deref() else {+ continue;+ };+ let Some(cached) = CachedCiStatus::read(repo, branch) else {+ continue;+ };+ if cached.is_valid(&item.head, now_secs, &repo_path) {+ any |= cached.status.is_some();+ item.pr_status = Some(cached.status);+ } else if let Some(stale) = cached.status.filter(|s| s.number.is_some()) {+ item.pr_status = Some(Some(PrStatus {+ is_stale: true,+ ..stale+ }));+ any = true;+ }+ }+ if any {+ for item in items.iter_mut() {+ if item.pr_status.is_none() {+ item.pr_status = Some(None);+ }+ }+ }+ any+}+#[cfg(test)]mod tests {+ use super::super::model::ListItem;use super::*;+ use worktrunk::testing::TestRepo;#[test]fn test_is_retriable_error() {@@ -887,4 +952,130 @@ mod tests {let out = fake_output("", "");assert!(retriable_pr_error(&out).is_none());}++ fn passed_pr_status(number: Option<u64>) -> PrStatus {+ PrStatus {+ ci_status: CiStatus::Passed,+ source: CiSource::PullRequest,+ is_stale: false,+ url: None,+ number: number.map(PrRef::pr),+ review_state: None,+ }+ }++ fn seed_cache(+ repo: &Repository,+ branch: &str,+ status: Option<PrStatus>,+ checked_at: u64,+ head: &str,+ ) {+ CachedCiStatus {+ status,+ checked_at,+ head: head.to_string(),+ branch: branch.to_string(),+ }+ .write(repo, branch);+ }++ #[test]+ fn test_populate_from_cache() {+ let test = TestRepo::new();+ let repo = &test.repo;+ let now = epoch_now();++ seed_cache(repo, "fresh", Some(passed_pr_status(Some(123))), now, "aaa");+ // Expired (past the 60s max TTL) but carries a number+ seed_cache(+ repo,+ "expired-pr",+ Some(passed_pr_status(Some(77))),+ now - 10_000,+ "bbb",+ );+ // Expired branch-workflow dot — no number to preserve+ seed_cache(+ repo,+ "expired-dot",+ Some(passed_pr_status(None)),+ now - 10_000,+ "ccc",+ );+ // Fresh "no CI found" entry+ seed_cache(repo, "fresh-none", None, now, "ddd");++ let mut items = vec![+ ListItem::new_branch("aaa".to_string(), "fresh".to_string()),+ ListItem::new_branch("bbb".to_string(), "expired-pr".to_string()),+ ListItem::new_branch("ccc".to_string(), "expired-dot".to_string()),+ ListItem::new_branch("ddd".to_string(), "fresh-none".to_string()),+ ListItem::new_branch("eee".to_string(), "uncached".to_string()),+ ];+ assert!(populate_from_cache(repo, &mut items));++ let fresh = items[0].pr_status.as_ref().unwrap().as_ref().unwrap();+ assert_eq!(fresh.number.unwrap().number, 123);+ assert!(!fresh.is_stale);++ let expired = items[1].pr_status.as_ref().unwrap().as_ref().unwrap();+ assert_eq!(expired.number.unwrap().number, 77);+ assert!(expired.is_stale, "expired entries render dimmed");++ assert!(+ matches!(items[2].pr_status, Some(None)),+ "expired dot conveys only its outdated color — resolved to blank"+ );+ assert!(+ matches!(items[3].pr_status, Some(None)),+ "fresh no-CI entry marks the cell as resolved-empty"+ );+ assert!(+ matches!(items[4].pr_status, Some(None)),+ "no task will fill the cell later — blank, not pending"+ );+ }++ #[test]+ fn test_populate_from_cache_head_moved_keeps_number_as_stale() {+ let test = TestRepo::new();+ let repo = &test.repo;++ // Fresh timestamp but the branch has new commits since the fetch —+ // the number still identifies the PR, the colors may not.+ seed_cache(+ repo,+ "feature",+ Some(passed_pr_status(Some(9))),+ epoch_now(),+ "old-head",+ );+ let mut items = vec![ListItem::new_branch(+ "new-head".to_string(),+ "feature".to_string(),+ )];+ assert!(populate_from_cache(repo, &mut items));+ let status = items[0].pr_status.as_ref().unwrap().as_ref().unwrap();+ assert_eq!(status.number.unwrap().number, 9);+ assert!(status.is_stale);+ }++ #[test]+ fn test_populate_from_cache_without_usable_entries_returns_false() {+ // No cache at all+ let test = TestRepo::new();+ let mut items = vec![ListItem::new_branch(+ "aaa".to_string(),+ "feature".to_string(),+ )];+ assert!(!populate_from_cache(&test.repo, &mut items));+ assert!(items[0].pr_status.is_none());++ // Only a fresh "no CI" entry: the cell resolves to empty, but no row+ // gained a status, so the CI column shouldn't be allocated.+ seed_cache(&test.repo, "feature", None, epoch_now(), "aaa");+ assert!(!populate_from_cache(&test.repo, &mut items));+ assert!(matches!(items[0].pr_status, Some(None)));+ }}diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rsindex 915c71907..73be63acd 100644--- a/src/commands/list/collect/mod.rs+++ b/src/commands/list/collect/mod.rs@@ -1058,6 +1058,7 @@ pub fn collect(user_marker: None,status_symbols: StatusSymbols::default(),statusline: None,+ custom_values: Vec::new(),kind: ItemKind::Worktree(Box::new(worktree_data)),}})@@ -1091,10 +1092,55 @@ pub fn collect(effective_skip_tasks.insert(TaskKind::SummaryGenerate);}+ // Custom [list.custom-columns] values expand before layout: their inputs+ // (branch, worktree identity, vars from the bulk config snapshot) are+ // already in memory, so cells paint with the skeleton and column widths+ // are measured from content like Branch/Path. Pure CPU — no subprocess.+ //+ // A broken column definition aborts `wt list` with the error. The picker+ // shares this path but runs collect on a background thread while skim+ // owns the terminal, so it can't surface an abort — it stashes a warning+ // (drained after the picker closes) and renders without custom columns.+ let custom_columns =+ match super::custom_columns::resolve_custom_columns(&config.list.custom_columns, repo) {+ Ok(columns) => columns,+ Err(e) if progressive_handler.is_some() => {+ emit_warning(warning_message(format!("Custom columns disabled: {e}")).to_string());+ Vec::new()+ }+ Err(e) => return Err(e),+ };+ if !custom_columns.is_empty() {+ let all_vars = repo.all_vars_from_snapshot()?;+ super::custom_columns::expand_custom_columns(+ &custom_columns,+ &mut all_items,+ &all_vars,+ repo,+ );+ }++ // The picker skips the networked CiStatus task, but cached statuses are+ // local data: fill rows from `.git/wt/cache/ci-status/` so PR/MR numbers+ // appear in the picker without touching the wire. The CI column is+ // allocated only when some row actually had a usable cache entry —+ // `layout_skip_tasks` diverges from `effective_skip_tasks` exactly then+ // (the skip set still governs task spawning; this copy only tells layout+ // which columns will have data).+ let mut layout_skip_tasks = effective_skip_tasks.clone();+ if progressive_handler.is_some()+ && effective_skip_tasks.contains(&TaskKind::CiStatus)+ && super::ci_status::populate_from_cache(repo, &mut all_items)+ {+ layout_skip_tasks.remove(&TaskKind::CiStatus);+ }+// CI column width hint: the largest PR/MR number any previous fetch saw// (one small file read — cheap enough for the pre-skeleton budget, and- // the skeleton can't size the column without it).- let max_pr_number = (!effective_skip_tasks.contains(&TaskKind::CiStatus))+ // the skeleton can't size the column without it). Also covers the+ // cache-populated picker rows: `detect` re-ratchets on every cache hit,+ // so the stored maximum is at least as wide as any cached number.+ let max_pr_number = (!layout_skip_tasks.contains(&TaskKind::CiStatus)).then(|| super::ci_status::MaxPrNumber::read(repo)).flatten();@@ -1103,13 +1149,14 @@ pub fn collect(// terminal — the rest belongs to the preview pane.let layout = super::layout::calculate_layout_with_width(&all_items,- &effective_skip_tasks,+ &layout_skip_tasks,list_width.or_else(crate::display::terminal_width).unwrap_or(usize::MAX),&main_worktree.path,url_template.as_deref(),max_pr_number,+ &custom_columns,);// Single-line invariant: with no detectable width, an unlimited width@@ -1785,7 +1832,10 @@ pub fn collect(handler.on_collect_complete();}- Ok(Some(super::model::ListData { items }))+ Ok(Some(super::model::ListData {+ items,+ custom_columns,+ }))}// ============================================================================@@ -1882,6 +1932,7 @@ pub fn build_worktree_item(user_marker: None,status_symbols: StatusSymbols::default(),statusline: None,+ custom_values: Vec::new(),kind: ItemKind::Worktree(Box::new(WorktreeData::from_worktree(wt,is_main,@@ -2237,8 +2288,15 @@ mod tests {ListItem::new_branch("bbb".into(), "row-one".into()),];let skip_tasks: HashSet<TaskKind> = HashSet::new();- let layout =- calculate_layout_with_width(&items, &skip_tasks, 80, Path::new("/tmp"), None, None);+ let layout = calculate_layout_with_width(+ &items,+ &skip_tasks,+ 80,+ Path::new("/tmp"),+ None,+ None,+ &[],+ );let placeholder = super::super::render::PLACEHOLDER;// Row 0 has data → format_list_item_line; row 1 doesn't → skeleton.diff --git a/src/commands/list/columns.rs b/src/commands/list/columns.rsindex 1e2eb7ebc..f00d6056d 100644--- a/src/commands/list/columns.rs+++ b/src/commands/list/columns.rs@@ -17,6 +17,11 @@ pub enum ColumnKind {Commit,Time,Message,+ /// User-defined column from `[list.custom-columns]`; the index points into the+ /// resolved column list for this invocation. Values are expanded before+ /// layout, so widths are measured from content and headers come from the+ /// resolved name (not [`ColumnKind::header`]).+ Custom(u8),}impl ColumnKind {@@ -36,6 +41,9 @@ impl ColumnKind {ColumnKind::Commit => "Commit",ColumnKind::Summary => "Summary",ColumnKind::Message => "Message",+ // Header is the resolved column name; layout substitutes it when+ // building `ColumnLayout`.+ ColumnKind::Custom(_) => "",}}@@ -111,11 +119,23 @@ pub const COLUMN_SPECS: &[ColumnSpec] = &[ColumnSpec::new(ColumnKind::Message, 13, None),];-pub fn column_display_index(kind: ColumnKind) -> usize {- COLUMN_SPECS+/// Sort key for display order: (slot in `COLUMN_SPECS`, sub-order).+///+/// Custom columns share the Url slot with a non-zero sub-order, so they+/// render after Url and before Commit, in their resolution order.+pub fn column_display_index(kind: ColumnKind) -> (usize, usize) {+ if let ColumnKind::Custom(i) = kind {+ let url_slot = COLUMN_SPECS+ .iter()+ .position(|spec| spec.kind == ColumnKind::Url)+ .unwrap_or(usize::MAX);+ return (url_slot, i as usize + 1);+ }+ let slot = COLUMN_SPECS.iter().position(|spec| spec.kind == kind)- .unwrap_or(usize::MAX)+ .unwrap_or(usize::MAX);+ (slot, 0)}#[cfg(test)]@@ -243,4 +263,15 @@ mod tests {);}}++ #[test]+ fn test_custom_columns_display_between_url_and_commit() {+ let url = column_display_index(ColumnKind::Url);+ let commit = column_display_index(ColumnKind::Commit);+ let first = column_display_index(ColumnKind::Custom(0));+ let second = column_display_index(ColumnKind::Custom(1));+ assert!(url < first, "custom columns render after Url");+ assert!(first < second, "custom columns keep resolution order");+ assert!(second < commit, "custom columns render before Commit");+ }}diff --git a/src/commands/list/custom_columns.rs b/src/commands/list/custom_columns.rsnew file mode 100644index 000000000..227315b2c--- /dev/null+++ b/src/commands/list/custom_columns.rs@@ -0,0 +1,336 @@+//! User-defined `wt list` columns from `[list.custom-columns]` in user config.+//!+//! Resolved once per invocation, then expanded eagerly for every row before+//! the table skeleton renders: the template inputs (branch, worktree+//! identity, per-branch vars from the bulk config snapshot) are all in memory+//! by then, so cells paint with the skeleton, widths are measured from+//! content like Branch/Path, and a column that renders empty for every row is+//! dropped by the regular empty-column penalty. Layout participation lives in+//! `columns.rs` / `layout.rs` via `ColumnKind::Custom`.+//!+//! Expansion stays off the skeleton's critical costs: one minijinja+//! environment and one parse per column per invocation, one vars conversion+//! per branch, zero subprocesses per cell.++use std::collections::{BTreeMap, HashMap};++use ansi_str::AnsiStr;+use minijinja::Value;+use worktrunk::config::{+ ListColumnConfig, template_environment, validate_list_column_template, vars_map_to_value,+};+use worktrunk::git::Repository;+use worktrunk::path::to_posix_path;++use super::model::ListItem;++/// Default maximum display width for a custom column.+const DEFAULT_MAX_WIDTH: usize = 40;++/// Default drop priority — the URL band (see `COLUMN_SPECS`).+const DEFAULT_PRIORITY: u8 = 9;++/// A custom column resolved from config, ready to expand.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ResolvedCustomColumn {+ /// Header text (the TOML key).+ pub name: String,+ /// minijinja template; the rendered result is the cell text.+ pub template: String,+ /// Maximum display width; longer values truncate.+ pub max_width: usize,+ /// Drop order when the terminal narrows (lower = kept longer).+ pub priority: u8,+}++/// Resolve `[list.custom-columns]` config into expansion-ready columns.+///+/// Validates each definition and orders the result by (priority, name),+/// which is also the display order among custom columns. Errors abort+/// `wt list` — column config is consumed only here, so a broken template+/// can't affect other commands. (The picker degrades instead; see the+/// resolution site in `collect()`.)+pub fn resolve_custom_columns(+ columns: &BTreeMap<String, ListColumnConfig>,+ repo: &Repository,+) -> anyhow::Result<Vec<ResolvedCustomColumn>> {+ // `ColumnKind::Custom(u8)` indexes the resolved list; more entries than+ // u8 can address would silently alias columns.+ anyhow::ensure!(+ columns.len() <= usize::from(u8::MAX) + 1,+ "[list.custom-columns] supports at most 256 columns ({} configured)",+ columns.len()+ );+ let mut resolved: Vec<ResolvedCustomColumn> = columns+ .iter()+ .map(|(name, config)| {+ anyhow::ensure!(+ !name.trim().is_empty() && !name.chars().any(char::is_control),+ "Invalid [list.custom-columns] name {name:?}: must be non-empty without control characters"+ );+ anyhow::ensure!(+ config.width != Some(0),+ "Invalid [list.custom-columns.{name}] width: must be at least 1"+ );+ validate_list_column_template(&config.template, repo, &format!("list.custom-columns.{name}"))?;+ Ok(ResolvedCustomColumn {+ name: name.clone(),+ template: config.template.clone(),+ max_width: config.width.unwrap_or(DEFAULT_MAX_WIDTH),+ priority: config.priority.unwrap_or(DEFAULT_PRIORITY),+ })+ })+ .collect::<anyhow::Result<_>>()?;+ resolved.sort_by(|a, b| (a.priority, &a.name).cmp(&(b.priority, &b.name)));+ Ok(resolved)+}++/// Expand every custom column for every item, populating+/// `ListItem::custom_values`.+///+/// `all_vars` is the pre-fetched vars map for all branches (one snapshot+/// read covers the whole table — no subprocess per cell). Render errors+/// produce an empty cell, logged at `-vv`: a vars key absent on this branch+/// is the expected sparse-column shape, and config-level typos were already+/// rejected at resolution.+pub fn expand_custom_columns(+ columns: &[ResolvedCustomColumn],+ items: &mut [ListItem],+ all_vars: &HashMap<String, BTreeMap<String, String>>,+ repo: &Repository,+) {+ let env = template_environment(repo);+ let names: Vec<String> = columns+ .iter()+ .map(|column| format!("list.custom-columns.{}", column.name))+ .collect();+ // Parse once per column; resolution already validated syntax, so a+ // failure here is unreachable in practice and renders empty cells.+ let templates: Vec<Option<minijinja::Template>> = columns+ .iter()+ .zip(&names)+ .map(+ |(column, name)| match env.template_from_named_str(name, &column.template) {+ Ok(template) => Some(template),+ Err(e) => {+ log::debug!("[{name}] parse failed after validation: {e}");+ None+ }+ },+ )+ .collect();++ // Convert each branch's vars to a template value once, not per cell+ let branch_values: HashMap<&str, Value> = all_vars+ .iter()+ .map(|(branch, entries)| (branch.as_str(), vars_map_to_value(entries)))+ .collect();+ let empty_vars = vars_map_to_value(&BTreeMap::new());++ // Worktree identity is only computed when a template references it:+ // `to_posix_path` shells out to cygpath per call on Windows (Git Bash),+ // which would put O(worktrees) subprocesses on the time-to-skeleton path+ // for columns that never mention the worktree.+ let needs_worktree = templates.iter().flatten().any(|template| {+ let referenced = template.undeclared_variables(false);+ referenced.contains("worktree_path") || referenced.contains("worktree_name")+ });++ for item in items {+ let (worktree_path, worktree_name) = if needs_worktree {+ item.worktree_data()+ .map(|data| {+ let path = to_posix_path(&data.path.to_string_lossy());+ let name = data+ .path+ .file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_default();+ (path, name)+ })+ .unwrap_or_default()+ } else {+ Default::default()+ };+ let branch = item.branch.as_deref().unwrap_or("");++ let mut context: HashMap<String, Value> = HashMap::new();+ context.insert("branch".to_string(), Value::from(branch));+ context.insert("worktree_path".to_string(), Value::from(worktree_path));+ context.insert("worktree_name".to_string(), Value::from(worktree_name));+ // Always inject vars (empty for unknown branches) so+ // `{{ vars.key | default(...) }}` works in SemiStrict mode+ let vars = branch_values.get(branch).unwrap_or(&empty_vars).clone();+ context.insert("vars".to_string(), vars);+ let context = Value::from_object(context);++ item.custom_values = templates+ .iter()+ .zip(&names)+ .map(|(template, name)| {+ let Some(template) = template else {+ return String::new();+ };+ match template.render(&context) {+ Ok(value) => sanitize_cell(&value),+ Err(e) => {+ log::debug!("[{name}] render failed for row {branch:?}: {e}");+ String::new()+ }+ }+ })+ .collect();+ }+}++/// Flatten a rendered value to one trimmed line: ANSI escape sequences are+/// removed, newlines and tabs become spaces, other control characters drop.+fn sanitize_cell(value: &str) -> String {+ value+ .ansi_strip()+ .chars()+ .filter_map(|c| match c {+ '\n' | '\r' | '\t' => Some(' '),+ c if c.is_control() => None,+ c => Some(c),+ })+ .collect::<String>()+ .trim()+ .to_string()+}++#[cfg(test)]+mod tests {+ use super::*;+ use worktrunk::testing::TestRepo;++ #[test]+ fn test_sanitize_cell() {+ assert_eq!(sanitize_cell("plain"), "plain");+ assert_eq!(sanitize_cell(" padded "), "padded");+ assert_eq!(sanitize_cell("two\nlines\there"), "two lines here");+ assert_eq!(sanitize_cell("bell\u{7}gone"), "bellgone");+ assert_eq!(sanitize_cell("\u{1b}[31mred\u{1b}[0m"), "red");+ assert_eq!(sanitize_cell("\n\n"), "");+ }++ fn column_config(template: &str) -> ListColumnConfig {+ ListColumnConfig {+ template: template.to_string(),+ width: None,+ priority: None,+ }+ }++ #[test]+ fn test_resolve_orders_by_priority_then_name() {+ let test = TestRepo::new();+ let mut columns = BTreeMap::new();+ columns.insert("B".to_string(), column_config("{{ branch }}"));+ columns.insert(+ "A".to_string(),+ ListColumnConfig {+ template: "{{ branch }}".to_string(),+ width: Some(10),+ priority: Some(12),+ },+ );+ columns.insert(+ "C".to_string(),+ ListColumnConfig {+ template: "{{ branch }}".to_string(),+ width: None,+ priority: Some(3),+ },+ );++ let resolved = resolve_custom_columns(&columns, &test.repo).unwrap();+ let names: Vec<&str> = resolved.iter().map(|c| c.name.as_str()).collect();+ assert_eq!(names, ["C", "B", "A"]);+ assert_eq!(resolved[0].priority, 3);+ assert_eq!(resolved[1].priority, DEFAULT_PRIORITY);+ assert_eq!(resolved[1].max_width, DEFAULT_MAX_WIDTH);+ assert_eq!(resolved[2].max_width, 10);+ }++ #[test]+ fn test_resolve_rejects_invalid_definitions() {+ let test = TestRepo::new();++ let mut blank_name = BTreeMap::new();+ blank_name.insert(" ".to_string(), column_config("x"));+ let err = resolve_custom_columns(&blank_name, &test.repo).unwrap_err();+ assert!(err.to_string().contains("name"), "got: {err}");++ let mut zero_width = BTreeMap::new();+ zero_width.insert(+ "Ok".to_string(),+ ListColumnConfig {+ template: "x".to_string(),+ width: Some(0),+ priority: None,+ },+ );+ let err = resolve_custom_columns(&zero_width, &test.repo).unwrap_err();+ assert!(err.to_string().contains("width"), "got: {err}");++ let mut unknown_var = BTreeMap::new();+ unknown_var.insert("Ok".to_string(), column_config("{{ nope }}"));+ let err = resolve_custom_columns(&unknown_var, &test.repo).unwrap_err();+ assert!(err.to_string().contains("nope"), "got: {err}");++ let too_many: BTreeMap<String, ListColumnConfig> = (0..=256)+ .map(|i| (format!("C{i:03}"), column_config("x")))+ .collect();+ let err = resolve_custom_columns(&too_many, &test.repo).unwrap_err();+ assert!(err.to_string().contains("256"), "got: {err}");+ }++ #[test]+ fn test_expand_custom_columns_per_row() {+ let test = TestRepo::new();+ let columns = vec![+ ResolvedCustomColumn {+ name: "Ticket".to_string(),+ template: "{{ vars.ticket }}".to_string(),+ max_width: 40,+ priority: 9,+ },+ ResolvedCustomColumn {+ name: "Port".to_string(),+ template: "{{ vars.config.port }}".to_string(),+ max_width: 40,+ priority: 9,+ },+ ResolvedCustomColumn {+ name: "Tag".to_string(),+ template: "{{ branch }}!".to_string(),+ max_width: 40,+ priority: 9,+ },+ ];+ let mut all_vars = HashMap::new();+ all_vars.insert(+ "feature".to_string(),+ BTreeMap::from([+ ("ticket".to_string(), "JIRA-9\nwrapped".to_string()),+ ("config".to_string(), r#"{"port": 8080}"#.to_string()),+ ]),+ );++ let mut items = vec![+ ListItem::new_branch("abc12345".to_string(), "feature".to_string()),+ ListItem::new_branch("abc12345".to_string(), "other".to_string()),+ ];+ expand_custom_columns(&columns, &mut items, &all_vars, &test.repo);++ // Vars-backed cells are sanitized to one line; nested JSON access+ // works; identity vars expand+ assert_eq!(+ items[0].custom_values,+ ["JIRA-9 wrapped", "8080", "feature!"]+ );+ // A branch without the vars keys renders empty cells, not errors+ assert_eq!(items[1].custom_values, ["", "", "other!"]);+ }+}diff --git a/src/commands/list/json_output.rs b/src/commands/list/json_output.rsindex 9845f2c94..785dbd18d 100644--- a/src/commands/list/json_output.rs+++ b/src/commands/list/json_output.rs@@ -23,6 +23,7 @@ use serde::Serialize;use worktrunk::git::{GitRepoInfo, LineDiff, Repository};use super::ci_status::{CiSource, PrStatus, ReviewState};+use super::custom_columns::ResolvedCustomColumn;use super::model::{ItemKind, ListItem, UpstreamStatus};/// JSON output for a single list item@@ -117,6 +118,11 @@ pub struct JsonItem {/// Custom variables stored via `wt config state vars`#[serde(skip_serializing_if = "BTreeMap::is_empty")]pub vars: BTreeMap<String, String>,++ /// Rendered `[list.custom-columns]` values, keyed by column header.+ /// Empty cells are omitted.+ #[serde(skip_serializing_if = "BTreeMap::is_empty")]+ pub columns: BTreeMap<String, String>,}/// Commit information@@ -259,8 +265,9 @@ pub struct JsonCi {impl JsonItem {/// Convert a ListItem to the new JSON structure///- /// `all_vars` is pre-fetched vars data for all branches (from `repo.all_vars_entries()`),- /// avoiding N+1 git process spawns. Entries are moved out via `.remove()` to avoid cloning.+ /// `all_vars` is pre-fetched vars data for all branches (from+ /// `repo.all_vars_from_snapshot()`), avoiding N+1 git process spawns.+ /// Entries are moved out via `.remove()` to avoid cloning.////// `repo` is repository metadata (from `repo.repo_info()`). It is repo-wide, so the caller/// computes it once and passes the same value to every item.@@ -269,6 +276,7 @@ impl JsonItem {all_vars: &mut HashMap<String, BTreeMap<String, String>>,repo: Option<&GitRepoInfo>,ci_provider_override: Option<&str>,+ custom_columns: &[ResolvedCustomColumn],) -> Self {let (kind_str, worktree_data) = match &item.kind {ItemKind::Worktree(data) => ("worktree", Some(data.as_ref())),@@ -389,6 +397,14 @@ impl JsonItem {// Summary: flatten Option<Option<String>> → Option<String>let summary = item.summary.as_ref().and_then(|s| s.clone());+ // Rendered custom column values, keyed by header; empty cells omitted+ let columns = custom_columns+ .iter()+ .zip(&item.custom_values)+ .filter(|(_, value)| !value.is_empty())+ .map(|(column, value)| (column.name.clone(), value.clone()))+ .collect();+JsonItem {branch: item.branch.clone(),path,@@ -413,6 +429,7 @@ impl JsonItem {statusline,symbols,vars,+ columns,}}}@@ -543,9 +560,18 @@ fn format_raw_symbols(symbols: &super::model::StatusSymbols) -> String {/// Convert a list of ListItems to JSON output///-/// Fetches all vars data in a single git call, then distributes per-branch.-pub fn to_json_items(items: &[ListItem], repo: &Repository) -> Vec<JsonItem> {- let mut all_vars = repo.all_vars_entries();+/// Reads all vars from the bulk config snapshot (no subprocess, and —+/// unlike the line-parsed `--get-regexp` read — multiline values survive),+/// then distributes per-branch. The same source feeds the rendered `columns`+/// values, so the two fields can't diverge. The snapshot was loaded earlier+/// in this invocation; an error here means the bulk read failed, in which+/// case `collect()` already surfaced it, so the empty fallback is dead code.+pub fn to_json_items(+ items: &[ListItem],+ custom_columns: &[ResolvedCustomColumn],+ repo: &Repository,+) -> Vec<JsonItem> {+ let mut all_vars = repo.all_vars_from_snapshot().unwrap_or_default();let repo_metadata = repo.repo_info();let ci_provider_override = repo.forge_platform_override();items@@ -556,6 +582,7 @@ pub fn to_json_items(items: &[ListItem], repo: &Repository) -> Vec<JsonItem> {&mut all_vars,repo_metadata.as_ref(),ci_provider_override.as_deref(),+ custom_columns,)}).collect()@@ -1036,7 +1063,7 @@ mod tests {item.summary = Some(Some("Add login page".to_string()));// repo_url/repo are set when provided, absent (skipped) when None.- let json_item = JsonItem::from_list_item(&item, &mut all_vars, None, None);+ let json_item = JsonItem::from_list_item(&item, &mut all_vars, None, None, &[]);assert_eq!(json_item.summary, Some("Add login page".to_string()));assert!(json_item.repo_url.is_none());assert!(json_item.repo.is_none());@@ -1050,7 +1077,7 @@ mod tests {project: None,remote: Some("origin".to_string()),};- let json_item = JsonItem::from_list_item(&item, &mut all_vars, Some(&repo), None);+ let json_item = JsonItem::from_list_item(&item, &mut all_vars, Some(&repo), None, &[]);assert_eq!(json_item.repo_url,Some("https://github.com/owner/repo".to_string())@@ -1066,14 +1093,14 @@ mod tests {let mut item = ListItem::new_branch("abc1234".into(), "feature".into());// Both "not collected" and "no summary" should be absent in JSONassert!(- JsonItem::from_list_item(&item, &mut all_vars, None, None)+ JsonItem::from_list_item(&item, &mut all_vars, None, None, &[]).summary.is_none());item.summary = Some(None);assert!(- JsonItem::from_list_item(&item, &mut all_vars, None, None)+ JsonItem::from_list_item(&item, &mut all_vars, None, None, &[]).summary.is_none());diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rsindex c8a8bad2b..69721ac03 100644--- a/src/commands/list/layout.rs+++ b/src/commands/list/layout.rs@@ -196,6 +196,7 @@ use crate::display::shorten_path;use super::collect::{TaskKind, parse_port_from_url};use super::columns::{COLUMN_SPECS, ColumnKind, ColumnSpec, column_display_index};+use super::custom_columns::ResolvedCustomColumn;// Re-export DiffVariant for external use (e.g., picker module)pub use super::columns::DiffVariant;@@ -274,6 +275,10 @@ pub struct ColumnWidths {pub working_diff: DiffWidths,pub branch_diff: DiffWidths,pub upstream: DiffWidths,+ /// Measured widths for `[list.custom-columns]` columns, indexed like the+ /// resolved column list. Values are final before layout (no estimates);+ /// 0 means the column is empty for every row and is excluded entirely.+ pub custom: Vec<usize>,}/// Tracks which columns have actual data (vs just headers)@@ -437,6 +442,10 @@ impl ColumnKind {ColumnKind::Commit => true,ColumnKind::Summary => true, // Placeholder shown until data arrivesColumnKind::Message => true,+ // Custom values are final before layout (nothing arrives later),+ // so all-empty columns are excluded from candidates instead of+ // taking the EMPTY_PENALTY path built for still-loading data.+ ColumnKind::Custom(_) => true,}}@@ -479,6 +488,7 @@ impl ColumnKind {ColumnKind::AheadBehind => diff(widths.ahead_behind),ColumnKind::BranchDiff => diff(widths.branch_diff),ColumnKind::Upstream => diff(widths.upstream),+ ColumnKind::Custom(i) => text(widths.custom.get(i as usize).copied().unwrap_or(0)),}}}@@ -500,7 +510,9 @@ pub struct DiffColumnConfig {#[derive(Clone, Debug)]pub struct ColumnLayout {pub kind: ColumnKind,- pub header: &'static str,+ /// Borrowed from [`ColumnKind::header`] for built-ins; owned for custom+ /// columns, whose header is the resolved column name.+ pub header: std::borrow::Cow<'static, str>,pub start: usize,pub width: usize,pub format: ColumnFormat,@@ -569,6 +581,7 @@ fn build_estimated_widths(has_branch_worktree_mismatch: bool,url_width: usize,max_pr_number: Option<u64>,+ custom_widths: Vec<usize>,) -> LayoutMetadata {// Fixed widths for slow columns (require expensive git operations)// Values exceeding these widths use compact notation (K suffix)@@ -646,6 +659,7 @@ fn build_estimated_widths(positive_digits: 2,negative_digits: 2,},+ custom: custom_widths,};LayoutMetadata {@@ -666,10 +680,21 @@ fn allocate_columns_with_priority(commit_width: usize,terminal_width: usize,main_worktree_path: PathBuf,+ custom_columns: &[ResolvedCustomColumn],) -> LayoutConfig {let spacing = 2;let mut remaining = terminal_width;+ // Custom columns join the candidate pool with their configured priority.+ // Width 0 means empty for every row — excluded entirely (values are+ // final, so unlike still-loading built-ins nothing can arrive later).+ let custom_specs: Vec<ColumnSpec> = custom_columns+ .iter()+ .enumerate()+ .filter(|&(i, _)| metadata.widths.custom.get(i).copied().unwrap_or(0) > 0)+ .map(|(i, column)| ColumnSpec::new(ColumnKind::Custom(i as u8), column.priority, None))+ .collect();+// Build candidates with priorities// Filter out columns whose required task is being skippedlet mut candidates: Vec<ColumnCandidate> = COLUMN_SPECS@@ -678,6 +703,7 @@ fn allocate_columns_with_priority(spec.requires_task.is_none_or(|task| !skip_tasks.contains(&task))})+ .chain(custom_specs.iter()).map(|spec| ColumnCandidate {spec,priority: if spec.kind.has_data(&metadata.data_flags) {@@ -688,6 +714,8 @@ fn allocate_columns_with_priority(}).collect();+ // Stable sort: a custom column tying a built-in's priority allocates+ // after it (customs are appended to the candidate list).candidates.sort_by_key(|candidate| candidate.priority);// Store candidate kinds for later calculation of hidden columns@@ -861,9 +889,15 @@ fn allocate_columns_with_priority(};position = start + col.width;+ let header = match col.spec.kind {+ ColumnKind::Custom(i) => {+ std::borrow::Cow::Owned(custom_columns[i as usize].name.clone())+ }+ kind => std::borrow::Cow::Borrowed(kind.header()),+ };columns.push(ColumnLayout {kind: col.spec.kind,- header: col.spec.kind.header(),+ header,start,width: col.width,format: col.format,@@ -920,6 +954,7 @@ pub fn calculate_layout_with_width(main_worktree_path: &Path,url_template: Option<&str>,max_pr_number: Option<u64>,+ custom_columns: &[ResolvedCustomColumn],) -> LayoutConfig {// Calculate actual widths for things we know// Include branch names from both worktrees and standalone branches@@ -949,6 +984,26 @@ pub fn calculate_layout_with_width(// Estimate URL width from template (heuristic, no expansion needed)let url_width = estimate_url_width(url_template, supports_hyperlinks(Stream::Stdout));+ // Custom column widths are measured, not estimated: values were expanded+ // before layout. A column empty on every row stays 0 and is excluded.+ let custom_widths: Vec<usize> = custom_columns+ .iter()+ .enumerate()+ .map(|(i, column)| {+ let widest_value = items+ .iter()+ .filter_map(|item| item.custom_values.get(i))+ .map(|value| value.width())+ .max()+ .unwrap_or(0);+ if widest_value == 0 {+ 0+ } else {+ fit_header(&column.name, widest_value.min(column.max_width))+ }+ })+ .collect();+// Build pre-allocated width estimates (same as buffered mode)let metadata = build_estimated_widths(max_branch,@@ -956,6 +1011,7 @@ pub fn calculate_layout_with_width(has_branch_worktree_mismatch,url_width,max_pr_number,+ custom_widths,);let commit_width = fit_header(ColumnKind::Commit.header(), COMMIT_HASH_WIDTH);@@ -967,6 +1023,7 @@ pub fn calculate_layout_with_width(commit_width,terminal_width,main_worktree_path.to_path_buf(),+ custom_columns,)}@@ -1147,6 +1204,7 @@ mod tests {positive_digits: 2,negative_digits: 2,},+ custom: Vec::new(),};// Text columns return (width, ColumnFormat::Text)@@ -1214,6 +1272,7 @@ mod tests {positive_digits: 0,negative_digits: 0,},+ custom: Vec::new(),};assert!(ColumnKind::Branch.ideal(&zero_widths, 0, 0).is_none());assert!(ColumnKind::WorkingDiff.ideal(&zero_widths, 0, 0).is_none());@@ -1225,7 +1284,7 @@ mod tests {// Empty skip set means all tasks are computed (equivalent to --full)// has_branch_worktree_mismatch=true to test the path flag is passed through// url_width=0 since we're not testing URL column here- let metadata = build_estimated_widths(20, &HashSet::new(), true, 0, None);+ let metadata = build_estimated_widths(20, &HashSet::new(), true, 0, None, Vec::new());let widths = metadata.widths;// Line diffs (Signs variant: +/-) allocate 3 digits for 100-999 range@@ -1295,11 +1354,12 @@ mod tests {#[test]fn test_ci_column_width_from_max_pr_number() {// Cached largest number sizes the column: "#12345" → 6- let metadata = build_estimated_widths(20, &HashSet::new(), false, 0, Some(12345));+ let metadata =+ build_estimated_widths(20, &HashSet::new(), false, 0, Some(12345), Vec::new());assert_eq!(metadata.widths.ci_status, 6);// Never below header width ("CI" → 2)- let metadata = build_estimated_widths(20, &HashSet::new(), false, 0, Some(1));+ let metadata = build_estimated_widths(20, &HashSet::new(), false, 0, Some(1), Vec::new());assert_eq!(metadata.widths.ci_status, 2);}@@ -1345,6 +1405,7 @@ mod tests {user_marker: None,status_symbols: StatusSymbols::default(),statusline: None,+ custom_values: Vec::new(),kind: ItemKind::Worktree(Box::new(WorktreeData {path: PathBuf::from("/test/path"),detached: false,@@ -1374,6 +1435,7 @@ mod tests {&main_worktree_path,None,None,+ &[],);assert!(@@ -1457,6 +1519,7 @@ mod tests {user_marker: None,status_symbols: StatusSymbols::default(),statusline: None,+ custom_values: Vec::new(),kind: ItemKind::Worktree(Box::new(WorktreeData {path: PathBuf::from("/test"),detached: false,@@ -1486,6 +1549,7 @@ mod tests {&main_worktree_path,None,None,+ &[],);assert!(@@ -1583,6 +1647,7 @@ mod tests {user_marker: None,status_symbols: StatusSymbols::default(),statusline: None,+ custom_values: Vec::new(),kind: ItemKind::Worktree(Box::new(WorktreeData {path: PathBuf::from("/test/wt"),detached: false,@@ -1604,7 +1669,15 @@ mod tests {/// Helper: compute layout with explicit terminal width and skip_tasks.fn layout_at_width(width: usize, skip_tasks: &HashSet<TaskKind>) -> LayoutConfig {let items = vec![make_test_item("feature-branch")];- calculate_layout_with_width(&items, skip_tasks, width, Path::new("/test"), None, None)+ calculate_layout_with_width(+ &items,+ skip_tasks,+ width,+ Path::new("/test"),+ None,+ None,+ &[],+ )}/// Default skip_tasks for non-full mode (Summary, BranchDiff, CI skipped).@@ -1830,6 +1903,7 @@ mod tests {user_marker: None,status_symbols: StatusSymbols::default(),statusline: None,+ custom_values: Vec::new(),kind: ItemKind::Worktree(Box::new(WorktreeData {path: PathBuf::from(path),detached: false,@@ -1877,7 +1951,8 @@ mod tests {let skip = full_skip_tasks();// At very wide terminals: both Path and Summary coexist- let layout_wide = calculate_layout_with_width(&items, &skip, 300, main_path, None, None);+ let layout_wide =+ calculate_layout_with_width(&items, &skip, 300, main_path, None, None, &[]);assert!(find_column(&layout_wide, ColumnKind::Summary).is_some(),"Summary should be present at 300"@@ -1890,7 +1965,8 @@ mod tests {// At moderate widths (170): Summary should reach at least 50 chars.// Currently Path eats ~30 chars from Summary's expansion budget,// leaving Summary at ~48 and dropping Message entirely.- let layout_170 = calculate_layout_with_width(&items, &skip, 170, main_path, None, None);+ let layout_170 =+ calculate_layout_with_width(&items, &skip, 170, main_path, None, None, &[]);let summary_170 = find_column(&layout_170, ColumnKind::Summary).expect("Summary should be present at 170").width;@@ -1961,6 +2037,7 @@ mod tests {user_marker: None,status_symbols: StatusSymbols::default(),statusline: None,+ custom_values: Vec::new(),kind: ItemKind::Worktree(Box::new(WorktreeData {path: PathBuf::from(path),detached: false,@@ -2028,7 +2105,7 @@ mod tests {let main_path = Path::new("/test/worktrunk");let skip = full_skip_tasks();- let layout = calculate_layout_with_width(&items, &skip, 170, main_path, None, None);+ let layout = calculate_layout_with_width(&items, &skip, 170, main_path, None, None, &[]);let mut lines = Vec::new();lines.push(layout.render_header_line().plain_text());@@ -2055,7 +2132,7 @@ mod tests {// At 30 cols, ideal branch width (~57) can't fit, but Branch should still// be allocated at a reduced width rather than dropped.- let layout = calculate_layout_with_width(&items, &skip, 30, main_path, None, None);+ let layout = calculate_layout_with_width(&items, &skip, 30, main_path, None, None, &[]);let branch = find_column(&layout, ColumnKind::Branch);assert!(branch.is_some(),@@ -2068,7 +2145,7 @@ mod tests {);// At 80 cols, Branch should fit comfortably- let layout = calculate_layout_with_width(&items, &skip, 80, main_path, None, None);+ let layout = calculate_layout_with_width(&items, &skip, 80, main_path, None, None, &[]);let branch = find_column(&layout, ColumnKind::Branch).unwrap();assert!(branch.width > 6,@@ -2101,4 +2178,102 @@ mod tests {"Message should still appear");}++ fn custom_column(name: &str, max_width: usize, priority: u8) -> ResolvedCustomColumn {+ ResolvedCustomColumn {+ name: name.to_string(),+ template: String::new(),+ max_width,+ priority,+ }+ }++ #[test]+ fn test_custom_columns_measured_width_and_position() {+ let columns = [+ custom_column("Ticket", 10, 9),+ custom_column("WideHeaderName", 40, 9),+ ];+ let mut item = make_test_item("feature");+ item.custom_values = vec!["JIRA-1234-overflows".to_string(), "x".to_string()];+ let items = vec![item];++ let layout = calculate_layout_with_width(+ &items,+ &non_full_skip_tasks(),+ 300,+ Path::new("/test"),+ None,+ None,+ &columns,+ );++ // Value wider than max_width clamps to it+ let ticket = find_column(&layout, ColumnKind::Custom(0)).expect("Ticket allocated");+ assert_eq!(ticket.header, "Ticket");+ assert_eq!(ticket.width, 10);++ // Value narrower than the header floors at header width+ let wide = find_column(&layout, ColumnKind::Custom(1)).expect("second column allocated");+ assert_eq!(wide.width, "WideHeaderName".len());++ // Display position: custom columns keep resolution order and render+ // before Commit+ let pos = |kind| layout.columns.iter().position(|c| c.kind == kind).unwrap();+ assert!(pos(ColumnKind::Custom(0)) < pos(ColumnKind::Custom(1)));+ assert!(pos(ColumnKind::Custom(1)) < pos(ColumnKind::Commit));+ }++ #[test]+ fn test_custom_column_empty_everywhere_is_excluded() {+ let columns = [custom_column("Ticket", 40, 9)];+ let mut item = make_test_item("feature");+ item.custom_values = vec![String::new()];+ let items = vec![item];++ // Skip UrlStatus like collect does when no URL template is+ // configured; otherwise the zero-width Url candidate counts as a+ // hidden column and obscures the assertion below.+ let mut skip_tasks = non_full_skip_tasks();+ skip_tasks.insert(TaskKind::UrlStatus);++ let layout = calculate_layout_with_width(+ &items,+ &skip_tasks,+ 300,+ Path::new("/test"),+ None,+ None,+ &columns,+ );++ // Values are final before layout, so an all-empty column is excluded+ // entirely — not allocated and not counted as hidden+ assert!(find_column(&layout, ColumnKind::Custom(0)).is_none());+ assert_eq!(layout.hidden_column_count, 0);+ }++ #[test]+ fn test_custom_column_dropped_on_narrow_terminal() {+ let columns = [custom_column("Ticket", 40, 9)];+ let mut item = make_test_item("feature");+ item.custom_values = vec!["JIRA-1234".to_string()];+ let items = vec![item];++ let narrow = calculate_layout_with_width(+ &items,+ &non_full_skip_tasks(),+ 30,+ Path::new("/test"),+ None,+ None,+ &columns,+ );++ // Priority 9 loses to the core columns when space runs out, and the+ // unallocated candidate counts toward the hidden-column footer+ assert!(find_column(&narrow, ColumnKind::Custom(0)).is_none());+ assert!(find_column(&narrow, ColumnKind::Branch).is_some());+ assert!(narrow.hidden_column_count > 0);+ }}diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rsindex 3f3302b8d..12713c71e 100644--- a/src/commands/list/mod.rs+++ b/src/commands/list/mod.rs@@ -121,6 +121,7 @@pub mod ci_status;pub(crate) mod collect;pub(crate) mod columns;+pub(crate) mod custom_columns;pub mod json_output;pub(crate) mod layout;pub mod model;@@ -160,12 +161,16 @@ pub fn handle_list(render_target,)?;- let Some(ListData { items, .. }) = list_data else {+ let Some(ListData {+ items,+ custom_columns,+ }) = list_data+ else {return Ok(());};if matches!(render_target, RenderTarget::Json) {- let json_items = json_output::to_json_items(&items, &repo);+ let json_items = json_output::to_json_items(&items, &custom_columns, &repo);let json =serde_json::to_string_pretty(&json_items).context("Failed to serialize to JSON")?;println!("{}", json);diff --git a/src/commands/list/model/item.rs b/src/commands/list/model/item.rsindex 26add1252..e874e9e89 100644--- a/src/commands/list/model/item.rs+++ b/src/commands/list/model/item.rs@@ -217,6 +217,13 @@ pub struct ListItem {/// `JsonItem` for the `statusline` field.pub statusline: Option<String>,+ /// Rendered `[list.custom-columns]` values, indexed like the resolved column+ /// list (`ColumnKind::Custom`). Unlike the `Option`-gated fields above,+ /// these are final at construction time: templates expand from in-memory+ /// data before layout, so there is no loading state. Empty when no custom+ /// columns are configured.+ pub custom_values: Vec<String>,+// Type-specific data (worktree vs branch)pub kind: ItemKind,}@@ -224,6 +231,9 @@ pub struct ListItem {/// Container for list command results.pub struct ListData {pub items: Vec<ListItem>,+ /// Resolved `[list.custom-columns]` definitions; each item's `custom_values`+ /// uses the same indexing.+ pub custom_columns: Vec<crate::commands::list::custom_columns::ResolvedCustomColumn>,}impl ListItem {@@ -260,6 +270,7 @@ impl ListItem {user_marker: None,status_symbols: StatusSymbols::default(),statusline: None,+ custom_values: Vec::new(),kind: ItemKind::Branch(scope),}}diff --git a/src/commands/list/render.rs b/src/commands/list/render.rsindex b04c99b1f..ec4d17bce 100644--- a/src/commands/list/render.rs+++ b/src/commands/list/render.rs@@ -318,6 +318,33 @@ impl LayoutConfig {cell.push_styled(short_head, dim);}}+ ColumnKind::Custom(i) => {+ // Custom values are expanded before the skeleton renders —+ // show them like Branch/Path rather than a placeholder.+ let text = item+ .custom_values+ .get(i as usize)+ .map(String::as_str)+ .unwrap_or("");+ return col.render_text_cell(text, None);+ }+ ColumnKind::CiStatus if item.pr_status.is_some() => {+ // Resolved before the skeleton only by the picker's+ // cache-only fill, where no task will repaint the cell;+ // `wt list` never sets pr_status this early and keeps+ // the placeholder arm below.+ return match &item.pr_status {+ Some(Some(pr_status)) => {+ let mut ci = StyledLine::new();+ ci.push_raw(+ pr_status+ .format_cell(col.width, supports_hyperlinks(Stream::Stdout)),+ );+ ci+ }+ _ => StyledLine::new(),+ };+ }_ => {// Show spinner for data columns (placeholder_cell handles alignment)return col.placeholder_cell(spinner);@@ -557,6 +584,16 @@ impl ColumnLayout {cell.push_styled(msg, Style::new().dimmed());cell}+ // Values are expanded before layout — no loading state, so an+ // absent or empty value is an empty cell, never a placeholder.+ ColumnKind::Custom(i) => {+ let text = item+ .custom_values+ .get(i as usize)+ .map(String::as_str)+ .unwrap_or("");+ self.render_text_cell(text, text_style)+ }}}}@@ -1252,7 +1289,7 @@ mod tests {let layout = LayoutConfig {columns: vec![ColumnLayout {kind: ColumnKind::Summary,- header: "Summary",+ header: std::borrow::Cow::Borrowed("Summary"),start: 0,width: 10,format: ColumnFormat::Text,@@ -1279,7 +1316,7 @@ mod tests {let summary_col = ColumnLayout {kind: ColumnKind::Summary,- header: "Summary",+ header: std::borrow::Cow::Borrowed("Summary"),start: 0,width: 40,format: ColumnFormat::Text,@@ -1314,7 +1351,7 @@ mod tests {let col = ColumnLayout {kind: ColumnKind::WorkingDiff,- header: "Working",+ header: std::borrow::Cow::Borrowed("Working"),start: 0,width: 9,format: ColumnFormat::Diff(DiffColumnConfig {@@ -1357,7 +1394,7 @@ mod tests {let col = ColumnLayout {kind: ColumnKind::Upstream,- header: "Remote⇅",+ header: std::borrow::Cow::Borrowed("Remote⇅"),start: 0,width: 7,format: ColumnFormat::Diff(DiffColumnConfig {diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex c841c2a4d..5c3cfeae6 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -103,6 +103,7 @@ use std::rc::Rc;use std::sync::atomic::AtomicUsize;use std::sync::{Arc, Mutex};+use ansi_str::AnsiStr;use anyhow::Context;// bounded/unbounded/Sender are re-exported by skim::preludeuse skim::prelude::*;@@ -523,6 +524,10 @@ pub fn handle_picker(// Skip expensive operations — BranchDiff walks history per item,// CiStatus hits the network. Both are slow enough that waiting for// them adds perceptible cost for a modest column-population win.+ // Cached CI statuses still appear: when the CiStatus task is skipped+ // under a progressive handler, collect fills rows from the CI cache+ // (one local file read per branch, no fetch), so PR/MR numbers from+ // recent `wt list --full` or statusline runs show in the picker.let skip_tasks: std::collections::HashSet<collect::TaskKind> =[collect::TaskKind::BranchDiff, collect::TaskKind::CiStatus].into_iter()@@ -756,7 +761,7 @@ pub fn handle_picker(// `Skim::run_with` returns and stderr is safe again).let stashed_warnings: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));- let handler: Arc<dyn collect::PickerProgressHandler> =+ let handler: Arc<progressive_handler::PickerHandler> =Arc::new(progressive_handler::PickerHandler {tx: tx.clone(),shared_items: Arc::clone(&shared_items),@@ -773,7 +778,7 @@ pub fn handle_picker(// Spawn collect on a background thread. The handler holds the only// remaining `tx` clone; when the bg thread exits, `tx` drops, and skim's// heartbeat stops. Contract: background work done → picker idle.- let bg_handler = Arc::clone(&handler);+ let bg_handler: Arc<dyn collect::PickerProgressHandler> = handler.clone();let bg_repo = repo.clone();let bg_skip_tasks = skip_tasks.clone();let bg_handle = std::thread::Builder::new()@@ -799,9 +804,11 @@ pub fn handle_picker(worktrunk::trace::instant("Picker collect spawned");// Drop main-thread copies so the bg thread's `tx` clone is the last- // sender (its drop is what stops skim's heartbeat).+ // sender (its drop is what stops skim's heartbeat). The dry run keeps+ // the handler — skim never runs there, so the heartbeat contract+ // doesn't apply, and the dump below reads its rendered rows.drop(tx);- drop(handler);+ let dry_run_handler = is_dry_run.then_some(handler);// Dry-run / preview-bench: skim is bypassed. Wait for collect (which// spawns previews via the handler) to finish, then for the orchestrator's@@ -816,7 +823,23 @@ pub fn handle_picker(orchestrator.wait_for_idle();if is_dry_run {drain_stashed_warnings(&stashed_warnings);- println!("{}", orchestrator.dump_cache_json());+ // Final rendered rows (ANSI stripped) — lets tests assert on+ // picker row content without a PTY.+ let rows: Vec<String> = dry_run_handler+ .as_ref()+ .and_then(|h| h.rendered_slots.get())+ .map(|slots| {+ slots+ .iter()+ .map(|slot| slot.lock().unwrap().ansi_strip().trim_end().to_string())+ .collect()+ })+ .unwrap_or_default();+ let dump = serde_json::json!({+ "rows": rows,+ "entries": orchestrator.cache_entries_json(),+ });+ println!("{}", serde_json::to_string_pretty(&dump)?);}return Ok(());}diff --git a/src/commands/picker/preview_orchestrator.rs b/src/commands/picker/preview_orchestrator.rsindex 68ed94611..7839ca307 100644--- a/src/commands/picker/preview_orchestrator.rs+++ b/src/commands/picker/preview_orchestrator.rs@@ -252,9 +252,10 @@ impl PreviewOrchestrator {}}- /// Dump cache state as JSON for dry-run diagnostics. Byte-length only+ /// Preview-cache inventory for the dry-run dump: one sorted+ /// `{branch, mode, bytes}` object per cached preview. Byte-length only/// (not content) keeps output small and deterministic across terminals.- pub(super) fn dump_cache_json(&self) -> String {+ pub(super) fn cache_entries_json(&self) -> serde_json::Value {let mut entries: Vec<_> = self.cache.iter()@@ -265,13 +266,12 @@ impl PreviewOrchestrator {.collect();entries.sort();- let items: Vec<String> = entries- .iter()+ entries+ .into_iter().map(|(branch, mode, bytes)| {- format!(" {{ \"branch\": {branch:?}, \"mode\": {mode}, \"bytes\": {bytes} }}")+ serde_json::json!({ "branch": branch, "mode": mode, "bytes": bytes })})- .collect();- format!("{{\n \"entries\": [\n{}\n ]\n}}", items.join(",\n"))+ .collect()}}@@ -454,7 +454,7 @@ mod tests {}#[test]- fn dump_cache_json_format() {+ fn cache_entries_json_format() {let t = TestRepo::new();let orch = orch_for(&t);orch.cache.insert(@@ -463,10 +463,14 @@ mod tests {);orch.cache.insert(("branch-b".to_string(), PreviewMode::Log), "xy".to_string());- let json = orch.dump_cache_json();// Structural assertion — future field additions shouldn't flake the test.- let parsed: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");- let entries = parsed["entries"].as_array().expect("entries array");+ let entries = orch.cache_entries_json();+ let entries = entries.as_array().expect("entries array");assert_eq!(entries.len(), 2);+ for e in entries {+ assert!(e["branch"].is_string());+ assert!(e["mode"].is_number());+ assert!(e["bytes"].is_number());+ }}}diff --git a/src/commands/statusline.rs b/src/commands/statusline.rsindex 6988b2a02..5bee2fe35 100644--- a/src/commands/statusline.rs+++ b/src/commands/statusline.rs@@ -748,6 +748,8 @@ fn run_json() -> Result<()> {all_vars.insert(branch.clone(), entries);}}+ // No custom columns: the statusline path never expands `[list.custom-columns]`+ // (prompt hot path; its compact format has no column grid).let repo_metadata = repo.repo_info();let ci_provider_override = repo.forge_platform_override();let json_item = json_output::JsonItem::from_list_item(@@ -755,6 +757,7 @@ fn run_json() -> Result<()> {&mut all_vars,repo_metadata.as_ref(),ci_provider_override.as_deref(),+ &[],);// Output as JSON array (consistent with wt list --format=json)diff --git a/src/config/expansion.rs b/src/config/expansion.rsindex 1a49afd46..cb6dab48d 100644--- a/src/config/expansion.rs+++ b/src/config/expansion.rs@@ -99,6 +99,13 @@ pub const DEPRECATED_TEMPLATE_VARS: &[&str] = &["main_worktree_path",];+/// Variables available in `wt list` custom-column templates (plus `vars.*`).+///+/// Deliberately narrower than [`base_vars`]: column values are computed per+/// row before the table skeleton renders, so only row-identity data that is+/// already in memory at that point is offered.+pub const LIST_COLUMN_VARS: &[&str] = &["branch", "worktree_path", "worktree_name"];+/// The context in which a template will be expanded.////// Validation uses this to answer "which variables are available here?" —@@ -712,9 +719,11 @@ fn build_undefined_vars_error(/// Set up a minijinja environment with worktrunk's custom filters and functions.///-/// Shared by [`expand_template`] and [`validate_template`] to ensure both use-/// the same filters, functions, and undefined-behavior settings.-fn setup_template_env(repo: &Repository) -> Environment<'static> {+/// Shared by [`expand_template`], [`validate_template`], and the `wt list`+/// custom-column renderer (which holds one environment across all rows) so+/// every template user gets the same filters, functions, and+/// undefined-behavior settings.+pub fn template_environment(repo: &Repository) -> Environment<'static> {let mut env = Environment::new();// SemiStrict: errors on undefined variable use (printing, iteration) but allows// truthiness checks ({% if var %}). This catches typos while supporting optional vars.@@ -864,7 +873,7 @@ pub fn validate_template();}- let env = setup_template_env(repo);+ let env = template_environment(repo);let tmpl = env.template_from_named_str(name, template)@@ -945,7 +954,7 @@ pub fn expand_template(}}- let mut env = setup_template_env(repo);+ let mut env = template_environment(repo);if escape_mode != ShellEscapeMode::Literal {// Preserve trailing newlines in templates (important for multiline shell commands)env.set_keep_trailing_newline(true);@@ -1004,24 +1013,13 @@ pub fn expand_template(// Only look up vars data if the parsed template references the top-level// `vars` object (avoids a git process spawn per expansion while supporting// every MiniJinja access form without false positives from literal text).- // JSON objects/arrays are parsed so nested access works; plain strings and- // numbers stay as-is.if tmpl.undeclared_variables(false).contains("vars")&& let Some(branch) = vars.get("branch"){- let entries = repo.vars_entries(branch);- let vars_map: std::collections::BTreeMap<String, Value> = entries- .into_iter()- .map(|(k, v)| {- let value = serde_json::from_str::<serde_json::Value>(&v)- .ok()- .filter(|j| j.is_object() || j.is_array())- .map(|j| Value::from_serialize(&j))- .unwrap_or_else(|| Value::from(v));- (k, value)- })- .collect();- context.insert("vars".to_string(), Value::from_serialize(&vars_map));+ context.insert(+ "vars".to_string(),+ vars_map_to_value(&repo.vars_entries(branch)),+ );}let result = tmpl@@ -1055,6 +1053,95 @@ pub fn expand_template(Ok(result)}+/// Convert raw vars entries into a minijinja object value.+///+/// JSON objects/arrays are parsed so nested access (`{{ vars.config.port }}`)+/// works; plain strings and numbers stay as-is.+pub fn vars_map_to_value(entries: &std::collections::BTreeMap<String, String>) -> Value {+ let vars_map: std::collections::BTreeMap<&str, Value> = entries+ .iter()+ .map(|(k, v)| {+ let value = serde_json::from_str::<serde_json::Value>(v)+ .ok()+ .filter(|j| j.is_object() || j.is_array())+ .map(|j| Value::from_serialize(&j))+ .unwrap_or_else(|| Value::from(v.clone()));+ (k.as_str(), value)+ })+ .collect();+ Value::from_serialize(&vars_map)+}++/// A vars stand-in that answers every key with a placeholder string.+///+/// Used only by [`validate_list_column_template`]'s trial render: list+/// columns lean on `{{ vars.key }}` for keys that only some branches set, so+/// validating against an empty map (as [`validate_template`] does) would+/// wrongly reject the dominant pattern. Answering every key keeps the trial+/// render exercising filters without constraining which keys exist.+#[derive(Debug)]+struct AnyKeyVars;++impl Object for AnyKeyVars {+ fn get_value(self: &Arc<Self>, _key: &Value) -> Option<Value> {+ Some(Value::from("PLACEHOLDER"))+ }+}++/// Validate a `wt list` custom-column template.+///+/// Checks syntax, restricts top-level variables to `LIST_COLUMN_VARS` ∪+/// `vars`, and trial-renders with placeholder values so filter errors (e.g. a+/// misspelled filter name) surface at config resolution rather than as+/// silently empty cells. `vars.*` access is unconstrained — any key+/// validates, since which keys exist is per-branch runtime state.+pub fn validate_list_column_template(+ template: &str,+ repo: &Repository,+ name: &str,+) -> Result<(), TemplateExpandError> {+ let env = template_environment(repo);+ let tmpl = env+ .template_from_named_str(name, template)+ .map_err(|e| build_template_error(&e, template, name, Vec::new()))?;++ let mut undefined: Vec<String> = tmpl+ .undeclared_variables(false)+ .into_iter()+ .filter(|var| var != "vars" && !LIST_COLUMN_VARS.contains(&var.as_str()))+ .collect();+ undefined.sort();+ if !undefined.is_empty() {+ let mut available = LIST_COLUMN_VARS.to_vec();+ available.push("vars.<key>");+ return Err(build_undefined_vars_error(+ name,+ &undefined,+ sorted_available_vars(&available),+ ));+ }++ let mut context: HashMap<String, Value> = LIST_COLUMN_VARS+ .iter()+ .map(|&k| (k.to_string(), Value::from("PLACEHOLDER")))+ .collect();+ context.insert("vars".to_string(), Value::from_object(AnyKeyVars));+ match tmpl.render(Value::from_object(context)) {+ Ok(_) => Ok(()),+ // At runtime an undefined value renders as an empty cell by design+ // (e.g. nested access like `{{ vars.config.port }}` against the flat+ // placeholder), so it is never a config error here. Everything else —+ // unknown filters, type errors — is a real config problem.+ Err(e) if e.kind() == ErrorKind::UndefinedError => Ok(()),+ Err(e) => Err(build_template_error(+ &e,+ template,+ name,+ sorted_available_vars(LIST_COLUMN_VARS),+ )),+ }+}+#[cfg(test)]mod tests {use insta::assert_snapshot;@@ -2898,4 +2985,52 @@ mod tests {// in alias ordering, so the output ends with it.assert!(out.ends_with("args = "), "got: {out:?}");}++ #[test]+ fn test_vars_map_to_value_parses_json() {+ let mut entries = std::collections::BTreeMap::new();+ entries.insert("ticket".to_string(), "JIRA-1".to_string());+ entries.insert("config".to_string(), r#"{"port": 8080}"#.to_string());+ let value = vars_map_to_value(&entries);++ // Plain strings stay as-is; JSON objects support nested access+ assert_eq!(+ value.get_attr("ticket").unwrap(),+ Value::from("JIRA-1".to_string())+ );+ assert_eq!(+ value.get_attr("config").unwrap().get_attr("port").unwrap(),+ Value::from(8080)+ );+ }++ #[test]+ fn test_validate_list_column_template() {+ let test = test_repo();++ // Row-identity vars, unconstrained vars.* keys, and filters validate+ validate_list_column_template("{{ branch }} {{ worktree_name }}", &test.repo, "t").unwrap();+ validate_list_column_template("{{ vars.any_key_at_all }}", &test.repo, "t").unwrap();+ validate_list_column_template("{{ branch | sanitize }}", &test.repo, "t").unwrap();+ // Nested vars access (JSON values at runtime) must not be rejected+ // even though the trial render's placeholder vars are flat strings+ validate_list_column_template("{{ vars.config.port }}", &test.repo, "t").unwrap();++ // Unknown top-level variables list the available set, vars included+ let err = validate_list_column_template("{{ branhc }}", &test.repo, "t").unwrap_err();+ assert!(err.message.contains("branhc"), "got: {}", err.message);+ assert_eq!(+ err.available_vars,+ vec!["branch", "vars.<key>", "worktree_name", "worktree_path"]+ );++ // Syntax errors fail+ validate_list_column_template("{{ branch", &test.repo, "t").unwrap_err();++ // Misspelled filters surface via the trial render rather than as+ // silently empty cells at runtime+ let err =+ validate_list_column_template("{{ branch | nosuch }}", &test.repo, "t").unwrap_err();+ assert!(err.message.contains("nosuch"), "got: {}", err.message);+ }}diff --git a/src/config/mod.rs b/src/config/mod.rsindex c1c54c01c..43132c90a 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -147,8 +147,9 @@ pub use expansion::{ACTIVE_VARS, ALIAS_ARGS_KEY, DEPRECATED_TEMPLATE_VARS, EXEC_BASE_VARS, REPO_VARS,TemplateExpandError, ValidationScope, alias_context_filter, base_vars, expand_template,format_alias_variables, format_hook_variables, redact_credentials, referenced_vars_for_config,- sanitize_branch_name, sanitize_db, short_hash, template_references_var, validate_template,- validate_template_syntax, vars_available_in,+ sanitize_branch_name, sanitize_db, short_hash, template_environment, template_references_var,+ validate_list_column_template, validate_template, validate_template_syntax, vars_available_in,+ vars_map_to_value,};pub use hooks::HooksConfig;pub use project::{@@ -160,10 +161,11 @@ pub use unknown_tree::{};pub(crate) use user::LoadError;pub use user::{- CommitConfig, CommitGenerationConfig, CopyIgnoredConfig, ListConfig, MergeConfig, RemoveConfig,- ResolvedConfig, StageMode, StepConfig, SwitchConfig, SwitchPickerConfig, UserConfig,- UserProjectOverrides, config_path, default_config_path, default_system_config_path,- require_config_path, set_config_path, system_config_path, valid_user_config_keys,+ CommitConfig, CommitGenerationConfig, CopyIgnoredConfig, ListColumnConfig, ListConfig,+ MergeConfig, RemoveConfig, ResolvedConfig, StageMode, StepConfig, SwitchConfig,+ SwitchPickerConfig, UserConfig, UserProjectOverrides, config_path, default_config_path,+ default_system_config_path, require_config_path, set_config_path, system_config_path,+ valid_user_config_keys,};#[cfg(test)]diff --git a/src/config/user/mod.rs b/src/config/user/mod.rsindex 186b7240a..c84aa2895 100644--- a/src/config/user/mod.rs+++ b/src/config/user/mod.rs@@ -28,8 +28,9 @@ pub use path::{pub use resolved::ResolvedConfig;pub use schema::valid_user_config_keys;pub use sections::{- CommitConfig, CommitGenerationConfig, CopyIgnoredConfig, ListConfig, MergeConfig, RemoveConfig,- StageMode, StepConfig, SwitchConfig, SwitchPickerConfig, UserProjectOverrides,+ CommitConfig, CommitGenerationConfig, CopyIgnoredConfig, ListColumnConfig, ListConfig,+ MergeConfig, RemoveConfig, StageMode, StepConfig, SwitchConfig, SwitchPickerConfig,+ UserProjectOverrides,};/// Describes a problem encountered during config loading. Each variantdiff --git a/src/config/user/sections.rs b/src/config/user/sections.rsindex e0ef91264..ec7a2cfbf 100644--- a/src/config/user/sections.rs+++ b/src/config/user/sections.rs@@ -127,6 +127,37 @@ impl Merge for CommitGenerationConfig {}}+/// A custom column in the `wt list` table, keyed by its header text.+///+/// The value is a minijinja template rendered per row with `{{ branch }}`,+/// `{{ worktree_path }}`, `{{ worktree_name }}` (empty for branch-only rows),+/// and `{{ vars.* }}` (per-branch state from `wt config state vars set`).+/// Rows where the template renders empty show an empty cell; a column that is+/// empty for every row is dropped from the table.+///+/// *(Experimental — fields may change in future releases.)*+///+/// ```toml+/// [list.custom-columns.Ticket]+/// template = "{{ vars.ticket }}"+/// ```+#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, JsonSchema)]+pub struct ListColumnConfig {+ /// Template rendered per row; the result is the cell text+ pub template: String,++ /// Maximum display width; longer values truncate (default: 40).+ /// Values below the header's width are raised to it — a column is never+ /// narrower than its header.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub width: Option<usize>,++ /// Drop order when the terminal narrows; lower = kept longer (default: 9,+ /// alongside the URL column; built-in columns range 0-13)+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub priority: Option<u8>,+}+/// Configuration for the `wt list` command#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, JsonSchema)]pub struct ListConfig {@@ -160,6 +191,16 @@ pub struct ListConfig {/// Disabled when --full is used. Default: no budget (wait for all results).#[serde(rename = "timeout-ms", skip_serializing_if = "Option::is_none")]pub timeout_ms: Option<u64>,++ /// Custom columns, keyed by header text. See [`ListColumnConfig`].+ ///+ /// *(Experimental — fields may change in future releases.)*+ #[serde(+ default,+ rename = "custom-columns",+ skip_serializing_if = "BTreeMap::is_empty"+ )]+ pub custom_columns: BTreeMap<String, ListColumnConfig>,}impl ListConfig {@@ -202,6 +243,15 @@ impl ListConfig {impl Merge for ListConfig {fn merge_with(&self, other: &Self) -> Self {+ // Custom columns merge per key: a more specific layer overrides or+ // adds individual columns without clearing the rest.+ let mut custom_columns = self.custom_columns.clone();+ custom_columns.extend(+ other+ .custom_columns+ .iter()+ .map(|(k, v)| (k.clone(), v.clone())),+ );Self {full: other.full.or(self.full),branches: other.branches.or(self.branches),@@ -209,6 +259,7 @@ impl Merge for ListConfig {summary: other.summary.or(self.summary),task_timeout_ms: other.task_timeout_ms.or(self.task_timeout_ms),timeout_ms: other.timeout_ms.or(self.timeout_ms),+ custom_columns,}}}diff --git a/src/config/user/tests.rs b/src/config/user/tests.rsindex 3d2bb94ad..8e8fe0281 100644--- a/src/config/user/tests.rs+++ b/src/config/user/tests.rs@@ -278,6 +278,7 @@ fn test_list_config_serde() {summary: None,task_timeout_ms: Some(500),timeout_ms: None,+ custom_columns: Default::default(),};let json = serde_json::to_string(&config).unwrap();let parsed: ListConfig = serde_json::from_str(&json).unwrap();@@ -606,6 +607,7 @@ fn test_merge_list_config() {summary: Some(true),task_timeout_ms: Some(1000),timeout_ms: Some(2000),+ custom_columns: Default::default(),};let override_config = ListConfig {full: None, // Should fall back to base@@ -614,6 +616,7 @@ fn test_merge_list_config() {summary: None, // Should fall back to basetask_timeout_ms: None, // Should fall back to basetimeout_ms: None, // Should fall back to base+ custom_columns: Default::default(),};let merged = base.merge_with(&override_config);@@ -625,6 +628,36 @@ fn test_merge_list_config() {assert_eq!(merged.timeout_ms, Some(2000)); // From base}+#[test]+fn test_merge_list_config_columns_per_key() {+ let column = |template: &str| sections::ListColumnConfig {+ template: template.to_string(),+ width: None,+ priority: None,+ };++ let mut base = ListConfig::default();+ base.custom_columns+ .insert("A".to_string(), column("base-a"));+ base.custom_columns+ .insert("B".to_string(), column("base-b"));++ let mut override_config = ListConfig::default();+ override_config+ .custom_columns+ .insert("B".to_string(), column("override-b"));+ override_config+ .custom_columns+ .insert("C".to_string(), column("c"));++ // Per-key union: the override wins on collision without clearing the rest+ let merged = base.merge_with(&override_config);+ assert_eq!(merged.custom_columns.len(), 3);+ assert_eq!(merged.custom_columns["A"].template, "base-a");+ assert_eq!(merged.custom_columns["B"].template, "override-b");+ assert_eq!(merged.custom_columns["C"].template, "c");+}+#[test]fn test_merge_commit_config() {let base = CommitConfig {@@ -1026,6 +1059,7 @@ fn test_list_config_accessor_methods_with_values() {summary: Some(true),task_timeout_ms: Some(5000),timeout_ms: Some(3000),+ custom_columns: Default::default(),};assert!(config.full());assert!(config.branches());diff --git a/src/git/repository/config.rs b/src/git/repository/config.rsindex d2034e503..0aae6e912 100644--- a/src/git/repository/config.rs+++ b/src/git/repository/config.rs@@ -175,13 +175,7 @@ impl Repository {let Some((config_key, value)) = line.split_once(' ') else {continue;};- let Some(rest) = config_key.strip_prefix("worktrunk.state.") else {- continue;- };- // Use rsplit_once: var keys cannot contain dots (validated by- // validate_vars_key), so the last `.vars.` is always the real separator.- // split_once would misparse branch names containing `.vars.`.- let Some((branch, key)) = rest.rsplit_once(".vars.") else {+ let Some((branch, key)) = parse_vars_config_key(config_key) else {continue;};result@@ -192,6 +186,38 @@ impl Repository {result}+ /// Get all vars entries across all branches from the bulk config snapshot.+ ///+ /// Unlike [`Self::all_vars_entries`], this reads the in-memory+ /// `Repository::all_config` map and spawns no subprocess. The snapshot+ /// is loaded once per process, so writes made by other processes after+ /// that load are invisible — coherent for a single read like `wt list`+ /// rendering, wrong for hook/alias pipelines that must observe writes+ /// from earlier steps (those use [`Self::vars_entries`]).+ pub fn all_vars_from_snapshot(+ &self,+ ) -> anyhow::Result<std::collections::HashMap<String, std::collections::BTreeMap<String, String>>>+ {+ let guard = self.all_config()?.read().unwrap();+ let mut result: std::collections::HashMap<+ String,+ std::collections::BTreeMap<String, String>,+ > = std::collections::HashMap::new();+ for (config_key, values) in guard.iter() {+ let Some((branch, key)) = parse_vars_config_key(config_key) else {+ continue;+ };+ let Some(value) = values.last() else {+ continue;+ };+ result+ .entry(branch.to_string())+ .or_default()+ .insert(key.to_string(), value.clone());+ }+ Ok(result)+ }+/// Set the previous branch in worktrunk.history for `wt switch -` support.////// Stores the branch we're switching FROM, so `wt switch -` can return to it.@@ -655,6 +681,17 @@ impl Repository {}}+/// Split a `worktrunk.state.<branch>.vars.<key>` config key into `(branch, key)`.+///+/// Uses `rsplit_once`: var keys cannot contain dots (validated by+/// `validate_vars_key`), so the last `.vars.` is always the real separator.+/// `split_once` would misparse branch names containing `.vars.`.+fn parse_vars_config_key(config_key: &str) -> Option<(&str, &str)> {+ config_key+ .strip_prefix("worktrunk.state.")?+ .rsplit_once(".vars.")+}+#[cfg(test)]mod tests {use super::*;@@ -743,4 +780,25 @@ mod tests {repo.mark_hint_shown("legacy").unwrap();assert_eq!(repo.hint_count("legacy"), 2);}++ /// The snapshot read must parse the same entries as the subprocess read,+ /// including branch names that themselves contain `.vars.`.+ #[test]+ fn test_all_vars_from_snapshot_matches_subprocess_read() {+ let test = TestRepo::with_initial_commit();+ let repo = Repository::at(test.root_path()).unwrap();++ repo.set_config("worktrunk.state.feature.vars.ticket", "JIRA-1")+ .unwrap();+ repo.set_config("worktrunk.state.feature.vars.note", "a note")+ .unwrap();+ repo.set_config("worktrunk.state.weird.vars.branch.vars.key", "v")+ .unwrap();++ let snapshot = repo.all_vars_from_snapshot().unwrap();+ assert_eq!(snapshot, repo.all_vars_entries());+ assert_eq!(snapshot["feature"]["ticket"], "JIRA-1");+ assert_eq!(snapshot["feature"]["note"], "a note");+ assert_eq!(snapshot["weird.vars.branch"]["key"], "v");+ }}diff --git a/tests/integration_tests/list_config.rs b/tests/integration_tests/list_config.rsindex 14e6226a8..774db6842 100644--- a/tests/integration_tests/list_config.rs+++ b/tests/integration_tests/list_config.rs@@ -632,3 +632,162 @@ task-timeout-ms = 1stderr);}++#[rstest]+fn test_list_custom_columns(repo: TestRepo) {+ // A vars-backed column (only feature-a has the key; other rows render+ // empty cells) and a filter-driven column with a value on every row.+ fs::write(+ repo.test_config_path(),+ r#"[list.custom-columns.Ticket]+template = "{{ vars.ticket }}"++[list.custom-columns.Codename]+template = "{{ branch | codename }}"+priority = 12+"#,+ )+ .unwrap();+ repo.run_git(&[+ "config",+ "worktrunk.state.feature-a.vars.ticket",+ "JIRA-1234",+ ]);++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ cmd.arg("list").current_dir(repo.root_path());++ assert_cmd_snapshot!(cmd);+ });+}++#[rstest]+fn test_list_custom_column_empty_everywhere_dropped(repo: TestRepo) {+ // No branch has the vars key, so the column drops from the table+ // entirely (no header, no reserved width).+ fs::write(+ repo.test_config_path(),+ r#"[list.custom-columns.Ticket]+template = "{{ vars.ticket }}"+"#,+ )+ .unwrap();++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ cmd.arg("list").current_dir(repo.root_path());++ assert_cmd_snapshot!(cmd);+ });+}++#[rstest]+fn test_list_custom_columns_json(repo: TestRepo) {+ fs::write(+ repo.test_config_path(),+ r#"[list.custom-columns.Ticket]+template = "{{ vars.ticket }}"+"#,+ )+ .unwrap();+ repo.run_git(&[+ "config",+ "worktrunk.state.feature-a.vars.ticket",+ "JIRA-1234",+ ]);++ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ cmd.args(["list", "--format=json"])+ .current_dir(repo.root_path());++ let output = cmd.output().unwrap();+ let stdout = String::from_utf8_lossy(&output.stdout);+ let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();+ let items = json.as_array().unwrap();++ let by_branch = |branch: &str| {+ items+ .iter()+ .find(|item| item["branch"] == branch)+ .unwrap_or_else(|| panic!("no item for branch {branch}"))+ };++ // Rendered value keyed by header; rows with an empty cell omit the key+ assert_eq!(by_branch("feature-a")["columns"]["Ticket"], "JIRA-1234");+ assert!(by_branch("feature-b")["columns"].is_null());+}++#[rstest]+fn test_list_custom_column_invalid_template(repo: TestRepo) {+ // An unknown top-level variable aborts wt list with the available set+ fs::write(+ repo.test_config_path(),+ r#"[list.custom-columns.Ticket]+template = "{{ branhc }}"+"#,+ )+ .unwrap();++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ cmd.arg("list").current_dir(repo.root_path());++ assert_cmd_snapshot!(cmd);+ });+}++#[rstest]+fn test_list_custom_column_worktree_identity(repo: TestRepo) {+ // A template referencing worktree identity sets `needs_worktree`, so the+ // per-row worktree-data lookup runs: a worktree-attached row resolves the+ // directory name, a branch with no worktree falls back to an empty cell.+ fs::write(+ repo.test_config_path(),+ r#"[list.custom-columns.Dir]+template = "{{ worktree_name }}"+"#,+ )+ .unwrap();+ // A branch with no worktree — only visible with --branches.+ repo.run_git(&["branch", "lonely"]);++ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ cmd.args(["list", "--branches", "--format=json"])+ .current_dir(repo.root_path());++ let output = cmd.output().unwrap();+ let stdout = String::from_utf8_lossy(&output.stdout);+ let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();+ let items = json.as_array().unwrap();++ let by_branch = |branch: &str| {+ items+ .iter()+ .find(|item| item["branch"] == branch)+ .unwrap_or_else(|| panic!("no item for branch {branch}"))+ };++ // Worktree-attached row: the Dir column is the worktree directory name.+ let feature_dir = by_branch("feature-a")["columns"]["Dir"]+ .as_str()+ .expect("feature-a has a Dir value");+ assert!(+ feature_dir.contains("feature-a"),+ "worktree row shows its directory name, got: {feature_dir}"+ );++ // Branch with no worktree: worktree_name is empty, so the cell is omitted.+ assert!(+ by_branch("lonely")["columns"].is_null(),+ "branch-only row has no worktree name, so the Dir cell is empty"+ );+}diff --git a/tests/integration_tests/switch_picker_dry_run.rs b/tests/integration_tests/switch_picker_dry_run.rsindex 4efd927e4..c65bdd82c 100644--- a/tests/integration_tests/switch_picker_dry_run.rs+++ b/tests/integration_tests/switch_picker_dry_run.rs@@ -2,9 +2,9 @@//!//! Setting the env var bypasses skim entirely: the picker runs the full//! pre-compute pipeline (speculative first-item spawn, collect, full spawn-//! loop, summaries), waits for all tasks, prints the cache inventory as JSON,-//! and exits. This exercises the non-TUI wiring inside `handle_picker`-//! without needing a PTY.+//! loop, summaries), waits for all tasks, prints the rendered rows and the+//! preview-cache inventory as JSON, and exits. This exercises the non-TUI+//! wiring inside `handle_picker` without needing a PTY.//!//! Unix-only: `wt switch` rejects the interactive picker on Windows//! ("Interactive picker is not available on Windows") before the dry-run@@ -12,7 +12,7 @@#![cfg(unix)]-use crate::common::{TestRepo, repo};+use crate::common::{TEST_EPOCH, TestRepo, repo};use rstest::rstest;/// Runs the dry-run picker with summaries disabled (default). Covers the@@ -57,6 +57,74 @@ fn test_picker_dry_run_dumps_cache_json(mut repo: TestRepo) {}}+/// Cached CI statuses surface PR numbers in picker rows without any network+/// access: the picker skips the CiStatus task, and collect fills `pr_status`+/// from `.git/wt/cache/ci-status/` instead. A fresh entry renders its+/// number; a branch without one renders an empty CI cell.+#[rstest]+fn test_picker_dry_run_shows_cached_pr_numbers(mut repo: TestRepo) {+ repo.add_worktree("feature-a");+ repo.add_worktree("feature-b");++ // Seed the cache the way a previous `wt list --full` fetch would have:+ // a fresh entry (TEST_EPOCH is the subprocess's `epoch_now()`) for+ // feature-a's current HEAD.+ let head = repo.git_output(&["rev-parse", "feature-a"]);+ let cache_dir = repo.path().join(".git/wt/cache/ci-status");+ std::fs::create_dir_all(&cache_dir).unwrap();+ let entry = serde_json::json!({+ "status": {+ "ci_status": "passed",+ "source": "pr",+ "is_stale": false,+ "number": { "number": 123, "sigil": "#" },+ },+ "checked_at": TEST_EPOCH,+ "head": head.trim(),+ "branch": "feature-a",+ });+ std::fs::write(cache_dir.join("feature-a.json"), entry.to_string()).unwrap();++ let output = repo+ .wt_command()+ .args(["switch"])+ .env("WORKTRUNK_PICKER_DRY_RUN", "1")+ .output()+ .unwrap();++ assert!(+ output.status.success(),+ "dry-run should exit 0; stderr:\n{}",+ String::from_utf8_lossy(&output.stderr)+ );++ let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8");+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");+ let rows: Vec<&str> = parsed["rows"]+ .as_array()+ .expect("top-level `rows` array")+ .iter()+ .map(|r| r.as_str().expect("row is a string"))+ .collect();++ let feature_row = rows+ .iter()+ .find(|r| r.contains("feature-a"))+ .expect("feature-a row present");+ assert!(+ feature_row.contains("#123"),+ "cached PR number should render in the picker row, got: {feature_row}"+ );+ let other_row = rows+ .iter()+ .find(|r| r.contains("feature-b"))+ .expect("feature-b row present");+ assert!(+ !other_row.contains('#'),+ "uncached branch renders an empty CI cell, got: {other_row}"+ );+}+/// Verifies that warnings collect emits while running on the picker's bg/// thread (here, the stale-default-branch warning) reach stderr — they're/// stashed during the run and drained after the dry-run path joins the bg@@ -170,3 +238,100 @@ fn test_picker_preview_bench_produces_no_output(mut repo: TestRepo) {String::from_utf8_lossy(&output.stderr));}++/// The picker renders custom `[list.custom-columns]` cells in its skeleton+/// rows — the `ColumnKind::Custom` arm of `render_skeleton_row`, which the+/// piped `wt list` snapshot tests never reach because they skip the skeleton.+#[rstest]+fn test_picker_dry_run_renders_custom_columns(mut repo: TestRepo) {+ repo.add_worktree("feature-a");+ std::fs::write(+ repo.test_config_path(),+ r#"[list.custom-columns.Ticket]+template = "{{ vars.ticket }}"+"#,+ )+ .unwrap();+ repo.run_git(&[+ "config",+ "worktrunk.state.feature-a.vars.ticket",+ "JIRA-1234",+ ]);++ let output = repo+ .wt_command()+ .args(["switch"])+ .env("WORKTRUNK_PICKER_DRY_RUN", "1")+ .output()+ .unwrap();++ assert!(+ output.status.success(),+ "dry-run should exit 0; stderr:\n{}",+ String::from_utf8_lossy(&output.stderr)+ );++ let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8");+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");+ let rows: Vec<&str> = parsed["rows"]+ .as_array()+ .expect("top-level `rows` array")+ .iter()+ .map(|r| r.as_str().expect("row is a string"))+ .collect();++ let feature_row = rows+ .iter()+ .find(|r| r.contains("feature-a"))+ .expect("feature-a row present");+ assert!(+ feature_row.contains("JIRA-1234"),+ "custom column value renders in the picker skeleton row, got: {feature_row}"+ );+}++/// A broken custom-column template aborts `wt list`, but the picker shares the+/// collect path while skim owns the terminal and can't surface an abort: it+/// stashes a warning (drained after close) and renders without the column.+/// Covers the `progressive_handler` degradation arm in `collect`.+#[rstest]+fn test_picker_dry_run_invalid_custom_column_degrades(mut repo: TestRepo) {+ repo.add_worktree("feature-a");+ std::fs::write(+ repo.test_config_path(),+ r#"[list.custom-columns.Ticket]+template = "{{ branhc }}"+"#,+ )+ .unwrap();++ let output = repo+ .wt_command()+ .args(["switch"])+ .env("WORKTRUNK_PICKER_DRY_RUN", "1")+ .output()+ .unwrap();++ // The picker degrades rather than aborting: it still exits 0 and renders+ // its rows, with the broken column dropped.+ assert!(+ output.status.success(),+ "picker degrades on a broken column instead of aborting; stderr:\n{}",+ String::from_utf8_lossy(&output.stderr)+ );++ let stderr = String::from_utf8(output.stderr).expect("stderr is utf-8");+ assert!(+ stderr.contains("Custom columns disabled"),+ "expected a stashed degradation warning on stderr, got: {stderr}"+ );++ let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8");+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");+ let rows = parsed["rows"].as_array().expect("top-level `rows` array");+ assert!(+ rows.iter()+ .any(|r| r.as_str().unwrap_or("").contains("feature-a")),+ "rows still render without the broken column, got: {stdout}"+ );+}diff --git a/tests/snapshots/integration__integration_tests__help__help_config_create.snap b/tests/snapshots/integration__integration_tests__help__help_config_create.snapindex 8ffffacc3..ab5a4454a 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_create.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_create.snap@@ -165,6 +165,33 @@ Creates [2m~/.config/worktrunk/config.toml[0m with the following content:[107m [0m [2m# task-timeout-ms = 0 # Kill individual git commands after N ms; 0 disables[0m[107m [0m [2m# timeout-ms = 0 # Wall-clock budget for the entire collect phase; 0 disables[0m[107m [0m [2m#[0m+[107m [0m [2m# #### Custom columns [experimental][0m+[107m [0m [2m#[0m+[107m [0m [2m# Custom columns add per-branch context to the `wt list` table. Each[0m+[107m [0m [2m# `[list.custom-columns]` entry is a column: the key is the header, the template[0m+[107m [0m [2m# renders each row's cell.[0m+[107m [0m [2m#[0m+[107m [0m [2m# [list.custom-columns.Ticket][0m+[107m [0m [2m# template = "{{ vars.ticket }}" # Required; the result is the cell text[0m+[107m [0m [2m# width = 20 # Optional max display width (default: 40)[0m+[107m [0m [2m# priority = 9 # Optional drop order when the terminal narrows;[0m+[107m [0m [2m# # lower = kept longer (default: 9, the URL band)[0m+[107m [0m [2m#[0m+[107m [0m [2m# Templates may reference `{{ branch }}`, `{{ worktree_path }}`,[0m+[107m [0m [2m# `{{ worktree_name }}` (empty for branch-only rows), and `{{ vars.* }}` —[0m+[107m [0m [2m# per-branch values stored with[0m+[107m [0m [2m# `wt config state vars set` (https://worktrunk.dev/config/#wt-config-state-vars).[0m+[107m [0m [2m# All standard filters work (`sanitize`, `hash_port`, `codename`, …). A row[0m+[107m [0m [2m# where the template renders empty (e.g. a branch without the vars key) shows an[0m+[107m [0m [2m# empty cell; a column that is empty for every row is dropped from the table.[0m+[107m [0m [2m# `wt list --format json` includes the rendered values under `columns`.[0m+[107m [0m [2m#[0m+[107m [0m [2m# A `Note` column showing free-form descriptions, set per branch with[0m+[107m [0m [2m# `wt config state vars set note "Bug fix for production fire"`:[0m+[107m [0m [2m#[0m+[107m [0m [2m# [list.custom-columns.Note][0m+[107m [0m [2m# template = "{{ vars.note }}"[0m+[107m [0m [2m#[0m[107m [0m [2m# ### Commit[0m[107m [0m [2m#[0m[107m [0m [2m# Shared by `wt step commit`, `wt step squash`, and `wt merge`.[0mdiff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snapindex 712ab47ee..e44e6bc51 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap@@ -213,6 +213,33 @@ Persistent flag values for [2mwt list[0m. Override on command line as needed.[107m [0m [2mtask-timeout-ms = [0m[2m[33m0[0m[2m [0m[2m# Kill individual git commands after N ms; 0 disables[0m[107m [0m [2mtimeout-ms = [0m[2m[33m0[0m[2m [0m[2m# Wall-clock budget for the entire collect phase; 0 disables[0m+[1mCustom columns [experimental][0m++Custom columns add per-branch context to the [2mwt list[0m table. Each+[2m[list.custom-columns][0m entry is a column: the key is the header, the template+renders each row's cell.++[107m [0m [2m[36m[list.custom-columns.Ticket][0m+[107m [0m [2mtemplate = [0m[2m[32m"{{ vars.ticket }}"[0m[2m [0m[2m# Required; the result is the cell text[0m+[107m [0m [2mwidth = [0m[2m[33m20[0m[2m [0m[2m# Optional max display width (default: 40)[0m+[107m [0m [2mpriority = [0m[2m[33m9[0m[2m [0m[2m# Optional drop order when the terminal narrows;[0m+[107m [0m [2m [0m[2m# lower = kept longer (default: 9, the URL band)[0m++Templates may reference [2m{{ branch }}[0m, [2m{{ worktree_path }}[0m,+[2m{{ worktree_name }}[0m (empty for branch-only rows), and [2m{{ vars.* }}[0m —+per-branch values stored with+[2mwt config state vars set[0m.+All standard filters work ([2msanitize[0m, [2mhash_port[0m, [2mcodename[0m, …). A row+where the template renders empty (e.g. a branch without the vars key) shows an+empty cell; a column that is empty for every row is dropped from the table.+[2mwt list --format json[0m includes the rendered values under [2mcolumns[0m.++A [2mNote[0m column showing free-form descriptions, set per branch with+[2mwt config state vars set note "Bug fix for production fire"[0m:++[107m [0m [2m[36m[list.custom-columns.Note][0m+[107m [0m [2mtemplate = [0m[2m[32m"{{ vars.note }}"[0m+[32mCommit[0mShared by [2mwt step commit[0m, [2mwt step squash[0m, and [2mwt merge[0m.diff --git a/tests/snapshots/integration__integration_tests__help__help_list_long.snap b/tests/snapshots/integration__integration_tests__help__help_list_long.snapindex 4d7e3f39f..94e481ec1 100644--- a/tests/snapshots/integration__integration_tests__help__help_list_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_list_long.snap@@ -128,21 +128,22 @@ Output as JSON for scripting:[1m[32mColumns[0m- Column Shows- ─────── ───────────────────────────────────────────────────────────────────────────────────────────────────- Branch Branch name- Status Compact symbols (see below)- HEAD± Uncommitted changes: +added -deleted lines- main↕ Commits ahead/behind default branch- main…± Line diffs since the merge-base (three-dot) with the default branch; [2m--full[0m only- Summary LLM-generated branch summary; requires [2m--full[0m, [2msummary = true[0m, and [2mcommit.generation[0m [experimental]- Remote⇅ Commits ahead/behind tracking branch- CI PR/MR number colored by pipeline status; [2m--full[0m only- Path Worktree directory- URL Dev server URL from project config; dimmed if port is not listening- Commit Short hash (8 chars)- Age Time since last commit- Message Last commit message (truncated)+ Column Shows+ ──────── ───────────────────────────────────────────────────────────────────────────────────────────────────+ Branch Branch name+ Status Compact symbols (see below)+ HEAD± Uncommitted changes: +added -deleted lines+ main↕ Commits ahead/behind default branch+ main…± Line diffs since the merge-base (three-dot) with the default branch; [2m--full[0m only+ Summary LLM-generated branch summary; requires [2m--full[0m, [2msummary = true[0m, and [2mcommit.generation[0m [experimental]+ Remote⇅ Commits ahead/behind tracking branch+ CI PR/MR number colored by pipeline status; [2m--full[0m only+ Path Worktree directory+ URL Dev server URL from project config; dimmed if port is not listening+ (custom) User-defined custom columns from [2m[list.custom-columns][0m user config [experimental]+ Commit Short hash (8 chars)+ Age Time since last commit+ Message Last commit message (truncated)The [2mmain[0m header label is used regardless of the default branch's actual name.@@ -182,6 +183,15 @@ CI cells are clickable links to the PR or pipeline page, and appear dimmed whenReuses the [2mcommit.generation[0m command — the same LLM that generates commit messages. Enable with [2msummary = true[0m in [2m[list][0m config; requires [2m--full[0m. Results are cached until the branch's diff changes.+[32mCustom columns [experimental][0m++Each [2m[list.custom-columns][0m entry in user config adds a column: the key is the header, the template renders each row's cell. Templates can reference per-branch [2m{{ vars.* }}[0m stored with [2mwt config state vars set[0m — useful for tracking what each of many (often agent-driven) branches is for:++[107m [0m [2m[36m[list.custom-columns.Ticket][0m+[107m [0m [2mtemplate = [0m[2m[32m"{{ vars.ticket }}"[0m++A column that renders empty for every row is dropped from the table. Templates, widths, and drop priority: custom columns config.+[1m[32mStatus symbols[0mThe Status column has multiple subcolumns. Within each, only the first matching symbol is shown (listed in priority order):@@ -254,31 +264,32 @@ Query structured data with [2m--format=json[0m:[1mFields:[0m- Field Type Description- ────────────────── ─────────── ───────────────────────────────────────────────────────────────────────────────────────────────- [2mbranch[0m string/null Branch name (null for detached HEAD)- [2mpath[0m string Worktree path (absent for branches without worktrees)- [2mkind[0m string [2m"worktree"[0m or [2m"branch"[0m- [2mcommit[0m object Commit info (see below)- [2mworking_tree[0m object Working tree state (see below)- [2mmain_state[0m string Relation to the default branch (see below)- [2mintegration_reason[0m string Why branch is integrated (see below)- [2moperation_state[0m string [2m"conflicts"[0m, [2m"rebase"[0m, or [2m"merge"[0m; absent when clean- [2mmain[0m object Relationship to the default branch (see below); absent when is_main- [2mremote[0m object Tracking branch info (see below); absent when no tracking- [2mworktree[0m object Worktree metadata (see below)- [2mis_main[0m boolean Is the main worktree- [2mis_current[0m boolean Is the current worktree- [2mis_previous[0m boolean Previous worktree from wt switch- [2mci[0m object CI status (see below); absent when no CI- [2mrepo_url[0m string Repository web URL derived from the primary remote; absent when the remote URL cannot be parsed- [2mrepo[0m object Structured repository metadata (see below); includes [2mremote[0m- [2murl[0m string Dev server URL from project config; absent when not configured- [2murl_active[0m boolean Whether the URL's port is listening; absent when not configured- [2msummary[0m string LLM-generated branch summary; absent when not configured or no summary- [2mstatusline[0m string Pre-formatted status with ANSI colors- [2msymbols[0m string Raw status symbols without colors (e.g., [2m"!?↓"[0m)- [2mvars[0m object Per-branch variables from [2mwt config state vars[0m (absent when empty)+ Field Type Description+ ────────────────── ─────────── ────────────────────────────────────────────────────────────────────────────────────────────────+ [2mbranch[0m string/null Branch name (null for detached HEAD)+ [2mpath[0m string Worktree path (absent for branches without worktrees)+ [2mkind[0m string [2m"worktree"[0m or [2m"branch"[0m+ [2mcommit[0m object Commit info (see below)+ [2mworking_tree[0m object Working tree state (see below)+ [2mmain_state[0m string Relation to the default branch (see below)+ [2mintegration_reason[0m string Why branch is integrated (see below)+ [2moperation_state[0m string [2m"conflicts"[0m, [2m"rebase"[0m, or [2m"merge"[0m; absent when clean+ [2mmain[0m object Relationship to the default branch (see below); absent when is_main+ [2mremote[0m object Tracking branch info (see below); absent when no tracking+ [2mworktree[0m object Worktree metadata (see below)+ [2mis_main[0m boolean Is the main worktree+ [2mis_current[0m boolean Is the current worktree+ [2mis_previous[0m boolean Previous worktree from wt switch+ [2mci[0m object CI status (see below); absent when no CI+ [2mrepo_url[0m string Repository web URL derived from the primary remote; absent when the remote URL cannot be parsed+ [2mrepo[0m object Structured repository metadata (see below); includes [2mremote[0m+ [2murl[0m string Dev server URL from project config; absent when not configured+ [2murl_active[0m boolean Whether the URL's port is listening; absent when not configured+ [2msummary[0m string LLM-generated branch summary; absent when not configured or no summary+ [2mstatusline[0m string Pre-formatted status with ANSI colors+ [2msymbols[0m string Raw status symbols without colors (e.g., [2m"!?↓"[0m)+ [2mvars[0m object Per-branch variables from [2mwt config state vars[0m (absent when empty)+ [2mcolumns[0m object Rendered custom column values keyed by header; empty cells omitted (absent when none configured)[32mCommit object[0mdiff --git a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snapindex 5c58adc05..ef6e1c61f 100644--- a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap+++ b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap@@ -137,23 +137,25 @@ Output as JSON for scripting:[1m[32mColumns[0m- Column Shows- ─────── ──────────────────────────────────────────────────────────────────────- Branch Branch name- Status Compact symbols (see below)- HEAD± Uncommitted changes: +added -deleted lines- main↕ Commits ahead/behind default branch- main…± Line diffs since the merge-base (three-dot) with the default branch;- [2m--full[0m only- Summary LLM-generated branch summary; requires [2m--full[0m, [2msummary = true[0m, and- [2mcommit.generation[0m [experimental]- Remote⇅ Commits ahead/behind tracking branch- CI PR/MR number colored by pipeline status; [2m--full[0m only- Path Worktree directory- URL Dev server URL from project config; dimmed if port is not listening- Commit Short hash (8 chars)- Age Time since last commit- Message Last commit message (truncated)+ Column Shows+ ──────── ─────────────────────────────────────────────────────────────────────+ Branch Branch name+ Status Compact symbols (see below)+ HEAD± Uncommitted changes: +added -deleted lines+ main↕ Commits ahead/behind default branch+ main…± Line diffs since the merge-base (three-dot) with the default branch;+ [2m--full[0m only+ Summary LLM-generated branch summary; requires [2m--full[0m, [2msummary = true[0m, and+ [2mcommit.generation[0m [experimental]+ Remote⇅ Commits ahead/behind tracking branch+ CI PR/MR number colored by pipeline status; [2m--full[0m only+ Path Worktree directory+ URL Dev server URL from project config; dimmed if port is not listening+ (custom) User-defined custom columns from [2m[list.custom-columns][0m user config+ [experimental]+ Commit Short hash (8 chars)+ Age Time since last commit+ Message Last commit message (truncated)The [2mmain[0m header label is used regardless of the default branch's actual name.@@ -208,6 +210,19 @@ Reuses the [2mcommit.generation[0m command — the same LLM that generates commessages. Enable with [2msummary = true[0m in [2m[list][0m config; requires [2m--full[0m. Resultsare cached until the branch's diff changes.+[32mCustom columns [experimental][0m++Each [2m[list.custom-columns][0m entry in user config adds a column: the key is the+header, the template renders each row's cell. Templates can reference per-branch+ [2m{{ vars.* }}[0m stored with [2mwt config state vars set[0m — useful for tracking what+each of many (often agent-driven) branches is for:++[107m [0m [2m[36m[list.custom-columns.Ticket][0m+[107m [0m [2mtemplate = [0m[2m[32m"{{ vars.ticket }}"[0m++A column that renders empty for every row is dropped from the table. Templates,+widths, and drop priority: custom columns config.+[1m[32mStatus symbols[0mThe Status column has multiple subcolumns. Within each, only the first matching@@ -324,6 +339,9 @@ Query structured data with [2m--format=json[0m:[2msymbols[0m string Raw status symbols without colors (e.g., [2m"!?↓"[0m)[2mvars[0m object Per-branch variables from [2mwt config state vars[0m(absent when empty)+ [2mcolumns[0m object Rendered custom column values keyed by header;+ empty cells omitted (absent when none+ configured)[32mCommit object[0mdiff --git a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap b/tests/snapshots/integration__integration_tests__help__help_switch_long.snapindex 92854ad44..1ef10508a 100644--- a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap@@ -168,6 +168,8 @@ Shortcuts also apply to [2m--base[0m. For a fork PR/MR, the head commit is fetWhen called without arguments, [2mwt switch[0m opens an interactive picker to browse and select worktrees with live preview.+The CI column shows cached PR/MR status when earlier runs ([2mwt list --full[0m, the statusline) have fetched it — the picker never fetches CI status itself. An entry whose branch has moved or whose TTL has passed keeps its PR/MR number, dimmed.+[1mKeybindings:[0mKey Actiondiff --git a/tests/snapshots/integration__integration_tests__list_config__list_custom_column_empty_everywhere_dropped.snap b/tests/snapshots/integration__integration_tests__list_config__list_custom_column_empty_everywhere_dropped.snapnew file mode 100644index 000000000..2addc3b0a--- /dev/null+++ b/tests/snapshots/integration__integration_tests__list_config__list_custom_column_empty_everywhere_dropped.snap@@ -0,0 +1,54 @@+---+source: tests/integration_tests/list_config.rs+info:+ program: wt+ args:+ - list+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----+ [1mBranch[0m [1mStatus[0m [1mHEAD±[0m [1mmain↕[0m [1mRemote⇅[0m [1mPath[0m [1mCommit[0m [1mAge[0m [1mMessage[0m+@ main [2m^[22m[2m|[22m [2m|[0m . [2m05a4a45d[0m [2m16h[0m [2mInitial commit[0m++ feature-a [2m↑[22m [32m↑1[0m ../repo.feature-a [2m1b87d473[0m [2m16h[0m [2mAdd feature-a file[0m++ feature-b [2m↑[22m [32m↑1[0m ../repo.feature-b [2mf62940fc[0m [2m16h[0m [2mAdd feature-b file[0m++ feature-c [2m↑[22m [32m↑1[0m ../repo.feature-c [2m345c7c93[0m [2m16h[0m [2mAdd feature-c file[0m++[2m○[22m [2mShowing 4 worktrees, 3 ahead[0m++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__list_config__list_custom_column_invalid_template.snap b/tests/snapshots/integration__integration_tests__list_config__list_custom_column_invalid_template.snapnew file mode 100644index 000000000..b7412f7ec--- /dev/null+++ b/tests/snapshots/integration__integration_tests__list_config__list_custom_column_invalid_template.snap@@ -0,0 +1,49 @@+---+source: tests/integration_tests/list_config.rs+info:+ program: wt+ args:+ - list+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[31m✗[39m [31mFailed to expand list.custom-columns.Ticket: undefined value: `branhc`[39m+[2m↳[22m [2mAvailable variables: [4mbranch[24m, [4mvars.<key>[24m, [4mworktree_name[24m, [4mworktree_path[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__list_config__list_custom_columns.snap b/tests/snapshots/integration__integration_tests__list_config__list_custom_columns.snapnew file mode 100644index 000000000..ce6b80b40--- /dev/null+++ b/tests/snapshots/integration__integration_tests__list_config__list_custom_columns.snap@@ -0,0 +1,54 @@+---+source: tests/integration_tests/list_config.rs+info:+ program: wt+ args:+ - list+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----+ [1mBranch[0m [1mStatus[0m [1mHEAD±[0m [1mmain↕[0m [1mRemote⇅[0m [1mPath[0m [1mTicket[0m [1mCodename[0m [1mCommit[0m [1mAge[0m [1mMessage[0m+@ main [2m^[22m[2m|[22m [2m|[0m . mellow-kite [2m05a4a45d[0m [2m16h[0m [2mInitial commit[0m++ feature-a [2m↑[22m [32m↑1[0m ../repo.feature-a JIRA-1234 fearless-iguanodon [2m1b87d473[0m [2m16h[0m [2mAdd feature-a file[0m++ feature-b [2m↑[22m [32m↑1[0m ../repo.feature-b spirited-mink [2mf62940fc[0m [2m16h[0m [2mAdd feature-b file[0m++ feature-c [2m↑[22m [32m↑1[0m ../repo.feature-c secure-sicklebill [2m345c7c93[0m [2m16h[0m [2mAdd feature-c file[0m++[2m○[22m [2mShowing 4 worktrees, 3 ahead[0m++----- stderr -----