worktrunk 0.41.0

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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
//! Interactive branch/worktree selector.
//!
//! A skim-based TUI for selecting and switching between worktrees. The picker
//! shares `super::list::collect::collect` with `wt list` — see
//! `commands/list/collect/mod.rs` for the rendering-pipeline spec — but inverts
//! the ordering because skim's `preview_window` height is baked into
//! `SkimOptions` before `Skim::run_with` takes over the terminal, so we have
//! to estimate the visible row count up front rather than learn it from
//! collect's skeleton pass.
//!
//! # "Skeleton"
//!
//! Same meaning as in `wt list`: the column/row frame with placeholder cells
//! the user sees first. In the picker, `collect::collect` builds those rows
//! and streams them via `on_skeleton` → `PickerHandler` → `SkimItemSender` →
//! skim. (Not to be confused with the rendered skeleton-row *strings* that
//! flow through that channel.)
//!
//! # Startup flow
//!
//! On the main thread, `handle_picker`:
//!
//! 1. `current_or_recover` + config resolution.
//! 2. `PreviewState::new` — auto-detects Right vs Down layout.
//! 3. Allocates the `PreviewOrchestrator` and kicks off a *speculative*
//!    `git diff HEAD` for the current worktree on the preview pool. That bg
//!    work overlaps with everything below.
//! 4. Computes `num_items_estimate` — `list_worktrees` plus (conditionally)
//!    `list_local_branches` / `list_remote_branches`, capped at
//!    `MAX_VISIBLE_ITEMS`. Only used to size skim's `preview_window`.
//! 5. Builds `SkimOptions` (immutable after this — which is why steps 1-4 have
//!    to run first).
//! 6. Spawns the `picker-collect` bg thread, which calls `collect::collect`.
//! 7. Calls `Skim::run_with(rx)`; skim paints the empty frame and then ingests
//!    skeleton rows from the channel as the bg thread streams them via
//!    `on_skeleton`.
//!
//! Time-to-skeleton = steps 1-6 on the main thread *plus* collect's
//! pre-skeleton phase on the bg thread.
//!
//! ## Phase timings
//!
//! Representative medians on the worktrunk dev repo (7 worktrees, 6 branches,
//! warm caches, release build).
//!
//! | Phase (instant-to-instant) | median | cmds |
//! |-----------------------------|-------:|-----:|
//! | `Picker started → Picker config resolved` | ~16ms | 3 |
//! | `Picker config resolved → Picker layout detected` | <1ms | 0 |
//! | `Picker layout detected → Picker estimate computed` | ~39ms | 11 (includes bg preview `git diff`s) |
//! | `Picker estimate computed → Picker skim options built` | <1ms | 0 |
//! | `Picker skim options built → Picker collect spawned` | <100µs | 0 |
//! | `Picker collect spawned → List collect started` | <100µs | 0 |
//! | `List collect started → Skeleton rendered` (bg, pre-skeleton) | ~41ms | 25 |
//! | **Time-to-skeleton** (≈ main-thread prelude + bg pre-skeleton) | **~96ms** | |
//! | `Skeleton rendered → Spawning worker thread` (post-skeleton, pre-work) | ~156ms | 86 |
//! | `Parallel execution started → All results drained` (post-skeleton work) | ~1.1s | 254 |
//! | Wall clock under `WORKTRUNK_PICKER_DRY_RUN=1` (median / p95) | ~1.4s / ~4.4s | |
//!
//! Skim's own paint cost isn't observable from the dry-run path — skim is
//! bypassed there.
//!
//! ### Reproducing
//!
//! End-to-end time-to-first-output (criterion, synthetic repo):
//!
//! ```bash
//! cargo bench --bench time_to_first_output -- switch
//! ```
//!
//! Per-phase breakdown on a specific repo (a single trace is usually enough
//! to spot where time goes; re-run a few times if you want variance):
//!
//! ```bash
//! RUST_LOG=debug ./target/release/wt -C <repo> switch \
//!   2> >(cargo run -p wt-perf --release -q -- trace > trace.json)
//! # Open trace.json in Perfetto, or run the phase-duration SQL query
//! # documented in benches/CLAUDE.md §"What's on the critical path?".
//! ```
//!
//! # TODO(picker-perf): dedupe git calls
//!
//! `num_items_estimate` and `collect::collect` each call `list_worktrees` and
//! `list_local_branches`. Pre-seed collect's OnceCells from the main-thread
//! fetch to save one of each on the bg thread's critical path toward skeleton.

mod items;
mod log_formatter;
mod pager;
mod preview;
mod preview_orchestrator;
mod progressive_handler;
mod summary;

use std::cell::RefCell;
use std::io::IsTerminal;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::atomic::AtomicUsize;
use std::sync::{Arc, Mutex};

