worktrunk 0.35.3

A CLI for Git worktree management, designed for parallel AI agent workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//! Skim item implementations.
//!
//! Wrappers for ListItem and header row that implement SkimItem for the interactive selector.

use std::borrow::Cow;
use std::collections::HashSet;
use std::sync::Arc;

use anstyle::Reset;
use color_print::cformat;
use dashmap::DashMap;
use skim::prelude::*;
use worktrunk::git::Repository;
use worktrunk::styling::INFO_SYMBOL;

use super::super::list::model::ListItem;
use super::log_formatter::{
    FIELD_DELIM, batch_fetch_stats, format_log_output, process_log_with_dimming, strip_hash_markers,
};
use super::pager::{diff_pager, pipe_through_pager};
use super::preview::{PreviewMode, PreviewStateData};

/// Cache key for pre-computed previews: (branch_name, mode).
pub(super) type PreviewCacheKey = (String, PreviewMode);

/// Cache for pre-computed previews, keyed by (branch_name, mode).
/// Shared across all WorktreeSkimItems for background pre-computation.
pub(super) type PreviewCache = Arc<DashMap<PreviewCacheKey, String>>;

/// Header item for column names (non-selectable)
pub(super) struct HeaderSkimItem {
    pub display_text: String,
    pub display_text_with_ansi: String,
}

impl SkimItem for HeaderSkimItem {
    fn text(&self) -> Cow<'_, str> {
        Cow::Borrowed(&self.display_text)
    }

    fn display<'a>(&'a self, _context: skim::DisplayContext<'a>) -> skim::AnsiString<'a> {
        skim::AnsiString::parse(&self.display_text_with_ansi)
    }

    fn output(&self) -> Cow<'_, str> {
        Cow::Borrowed("") // Headers produce no output if selected
    }
}

/// Common diff rendering: check stat, show stat + full diff if non-empty.
fn compute_diff_preview(args: &[&str], no_changes_msg: &str, width: usize) -> String {
    let mut output = String::new();
    let Ok(repo) = Repository::current() else {
        return format!("{no_changes_msg}\n");
    };

    // Check stat output first
    let mut stat_args = args.to_vec();
    stat_args.push("--stat");
    stat_args.push("--color=always");
    let stat_width_arg = format!("--stat-width={}", width);
    stat_args.push(&stat_width_arg);

    if let Ok(stat) = repo.run_command(&stat_args)
        && !stat.trim().is_empty()
    {
        output.push_str(&stat);

        // Build diff args with color
        let mut diff_args = args.to_vec();
        diff_args.push("--color=always");

        if let Ok(diff) = repo.run_command(&diff_args) {
            output.push_str(&diff);
        }
    } else {
        output.push_str(no_changes_msg);
        output.push('\n');
    }

    output
}

/// Wrapper to implement SkimItem for ListItem
pub(super) struct WorktreeSkimItem {
    pub display_text: String,
    pub display_text_with_ansi: String,
    pub branch_name: String,
    pub item: Arc<ListItem>,
    /// Shared cache for pre-computed previews (all modes)
    pub preview_cache: PreviewCache,
}

impl SkimItem for WorktreeSkimItem {
    fn text(&self) -> Cow<'_, str> {
        Cow::Borrowed(&self.display_text)
    }

    fn display<'a>(&'a self, _context: skim::DisplayContext<'a>) -> skim::AnsiString<'a> {
        skim::AnsiString::parse(&self.display_text_with_ansi)
    }

    fn output(&self) -> Cow<'_, str> {
        Cow::Borrowed(&self.branch_name)
    }

    fn preview(&self, context: PreviewContext<'_>) -> ItemPreview {
        let mode = PreviewStateData::read_mode();

        // Build preview: tabs header + content
        let mut result = Self::render_preview_tabs(mode);
        result.push_str(&self.preview_for_mode(mode, context.width, context.height));

        ItemPreview::AnsiText(result)
    }
}

