knixl 1.5.0

Compile opinionated KDL into maintainable, committed NixOS module source.
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
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
//! Install screen. The reducer is split so the decision logic (focus movement, host switch,
//! apply gating, verify-result handling) is pure and unit-tested, while the parts that spawn
//! async `Cmd`s (the nix verify, the spinner tick) read the injected `config()` and stay as
//! thin glue.

use bubbletea_rs::event::{KeyMsg, WindowSizeMsg};
use bubbletea_rs::{command, Cmd, Model as BubbleTeaModel, Msg};
use bubbletea_widgets::{spinner, textinput, viewport};
use crossterm::event::{KeyCode, KeyModifiers};
use lipgloss::{join_vertical, rounded_border, Style, LEFT};

use knixl_pipeline::install::HostInfo;

use super::{
    config, theme, widgets, BuildOutcome, Entry, Nav, PinOutcome, Step, StrategyOutcome, Verified,
};

/// Does `pkgs.<pkg>` resolve. Host-independent, recomputed when the package changes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Resolve {
    Yes,
    No,
    Skipped,
}

/// Does the drafted host file parse under nix. Re-run per host and per package edit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Parse {
    Running,
    Ok,
    Failed(String),
    Skipped,
}

/// The async verify result, delivered back to `update` as a message.
struct VerifyDone {
    seq: u64,
    verified: Verified,
}

/// The `--build` status. `Off` means `--build` was not requested (never gates apply).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BuildState {
    Off,
    Building,
    Ok,
    Failed,
    Skipped,
}

/// The async build result, delivered back to `update`.
struct BuildDone {
    seq: u64,
    outcome: BuildOutcome,
}

/// The version-pin resolve status. `Off` means no version was requested (never gates apply,
/// unlike the build/verify checks, which stay strict-gated: an unresolved pin always refuses).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PinState {
    Off,
    Resolving,
    Resolved,
    Failed,
}

/// The async pin-resolve result, delivered back to `update`.
struct PinDone {
    seq: u64,
    outcome: PinOutcome,
}

/// The pin-strategy selection status. `Off` covers both "no version requested" and "a
/// version was requested but the pin has not resolved yet"; like `PinState::Off`, it never
/// gates apply. `Selecting` replaces the ambient `--build` check for a versioned install once
/// the pin resolves a rev.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StrategyState {
    Off,
    Selecting,
    Chosen(knixl_lock::model::PinStrategy),
    Failed,
}

/// The async strategy-selection result, delivered back to `update`.
struct StrategyDone {
    seq: u64,
    outcome: StrategyOutcome,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Focus {
    Host,
    Package,
    Strict,
    Preview,
    Apply,
    Cancel,
}

const FOCUS_ORDER: [Focus; 6] = [
    Focus::Host,
    Focus::Package,
    Focus::Strict,
    Focus::Preview,
    Focus::Apply,
    Focus::Cancel,
];

pub struct InstallModel {
    pkg: textinput::Model,
    hosts: Vec<HostInfo>,
    host_sel: usize,
    strict: bool,
    /// Threaded from the entry point (`--no-abi-check`) through to `Nav::Apply`/
    /// `Outcome::Install`, unchanged and never toggled from within the screen (no UI control
    /// for it): strategy selection already closed over its own copy before the TUI started.
    no_abi_check: bool,
    focus: Focus,
    resolves: Resolve,
    parses: Parse,
    preview: viewport::Model,
    preview_text: String,
    verifying: bool,
    seq: u64,
    spinner: spinner::Model,
    build: BuildState,
    build_spinner: spinner::Model,
    build_seq: u64,
    /// The version requested at entry (`install pkg@version`), if any. Host-independent.
    version: Option<String>,
    pin: PinState,
    pin_spinner: spinner::Model,
    pin_seq: u64,
    /// The resolved rev, set once `pin` reaches `Resolved`. Carried through to `Nav::Apply`
    /// for the CLI to write the pin.
    pin_resolved: Option<String>,
    strategy: StrategyState,
    strategy_spinner: spinner::Model,
    strategy_seq: u64,
    /// The label (`Chosen`) or error message (`Failed`) for the strategy status row.
    strategy_msg: Option<String>,
    dims: (usize, usize),
}

/// An amber dot spinner for the in-flight verify.
fn new_spinner() -> spinner::Model {
    spinner::new(&[
        spinner::with_spinner(spinner::DOT.clone()),
        spinner::with_style(theme::amber()),
    ])
}

/// Viewport dimensions for a given terminal size: a padded inner box, clamped.
fn view_dims(size: (u16, u16)) -> (usize, usize) {
    let w = (size.0 as usize).saturating_sub(6).clamp(20, 80);
    let h = (size.1 as usize).saturating_sub(12).clamp(3, 20);
    (w, h)
}

/// Below this the layout can't fit; `view` shows a resize hint instead.
fn too_small(size: (u16, u16)) -> bool {
    size.0 < 30 || size.1 < 12
}

impl InstallModel {
    /// Build the screen for the current entry, focus the package field, and kick the first
    /// verify. Reads `config()` (hosts, entry, verify), so it runs under the program only.
    pub fn enter(size: (u16, u16)) -> (Self, Option<Cmd>) {
        let cfg = config();
        let (host_sel, pkg_value, strict, version, no_abi_check) = match &cfg.entry {
            Entry::Install {
                pkg,
                strict,
                host,
                version,
                no_abi_check,
            } => {
                let idx = host
                    .as_ref()
                    .and_then(|n| cfg.hosts.iter().position(|h| &h.name == n))
                    .unwrap_or(0);
                (idx, pkg.clone(), *strict, version.clone(), *no_abi_check)
            }
            Entry::Hub => (0, String::new(), false, None, false),
        };

        let mut pkg = textinput::new();
        pkg.set_placeholder("package name");
        pkg.set_value(&pkg_value);
        // focus() returns a cursor-blink command we don't drive; drop it explicitly.
        std::mem::drop(pkg.focus());

        let (w, h) = view_dims(size);
        // The injected build/pin fns are the single source of truth for whether `--build` /
        // a version were requested (Hub never injects either, so it always seeds `Off` there).
        // A versioned install never gets the ambient build: strategy selection replaces it
        // once the pin resolves (see `begin_strategy`), so `build_state` stays `Off` there.
        let build_state = if cfg.build.is_some() && version.is_none() {
            BuildState::Building
        } else {
            BuildState::Off
        };
        let pin_state = if cfg.pin.is_some() && version.is_some() {
            PinState::Resolving
        } else {
            PinState::Off
        };
        let mut model = InstallModel {
            pkg,
            hosts: cfg.hosts.clone(),
            host_sel,
            strict,
            no_abi_check,
            focus: Focus::Package,
            resolves: Resolve::Skipped,
            parses: Parse::Skipped,
            preview: viewport::new(w, h),
            preview_text: String::new(),
            verifying: false,
            seq: 0,
            spinner: new_spinner(),
            build: build_state,
            build_spinner: new_spinner(),
            build_seq: 0,
            version,
            pin: pin_state,
            pin_spinner: new_spinner(),
            pin_seq: 0,
            pin_resolved: None,
            strategy: StrategyState::Off,
            strategy_spinner: new_spinner(),
            strategy_seq: 0,
            strategy_msg: None,
            dims: (w, h),
        };
        let verify = model.begin_verify();
        let build = model.begin_build();
        let pin = model.begin_pin();
        (model, batch_all(vec![verify, build, pin]))
    }