use anyhow::Context;
// bounded/unbounded/Sender are re-exported by skim::prelude
use skim::prelude::*;
use skim::reader::CommandCollector;
use worktrunk::git::{Repository, current_or_recover};

use super::command_executor::FailureStrategy;
use super::handle_switch::{
    approve_switch_hooks, run_pre_switch_hooks, spawn_switch_background_hooks, switch_extra_vars,
};
use super::hooks::{execute_hook, spawn_background_hooks};
use super::list::collect;
use super::repository_ext::{RemoveTarget, RepositoryCliExt};
use super::worktree::hooks::PostRemoveContext;
use super::worktree::{
    RemoveResult, SwitchBranchInfo, SwitchResult, execute_switch,
    offer_bare_repo_worktree_path_fix, path_mismatch, plan_switch,
};
use crate::commands::command_executor::CommandContext;
use crate::output::handle_switch_output;
use worktrunk::git::{
    BranchDeletionMode, RemoveOptions, delete_branch_if_safe, remove_worktree_with_cleanup,
};

use items::{PreviewCache, WorktreeSkimItem};
use preview::{PreviewLayout, PreviewMode, PreviewState};
use preview_orchestrator::PreviewOrchestrator;

/// Action selected by the user in the picker.
enum PickerAction {
    /// Switch to the selected worktree (Enter key).
    Switch,
    /// Create a new worktree from the search query (alt-c).
    Create,
}

/// Custom command collector for skim's `reload` action.
///
/// When alt-r is pressed, skim runs `execute-silent` to write the selected branch
/// name to a signal file, then `reload` invokes this collector. The collector reads
/// the signal file, removes the item from the list, and streams the remaining items
/// back to skim — all without leaving the picker.
///
/// Git operations (worktree removal, branch deletion) are deferred to a background
/// thread because skim 0.20 calls `invoke()` on the main event loop thread.
/// Blocking it freezes the TUI.
///
/// Cursor position resets to the first item after reload (skim 0.20 limitation,
/// tracked in #1695).
struct PickerCollector {
    items: Arc<Mutex<Vec<Arc<dyn SkimItem>>>>,
    signal_path: PathBuf,
    repo: Repository,
}

impl PickerCollector {
    /// Execute removal in background: pre-remove hooks + worktree + branch + post-remove hooks.
    ///
    /// Called from a background thread after the picker optimistically removes the item
    /// from the list. The entire operation runs off skim's event loop so the TUI stays
    /// responsive. If pre-remove hooks fail, the removal is aborted (but the item is
    /// already gone from the picker — a tradeoff until we can show in-progress state).
    ///
    /// `repo` is only used for `BranchOnly` deletion. `RemovedWorktree` constructs
    /// its own from `main_path` (which may differ from the picker's startup repo in
    /// bare-repo setups).
    fn do_removal(repo: &Repository, result: &RemoveResult) -> anyhow::Result<()> {
        match result {
            RemoveResult::RemovedWorktree {
                main_path,
                worktree_path,
                branch_name,
                deletion_mode,
                target_branch,
                force_worktree,
                removed_commit,
                ..
            } => {
                let repo = Repository::at(main_path)?;
                let config = repo.user_config();
                let hook_branch = branch_name.as_deref().unwrap_or("HEAD");

                // Run pre-remove hooks (synchronously in this background thread).
                // Non-zero exit aborts the removal, matching `wt remove` semantics.
                let target_ref = repo
                    .worktree_at(main_path)
                    .branch()
                    .ok()
                    .flatten()
                    .unwrap_or_default();
                let target_path_str = worktrunk::path::to_posix_path(&main_path.to_string_lossy());
                let extra_vars: Vec<(&str, &str)> = vec![
                    ("target", &target_ref),
                    ("target_worktree_path", &target_path_str),
                ];
                let pre_ctx =
                    CommandContext::new(&repo, config, Some(hook_branch), worktree_path, false);
                execute_hook(
                    &pre_ctx,
                    worktrunk::HookType::PreRemove,
                    &extra_vars,
                    FailureStrategy::FailFast,
                    &[],
                    None, // no display path in TUI context
                )?;

                let output = remove_worktree_with_cleanup(
                    &repo,
                    worktree_path,
                    RemoveOptions {
                        branch: branch_name.clone(),
                        deletion_mode: *deletion_mode,
                        target_branch: target_branch.clone(),
                        force_worktree: *force_worktree,
                    },
                )?;
                if let Some(staged) = output.staged_path {
                    let _ = std::fs::remove_dir_all(&staged);
                }

                // Spawn post-remove hooks in background (log to files, no terminal output).
                let post_ctx =
                    CommandContext::new(&repo, config, Some(hook_branch), main_path, false);
                let remove_vars = PostRemoveContext::new(
                    worktree_path,
                    removed_commit.as_deref(),
                    main_path,
                    &repo,
                );
                let extra_vars = remove_vars.extra_vars(hook_branch);
                spawn_background_hooks(
                    &post_ctx,
                    worktrunk::HookType::PostRemove,
                    &extra_vars,
                    None, // no display path in TUI context
                )?;
            }
            RemoveResult::BranchOnly {
                branch_name,
                deletion_mode,
                ..
            } => {
                if !deletion_mode.should_keep() {
                    let default_branch = repo.default_branch();
                    let target = default_branch.as_deref().unwrap_or("HEAD");
                    let _ =
                        delete_branch_if_safe(repo, branch_name, target, deletion_mode.is_force());
                }
            }
        }
        Ok(())
    }
}