impl WorktreeSkimItem {
    /// Render the tab header for the preview window
    ///
    /// Shows all preview modes as tabs, with the current mode bolded
    /// and unselected modes dimmed. Controls shown below in normal text
    /// for visual distinction from inactive tabs.
    pub(super) fn render_preview_tabs(mode: PreviewMode) -> String {
        // Full SGR reset (\x1b[0m) to ensure clean state between styled elements.
        // Using anstyle::Reset instead of cformat's </> (\x1b[22m) because some terminals
        // don't properly handle the intensity-only reset after bold text. This matches
        // the pattern used in src/styling/format.rs for similar ANSI reset handling.
        let reset = Reset;

        /// Format a tab label with bold (active) or dimmed (inactive) styling
        fn format_tab(label: &str, is_active: bool) -> String {
            if is_active {
                cformat!("<bold>{}</>", label)
            } else {
                cformat!("<dim>{}</>", label)
            }
        }

        let tab1 = format_tab("1: HEAD±", mode == PreviewMode::WorkingTree);
        let tab2 = format_tab("2: log", mode == PreviewMode::Log);
        let tab3 = format_tab("3: main…±", mode == PreviewMode::BranchDiff);
        let tab4 = format_tab("4: remote⇅", mode == PreviewMode::UpstreamDiff);
        let tab5 = format_tab("5: summary", mode == PreviewMode::Summary);

        // Controls use dim yellow to distinguish from dimmed (white) tabs
        let controls = cformat!(
            "<dim,yellow>Enter: switch | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle</>"
        );

        // End each tab and controls with full reset to prevent style bleeding
        // into dividers and preview content
        format!(
            "{tab1}{reset} | {tab2}{reset} | {tab3}{reset} | {tab4}{reset} | {tab5}{reset}\n{controls}{reset}\n\n"
        )
    }

    /// Render preview for the given mode with specified dimensions.
    ///
    /// Uses cache if available, otherwise computes and caches. Diff-mode pager
    /// output is included in the cached value (via [`Self::compute_and_page_preview`])
    /// so that skim's event-loop thread — which calls `preview()` synchronously —
    /// never spawns a pager subprocess.
    fn preview_for_mode(&self, mode: PreviewMode, width: usize, height: usize) -> String {
        let cache_key = (self.branch_name.clone(), mode);

        let content = self
            .preview_cache
            .entry(cache_key)
            .or_insert_with(|| Self::compute_and_page_preview(&self.item, mode, width, height))
            .value()
            .clone();

        match mode {
            // Summary post-processing is cheap (string formatting, no subprocess).
            // Applied at display time because generate_and_cache_summary() inserts
            // raw LLM output.
            PreviewMode::Summary => super::summary::render_summary(&content, width),
            _ => content,
        }
    }

    /// Compute preview and apply pager for diff modes.
    ///
    /// Both the inline cache-miss path and background pre-computation use this so
    /// that the cache always stores display-ready content (no pager subprocess
    /// needed at render time).
    pub(super) fn compute_and_page_preview(
        item: &ListItem,
        mode: PreviewMode,
        width: usize,
        height: usize,
    ) -> String {
        let content = Self::compute_preview(item, mode, width, height);
        match mode {
            PreviewMode::WorkingTree | PreviewMode::BranchDiff | PreviewMode::UpstreamDiff => {
                if let Some(pager_cmd) = diff_pager() {
                    pipe_through_pager(&content, pager_cmd, width)
                } else {
                    content
                }
            }
            _ => content,
        }
    }

    /// Compute raw preview for any mode.
    pub(super) fn compute_preview(
        item: &ListItem,
        mode: PreviewMode,
        width: usize,
        height: usize,
    ) -> String {
        match mode {
            PreviewMode::WorkingTree => Self::compute_working_tree_preview(item, width),
            PreviewMode::Log => Self::compute_log_preview(item, width, height),
            PreviewMode::BranchDiff => Self::compute_branch_diff_preview(item, width),
            PreviewMode::UpstreamDiff => Self::compute_upstream_diff_preview(item, width),
            PreviewMode::Summary => Self::compute_summary_preview(item),
        }
    }