    // ---- pure decision logic (unit-tested) ----

    /// Apply is allowed only when no verify is in flight and each of resolve, parse, build,
    /// pin and strategy is `Ok`/`Chosen`/`Off`, or `Skipped` without `--strict`.
    fn apply_allowed(&self) -> bool {
        if self.hosts.is_empty() || self.verifying {
            return false;
        }
        let resolve_ok = match self.resolves {
            Resolve::Yes => true,
            Resolve::Skipped => !self.strict,
            Resolve::No => false,
        };
        let parse_ok = match &self.parses {
            Parse::Ok => true,
            Parse::Skipped => !self.strict,
            Parse::Running => false,
            Parse::Failed(_) => false,
        };
        let build_ok = match self.build {
            BuildState::Off | BuildState::Ok => true,
            BuildState::Skipped => !self.strict,
            BuildState::Building | BuildState::Failed => false,
        };
        // Unlike build/verify, a requested pin is never skippable under --strict: an
        // unresolved version always refuses (docs on `install`'s pin resolution).
        let pin_ok = match self.pin {
            PinState::Off | PinState::Resolved => true,
            PinState::Resolving | PinState::Failed => false,
        };
        // Mirrors pin_ok: a strategy selection in flight or failed always refuses, regardless
        // of --strict.
        let strategy_ok = match self.strategy {
            StrategyState::Off | StrategyState::Chosen(_) => true,
            StrategyState::Selecting | StrategyState::Failed => false,
        };
        resolve_ok && parse_ok && build_ok && pin_ok && strategy_ok
    }

    fn focus_index(&self) -> usize {
        FOCUS_ORDER
            .iter()
            .position(|f| *f == self.focus)
            .unwrap_or(0)
    }

    fn focus_next(&mut self) {
        let i = (self.focus_index() + 1) % FOCUS_ORDER.len();
        self.focus = FOCUS_ORDER[i];
    }

    fn focus_prev(&mut self) {
        let i = (self.focus_index() + FOCUS_ORDER.len() - 1) % FOCUS_ORDER.len();
        self.focus = FOCUS_ORDER[i];
    }

    /// Move the host selection; reports whether it actually changed (so the caller re-verifies
    /// and, for a versioned install with a resolved pin, re-fires strategy selection).
    fn set_host(&mut self, idx: usize) -> bool {
        if idx < self.hosts.len() && idx != self.host_sel {
            self.host_sel = idx;
            true
        } else {
            false
        }
    }

    fn toggle_strict(&mut self) {
        self.strict = !self.strict;
    }

    /// Fold an async verify result into the state, ignoring stale results from a superseded
    /// verify (host switched or package edited again before this one returned).
    fn on_verify_done(&mut self, seq: u64, verified: Verified) {
        if seq != self.seq {
            return;
        }
        self.verifying = false;
        self.resolves = verified.resolves;
        self.parses = verified.parses;
        self.set_preview(verified.preview);
    }

    fn set_preview(&mut self, text: String) {
        self.preview.set_content(&text);
        self.preview_text = text;
    }

    fn mark_verifying(&mut self) -> u64 {
        self.seq += 1;
        self.verifying = true;
        self.parses = Parse::Running;
        self.seq
    }

    fn mark_building(&mut self) -> u64 {
        self.build_seq += 1;
        self.build = BuildState::Building;
        self.build_seq
    }

    /// Fold an async build result into the state, ignoring a stale result from a superseded
    /// build (package edited again before this one returned).
    fn on_build_done(&mut self, seq: u64, outcome: BuildOutcome) {
        if seq != self.build_seq {
            return;
        }
        self.build = match outcome {
            BuildOutcome::Ok => BuildState::Ok,
            BuildOutcome::Failed => BuildState::Failed,
            BuildOutcome::Skipped => BuildState::Skipped,
        };
    }

    fn mark_resolving(&mut self) -> u64 {
        self.pin_seq += 1;
        self.pin = PinState::Resolving;
        self.pin_seq
    }

    /// Fold an async pin-resolve result into the state, ignoring a stale result from a
    /// superseded resolve (package edited again before this one returned).
    fn on_pin_done(&mut self, seq: u64, outcome: PinOutcome) {
        if seq != self.pin_seq {
            return;
        }
        match outcome {
            PinOutcome::Resolved(rev) => {
                self.pin = PinState::Resolved;
                self.pin_resolved = Some(rev);
            }
            PinOutcome::NotFound | PinOutcome::Unavailable | PinOutcome::Failed => {
                self.pin = PinState::Failed;
            }
        }
    }

    fn mark_selecting(&mut self) -> u64 {
        self.strategy_seq += 1;
        self.strategy = StrategyState::Selecting;
        self.strategy_seq
    }

    /// Fold an async strategy-selection result into the state, ignoring a stale result from a
    /// superseded selection (package/version edited again before this one returned).
    fn on_strategy_done(&mut self, seq: u64, outcome: StrategyOutcome) {
        if seq != self.strategy_seq {
            return;
        }
        match outcome {
            StrategyOutcome::Chosen { strategy, label } => {
                self.strategy = StrategyState::Chosen(strategy);
                self.strategy_msg = Some(label);
            }
            StrategyOutcome::Failed(msg) => {
                self.strategy = StrategyState::Failed;
                self.strategy_msg = Some(msg);
            }
        }
    }

