worktrunk 0.53.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
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
//! 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 global rayon pool.
//!    That bg work overlaps with everything below.
//! 4. Computes `num_items_estimate` — `list_worktrees` plus (conditionally)
//!    `local_branches` / `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
//! ```
//!
//! Preview pre-compute workload — spawn → all preview tasks drained,
//! skim bypassed (criterion, synthetic repo):
//!
//! ```bash
//! cargo bench --bench picker_preview
//! ```
//!
//! 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?".
//! ```

mod items;
mod log_formatter;
mod pager;
mod preview;
pub(crate) mod preview_cache;
mod preview_orchestrator;
mod progressive_handler;
mod summary;

use std::cell::RefCell;
use std::io::IsTerminal;
use std::path::{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::HookType;
use worktrunk::config::Approvals;
use worktrunk::git::{Repository, current_or_recover};
use worktrunk::styling::eprintln;

use super::hook_plan::{ApprovedHookPlan, HookPlanBuilder};
use super::hooks::HookAnnouncer;
use super::list::collect;
use super::list::progressive::RenderTarget;
use super::repository_ext::{RemoveTarget, RepositoryCliExt};
use super::worktree::{RemoveResult, SwitchPipeline};
use crate::cli::SwitchFormat;
use crate::output::handle_remove_output;
use worktrunk::git::{BranchDeletionMode, delete_branch_if_safe};

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

/// Drain stashed warnings to stderr. Called after skim has released the
/// terminal (or in the dry-run path after the bg thread joins) — eprintln
/// during the picker would corrupt skim's frame, so collect routes warnings
/// through `PickerProgressHandler::stash_warning` and we emit them here.
fn drain_stashed_warnings(stash: &Mutex<Vec<String>>) {
    for line in stash.lock().unwrap().drain(..) {
        eprintln!("{line}");
    }
}

/// 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,
}

/// The alt-r removal target parsed back out of a row's `output()` token.
///
/// A worktree-backed row's token is `worktree-path:<path>` (paths are
/// unique — detached worktrees would otherwise collide on the shared
/// `(detached)` label); a branch-only row's token is the bare branch name.
enum PickerRemovalTarget {
    WorktreePath(PathBuf),
    Branch(String),
}

impl PickerRemovalTarget {
    fn from_signal(signal: &str) -> Option<Self> {
        let signal = signal.trim();
        if signal.is_empty() {
            return None;
        }
        if let Some(path) = signal.strip_prefix(WORKTREE_OUTPUT_PREFIX) {
            if path.is_empty() {
                return None;
            }
            return Some(Self::WorktreePath(PathBuf::from(path)));
        }
        Some(Self::Branch(signal.to_string()))
    }
}

/// Resolve the switch identifier for a selected picker row, decoded from its
/// `output()` token: the worktree path for any worktree-backed row, the branch
/// name for a branch-only row.
///
/// `wt switch` accepts a worktree path for any existing worktree (`plan_switch`
/// phase 2b), so a worktree-backed row always switches by its unique path —
/// detached *and* branched alike. A branch-only row has no worktree, so its
/// branch name is the only handle.
///
/// Decoding `output()` rather than `downcast_ref::<WorktreeSkimItem>()` also
/// sidesteps skim 0.20's cross-thread `TypeId` mismatch, which makes the
/// downcast fail when the item originates on the reader thread.
fn picker_item_identifier(item: &dyn SkimItem) -> String {
    let output = item.output().to_string();
    match PickerRemovalTarget::from_signal(&output) {
        Some(PickerRemovalTarget::WorktreePath(path)) => path.to_string_lossy().into_owned(),
        _ => output,
    }
}

/// 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,
    /// Approvals snapshot, loaded once at picker startup. A queued removal runs
    /// its `pre-remove` / `post-remove` / `post-switch` hooks only when every
    /// one is in here — the picker can't show an approval prompt mid-render, so
    /// unapproved project commands are skipped, never run. See
    /// [`approved_removal_plan`].
    approvals: Arc<Approvals>,
}