    /// Compute Tab 1: Working tree preview (uncommitted changes vs HEAD)
    fn compute_working_tree_preview(item: &ListItem, width: usize) -> String {
        let Some(wt_info) = item.worktree_data() else {
            let branch = item.branch_name();
            return format!(
                "{INFO_SYMBOL} {branch} is branch only — press Enter to create worktree\n"
            );
        };

        let branch = item.branch_name();
        let path = wt_info.path.display().to_string();

        compute_diff_preview(
            &["-C", &path, "diff", "HEAD"],
            &cformat!("{INFO_SYMBOL} <bold>{branch}</> has no uncommitted changes"),
            width,
        )
    }

    /// Compute Tab 3: Branch diff preview (line diffs in commits ahead of default branch)
    fn compute_branch_diff_preview(item: &ListItem, width: usize) -> String {
        let branch = item.branch_name();
        let Ok(repo) = Repository::current() else {
            return cformat!("{INFO_SYMBOL} <bold>{branch}</> has no commits ahead of main\n");
        };
        let Some(default_branch) = repo.default_branch() else {
            return cformat!("{INFO_SYMBOL} <bold>{branch}</> has no commits ahead of main\n");
        };
        if item.counts.is_some_and(|c| c.ahead == 0) {
            return cformat!(
                "{INFO_SYMBOL} <bold>{branch}</> has no commits ahead of <bold>{default_branch}</>\n"
            );
        }

        let merge_base = format!("{}...{}", default_branch, item.head());
        compute_diff_preview(
            &["diff", &merge_base],
            &cformat!(
                "{INFO_SYMBOL} <bold>{branch}</> has no file changes vs <bold>{default_branch}</>"
            ),
            width,
        )
    }

    /// Compute Tab 4: Upstream diff preview (ahead/behind vs tracking branch)
    fn compute_upstream_diff_preview(item: &ListItem, width: usize) -> String {
        let branch = item.branch_name();

        let Some(active) = item.upstream.as_ref().and_then(|u| u.active()) else {
            return cformat!("{INFO_SYMBOL} <bold>{branch}</> has no upstream tracking branch\n");
        };

        let upstream_ref = format!("{}@{{u}}", branch);

        if active.ahead == 0 && active.behind == 0 {
            return cformat!("{INFO_SYMBOL} <bold>{branch}</> is up to date with upstream\n");
        }

        if active.ahead > 0 && active.behind > 0 {
            let range = format!("{}...{}", upstream_ref, item.head());
            compute_diff_preview(
                &["diff", &range],
                &cformat!(
                    "{INFO_SYMBOL} <bold>{branch}</> has diverged (⇡{} ⇣{}) but no unique file changes",
                    active.ahead,
                    active.behind
                ),
                width,
            )
        } else if active.ahead > 0 {
            let range = format!("{}...{}", upstream_ref, item.head());
            compute_diff_preview(
                &["diff", &range],
                &cformat!("{INFO_SYMBOL} <bold>{branch}</> has no unpushed file changes"),
                width,
            )
        } else {
            let range = format!("{}...{}", item.head(), upstream_ref);
            compute_diff_preview(
                &["diff", &range],
                &cformat!(
                    "{INFO_SYMBOL} <bold>{branch}</> is behind upstream (⇣{}) but no file changes",
                    active.behind
                ),
                width,
            )
        }
    }