    fn resize(&mut self, size: (u16, u16)) {
        let dims = view_dims(size);
        if dims != self.dims {
            self.dims = dims;
            self.preview = viewport::new(dims.0, dims.1);
            self.preview.set_content(&self.preview_text);
        }
    }

    // ---- async glue (reads config(); not unit-tested) ----

    /// Start a verify for the current host/package: bump the token, show the spinner, and
    /// batch the nix check with a spinner tick. No hosts means nothing to preview.
    fn begin_verify(&mut self) -> Option<Cmd> {
        if self.hosts.is_empty() {
            self.verifying = false;
            return None;
        }
        let seq = self.mark_verifying();
        let pkg = self.pkg.value();
        let host = self.hosts[self.host_sel].clone();
        Some(command::batch(vec![
            verify_cmd(seq, pkg, host),
            spin_start(self.spinner.tick_msg()),
        ]))
    }

    /// Start a build for the current package, if `--build` was requested. Host-independent,
    /// so this is NOT called on a host switch. Never runs for a versioned install: strategy
    /// selection (`begin_strategy`) replaces the ambient build there once the pin resolves.
    fn begin_build(&mut self) -> Option<Cmd> {
        if self.version.is_some() {
            return None;
        }
        config().build.as_ref()?; // None => --build not requested
        let seq = self.mark_building();
        let pkg = self.pkg.value();
        Some(command::batch(vec![
            build_cmd(seq, pkg),
            spin_start(self.build_spinner.tick_msg()),
        ]))
    }

    /// Start a pin resolve for the current package, if a version was requested. Host-
    /// independent, so this is NOT called on a host switch.
    fn begin_pin(&mut self) -> Option<Cmd> {
        config().pin.as_ref()?; // None => no version requested
        let version = self.version.clone()?;
        let seq = self.mark_resolving();
        let pkg = self.pkg.value();
        Some(command::batch(vec![
            pin_cmd(seq, pkg, version),
            spin_start(self.pin_spinner.tick_msg()),
        ]))
    }

    /// Start strategy selection for the resolved pin, if a strategy fn was injected. Called
    /// from `update`'s `PinDone` handling once the pin resolves a rev for a versioned install
    /// (replacing the ambient build there), and again from the `Focus::Host` handlers on a
    /// host switch. Always reads the *current* `host_sel` (see `StrategyFn` for why the
    /// decision is host-dependent).
    fn begin_strategy(&mut self, rev: String) -> Option<Cmd> {
        config().strategy.as_ref()?; // None => no version requested (unversioned installs skip this)
        let seq = self.mark_selecting();
        let pkg = self.pkg.value();
        let host = self.hosts[self.host_sel].name.clone();
        Some(command::batch(vec![
            strategy_cmd(seq, pkg, rev, host),
            spin_start(self.strategy_spinner.tick_msg()),
        ]))
    }

    /// Re-verify after a host switch, and re-fire strategy selection too if the pin has
    /// already resolved (see `begin_strategy` for why the decision is host-dependent). If
    /// not, strategy selection will fire from the eventual `PinDone` instead.
    fn on_host_changed(&mut self) -> Option<Cmd> {
        let verify = self.begin_verify();
        let strategy = (self.pin == PinState::Resolved)
            .then(|| self.pin_resolved.clone())
            .flatten()
            .and_then(|rev| self.begin_strategy(rev));
        batch_all(vec![verify, strategy])
    }

    pub fn update(&mut self, msg: Msg, size: (u16, u16)) -> Step {
        if msg.downcast_ref::<WindowSizeMsg>().is_some() {
            self.resize(size);
            return Step::stay();
        }
        if let Some(done) = msg.downcast_ref::<VerifyDone>() {
            self.on_verify_done(done.seq, done.verified.clone());
            return Step::stay();
        }
        if let Some(done) = msg.downcast_ref::<BuildDone>() {
            self.on_build_done(done.seq, done.outcome);
            return Step::stay();
        }
        if let Some(done) = msg.downcast_ref::<PinDone>() {
            let seq = done.seq;
            self.on_pin_done(seq, done.outcome.clone());
            // A fresh resolve (not a stale one) for a versioned install kicks strategy
            // selection instead of the ambient build (see `begin_build`'s guard).
            let cmd = if seq == self.pin_seq && self.pin == PinState::Resolved {
                self.pin_resolved
                    .clone()
                    .and_then(|rev| self.begin_strategy(rev))
            } else {
                None
            };
            return Step {
                nav: Nav::Stay,
                cmd,
            };
        }
        if let Some(done) = msg.downcast_ref::<StrategyDone>() {
            self.on_strategy_done(done.seq, done.outcome.clone());
            return Step::stay();
        }
        if let Some(tick) = msg.downcast_ref::<spinner::TickMsg>() {
            // Route the tick to whichever spinner owns it (each has a distinct id), and
            // re-arm only while that spinner's work is still in flight.
            if tick.id == self.build_spinner.id() {
                let cmd = self.build_spinner.update(msg);
                return Step {
                    nav: Nav::Stay,
                    cmd: if self.build == BuildState::Building {
                        cmd
                    } else {
                        None
                    },
                };
            }
            if tick.id == self.pin_spinner.id() {
                let cmd = self.pin_spinner.update(msg);
                return Step {
                    nav: Nav::Stay,
                    cmd: if self.pin == PinState::Resolving {
                        cmd
                    } else {
                        None
                    },
                };
            }
            if tick.id == self.strategy_spinner.id() {
                let cmd = self.strategy_spinner.update(msg);
                return Step {
                    nav: Nav::Stay,
                    cmd: if self.strategy == StrategyState::Selecting {
                        cmd
                    } else {
                        None
                    },
                };
            }
            let cmd = self.spinner.update(msg);
            return Step {
                nav: Nav::Stay,
                cmd: if self.verifying { cmd } else { None },
            };
        }
        let Some((code, mods)) = key_of(&msg) else {
            return Step::stay();
        };

        // Ctrl-C and Esc always back out, regardless of focus (so they still work while the
        // package field has focus and would otherwise swallow the key).
        if matches!(code, KeyCode::Char('c')) && mods.contains(KeyModifiers::CONTROL) {
            return Step::nav(Nav::Back);
        }
        if code == KeyCode::Esc {
            return Step::nav(Nav::Back);
        }
        // Tab and the arrow keys move the focus selector between controls. Left/Right stay
        // control-specific (host switch, cursor in the package field).
        if matches!(code, KeyCode::Tab | KeyCode::Down) {
            self.focus_next();
            return Step::stay();
        }
        if matches!(code, KeyCode::BackTab | KeyCode::Up) {
            self.focus_prev();
            return Step::stay();
        }

        match self.focus {
            Focus::Host => match code {
                KeyCode::Left => {
                    if self.host_sel > 0 && self.set_host(self.host_sel - 1) {
                        Step {
                            nav: Nav::Stay,
                            cmd: self.on_host_changed(),
                        }
                    } else {
                        Step::stay()
                    }
                }
                KeyCode::Right => {
                    if self.set_host(self.host_sel + 1) {
                        Step {
                            nav: Nav::Stay,
                            cmd: self.on_host_changed(),
                        }
                    } else {
                        Step::stay()
                    }
                }
                _ => Step::stay(),
            },
            Focus::Package => match code {
                // Enter commits the edited package name, re-verifies, and re-runs the build
                // and pin resolve (both package-only, so they re-run here but not on a host
                // switch).
                KeyCode::Enter => {
                    let v = self.begin_verify();
                    let b = self.begin_build();
                    let p = self.begin_pin();
                    Step {
                        nav: Nav::Stay,
                        cmd: batch_all(vec![v, b, p]),
                    }
                }
                _ => {
                    let cmd = self.pkg.update(msg);
                    Step {
                        nav: Nav::Stay,
                        cmd,
                    }
                }
            },
            Focus::Strict => match code {
                KeyCode::Char(' ') | KeyCode::Enter => {
                    self.toggle_strict();
                    Step::stay()
                }
                _ => Step::stay(),
            },
            Focus::Preview => {
                let cmd = self.preview.update(msg);
                Step {
                    nav: Nav::Stay,
                    cmd,
                }
            }
            Focus::Apply => match code {
                KeyCode::Enter if self.apply_allowed() => Step::nav(Nav::Apply {
                    host: self.hosts[self.host_sel].clone(),
                    pkg: self.pkg.value(),
                    strict: self.strict,
                    version: self.version.clone(),
                    pin: self.pin_resolved.clone(),
                    no_abi_check: self.no_abi_check,
                    strategy: match self.strategy {
                        StrategyState::Chosen(s) => Some(s),
                        _ => None,
                    },
                    strategy_reason: self.strategy_msg.clone(),
                }),
                _ => Step::stay(),
            },
            Focus::Cancel => match code {
                KeyCode::Enter => Step::nav(Nav::Back),
                _ => Step::stay(),
            },
        }
    }