impl PickerCollector {
    /// Build removal state from a fresh `Repository` so picker reloads after a
    /// background removal do not reuse the startup worktree inventory cache.
    ///
    /// `target` carries the exact worktree path or branch name decoded from
    /// the row's `output()` token — no `git worktree list` lookup, so a
    /// detached row can't be confused with another detached row.
    fn prepare_removal(
        &self,
        target: &PickerRemovalTarget,
    ) -> anyhow::Result<(Repository, RemoveResult)> {
        let repo = Repository::at(self.repo.discovery_path())?;

        // 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 = repo.current_worktree().root().ok();

        let result = {
            let config = repo.user_config();
            let remove_target = match target {
                PickerRemovalTarget::WorktreePath(path) => RemoveTarget::Path(path),
                PickerRemovalTarget::Branch(branch) => RemoveTarget::Branch(branch),
            };
            repo.prepare_worktree_removal(
                remove_target,
                BranchDeletionMode::SafeDelete,
                false,
                config,
                caller_path,
                None,
                None,
            )?
        };

        Ok((repo, result))
    }

    /// Execute a queued removal in the background.
    ///
    /// A `RemovedWorktree` result goes through [`handle_remove_output`] in its
    /// silent (TUI) mode — the git worktree removal with no `wt`-generated
    /// messages, spinner, or `cd` directive (skim owns the terminal). Its
    /// `pre-remove` / `post-remove` / `post-switch` hooks run only when they're
    /// already approved ([`approved_removal_plan`] — a read-only `Approvals`
    /// filter, no prompt): the picker can't prompt mid-render, so unapproved
    /// project commands are dropped from the plan, never run. (A hook that
    /// *does* run still
    /// streams its own output to stderr, like any hook — a rough edge of
    /// removing inside the picker.) A `BranchOnly` result just deletes the
    /// branch if it's safe to.
    ///
    /// Called from a background thread after the picker optimistically removes
    /// the item from the list, so the whole operation runs off skim's event loop
    /// and the TUI stays responsive. A removal failure is logged; the item stays
    /// gone from the picker — a tradeoff until we can show in-progress state.
    ///
    /// `repo` is the worktree the picker is operating from — the config source
    /// for the removal hooks (see [`approved_removal_plan`]) and the target of
    /// a `BranchOnly` deletion. `RemovedWorktree` removal itself is rooted at
    /// `main_path` (which may differ from the picker's startup repo in bare-repo
    /// setups).
    fn do_removal(
        repo: &Repository,
        result: &RemoveResult,
        approvals: &Approvals,
    ) -> anyhow::Result<()> {
        match result {
            RemoveResult::RemovedWorktree {
                main_path,
                worktree_path,
                ..
            } => {
                let main_repo = Repository::at(main_path)?;
                let plan = approved_removal_plan(repo, main_path, worktree_path, approvals)?;
                let mut announcer = HookAnnouncer::new(&main_repo, main_repo.user_config(), false);
                handle_remove_output(
                    result,
                    /* foreground */ true,
                    &plan,
                    /* quiet */ true,
                    /* silent */ true,
                    &mut announcer,
                )?;
                announcer.flush()?;
            }
            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");
                    if let Ok(snapshot) = repo.capture_refs() {
                        let _ = delete_branch_if_safe(
                            repo,
                            &snapshot,
                            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 token written by execute-silent)
        if let Ok(signal) = std::fs::read_to_string(&self.signal_path) {
            let selected_output = signal.trim().to_string();
            if let Some(removal_target) = PickerRemovalTarget::from_signal(&selected_output) {
                let preparation = self.prepare_removal(&removal_target);

                match preparation {
                    Ok((planning_repo, result)) => {
                        // Removal validated — remove the selected item from the
                        // picker list. The `output()` token is unique per row
                        // (a `worktree-path:` path for worktrees), so this
                        // drops exactly the selected row even when several
                        // detached rows share the `(detached)` branch label.
                        //
                        // 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 Some(home) = result.destination_path()
                        {
                            let _ = std::env::set_current_dir(home);
                            if let Ok(repo) = Repository::at(home) {
                                self.repo = repo;
                            }
                        }

                        // Defer actual git removal to a background thread so skim's
                        // event loop stays responsive.
                        let repo = planning_repo.clone();
                        let approvals = Arc::clone(&self.approvals);
                        let _ = std::thread::Builder::new()
                            .name(format!("picker-remove-{selected_output}"))
                            .spawn(move || {
                                if let Err(e) = Self::do_removal(&repo, &result, &approvals) {
                                    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)
    }
}

/// Whether every `pre-remove` / `post-remove` / `post-switch` command this
/// removal would run is already approved — a read-only check, no prompt.
///
/// `repo` is the worktree the picker is operating from; its `.config/wt.toml`
/// is what every removal hook resolves against, matching `wt remove` /
/// `wt merge`. `main_path` is the post-removal destination (the `post-switch`
/// anchor); `worktree_path` is the worktree being removed (the `pre-remove` /
/// `post-remove` anchor). The picker can't prompt mid-render, so it runs the
/// removal's hooks only when they're already approved (e.g. from a prior
/// `wt remove` / `wt merge`) and skips them otherwise — unapproved project
/// commands must never run. See CLAUDE.md → "Project Commands Run Only After
/// Approval".
fn approved_removal_plan(
    repo: &Repository,
    main_path: &Path,
    worktree_path: &Path,
    approvals: &Approvals,
) -> anyhow::Result<ApprovedHookPlan> {
    // Non-fatal: an unresolvable project identifier just means no project
    // pipeline can be matched against approvals — `approve_readonly` then
    // drops them (fail-closed), rather than aborting the picker removal.
    let project_id = repo.project_identifier().ok();
    let pid = project_id.as_deref();
    let user = repo.user_config();
    let project_config = repo.load_project_config()?;

    let mut builder = HookPlanBuilder::new();
    builder.add(
        worktree_path,
        &[HookType::PreRemove, HookType::PostRemove],
        project_config.as_ref(),
        user,
        pid,
    );
    builder.add(
        main_path,
        &[HookType::PostSwitch],
        project_config.as_ref(),
        user,
        pid,
    );
    Ok(builder.finish().approve_readonly(approvals, pid))
}

pub fn handle_picker(
    cli_branches: bool,
    cli_remotes: bool,
    change_dir_flag: Option<bool>,
    format: SwitchFormat,
) -> anyhow::Result<()> {
    // Interactive picker requires a terminal for the TUI. The dry-run and
    // preview-bench paths bypass skim entirely, so no TTY is required —
    // useful for tests, for diagnosing the pre-compute pipeline from scripts,
    // and for benchmarking the preview workload headlessly.
    let is_dry_run = std::env::var_os("WORKTRUNK_PICKER_DRY_RUN").is_some();
    let is_preview_bench = std::env::var_os("WORKTRUNK_PREVIEW_BENCH").is_some();
    let skip_tui = is_dry_run || is_preview_bench;
    if !skip_tui && !std::io::stdin().is_terminal() {
        anyhow::bail!("Interactive picker requires an interactive terminal");
    }
    worktrunk::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::trace::instant("Picker config resolved");

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

    // Prime the current worktree's root / git-dir / branch caches with one
    // batched `git rev-parse`. Subsumes the two standalone forks that the
    // speculative preview block below would otherwise make via `branch()`
    // and `root()`, and is also short-circuited when `collect::collect` calls
    // `repo.url_template()` → `load_project_config()` → `project_config_path()`
    // (which runs `prewarm_info` again — now a cache hit).
    let _ = repo.current_worktree().prewarm_info();

    // Preview cache is created up-front so the speculative first-item
    // preview can run in parallel with `collect::collect` below. Tasks
    // route to the global rayon pool (shared with the row pipeline).
    // Wrapped in `Arc` because the progressive handler (running on the
    // collect background thread) also calls `spawn_preview`.
    //
    // BranchDiff previews resolve the default branch's SHA via
    // `Repository::default_branch_sha`, which sources it from the
    // local-branch inventory cached on the shared `RepoCache`. N parallel
    // preview tasks share one inventory scan instead of each forking
    // `git rev-parse`. Read-only for the picker session — see the
    // accessor's docstring for the staleness contract.
    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.local_branches().map(|b| b.len()).unwrap_or(cap);
            estimate = estimate.max(local);
        }
        if estimate < cap && show_remotes {
            let remotes = repo.remote_branches().map(|b| b.len()).unwrap_or(0);
            estimate = estimate.saturating_add(remotes);
        }
        estimate
    };
    worktrunk::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");

    // Approvals snapshot for the session: alt-r removals consult it read-only
    // to filter the hook plan; see `approved_removal_plan`.
    let approvals = Arc::new(Approvals::load().context("Failed to load approvals")?);

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

    let signal_path_escaped =
        shell_escape::unix::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::unix::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)
        // Force the inline-mode clearing path on exit.
        //
        // tuikit only enters the alternate screen when the picker is full
        // height; at `height: "90%"` we're inline, so `smcup` is never
        // sent. But its `pause()` still emits `rmcup` whenever the option
        // `disable_alternate_screen` is false — and unmatched `rmcup`
        // varies by terminal: a no-op on most macOS terminals, but on some
        // Linux setups it leaves the picker frame on screen because no
        // explicit erase ran.
        //
        // skim plumbs `disable_alternate_screen = no_clear_start` (see
        // `skim/src/lib.rs` `Skim::run_with`), so setting `no_clear_start`
        // here forces pause() down the `cursor_goto + erase_down` branch,
        // which actually erases the rows skim drew on. The other side
        // effect, `clear_on_start = false`, is harmless for us — skim
        // immediately overdraws the rows it allocates.
        .no_clear_start(true)
        // 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::trace::instant("Picker skim options built");

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

    // Shared between the bg-thread handler (which pushes warnings while
    // skim owns the terminal) and the main thread (which drains them after
    // `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> =
        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,
            summary_hint,
            stashed_warnings: Arc::clone(&stashed_warnings),
            deferred_items: std::sync::OnceLock::new(),
        });

    // 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),
                },
                // Picker renders its own UI through `progressive_handler`;
                // collect must not write to stdout.
                RenderTarget::Json,
            );
        })
        .context("Failed to spawn picker-collect thread")?;
    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).
    drop(tx);
    drop(handler);

    // Dry-run / preview-bench: skim is bypassed. Wait for collect (which
    // spawns previews via the handler) to finish, then for the orchestrator's
    // pending tasks to drain on the global rayon pool. Dry-run additionally
    // drains stashed warnings and dumps the cache inventory; preview-bench
    // returns immediately so the measured wall clock is just "spawn → all
    // preview tasks drained", with no JSON serialization or stderr I/O in
    // the hot path.
    if skip_tui {
        drop(rx);
        let _ = bg_handle.join();
        orchestrator.wait_for_idle();
        if is_dry_run {
            drain_stashed_warnings(&stashed_warnings);
            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);

    // Skim has released the terminal — emit any warnings that collect's bg
    // thread stashed during the run. Late warnings (e.g. drain timeouts)
    // may still be in flight; we capture whatever has landed by now and let
    // the rest fall on the floor with the bg thread.
    drain_stashed_warnings(&stashed_warnings);

    // 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,
        };

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

        // Get the switch identifier: the query if creating new, otherwise the
        // selected item. `picker_item_identifier` yields a worktree path for
        // any worktree-backed row and the branch name for a branch-only row
        // (same as `wt switch` from CLI) — never the raw `worktree-path:` token.
        let selected = out.selected_items.first();
        let selected_name = selected.map(|item| picker_item_identifier(item.as_ref()));
        let query = out.query.trim().to_string();
        let identifier = resolve_identifier(&action, query, selected_name)?;

        // Load config — reuse the recovered repo if we recovered earlier.
        let repo = if is_recovered {
            repo.clone()
        } else {
            Repository::current().context("Failed to switch worktree")?
        };
        // Clone user config out — `SwitchPipeline` takes `&mut UserConfig` (the
        // bare-repo path-fix offer and the shell-integration offer record onto
        // it). Project config is loaded on demand inside the pipeline.
        let mut config = repo.user_config().clone();

        // Run the switch — the same `SwitchPipeline` as `wt switch <branch>`,
        // so hooks, approval, and output cannot drift from the argument path.
        // The picker has no `--execute`, offers no shell integration, and does
        // not capture pre-switch source identity (`capture_source: false` — an
        // existing switch's `{{ base }}` / `{{ base_worktree_path }}` stay
        // unset; result-derived `base` for creates and `target` still flow).
        SwitchPipeline {
            repo: &repo,
            config: &mut config,
            identifier: &identifier,
            create: should_create,
            base: None,
            clobber: false,
            verify: true,
            yes: false,
            change_dir,
            format,
            is_recovered,
            suggestion_ctx: None,
            capture_source: false,
            execute: None,
            execute_args: &[],
            shell_integration_binary: None,
        }
        .run()?;
    }

    Ok(())
}