    /// Compute log preview for a worktree item.
    /// This can be called from background threads for pre-computation.
    pub(super) fn compute_log_preview(item: &ListItem, width: usize, height: usize) -> String {
        // Minimum preview width to show timestamps (adds ~7 chars: space + 4-char time + space)
        // Note: preview is typically 50% of terminal width, so 50 = 100-col terminal
        const TIMESTAMP_WIDTH_THRESHOLD: usize = 50;
        // Tab header takes 3 lines (tabs + controls + blank)
        const HEADER_LINES: usize = 3;

        let mut output = String::new();
        let show_timestamps = width >= TIMESTAMP_WIDTH_THRESHOLD;
        // Calculate how many log lines fit in preview (height minus header)
        let log_limit = height.saturating_sub(HEADER_LINES).max(1);
        let head = item.head();
        let branch = item.branch_name();
        let Ok(repo) = Repository::current() else {
            output.push_str(&cformat!(
                "{INFO_SYMBOL} <bold>{branch}</> has no commits\n"
            ));
            return output;
        };
        let Some(default_branch) = repo.default_branch() else {
            output.push_str(&cformat!(
                "{INFO_SYMBOL} <bold>{branch}</> has no commits\n"
            ));
            return output;
        };

        // Get merge-base with default branch
        //
        // Note on error handling: This code runs in an interactive preview pane that updates
        // on every keystroke. We intentionally use silent fallbacks rather than propagating
        // errors to avoid disruptive error messages during navigation. The preview is
        // supplementary - users can still select worktrees even if preview fails.
        //
        // Alternative: Check specific conditions (default branch exists, valid HEAD, etc.) before
        // running git commands. This would provide better diagnostics but adds latency to
        // every preview render. Trade-off: simplicity + speed vs. detailed error messages.
        let Ok(merge_base_output) = repo.run_command(&["merge-base", &default_branch, head]) else {
            output.push_str(&cformat!(
                "{INFO_SYMBOL} <bold>{branch}</> has no commits\n"
            ));
            return output;
        };

        let merge_base = merge_base_output.trim();
        let is_default_branch = branch == default_branch;

        // Format strings for git log
        // Without timestamps: hash (colored/dimmed), then message
        // Format includes full hash (for matching) between SOH and NUL delimiters.
        // Display content uses \x1f to separate fields for timestamp parsing.
        // Format: SOH full_hash NUL short_hash \x1f timestamp \x1f decorations+message
        // Using delimiters allows parsing without assuming fixed hash length (SHA-256 safe)
        // Note: Use %x01/%x00 (git's hex escapes) to avoid embedding control chars in argv
        let timestamp_format = format!(
            "--format=%x01%H%x00%C(auto)%h{}%ct{}%C(auto)%d%C(reset) %s",
            FIELD_DELIM, FIELD_DELIM
        );
        let no_timestamp_format = "--format=%x01%H%x00%C(auto)%h%C(auto)%d%C(reset) %s";

        let log_limit_str = log_limit.to_string();

        // Get commits after merge-base (for dimming logic)
        // These are commits reachable from HEAD but not from merge-base, shown bright.
        // Commits before merge-base (shared with default branch) are shown dimmed.
        // Bounded to log_limit since we only need to check displayed commits.
        let unique_commits: Option<HashSet<String>> = if is_default_branch {
            // On default branch: no dimming (None means show everything bright)
            None
        } else {
            // On feature branch: get commits unique to this branch
            // rev-list A...B --right-only gives commits reachable from B but not A
            let range = format!("{}...{}", merge_base, head);
            let commits = repo
                .run_command(&["rev-list", &range, "--right-only", "-n", &log_limit_str])
                .map(|out| out.lines().map(String::from).collect())
                .unwrap_or_default();
            Some(commits) // Some(empty) means dim everything
        };

        // Get graph output (no --numstat to avoid blank continuation lines)
        let format: &str = if show_timestamps {
            &timestamp_format
        } else {
            no_timestamp_format
        };
        let args = vec![
            "log",
            "--graph",
            "--no-show-signature",
            format,
            "--color=always",
            "-n",
            &log_limit_str,
            head,
        ];

        if let Ok(log_output) = repo.run_command(&args) {
            let (processed, hashes) =
                process_log_with_dimming(&log_output, unique_commits.as_ref());
            if show_timestamps {
                // Batch fetch stats for all commits
                let stats = batch_fetch_stats(&repo, &hashes);
                output.push_str(&format_log_output(&processed, &stats));
            } else {
                // Strip hash markers (SOH...NUL) since we're not using format_log_output
                output.push_str(&strip_hash_markers(&processed));
            }
        }

        output
    }