    pub fn view(&self, size: (u16, u16)) -> String {
        if too_small(size) {
            return theme::dim().render("terminal too small \u{2013} resize to install");
        }
        if self.hosts.is_empty() {
            return format!(
                "{}\n{}",
                theme::chip(" install "),
                theme::dim().render("no hosts found under hosts/"),
            );
        }

        let host = &self.hosts[self.host_sel];
        let host_line = format!(
            "{}{}{}{}{}",
            marker(self.focus == Focus::Host),
            theme::dim().render("host   "),
            theme::amber().render("\u{2039} "),
            Style::new().bold(true).render(&host.name),
            theme::amber().render(" \u{203a}   \u{2190}/\u{2192}"),
        );
        let pkg_line = format!(
            "{}{}{}",
            marker(self.focus == Focus::Package),
            theme::dim().render("pkg    "),
            self.pkg.view(),
        );
        let strict_line = format!(
            "{}{}{} strict",
            marker(self.focus == Focus::Strict),
            theme::dim().render("check  "),
            theme::toggle(self.strict),
        );

        let verify_line = format!(
            "{}{}{}",
            marker(false),
            theme::dim().render("verify "),
            self.verify_status()
        );

        let build_line = (self.build != BuildState::Off).then(|| {
            let status = match self.build {
                BuildState::Building => format!("{} building", self.build_spinner.view()),
                BuildState::Ok => theme::good().render("\u{2713} builds"),
                BuildState::Failed => theme::bad().render("\u{2717} build failed"),
                BuildState::Skipped => theme::amber().render("\u{00b7} build skipped"),
                BuildState::Off => String::new(),
            };
            format!(
                "{}{}{}",
                marker(false),
                theme::dim().render("build  "),
                status
            )
        });

        let pin_line = (self.pin != PinState::Off).then(|| {
            let status = match self.pin {
                PinState::Resolving => format!("{} resolving", self.pin_spinner.view()),
                PinState::Resolved => {
                    let rev = self
                        .pin_resolved
                        .as_deref()
                        .map(short_rev)
                        .unwrap_or_default();
                    theme::good().render(&format!("\u{2713} pinned {rev}"))
                }
                PinState::Failed => theme::bad().render("\u{2717} pin failed"),
                PinState::Off => String::new(),
            };
            format!(
                "{}{}{}",
                marker(false),
                theme::dim().render("pin    "),
                status
            )
        });

        let strategy_line = (self.strategy != StrategyState::Off).then(|| {
            let status = match self.strategy {
                StrategyState::Selecting => format!("{} selecting", self.strategy_spinner.view()),
                StrategyState::Chosen(_) => {
                    let label = self.strategy_msg.as_deref().unwrap_or_default();
                    theme::good().render(&format!("\u{2713} strategy: {label}"))
                }
                StrategyState::Failed => {
                    let msg = self.strategy_msg.as_deref().unwrap_or("selection failed");
                    theme::bad().render(&format!("\u{2717} {msg}"))
                }
                StrategyState::Off => String::new(),
            };
            format!(
                "{}{}{}",
                marker(false),
                theme::dim().render("strategy "),
                status
            )
        });

        let preview_box = Style::new()
            .border(rounded_border())
            .border_foreground(theme::border(self.focus == Focus::Preview))
            .render(&self.preview.view());
        let preview_hdr = format!(
            "{}{}",
            marker(self.focus == Focus::Preview),
            theme::dim().render(&format!("{}.nix", host.name)),
        );

        let apply = self.button("apply", self.focus == Focus::Apply, self.apply_allowed());
        let cancel = self.button("cancel", self.focus == Focus::Cancel, true);
        let buttons = format!("{apply}  {cancel}");

        let hint = widgets::footer(&[
            ("tab", "move"),
            ("enter", "act"),
            ("\u{2190}/\u{2192}", "host"),
            ("space", "strict"),
            ("esc", "back"),
        ]);

        let mut lines = vec![
            theme::chip(" install "),
            host_line,
            pkg_line,
            strict_line,
            verify_line,
        ];
        if let Some(b) = build_line {
            lines.push(b);
        }
        if let Some(p) = pin_line {
            lines.push(p);
        }
        if let Some(s) = strategy_line {
            lines.push(s);
        }
        lines.extend([preview_hdr, preview_box, buttons, hint]);
        let refs: Vec<&str> = lines.iter().map(String::as_str).collect();
        join_vertical(LEFT, &refs)
    }