/// Resolve the branch identifier from picker output.
///
/// Extracted from the picker's accept handler for testability.
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::items::WorktreeSkimItem;
    use super::preview::{PreviewLayout, PreviewMode, PreviewStateData};
    use super::{
        PickerAction, PickerCollector, PickerRemovalTarget, drain_stashed_warnings,
        picker_item_identifier, resolve_identifier,
    };
    use crate::commands::list::model::{ItemKind, ListItem, WorktreeData};
    use crate::commands::worktree::RemoveResult;
    use skim::prelude::SkimItem;
    use skim::reader::CommandCollector;
    use std::fs;
    use std::path::Path;
    use std::sync::atomic::AtomicUsize;
    use std::sync::{Arc, Mutex};
    use std::time::{Duration, Instant};
    use worktrunk::config::Approvals;
    use worktrunk::git::BranchDeletionMode;

    /// Empties the stash and emits each line. Verifies post-skim drain
    /// semantics without standing up a real picker.
    #[test]
    fn drain_stashed_warnings_empties_the_stash() {
        let stash = Mutex::new(vec!["one".to_string(), "two".to_string()]);
        drain_stashed_warnings(&stash);
        assert!(stash.lock().unwrap().is_empty());
    }

    /// A fresh stash with no warnings is a no-op — exercising the empty path
    /// keeps the loop body covered when the picker exits cleanly.
    #[test]
    fn drain_stashed_warnings_handles_empty_stash() {
        let stash: Mutex<Vec<String>> = Mutex::new(Vec::new());
        drain_stashed_warnings(&stash);
        assert!(stash.lock().unwrap().is_empty());
    }

    #[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"));
    }

    /// `from_signal` rejects tokens that carry no usable target: a blank or
    /// whitespace-only signal, and a bare `worktree-path:` prefix with no path
    /// after it. A non-empty branch token and a prefixed path both parse.
    #[test]
    fn test_picker_removal_target_from_signal() {
        assert!(PickerRemovalTarget::from_signal("").is_none());
        assert!(PickerRemovalTarget::from_signal("   ").is_none());
        assert!(PickerRemovalTarget::from_signal("worktree-path:").is_none());

        assert!(matches!(
            PickerRemovalTarget::from_signal("feature/foo"),
            Some(PickerRemovalTarget::Branch(branch)) if branch == "feature/foo"
        ));
        assert!(matches!(
            PickerRemovalTarget::from_signal("worktree-path:/tmp/wt"),
            Some(PickerRemovalTarget::WorktreePath(path)) if path == std::path::Path::new("/tmp/wt")
        ));
    }

    /// `picker_item_identifier` yields the worktree path for every
    /// worktree-backed row — branched as well as detached — and the branch name
    /// for a branch-only row, matching what each row's `output()` token carries.
    #[test]
    fn test_picker_item_identifier() {
        let branched = branched_picker_item("feature/foo", Path::new("/tmp/wt-branched"));
        assert_eq!(
            picker_item_identifier(branched.as_ref()),
            "/tmp/wt-branched"
        );

        let detached = detached_picker_item(Path::new("/tmp/wt-detached"));
        assert_eq!(
            picker_item_identifier(detached.as_ref()),
            "/tmp/wt-detached"
        );

        let branch_only = branch_only_picker_item("feature/bar");
        assert_eq!(picker_item_identifier(branch_only.as_ref()), "feature/bar");
    }

    #[test]
    fn test_do_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, &Approvals::default()).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, &Approvals::default()).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, &Approvals::default()).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, &Approvals::default()).unwrap();
        assert!(!wt_path.exists(), "detached worktree should be removed");
    }

    /// A branch-only row's signal carries the bare branch name, which
    /// `PickerRemovalTarget::from_signal` decodes to `Branch`; `prepare_removal`
    /// then resolves it to the branch-only disposition.
    #[test]
    fn test_prepare_removal_resolves_branch_only_item() {
        let test = worktrunk::testing::TestRepo::with_initial_commit();
        let repo = worktrunk::git::Repository::at(test.path()).unwrap();

        // A branch at the same commit as main, with no worktree.
        repo.run_command(&["branch", "branch-only-feature"])
            .unwrap();

        let state_dir = tempfile::tempdir().unwrap();
        let collector = PickerCollector {
            items: Arc::new(Mutex::new(Vec::new())),
            signal_path: state_dir.path().join("remove"),
            repo,
            approvals: Arc::new(Approvals::default()),
        };

        let target = PickerRemovalTarget::from_signal("branch-only-feature").unwrap();
        let (_planning_repo, result) = collector.prepare_removal(&target).unwrap();
        assert!(
            matches!(&result, RemoveResult::BranchOnly { branch_name, .. } if branch_name == "branch-only-feature"),
            "a branch with no worktree should resolve to BranchOnly"
        );
    }

    /// A selection that names neither a worktree nor a local branch fails the
    /// `prepare_worktree_removal` validation, so `prepare_removal` returns the
    /// error rather than touching the picker list.
    #[test]
    fn test_prepare_removal_errors_on_unknown_target() {
        let test = worktrunk::testing::TestRepo::with_initial_commit();
        let repo = worktrunk::git::Repository::at(test.path()).unwrap();

        let state_dir = tempfile::tempdir().unwrap();
        let collector = PickerCollector {
            items: Arc::new(Mutex::new(Vec::new())),
            signal_path: state_dir.path().join("remove"),
            repo,
            approvals: Arc::new(Approvals::default()),
        };

        // `RemoveResult` isn't `Debug`; drop the Ok payload so `unwrap_err`
        // (which needs `T: Debug`) can report a failure cleanly.
        let target = PickerRemovalTarget::from_signal("no-such-branch").unwrap();
        let err = collector
            .prepare_removal(&target)
            .map(|_| ())
            .expect_err("unknown removal target should fail validation");
        assert!(
            err.to_string().contains("no-such-branch"),
            "error should name the unresolved target: {err:#}"
        );
    }

    /// A `pre-remove` hook the user hasn't approved must not run when the
    /// picker removes the worktree — the picker can't prompt mid-render, so
    /// unapproved project commands are skipped. The git removal still happens.
    #[test]
    fn test_do_removal_skips_unapproved_pre_remove_hook() {
        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();

        // A `pre-remove` hook in the invoking worktree's `.config/wt.toml` —
        // the config the picker removal resolves against — that would write a
        // marker if it ever ran.
        let marker_dir = tempfile::tempdir().unwrap();
        let marker = marker_dir.path().join("pre-remove-ran");
        fs::create_dir_all(test.path().join(".config")).unwrap();
        fs::write(
            test.path().join(".config/wt.toml"),
            format!("pre-remove = {:?}\n", format!("touch {}", marker.display())),
        )
        .unwrap();

        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,
        };

        // Empty approvals → `approve_readonly` drops the unapproved project
        // `pre-remove` pipeline from the plan, so it never runs.
        let approvals = Approvals::default();
        PickerCollector::do_removal(&repo, &result, &approvals).unwrap();
        assert!(!wt_path.exists(), "worktree should be removed");
        assert!(!marker.exists(), "unapproved pre-remove hook must not run");
    }

    /// Build a `WorktreeSkimItem` from a snapshot `ListItem`.
    fn picker_item(branch_name: &str, item: ListItem) -> Arc<dyn SkimItem> {
        Arc::new(WorktreeSkimItem {
            search_text: branch_name.to_string(),
            rendered: Arc::new(Mutex::new(String::new())),
            branch_name: branch_name.to_string(),
            item: Arc::new(item),
            preview_cache: Arc::new(dashmap::DashMap::new()),
        }) as Arc<dyn SkimItem>
    }

    /// Build a `WorktreeSkimItem` standing in for a detached-worktree row.
    fn detached_picker_item(path: &Path) -> Arc<dyn SkimItem> {
        let mut item = ListItem::new_branch("abc123".to_string(), "(detached)".to_string());
        item.branch = None;
        item.kind = ItemKind::Worktree(Box::new(WorktreeData {
            path: path.to_path_buf(),
            detached: true,
            ..Default::default()
        }));
        picker_item("(detached)", item)
    }

    /// Build a `WorktreeSkimItem` standing in for a branched-worktree row.
    fn branched_picker_item(branch: &str, path: &Path) -> Arc<dyn SkimItem> {
        let mut item = ListItem::new_branch("abc123".to_string(), branch.to_string());
        item.kind = ItemKind::Worktree(Box::new(WorktreeData {
            path: path.to_path_buf(),
            ..Default::default()
        }));
        picker_item(branch, item)
    }

    /// Build a `WorktreeSkimItem` standing in for a branch-only row (no worktree).
    fn branch_only_picker_item(branch: &str) -> Arc<dyn SkimItem> {
        picker_item(
            branch,
            ListItem::new_branch("abc123".to_string(), branch.to_string()),
        )
    }

    /// Two detached worktrees both render the branch label `(detached)`, but
    /// each row's `output()` token carries its unique path. alt-r on the
    /// second row must remove exactly that worktree — not the first detached
    /// one a branch-name match would resolve to — and drop only its row.
    #[test]
    fn test_invoke_removes_selected_detached_worktree_by_path_token() {
        let test = worktrunk::testing::TestRepo::with_initial_commit();
        let repo = worktrunk::git::Repository::at(test.path()).unwrap();
        let wt_dir = tempfile::tempdir().unwrap();
        let first_path = wt_dir.path().join("detached-one");
        let second_path = wt_dir.path().join("detached-two");

        for (branch, path) in [
            ("to-detach-one", first_path.as_path()),
            ("to-detach-two", second_path.as_path()),
        ] {
            repo.run_command(&["worktree", "add", "-b", branch, path.to_str().unwrap()])
                .unwrap();
            worktrunk::shell_exec::Cmd::new("git")
                .args(["checkout", "--detach", "HEAD"])
                .current_dir(path)
                .run()
                .unwrap();
        }

        let reported_paths: Vec<_> = repo
            .list_worktrees()
            .unwrap()
            .iter()
            .filter(|wt| wt.branch.is_none())
            .map(|wt| wt.path.clone())
            .collect();
        let first_reported = reported_paths
            .iter()
            .find(|path| path.file_name().is_some_and(|name| name == "detached-one"))
            .unwrap();
        let second_reported = reported_paths
            .iter()
            .find(|path| path.file_name().is_some_and(|name| name == "detached-two"))
            .unwrap();

        let first_item = detached_picker_item(first_reported);
        let second_item = detached_picker_item(second_reported);
        let first_output = first_item.output().to_string();
        let second_output = second_item.output().to_string();
        assert_ne!(first_output, second_output);
        assert_eq!(
            picker_item_identifier(second_item.as_ref()),
            second_reported.to_string_lossy()
        );

        let signal_dir = tempfile::tempdir().unwrap();
        let signal_path = signal_dir.path().join("remove-signal");
        fs::write(&signal_path, &second_output).unwrap();

        let items = Arc::new(Mutex::new(vec![
            Arc::clone(&first_item),
            Arc::clone(&second_item),
        ]));
        let mut collector = PickerCollector {
            items: Arc::clone(&items),
            signal_path,
            repo: repo.clone(),
            approvals: Arc::new(Approvals::default()),
        };

        let (_rx, _interrupt) = collector.invoke("remove", Arc::new(AtomicUsize::new(0)));

        let remaining: Vec<_> = items
            .lock()
            .unwrap()
            .iter()
            .map(|item| item.output().to_string())
            .collect();
        assert_eq!(remaining, vec![first_output]);

        let deadline = Instant::now() + Duration::from_secs(5);
        while second_path.exists() && Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(20));
        }
        assert!(first_path.exists(), "first detached worktree should remain");
        assert!(
            !second_path.exists(),
            "selected 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 TUI tests require interactive skim — verified
    // via tmux-cli during development.
}