impl CommandCollector for PickerCollector {
    fn invoke(
        &mut self,
        _cmd: &str,
        components_to_stop: Arc<AtomicUsize>,
    ) -> (SkimItemReceiver, Sender<i32>) {
        // Read the removal signal (item output text written by execute-silent)
        if let Ok(signal) = std::fs::read_to_string(&self.signal_path) {
            let selected_output = signal.trim().to_string();
            if !selected_output.is_empty() {
                // Validate removal before touching the list. prepare_worktree_removal
                // runs a few git commands (~15-20ms) — acceptable on skim's event loop.
                // Only remove the item and spawn background deletion if this succeeds.
                let caller_path = self.repo.current_worktree().root().ok();
                let config = self.repo.user_config();

                // Resolve removal target by path when possible (handles both
                // branched and detached worktrees). Branch-only items won't
                // match any worktree path, so they fall through to Branch.
                let worktree_path = self.repo.list_worktrees().ok().and_then(|wts| {
                    // Match by branch first, then fall back to detached (branch: None).
                    let by_branch = wts
                        .iter()
                        .find(|wt| wt.branch.as_deref() == Some(selected_output.as_str()));
                    let matched = by_branch.or_else(|| wts.iter().find(|wt| wt.branch.is_none()));
                    matched.map(|wt| wt.path.clone())
                });
                let target = match &worktree_path {
                    Some(path) => RemoveTarget::Path(path),
                    None => RemoveTarget::Branch(&selected_output),
                };

                let preparation = self.repo.prepare_worktree_removal(
                    target,
                    BranchDeletionMode::SafeDelete,
                    false,
                    config,
                    caller_path,
                    None,
                );

                match preparation {
                    Ok(result) => {
                        // Removal validated — remove item from the picker list.
                        //
                        // Note: skim's `as_any().downcast_ref::<WorktreeSkimItem>()` fails
                        // at runtime (TypeId mismatch between reader thread and main thread
                        // compilation units in skim 0.20). All item lookups use output()
                        // matching instead.
                        {
                            let mut items = self.items.lock().unwrap();
                            items.retain(|item| item.output().as_ref() != selected_output);
                        }

                        // If removing the current worktree, cd to home so skim and git
                        // commands continue to work after the directory disappears.
                        if matches!(
                            &result,
                            RemoveResult::RemovedWorktree {
                                changed_directory: true,
                                ..
                            }
                        ) && let Ok(home) = self.repo.home_path()
                        {
                            let _ = std::env::set_current_dir(&home);
                        }

                        // Defer actual git removal to a background thread so skim's
                        // event loop stays responsive.
                        let repo = self.repo.clone();
                        let _ = std::thread::Builder::new()
                            .name(format!("picker-remove-{selected_output}"))
                            .spawn(move || {
                                if let Err(e) = Self::do_removal(&repo, &result) {
                                    log::warn!(
                                        "picker: failed to remove '{selected_output}': {e:#}"
                                    );
                                }
                            });
                    }
                    Err(e) => {
                        log::info!("picker: cannot remove '{selected_output}': {e:#}");
                    }
                }

                // Clear signal for next removal
                let _ = std::fs::write(&self.signal_path, "");
            }
        }

        // Stream remaining items through a channel for skim to consume.
        // Uses unbounded channel so all items are sent immediately without blocking.
        let items = self.items.lock().unwrap();
        let (tx, rx) = unbounded();
        for item in items.iter() {
            let _ = tx.send(Arc::clone(item));
        }
        drop(tx);

        // Dummy interrupt channel — no subprocess to kill.
        // The reader's collect_item thread handles its own components_to_stop accounting;
        // we just need a valid Sender to satisfy the trait signature.
        let _ = components_to_stop;
        let (tx_interrupt, _rx_interrupt) = bounded(1);
        (rx, tx_interrupt)
    }
}