    fn verify_status(&self) -> String {
        let (r_txt, r) = match self.resolves {
            Resolve::Yes => ("\u{2713} resolves", theme::good()),
            Resolve::No => ("\u{2717} no such package", theme::bad()),
            Resolve::Skipped => ("\u{00b7} resolve skipped", theme::amber()),
        };
        if self.verifying {
            return format!("{} verifying", self.spinner.view());
        }
        let (p_txt, p) = match &self.parses {
            Parse::Ok => ("\u{2713} parses", theme::good()),
            Parse::Running => ("\u{2026} verifying", theme::amber()),
            Parse::Failed(_) => ("\u{2717} parse failed", theme::bad()),
            Parse::Skipped => ("\u{00b7} parse skipped", theme::amber()),
        };
        format!("{}  {}", r.render(r_txt), p.render(p_txt))
    }

    fn button(&self, label: &str, focused: bool, enabled: bool) -> String {
        let text = format!(" {label} ");
        if focused {
            theme::selected().render(&text)
        } else if enabled {
            theme::accent().render(&text)
        } else {
            theme::dim().render(&text)
        }
    }
}

fn marker(focused: bool) -> String {
    if focused {
        theme::accent().render("\u{25b8} ")
    } else {
        "  ".to_string()
    }
}

/// Extract the key code and modifiers if the message is a key press. `KeyCode`/`KeyModifiers`
/// are `Copy`, so we read them out and leave `msg` owned for forwarding to a widget.
fn key_of(msg: &Msg) -> Option<(KeyCode, KeyModifiers)> {
    msg.downcast_ref::<KeyMsg>().map(|k| (k.key, k.modifiers))
}

/// The nix verify, off the event-loop thread so the spinner keeps ticking. Resolves to a
/// `VerifyDone` carrying the token so a stale result (superseded verify) is discarded.
fn verify_cmd(seq: u64, pkg: String, host: HostInfo) -> Cmd {
    let verify = config().verify.clone();
    Box::pin(async move {
        match tokio::task::spawn_blocking(move || verify(&pkg, &host)).await {
            Ok(verified) => Some(Box::new(VerifyDone { seq, verified }) as Msg),
            Err(_) => None,
        }
    })
}

/// The package build, off the event-loop thread. Resolves to a `BuildDone` with the token so
/// a stale build (package edited again) is discarded. Only called when `config().build` is
/// `Some`.
fn build_cmd(seq: u64, pkg: String) -> Cmd {
    let build = config()
        .build
        .clone()
        .expect("build fn present when begin_build ran");
    Box::pin(async move {
        match tokio::task::spawn_blocking(move || build(&pkg)).await {
            Ok(outcome) => Some(Box::new(BuildDone { seq, outcome }) as Msg),
            Err(_) => None,
        }
    })
}

/// The pin resolve, off the event-loop thread. Resolves to a `PinDone` with the token so a
/// stale resolve (package edited again) is discarded. Only called when `config().pin` is
/// `Some` and a version was requested.
fn pin_cmd(seq: u64, pkg: String, version: String) -> Cmd {
    let pin = config()
        .pin
        .clone()
        .expect("pin fn present when begin_pin ran");
    Box::pin(async move {
        match tokio::task::spawn_blocking(move || pin(&pkg, &version)).await {
            Ok(outcome) => Some(Box::new(PinDone { seq, outcome }) as Msg),
            Err(_) => None,
        }
    })
}

/// The strategy selection, off the event-loop thread. Resolves to a `StrategyDone` with the
/// token so a stale selection (package/version edited again, or a host switch, before this one
/// returned) is discarded. Only called when `config().strategy` is `Some` and a pin has
/// resolved. `host` is forwarded rather than fixed at injection time; see `begin_strategy` for
/// why the decision is host-dependent.
fn strategy_cmd(seq: u64, pkg: String, rev: String, host: String) -> Cmd {
    let strategy = config()
        .strategy
        .clone()
        .expect("strategy fn present when begin_strategy ran");
    Box::pin(async move {
        match tokio::task::spawn_blocking(move || strategy(&pkg, &rev, &host)).await {
            Ok(outcome) => Some(Box::new(StrategyDone { seq, outcome }) as Msg),
            Err(_) => None,
        }
    })
}

/// Kick the spinner by emitting its first tick; the spinner's own `update` re-arms after that.
fn spin_start(tick: spinner::TickMsg) -> Cmd {
    Box::pin(async move { Some(Box::new(tick) as Msg) })
}

/// Batch together whichever of these commands are present, or `None` if all are absent.
/// Generalises the verify/build/pin fan-out at `enter` and on a package edit, each of which
/// may or may not have a command to run.
fn batch_all(cmds: Vec<Option<Cmd>>) -> Option<Cmd> {
    let mut present: Vec<Cmd> = cmds.into_iter().flatten().collect();
    match present.len() {
        0 => None,
        1 => present.pop(),
        _ => Some(command::batch(present)),
    }
}

/// A short form of a nixpkgs commit for the pin status line (first 7 chars, git-style).
fn short_rev(rev: &str) -> String {
    rev.chars().take(7).collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use knixl_lock::model::PinStrategy;
    use std::path::PathBuf;
    use std::sync::{Arc, Once};

    fn host(name: &str) -> HostInfo {
        HostInfo {
            name: name.into(),
            default: false,
            path: PathBuf::from(format!("hosts/{name}.kdl")),
        }
    }

    /// Sets the TUI's process-global config, once, with a `strategy` fn present. Most tests
    /// never actually drive the resulting `Cmd` to run it (`begin_strategy` only needs
    /// `config().strategy` to be `Some` to proceed past its guard, and instead supply their own
    /// `StrategyDone` outcome directly via `on_strategy_done`); the stub echoes the `host` arg
    /// back as `label` so a test that DOES drive the `Cmd` (proving `begin_strategy` forwards
    /// the currently selected host, #28 review fix) can tell which host it was called with.
    /// `CONFIG` is a `OnceLock`, so only the first caller across the whole test binary wins;
    /// every test that touches strategy selection calls this first, so it never matters which
    /// one runs first or whether it runs at all in isolation.
    fn with_strategy_config() {
        static ONCE: Once = Once::new();
        ONCE.call_once(|| {
            let _ = crate::tui::CONFIG.set(crate::tui::TuiConfig {
                root: PathBuf::new(),
                hosts: vec![],
                entry: Entry::Hub,
                verify: Arc::new(|_: &str, _: &HostInfo| Verified {
                    preview: String::new(),
                    resolves: Resolve::Skipped,
                    parses: Parse::Skipped,
                }),
                modules: vec![],
                build: None,
                pin: None,
                strategy: Some(Arc::new(|_pkg: &str, _rev: &str, host: &str| {
                    StrategyOutcome::Chosen {
                        strategy: PinStrategy::CommitMix,
                        label: host.to_string(),
                    }
                })),
            });
        });
    }

    /// A model built without the program's `config()` global, for testing the pure logic.
    fn model(hosts: usize) -> InstallModel {
        let mut pkg = textinput::new();
        pkg.set_value("ripgrep");
        InstallModel {
            pkg,
            hosts: (0..hosts).map(|i| host(&format!("h{i}"))).collect(),
            host_sel: 0,
            strict: false,
            no_abi_check: false,
            focus: Focus::Package,
            resolves: Resolve::Yes,
            parses: Parse::Ok,
            preview: viewport::new(40, 5),
            preview_text: String::new(),
            verifying: false,
            seq: 0,
            spinner: new_spinner(),
            build: BuildState::Off,
            build_spinner: new_spinner(),
            build_seq: 0,
            version: None,
            pin: PinState::Off,
            pin_spinner: new_spinner(),
            pin_seq: 0,
            pin_resolved: None,
            strategy: StrategyState::Off,
            strategy_spinner: new_spinner(),
            strategy_seq: 0,
            strategy_msg: None,
            dims: (40, 5),
        }
    }

    fn verified(resolves: Resolve, parses: Parse) -> Verified {
        Verified {
            preview: "environment.systemPackages = [ pkgs.ripgrep ];".into(),
            resolves,
            parses,
        }
    }

    #[test]
    fn focus_cycles_forward_and_back_wrapping() {
        let mut m = model(2);
        m.focus = Focus::Host;
        m.focus_next();
        assert_eq!(m.focus, Focus::Package);
        m.focus_prev();
        assert_eq!(m.focus, Focus::Host);
        m.focus_prev();
        assert_eq!(m.focus, Focus::Cancel, "wraps to the last control");
    }

    #[test]
    fn arrow_keys_move_the_focus_selector() {
        let mut m = model(2);
        assert_eq!(m.focus, Focus::Package);
        let key = |c| {
            Box::new(KeyMsg {
                key: c,
                modifiers: KeyModifiers::NONE,
            }) as Msg
        };
        m.update(key(KeyCode::Down), (80, 24));
        assert_eq!(m.focus, Focus::Strict, "down moves to the next control");
        m.update(key(KeyCode::Up), (80, 24));
        assert_eq!(m.focus, Focus::Package, "up moves back");
    }

    #[test]
    fn set_host_moves_and_clamps() {
        let mut m = model(3);
        assert!(m.set_host(2));
        assert_eq!(m.host_sel, 2);
        assert!(!m.set_host(2), "no change when already selected");
        assert!(!m.set_host(9), "out of range is refused");
        assert_eq!(m.host_sel, 2);
    }

    #[test]
    fn toggle_strict_flips() {
        let mut m = model(1);
        assert!(!m.strict);
        m.toggle_strict();
        assert!(m.strict);
    }

    #[test]
    fn apply_blocked_while_verifying_and_without_hosts() {
        let mut m = model(1);
        assert!(m.apply_allowed());
        m.verifying = true;
        assert!(!m.apply_allowed(), "in-flight verify blocks apply");
        let mut none = model(0);
        assert!(!none.apply_allowed(), "no hosts blocks apply");
        none.verifying = false;
    }

    #[test]
    fn apply_gating_matches_resolve_and_parse_under_strict() {
        let mut m = model(1);
        m.resolves = Resolve::No;
        assert!(!m.apply_allowed(), "unresolved never applies");

        m.resolves = Resolve::Skipped;
        m.parses = Parse::Skipped;
        m.strict = false;
        assert!(m.apply_allowed(), "skips are fine without --strict");
        m.strict = true;
        assert!(!m.apply_allowed(), "--strict rejects skipped checks");

        m.strict = false;
        m.parses = Parse::Failed("boom".into());
        assert!(!m.apply_allowed(), "a parse failure never applies");
    }

    #[test]
    fn verify_done_updates_status_and_preview() {
        let mut m = model(1);
        let seq = m.mark_verifying();
        assert!(m.verifying);
        m.on_verify_done(seq, verified(Resolve::No, Parse::Failed("nope".into())));
        assert!(!m.verifying);
        assert_eq!(m.resolves, Resolve::No);
        assert_eq!(m.parses, Parse::Failed("nope".into()));
        assert!(m.preview_text.contains("systemPackages"));
    }

    #[test]
    fn stale_verify_result_is_ignored() {
        let mut m = model(1);
        let first = m.mark_verifying();
        let _second = m.mark_verifying(); // supersedes the first
        m.on_verify_done(first, verified(Resolve::No, Parse::Ok));
        assert!(
            m.verifying,
            "the superseded result must not clear the in-flight state"
        );
        assert_eq!(m.resolves, Resolve::Yes, "stale resolve discarded");
    }

    #[test]
    fn resize_rebuilds_the_viewport_and_keeps_content() {
        let mut m = model(1);
        m.set_preview("a\nb\nc".into());
        m.resize((120, 40));
        assert_eq!(m.dims, view_dims((120, 40)));
        assert!(m.preview.view().contains('a'), "content survives a resize");
    }

    #[test]
    fn view_shows_controls_at_a_normal_size() {
        let m = model(2);
        let v = m.view((80, 24));
        assert!(v.contains("install"), "title");
        assert!(v.contains("ripgrep"), "package field");
        assert!(v.contains("h0"), "host");
        assert!(v.contains("apply"), "apply button");
        assert!(v.contains("cancel"), "cancel button");
    }

    #[test]
    fn view_shows_a_resize_hint_when_tiny() {
        let m = model(1);
        assert!(m.view((10, 5)).contains("resize"));
    }

    #[test]
    fn view_reports_no_hosts() {
        let m = model(0);
        assert!(m.view((80, 24)).contains("no hosts"));
    }

    #[test]
    fn build_gating_blocks_apply_until_it_succeeds() {
        let mut m = model(1);
        m.build = BuildState::Building; // requested + in flight
        assert!(!m.apply_allowed(), "in-flight build blocks apply");
        m.build = BuildState::Failed;
        assert!(!m.apply_allowed(), "failed build blocks apply");
        m.build = BuildState::Ok;
        assert!(m.apply_allowed(), "successful build allows apply");
    }

    #[test]
    fn build_skipped_gates_only_under_strict() {
        let mut m = model(1);
        m.build = BuildState::Skipped;
        m.strict = false;
        assert!(m.apply_allowed(), "skipped build is fine without --strict");
        m.strict = true;
        assert!(!m.apply_allowed(), "--strict rejects a skipped build");
    }

    #[test]
    fn build_off_does_not_affect_gating() {
        let mut m = model(1); // resolves Yes, parses Ok by default
        m.build = BuildState::Off;
        assert!(m.apply_allowed(), "no --build means the build never gates");
    }

    #[test]
    fn on_build_done_sets_state_and_ignores_stale() {
        let mut m = model(1);
        m.build = BuildState::Building;
        let seq = m.mark_building(); // bumps build_seq, sets Building
        m.on_build_done(seq, BuildOutcome::Ok);
        assert_eq!(m.build, BuildState::Ok);
        let stale = seq; // superseded
        m.mark_building();
        m.on_build_done(stale, BuildOutcome::Failed);
        assert_eq!(
            m.build,
            BuildState::Building,
            "stale build result discarded"
        );
    }

    #[test]
    fn pin_gating_blocks_apply_until_resolved() {
        let mut m = model(1);
        m.pin = PinState::Resolving;
        assert!(!m.apply_allowed(), "in-flight resolve blocks apply");
        m.pin = PinState::Failed;
        assert!(!m.apply_allowed(), "failed resolve blocks apply");
        m.pin = PinState::Resolved;
        assert!(m.apply_allowed(), "resolved allows apply");
    }

    #[test]
    fn pin_off_does_not_affect_gating() {
        let mut m = model(1);
        m.pin = PinState::Off;
        assert!(m.apply_allowed());
    }

    #[test]
    fn on_pin_done_ignores_stale() {
        let mut m = model(1);
        let seq = m.mark_resolving();
        m.mark_resolving();
        m.on_pin_done(seq, PinOutcome::Resolved("abc123".into()));
        assert_eq!(m.pin, PinState::Resolving, "stale resolve discarded");
    }

    #[test]
    fn begin_build_never_fires_for_a_versioned_install() {
        // No config() touch here: the version guard returns before `begin_build` reads it, so
        // this is safe to call even without `with_strategy_config`.
        let mut m = model(1);
        m.version = Some("1.2.3".into());
        assert!(
            m.begin_build().is_none(),
            "a versioned install gets strategy, not the ambient build"
        );
        assert_eq!(
            m.build,
            BuildState::Off,
            "build state is left untouched, never Building"
        );
    }

    #[test]
    fn versioned_pin_resolve_kicks_strategy_selection_instead_of_build() {
        with_strategy_config();
        let mut m = model(1);
        m.version = Some("1.2.3".into());
        m.build = BuildState::Off; // what `enter()` seeds for a versioned install
        let seq = m.mark_resolving();
        let msg = Box::new(PinDone {
            seq,
            outcome: PinOutcome::Resolved("deadbeef".into()),
        }) as Msg;
        let step = m.update(msg, (80, 24));

        assert_eq!(m.pin, PinState::Resolved);
        assert_eq!(
            m.build,
            BuildState::Off,
            "the ambient build never enters Building"
        );
        assert_eq!(
            m.strategy,
            StrategyState::Selecting,
            "the resolved pin kicks strategy selection"
        );
        assert!(step.cmd.is_some(), "strategy selection spawns a command");

        let strat_seq = m.strategy_seq;
        m.on_strategy_done(
            strat_seq,
            StrategyOutcome::Chosen {
                strategy: PinStrategy::CommitMix,
                label: "commit-mix".into(),
            },
        );
        assert_eq!(m.strategy, StrategyState::Chosen(PinStrategy::CommitMix));
    }

    #[test]
    fn stale_pin_resolve_does_not_kick_strategy_selection() {
        with_strategy_config();
        let mut m = model(1);
        m.version = Some("1.2.3".into());
        let first = m.mark_resolving();
        m.mark_resolving(); // supersedes the first
        let msg = Box::new(PinDone {
            seq: first,
            outcome: PinOutcome::Resolved("deadbeef".into()),
        }) as Msg;
        m.update(msg, (80, 24));
        assert_eq!(
            m.strategy,
            StrategyState::Off,
            "a stale pin resolve must not kick strategy selection"
        );
    }

    #[test]
    fn strategy_gating_blocks_apply_while_selecting_and_on_failure() {
        let mut m = model(1);
        m.strategy = StrategyState::Selecting;
        assert!(
            !m.apply_allowed(),
            "in-flight strategy selection blocks apply"
        );
        m.strategy = StrategyState::Failed;
        assert!(
            !m.apply_allowed(),
            "a failed strategy selection blocks apply"
        );
        m.strategy = StrategyState::Chosen(PinStrategy::CommitMix);
        assert!(m.apply_allowed(), "a chosen strategy allows apply");
    }

    #[test]
    fn strategy_off_does_not_affect_gating() {
        let mut m = model(1);
        m.strategy = StrategyState::Off;
        assert!(m.apply_allowed());
    }

    #[test]
    fn on_strategy_done_sets_state_and_ignores_stale() {
        let mut m = model(1);
        let seq = m.mark_selecting();
        m.on_strategy_done(
            seq,
            StrategyOutcome::Chosen {
                strategy: PinStrategy::Override,
                label: "override".into(),
            },
        );
        assert_eq!(m.strategy, StrategyState::Chosen(PinStrategy::Override));
        assert_eq!(m.strategy_msg.as_deref(), Some("override"));

        let stale = seq;
        m.mark_selecting();
        m.on_strategy_done(stale, StrategyOutcome::Failed("boom".into()));
        assert_eq!(
            m.strategy,
            StrategyState::Selecting,
            "stale strategy result discarded"
        );
    }

    #[test]
    fn on_strategy_done_sets_failed_with_message() {
        let mut m = model(1);
        let seq = m.mark_selecting();
        m.on_strategy_done(
            seq,
            StrategyOutcome::Failed("neither strategy builds".into()),
        );
        assert_eq!(m.strategy, StrategyState::Failed);
        assert_eq!(m.strategy_msg.as_deref(), Some("neither strategy builds"));
    }

    #[test]
    fn apply_carries_the_chosen_strategy_for_a_versioned_install() {
        let mut m = model(1);
        m.version = Some("1.2.3".into());
        m.pin = PinState::Resolved;
        m.pin_resolved = Some("deadbeef".into());
        m.strategy = StrategyState::Chosen(PinStrategy::Override);
        m.strategy_msg = Some("build ok".into());
        m.focus = Focus::Apply;
        let key = |c| {
            Box::new(KeyMsg {
                key: c,
                modifiers: KeyModifiers::NONE,
            }) as Msg
        };
        let step = m.update(key(KeyCode::Enter), (80, 24));
        match step.nav {
            Nav::Apply {
                strategy,
                version,
                strategy_reason,
                ..
            } => {
                assert_eq!(strategy, Some(PinStrategy::Override));
                assert_eq!(version, Some("1.2.3".to_string()));
                assert_eq!(
                    strategy_reason.as_deref(),
                    Some("build ok"),
                    "#28: the reason is carried alongside the strategy"
                );
            }
            _ => panic!("expected Nav::Apply"),
        }
    }

    #[test]
    fn apply_carries_no_strategy_for_an_unversioned_install() {
        let mut m = model(1); // version stays None, strategy stays Off
        m.focus = Focus::Apply;
        let key = |c| {
            Box::new(KeyMsg {
                key: c,
                modifiers: KeyModifiers::NONE,
            }) as Msg
        };
        let step = m.update(key(KeyCode::Enter), (80, 24));
        match step.nav {
            Nav::Apply {
                strategy,
                strategy_reason,
                ..
            } => {
                assert_eq!(strategy, None);
                assert_eq!(strategy_reason, None);
            }
            _ => panic!("expected Nav::Apply"),
        }
    }

    /// Host switch for a versioned install with an already-resolved pin must re-fire strategy
    /// selection (not just re-verify) and discard a stale `StrategyDone` from the host
    /// selected before the switch (see `begin_strategy` for why the decision is
    /// host-dependent).
    #[test]
    fn host_switch_refires_strategy_selection_for_a_resolved_pin() {
        with_strategy_config();
        let mut m = model(2);
        m.version = Some("1.2.3".into());
        m.pin = PinState::Resolved;
        m.pin_resolved = Some("deadbeef".into());
        m.focus = Focus::Host;

        // Seed a chosen strategy, as if it had already been decided for the initial host (h0).
        let stale_seq = m.mark_selecting();
        m.on_strategy_done(
            stale_seq,
            StrategyOutcome::Chosen {
                strategy: PinStrategy::CommitMix,
                label: "h0".into(),
            },
        );
        assert_eq!(m.strategy, StrategyState::Chosen(PinStrategy::CommitMix));

        let key = |c| {
            Box::new(KeyMsg {
                key: c,
                modifiers: KeyModifiers::NONE,
            }) as Msg
        };
        let step = m.update(key(KeyCode::Right), (80, 24));
        assert_eq!(m.host_sel, 1, "the host switched");
        assert_eq!(
            m.strategy,
            StrategyState::Selecting,
            "the switch re-fires strategy selection rather than leaving h0's stale decision"
        );
        assert_ne!(
            m.strategy_seq, stale_seq,
            "a fresh token supersedes h0's in-flight/chosen result"
        );
        assert!(
            step.cmd.is_some(),
            "verify and strategy selection are batched for the new host"
        );

        // A late `StrategyDone` carrying the old (stale) token must not clobber the fresh
        // selection under way for h1.
        m.on_strategy_done(
            stale_seq,
            StrategyOutcome::Chosen {
                strategy: PinStrategy::Override,
                label: "h0".into(),
            },
        );
        assert_eq!(
            m.strategy,
            StrategyState::Selecting,
            "the stale result from h0 is discarded"
        );
    }

    /// The injected `StrategyFn` must be called with the newly selected host's name, not the
    /// host selected when the pin resolved. Drives the real `Cmd` via `with_strategy_config`'s
    /// stub (which echoes `host` back as the outcome's `label`), so this proves the host
    /// argument is forwarded, not just that a re-fire was scheduled.
    #[test]
    fn begin_strategy_forwards_the_currently_selected_host() {
        with_strategy_config();
        let mut m = model(3); // hosts h0, h1, h2
        m.version = Some("1.2.3".into());
        m.pin = PinState::Resolved;
        m.pin_resolved = Some("deadbeef".into());

        assert!(m.set_host(2), "host selection changes to h2");
        let cmd = m
            .begin_strategy(m.pin_resolved.clone().unwrap())
            .expect("strategy fn is injected");

        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        let batch_msg = rt
            .block_on(cmd)
            .expect("the batched command resolves")
            .downcast::<bubbletea_rs::event::BatchCmdMsg>()
            .expect("begin_strategy batches the strategy call with a spinner tick");
        let mut outcome = None;
        for sub in batch_msg.0 {
            if let Some(msg) = rt.block_on(sub) {
                if let Ok(done) = msg.downcast::<StrategyDone>() {
                    outcome = Some(done.outcome);
                }
            }
        }
        match outcome.expect("the strategy command ran and produced a StrategyDone") {
            StrategyOutcome::Chosen { label, .. } => {
                assert_eq!(
                    label, "h2",
                    "the injected StrategyFn was called with the selected host, h2"
                );
            }
            StrategyOutcome::Failed(msg) => panic!("expected Chosen, got Failed({msg})"),
        }
    }
}