    /// Compute Tab 5: Summary preview (LLM-generated branch summary)
    ///
    /// Returns a synchronous placeholder when the background summary generation
    /// hasn't completed yet. The actual summary is generated by background threads
    /// and inserted into the preview cache.
    fn compute_summary_preview(_item: &ListItem) -> String {
        format!(
            "{INFO_SYMBOL} Generating summary...\n\n\
             Press 5 again to refresh once generation completes.\n"
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use insta::assert_snapshot;

    #[test]
    fn test_render_preview_tabs() {
        // All PreviewMode variants: verify tab labels, active styling, and structure
        for (name, mode) in [
            ("working_tree", PreviewMode::WorkingTree),
            ("log", PreviewMode::Log),
            ("branch_diff", PreviewMode::BranchDiff),
            ("upstream_diff", PreviewMode::UpstreamDiff),
            ("summary", PreviewMode::Summary),
        ] {
            assert_snapshot!(name, WorktreeSkimItem::render_preview_tabs(mode));
        }
    }

    #[test]
    fn test_compute_summary_preview() {
        // All inputs produce the same synchronous placeholder.
        // The background thread produces the real summary (or "No changes to summarize"
        // for the default branch).
        use crate::commands::list::model::{ItemKind, WorktreeData};

        let mut main_item = ListItem::new_branch("abc123".to_string(), "main".to_string());
        main_item.kind = ItemKind::Worktree(Box::new(WorktreeData {
            is_main: true,
            ..Default::default()
        }));

        let feature_item = ListItem::new_branch("abc123".to_string(), "feature".to_string());

        // Direct call and compute_preview dispatch both return the placeholder
        assert_snapshot!(
            "direct",
            WorktreeSkimItem::compute_summary_preview(&main_item)
        );
        assert_snapshot!(
            "via_compute_preview",
            WorktreeSkimItem::compute_preview(&feature_item, PreviewMode::Summary, 80, 40)
        );
    }

    #[test]
    fn test_preview_for_mode_summary_cache() {
        // Cache hit returns cached content; cache miss computes the placeholder
        let item = Arc::new(ListItem::new_branch(
            "abc123".to_string(),
            "feature".to_string(),
        ));

        let cache_hit = {
            let preview_cache: PreviewCache = Arc::new(DashMap::new());
            preview_cache.insert(
                ("feature".to_string(), PreviewMode::Summary),
                "Add auth module\n\nImplements JWT-based authentication.".to_string(),
            );
            WorktreeSkimItem {
                display_text: String::new(),
                display_text_with_ansi: String::new(),
                branch_name: "feature".to_string(),
                item: Arc::clone(&item),
                preview_cache,
            }
        };

        let cache_miss = {
            let preview_cache: PreviewCache = Arc::new(DashMap::new());
            WorktreeSkimItem {
                display_text: String::new(),
                display_text_with_ansi: String::new(),
                branch_name: "feature".to_string(),
                item: Arc::clone(&item),
                preview_cache,
            }
        };

        assert_snapshot!(
            "cache_hit",
            cache_hit.preview_for_mode(PreviewMode::Summary, 80, 40)
        );
        assert_snapshot!(
            "cache_miss",
            cache_miss.preview_for_mode(PreviewMode::Summary, 80, 40)
        );
    }

    #[test]
    fn test_render_preview_tabs_ansi_codes() {
        // Test that ANSI escape sequences properly reset to prevent style bleeding
        let output = WorktreeSkimItem::render_preview_tabs(PreviewMode::WorkingTree);

        let first_line = output.lines().next().unwrap();
        let second_line = output.lines().nth(1).unwrap();

        // Each styled tab should end with a full reset (\x1b[0m) before the divider
        // This prevents bold/dim from bleeding into the " | " dividers
        let full_reset = "\x1b[0m";

        // Count resets - should have one after each of the 5 tabs
        assert_eq!(first_line.matches(full_reset).count(), 5);

        // The sequence should be: style + text + [22m + [0m + divider
        // Check that dividers come after full resets
        let parts: Vec<&str> = first_line.split(" | ").collect();
        assert_eq!(parts.len(), 5);
        assert!(parts.iter().all(|part| part.ends_with(full_reset)));

        // Controls line should end with full reset to ensure clean state for preview content
        assert!(second_line.ends_with(full_reset));
    }
}