pub fn handle_picker(
    cli_branches: bool,
    cli_remotes: bool,
    change_dir_flag: Option<bool>,
) -> anyhow::Result<()> {
    // Interactive picker requires a terminal for the TUI. The dry-run path
    // bypasses skim entirely, so no TTY is required — useful for tests and
    // for diagnosing the pre-compute pipeline from scripts.
    if std::env::var_os("WORKTRUNK_PICKER_DRY_RUN").is_none() && !std::io::stdin().is_terminal() {
        anyhow::bail!("Interactive picker requires an interactive terminal");
    }
    worktrunk::shell_exec::trace_instant("Picker started");

    let (repo, is_recovered) = current_or_recover()?;

    // Merge CLI flags with resolved config (project-specific config is now available)
    let config = repo.config();
    let change_dir = change_dir_flag.unwrap_or_else(|| config.switch.cd());
    let show_branches = cli_branches || config.list.branches();
    let show_remotes = cli_remotes || config.list.remotes();
    worktrunk::shell_exec::trace_instant("Picker config resolved");

    // Initialize preview mode state file (auto-cleanup on drop)
    let state = PreviewState::new();
    worktrunk::shell_exec::trace_instant("Picker layout detected");

    // Preview cache + dedicated pool are created up-front so the speculative
    // first-item preview can run in parallel with `collect::collect` below.
    // Wrapped in `Arc` because the progressive handler (running on the
    // collect background thread) also calls `spawn_preview`.
    let orchestrator = Arc::new(PreviewOrchestrator::new(repo.clone()));
    let preview_cache: PreviewCache = Arc::clone(&orchestrator.cache);

    // Speculative warm-up: the picker sorts the current worktree first, and
    // the default tab (WorkingTree = `git diff HEAD` in that worktree) is
    // what skim will render first. Kicking this off before `collect::collect`
    // overlaps preview compute with list collection.
    // The real spawn later skips this key via `contains_key`.
    if let (Ok(Some(branch)), Ok(path)) = (
        repo.current_worktree().branch(),
        repo.current_worktree().root(),
    ) {
        use super::list::model::{ItemKind, ListItem, WorktreeData};
        let mut item = ListItem::new_branch(String::new(), branch);
        item.kind = ItemKind::Worktree(Box::new(WorktreeData {
            path,
            ..Default::default()
        }));
        // num_items doesn't matter for Right (dims independent of it); for
        // Down it only affects height, which doesn't alter pager wrapping.
        let dims = state.initial_layout.preview_dimensions(0);
        orchestrator.spawn_preview(Arc::new(item), PreviewMode::WorkingTree, dims);
    }

    // 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.
    let skip_tasks: std::collections::HashSet<collect::TaskKind> =
        [collect::TaskKind::BranchDiff, collect::TaskKind::CiStatus]
            .into_iter()
            .collect();

    // Per-task command timeout (bounds any single git invocation) from
    // shared `[list]` config. Still applies in progressive mode.
    let command_timeout = config.list.task_timeout();

    // Progressive rendering means the picker never blocks waiting for
    // collect — so there's no UI-freeze budget to bound. The drain runs
    // until its results channel closes or the fallback DRAIN_TIMEOUT
    // (120s) fires.

    // List width depends on the preview position. Right splits the terminal
    // ~50/50; Down gives the list the full width. Passed to `collect` so
    // the skeleton layout matches the picker's actual render width.
    let terminal_width = crate::display::terminal_width();
    let skim_list_width = match state.initial_layout {
        PreviewLayout::Right => terminal_width / 2,
        PreviewLayout::Down => terminal_width,
    };

    // Estimate item count for the preview window spec (only the Down
    // layout depends on it). Every row over MAX_VISIBLE_ITEMS is a no-op
    // for the height computation, so we short-circuit once we know the
    // list already fills the cap.
    let num_items_estimate = {
        let cap = preview::MAX_VISIBLE_ITEMS;
        let mut estimate = repo.list_worktrees().map(|w| w.len()).unwrap_or(cap);
        if estimate < cap && show_branches {
            // Local branches are a superset of worktree branches (each
            // linked worktree normally has one), so take the max rather
            // than summing.
            let local = repo.list_local_branches().map(|b| b.len()).unwrap_or(cap);
            estimate = estimate.max(local);
        }
        if estimate < cap && show_remotes {
            let remotes = repo.list_remote_branches().map(|b| b.len()).unwrap_or(0);
            estimate = estimate.saturating_add(remotes);
        }
        estimate
    };
    worktrunk::shell_exec::trace_instant("Picker estimate computed");
    let preview_window_spec = state
        .initial_layout
        .to_preview_window_spec(num_items_estimate);
    let preview_dims = state.initial_layout.preview_dimensions(num_items_estimate);

    // Summary hint: when summaries are disabled, prime the Summary cache
    // with config guidance instead of showing a perpetual "Generating…"
    // placeholder.
    let (llm_command, summary_hint) =
        if config.list.summary() && config.commit_generation.is_configured() {
            (config.commit_generation.command.clone(), None)
        } else {
            let hint = if !config.commit_generation.is_configured() {
                "Configure [commit.generation] command to enable LLM summaries.\n\n\
                 Example in ~/.config/worktrunk/config.toml:\n\n\
                 [commit.generation]\n\
                 command = \"llm -m haiku\"\n\n\
                 [list]\n\
                 summary = true\n"
            } else {
                "Enable summaries in ~/.config/worktrunk/config.toml:\n\n\
                 [list]\n\
                 summary = true\n"
            };
            (None, Some(hint.to_string()))
        };

    // Shared items list: populated by the handler's `on_skeleton` and read
    // by `PickerCollector` on alt-r reload. Starts empty — the collector's
    // `invoke` only fires after skim has displayed items, by which time
    // the handler has already published them.
    let shared_items: Arc<Mutex<Vec<Arc<dyn SkimItem>>>> = Arc::new(Mutex::new(Vec::new()));

    // Signal file for alt-r removal communication. execute-silent writes
    // the branch name here; the PickerCollector reads it on reload.
    // Cleaned up in PreviewState::Drop.
    let signal_path = state.path.with_extension("remove");

    let collector = PickerCollector {
        items: Arc::clone(&shared_items),
        signal_path: signal_path.clone(),
        repo: repo.clone(),
    };

    let signal_path_escaped =
        shell_escape::escape(signal_path.display().to_string().into()).into_owned();

    // Get state path for key bindings (shell-escaped for safety)
    let state_path_display = state.path.display().to_string();
    let state_path_str = shell_escape::escape(state_path_display.into()).into_owned();

    // Calculate half-page scroll: skim uses 90% of terminal height, half of that = 45%
    let half_page = terminal_size::terminal_size()
        .map(|(_, terminal_size::Height(h))| (h as usize * 45 / 100).max(5))
        .unwrap_or(10);

    // Configure skim options with Rust-based preview and mode switching keybindings
    let options = SkimOptionsBuilder::default()
        .height("90%".to_string())
        .layout("reverse".to_string())
        .header_lines(1) // Make first line (header) non-selectable
        .multi(false)
        .no_info(true) // Hide info line (matched/total counter)
        .preview(Some("".to_string())) // Enable preview (empty string means use SkimItem::preview())
        .preview_window(preview_window_spec)
        // Color scheme using fzf's --color=light values: dark text (237) on light gray bg (251)
        //
        // Terminal color compatibility is tricky:
        // - current_bg:254 (original): too bright on dark terminals, washes out text
        // - current_bg:236 (fzf dark): too dark on light terminals, jarring contrast
        // - current_bg:251 + current:-1: light bg works on both, but unstyled text
        //   becomes unreadable on dark terminals (light-on-light)
        // - current_bg:251 + current:237: fzf's light theme, best compromise
        //
        // The light theme works universally because:
        // - On dark terminals: light gray highlight stands out clearly
        // - On light terminals: light gray is subtle but visible
        // - Dark text (237) ensures readability regardless of terminal theme
        .color(Some(
            "fg:-1,bg:-1,header:-1,matched:108,current:237,current_bg:251,current_match:108"
                .to_string(),
        ))
        .cmd_collector(Rc::new(RefCell::new(collector)) as Rc<RefCell<dyn CommandCollector>>)
        .bind(vec![
            // Mode switching (1/2/3/4/5 keys change preview content)
            format!(
                "1:execute-silent(echo 1 > {0})+refresh-preview",
                state_path_str
            ),
            format!(
                "2:execute-silent(echo 2 > {0})+refresh-preview",
                state_path_str
            ),
            format!(
                "3:execute-silent(echo 3 > {0})+refresh-preview",
                state_path_str
            ),
            format!(
                "4:execute-silent(echo 4 > {0})+refresh-preview",
                state_path_str
            ),
            format!(
                "5:execute-silent(echo 5 > {0})+refresh-preview",
                state_path_str
            ),
            // Create new worktree with query as branch name (alt-c for "create")
            "alt-c:accept(create)".to_string(),
            // Remove selected worktree: write branch name to signal file, then
            // reload triggers PickerCollector which performs the removal and
            // streams updated items back — all without leaving the picker.
            format!(
                "alt-r:execute-silent(echo {{}} > {0})+reload(remove)",
                signal_path_escaped
            ),
            // Preview toggle (alt-p shows/hides preview)
            // Note: skim doesn't support change-preview-window like fzf, only toggle
            "alt-p:toggle-preview".to_string(),
            // Preview scrolling (half-page based on terminal height)
            format!("ctrl-u:preview-up({half_page})"),
            format!("ctrl-d:preview-down({half_page})"),
        ])
        // Legend/controls moved to preview window tabs (render_preview_tabs)
        .build()
        .map_err(|e| anyhow::anyhow!("Failed to build skim options: {}", e))?;
    worktrunk::shell_exec::trace_instant("Picker skim options built");

    let (tx, rx): (SkimItemSender, SkimItemReceiver) = unbounded();

    let handler: Arc<dyn collect::PickerProgressHandler> =
        Arc::new(progressive_handler::PickerHandler {
            tx: tx.clone(),
            shared_items: Arc::clone(&shared_items),
            rendered_slots: std::sync::OnceLock::new(),
            preview_cache: Arc::clone(&preview_cache),
            orchestrator: Arc::clone(&orchestrator),
            preview_dims,
            llm_command,
            repo: repo.clone(),
            summary_hint,
        });

    // 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_repo = repo.clone();
    let bg_skip_tasks = skip_tasks.clone();
    let bg_handle = std::thread::Builder::new()
        .name("picker-collect".into())
        .spawn(move || {
            let _ = collect::collect(
                &bg_repo,
                collect::ShowConfig::Resolved {
                    show_branches,
                    show_remotes,
                    skip_tasks: bg_skip_tasks,
                    command_timeout,
                    collect_deadline: None,
                    list_width: Some(skim_list_width),
                    progressive_handler: Some(bg_handler),
                },
                false, // show_progress (picker renders its own UI)
                false, // render_table
            );
        })
        .context("Failed to spawn picker-collect thread")?;
    worktrunk::shell_exec::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).
    drop(tx);
    drop(handler);

    // Dry-run: skim is bypassed. Wait for collect (which spawns previews
    // via the handler), then for the preview pool, then dump the cache.
    if std::env::var_os("WORKTRUNK_PICKER_DRY_RUN").is_some() {
        drop(rx);
        let _ = bg_handle.join();
        orchestrator.wait_for_idle();
        println!("{}", orchestrator.dump_cache_json());
        return Ok(());
    }

    // Run skim (single invocation — alt-r uses reload, not re-launch).
    // Skim receives items as the bg thread's handler sends them.
    //
    // Don't join `bg_handle` after skim exits: drain may still be running
    // network tasks, and joining would block exit for up to DRAIN_TIMEOUT
    // (120s). Process exit terminates the bg thread; its git subprocesses
    // are read-only.
    let output = Skim::run_with(&options, Some(rx));
    drop(bg_handle);

    // Handle selection (signal file cleaned up by PreviewState::Drop)
    if let Some(out) = output
        && !out.is_abort
    {
        // Determine action: create (alt-c) or switch (enter)
        // Remove is handled inline via reload — it never reaches accept.
        let action = match &out.final_event {
            Event::EvActAccept(Some(label)) if label == "create" => PickerAction::Create,
            _ => PickerAction::Switch,
        };

        // --no-cd: just output the selected branch name and exit (read-only, no side effects)
        if !change_dir {
            let selected_name = out
                .selected_items
                .first()
                .map(|item| item.output().to_string());
            let query = out.query.trim().to_string();
            let identifier = resolve_identifier(&action, query, selected_name)?;
            println!("{identifier}");
            return Ok(());
        }

        let should_create = matches!(action, PickerAction::Create);

        // Get branch name: from query if creating new, from selected item if switching.
        // For detached worktrees, use the path (same as `wt switch /path` from CLI).
        let selected = out.selected_items.first();
        let selected_name = selected.map(|item| {
            if !should_create
                && let Some(data) = item
                    .as_any()
                    .downcast_ref::<WorktreeSkimItem>()
                    .and_then(|s| s.item.worktree_data())
                    .filter(|d| d.detached)
            {
                return data.path.to_string_lossy().into_owned();
            }
            item.output().to_string()
        });
        let query = out.query.trim().to_string();
        let identifier = resolve_identifier(&action, query, selected_name)?;

        // Load config — reuse recovered repo if we recovered earlier
        let repo = if is_recovered {
            repo.clone()
        } else {
            Repository::current().context("Failed to switch worktree")?
        };
        // Load config, offering bare repo worktree-path fix if needed.
        // Reload from disk so mutations are picked up by plan_switch.
        let mut config = worktrunk::config::UserConfig::load().context("Failed to load config")?;
        offer_bare_repo_worktree_path_fix(&repo, &mut config)?;

        // Run pre-switch hooks before branch resolution or worktree creation.
        // {{ branch }} receives the raw user input (before resolution).
        // Skip when recovered — the source worktree is gone, nothing to run hooks against.
        if !is_recovered {
            run_pre_switch_hooks(&repo, &config, &identifier, true)?;
        }

        // Switch to existing worktree or create new one
        let plan = plan_switch(&repo, &identifier, should_create, None, false, &config)?;
        let hooks_approved = approve_switch_hooks(&repo, &config, &plan, false, true)?;
        let (result, branch_info) = execute_switch(&repo, plan, &config, false, hooks_approved)?;

        // Compute path mismatch lazily (deferred from plan_switch for existing worktrees).
        // Skip for detached HEAD worktrees (branch is None).
        let branch_info = match &result {
            SwitchResult::Existing { path } | SwitchResult::AlreadyAt(path) => {
                let expected_path = branch_info
                    .branch
                    .as_deref()
                    .and_then(|b| path_mismatch(&repo, b, path, &config));
                SwitchBranchInfo {
                    expected_path,
                    ..branch_info
                }
            }
            _ => branch_info,
        };

        // Show success message; emit cd directive if shell integration is active
        // When recovered from a deleted worktree, fall back to repo_path().
        let fallback_path = repo.repo_path()?.to_path_buf();
        let cwd = std::env::current_dir().unwrap_or(fallback_path.clone());
        let source_root = repo.current_worktree().root().unwrap_or(fallback_path);
        let hooks_display_path =
            handle_switch_output(&result, &branch_info, change_dir, Some(&source_root), &cwd)?;

        // Spawn background hooks after success message
        if hooks_approved {
            let mut pr_number_buf = String::new();
            let extra_vars = switch_extra_vars(&result, &mut pr_number_buf);
            spawn_switch_background_hooks(
                &repo,
                &config,
                &result,
                branch_info.branch.as_deref(),
                false,
                &extra_vars,
                hooks_display_path.as_deref(),
            )?;
        }
    }

    Ok(())
}

/// Resolve the branch identifier from picker output.
///
/// Extracted from the picker callback for testability. Used by both the
/// interactive path and the `--no-cd` print path.
fn resolve_identifier(
    action: &PickerAction,
    query: String,
    selected_name: Option<String>,
) -> anyhow::Result<String> {
    match action {
        PickerAction::Create => {
            if query.is_empty() {
                anyhow::bail!("Cannot create worktree: no branch name entered");
            }
            Ok(query)
        }
        PickerAction::Switch => match selected_name {
            Some(name) => Ok(name),
            None => {
                if query.is_empty() {
                    anyhow::bail!("No worktree selected");
                } else {
                    anyhow::bail!(
                        "No worktree matches '{query}' — use alt-c to create a new worktree"
                    );
                }
            }
        },
    }
}

#[cfg(test)]
pub mod tests {
    use super::preview::{PreviewLayout, PreviewMode, PreviewStateData};
    use super::{PickerAction, PickerCollector, resolve_identifier};
    use crate::commands::worktree::RemoveResult;
    use std::fs;
    use worktrunk::git::BranchDeletionMode;

    #[test]
    fn test_preview_state_data_roundtrip() {
        let state_path = PreviewStateData::state_path();

        // Write and read back various modes
        let _ = fs::write(&state_path, "1");
        assert_eq!(PreviewStateData::read_mode(), PreviewMode::WorkingTree);

        let _ = fs::write(&state_path, "2");
        assert_eq!(PreviewStateData::read_mode(), PreviewMode::Log);

        let _ = fs::write(&state_path, "3");
        assert_eq!(PreviewStateData::read_mode(), PreviewMode::BranchDiff);

        let _ = fs::write(&state_path, "4");
        assert_eq!(PreviewStateData::read_mode(), PreviewMode::UpstreamDiff);

        let _ = fs::write(&state_path, "5");
        assert_eq!(PreviewStateData::read_mode(), PreviewMode::Summary);

        // Cleanup
        let _ = fs::remove_file(&state_path);
    }

    #[test]
    fn test_preview_layout() {
        // Right uses absolute width derived from terminal size
        let spec = PreviewLayout::Right.to_preview_window_spec(10);
        assert!(spec.starts_with("right:"));

        // Down calculates based on item count
        let spec = PreviewLayout::Down.to_preview_window_spec(5);
        assert!(spec.starts_with("down:"));
    }

    #[test]
    fn test_resolve_identifier() {
        // Switch returns the selected name
        let result = resolve_identifier(
            &PickerAction::Switch,
            String::new(),
            Some("feature/foo".into()),
        );
        assert_eq!(result.unwrap(), "feature/foo");

        // Switch with no selection and empty query
        let result = resolve_identifier(&PickerAction::Switch, String::new(), None);
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("No worktree selected")
        );

        // Switch with no selection but a query — the panic from #1565
        let result = resolve_identifier(&PickerAction::Switch, "nonexistent".into(), None);
        let err = result.unwrap_err().to_string();
        assert!(err.contains("No worktree matches 'nonexistent'"));
        assert!(err.contains("alt-c"));

        // Create returns the query
        let result = resolve_identifier(&PickerAction::Create, "new-branch".into(), None);
        assert_eq!(result.unwrap(), "new-branch");

        // Create with empty query is an error
        let result = resolve_identifier(&PickerAction::Create, String::new(), None);
        assert!(result.unwrap_err().to_string().contains("no branch name"));
    }

    #[test]
    fn test_execute_removal_removes_worktree_and_branch() {
        let test = worktrunk::testing::TestRepo::with_initial_commit();
        let repo = worktrunk::git::Repository::at(test.path()).unwrap();
        let wt_dir = tempfile::tempdir().unwrap();
        let wt_path = wt_dir.path().join("feature");

        repo.run_command(&[
            "worktree",
            "add",
            "-b",
            "feature",
            wt_path.to_str().unwrap(),
        ])
        .unwrap();
        assert!(wt_path.exists());

        let result = RemoveResult::RemovedWorktree {
            main_path: test.path().to_path_buf(),
            worktree_path: wt_path.clone(),
            changed_directory: false,
            branch_name: Some("feature".to_string()),
            deletion_mode: BranchDeletionMode::SafeDelete,
            target_branch: Some("main".to_string()),
            integration_reason: None,
            force_worktree: false,
            expected_path: None,
            removed_commit: None,
        };

        PickerCollector::do_removal(&repo, &result).unwrap();
        assert!(!wt_path.exists(), "worktree should be removed");

        let output = repo.run_command(&["branch", "--list", "feature"]).unwrap();
        assert!(output.is_empty(), "branch should be deleted");
    }

    #[test]
    fn test_do_removal_branch_only_deletes_integrated_branch() {
        let test = worktrunk::testing::TestRepo::with_initial_commit();
        let repo = worktrunk::git::Repository::at(test.path()).unwrap();

        // Create a branch at the same commit (fully integrated into main)
        repo.run_command(&["branch", "feature"]).unwrap();

        let result = RemoveResult::BranchOnly {
            branch_name: "feature".to_string(),
            deletion_mode: BranchDeletionMode::SafeDelete,
            pruned: false,
            target_branch: None,
            integration_reason: None,
        };
        PickerCollector::do_removal(&repo, &result).unwrap();

        let output = repo.run_command(&["branch", "--list", "feature"]).unwrap();
        assert!(output.is_empty(), "integrated branch should be deleted");
    }

    #[test]
    fn test_do_removal_branch_only_retains_unmerged_branch() {
        let test = worktrunk::testing::TestRepo::with_initial_commit();
        let repo = worktrunk::git::Repository::at(test.path()).unwrap();

        // Create a branch with an unmerged commit
        repo.run_command(&["checkout", "-b", "unmerged"]).unwrap();
        fs::write(test.path().join("new.txt"), "unmerged work").unwrap();
        repo.run_command(&["add", "."]).unwrap();
        repo.run_command(&["commit", "-m", "unmerged work"])
            .unwrap();
        repo.run_command(&["checkout", "main"]).unwrap();

        let result = RemoveResult::BranchOnly {
            branch_name: "unmerged".to_string(),
            deletion_mode: BranchDeletionMode::SafeDelete,
            pruned: false,
            target_branch: None,
            integration_reason: None,
        };
        PickerCollector::do_removal(&repo, &result).unwrap();

        // Branch should be retained — SafeDelete won't delete unmerged branches
        let output = repo.run_command(&["branch", "--list", "unmerged"]).unwrap();
        assert!(
            !output.is_empty(),
            "unmerged branch should be retained with SafeDelete"
        );
    }

    #[test]
    fn test_do_removal_removes_detached_worktree() {
        let test = worktrunk::testing::TestRepo::with_initial_commit();
        let repo = worktrunk::git::Repository::at(test.path()).unwrap();
        let wt_dir = tempfile::tempdir().unwrap();
        let wt_path = wt_dir.path().join("detached");

        repo.run_command(&[
            "worktree",
            "add",
            "-b",
            "to-detach",
            wt_path.to_str().unwrap(),
        ])
        .unwrap();

        // Detach HEAD in the new worktree
        worktrunk::shell_exec::Cmd::new("git")
            .args(["checkout", "--detach", "HEAD"])
            .current_dir(&wt_path)
            .run()
            .unwrap();

        assert!(wt_path.exists());

        let result = RemoveResult::RemovedWorktree {
            main_path: test.path().to_path_buf(),
            worktree_path: wt_path.clone(),
            changed_directory: false,
            branch_name: None,
            deletion_mode: BranchDeletionMode::SafeDelete,
            target_branch: Some("main".to_string()),
            integration_reason: None,
            force_worktree: false,
            expected_path: None,
            removed_commit: None,
        };

        PickerCollector::do_removal(&repo, &result).unwrap();
        assert!(!wt_path.exists(), "detached worktree should be removed");
    }

    // Note: skim's `as_any().downcast_ref::<WorktreeSkimItem>()` fails at
    // runtime due to TypeId mismatch between skim's reader thread and the main
    // compilation unit (skim 0.20 bug). The invoke() code path uses output()
    // matching instead. Full invoke() tests require interactive skim — verified
    // via tmux-cli during development.
}