codewhale-tui 0.9.8

Terminal UI for open-source and open-weight coding models
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
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
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
//! `/fleet setup` — a progressive "set up your agent team" flow.
//!
//! Replaces the old six-column config matrix (#3791). Fleet is presented as an
//! agent team: the shortest valid path remains role → provider/model →
//! save/apply. From the Model step, `c` opens an optional, pure composition
//! advisory built only from configured routes; accept/edit/reject all return to
//! this same human-reviewed save path.
//! The review step shows resolved provider, model, auth/readiness, profile
//! availability, and overwrite consequences once before anything is written. Thinking defaults to
//! inherit and can be adjusted on the review step without an extra wizard
//! screen. "Save profile" persists the exact rendered TOML bytes.
//!
//! NOTE (audit #7 / #3167): the role/model taxonomy and copy below are
//! intentionally English for now; #3167 reworks this into an interactive
//! provider/model picker that will churn most of this text. The command entry
//! (`CmdFleetDescription`) is already localized.

use std::borrow::Cow;
use std::cell::RefCell;
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

use codewhale_workflow::fleet_composition::{
    CompositionError, CompositionRole, ConfiguredModel, FleetCompositionProposal,
    FleetCompositionRequest, RatificationState, RoleSuggestion,
};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
use ratatui::{
    buffer::Buffer,
    layout::{Constraint, Direction, Layout, Rect},
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Padding, Paragraph, Widget, Wrap},
};

use crate::config::Config;
use crate::fleet::profile::FleetProfileScope;
use crate::localization::{MessageId, tr};
use crate::palette;
use crate::tui::app::App;
use crate::tui::menu_style;
use crate::tui::views::{
    ActionHint, ModalKind, ModalView, ViewAction, ViewEvent, centered_modal_area,
    render_modal_footer_with_gutter, render_modal_surface, truncate_view_text,
};

const PROFILE_DIR: &str = ".codewhale/agents";

/// A selectable choice in a wizard step: a short identifier `label`, a one-line
/// `summary`, and a longer `description` shown (wrapped) in the detail pane.
#[derive(Clone)]
struct Choice {
    label: Cow<'static, str>,
    summary: Cow<'static, str>,
    description: Cow<'static, str>,
}

const CHOICE_LIST_WIDTH: u16 = 22;
const CHOICE_DETAIL_MIN_WIDTH: u16 = 58;
const CHOICE_TWO_COLUMN_MIN_WIDTH: u16 = CHOICE_LIST_WIDTH + CHOICE_DETAIL_MIN_WIDTH;

/// Agent-team roles. `label` doubles as the profile `role_hint` and file stem,
/// so these strings are part of the generated-profile contract.
const ROLES: [Choice; 9] = [
    Choice {
        label: Cow::Borrowed("manager"),
        summary: Cow::Borrowed("Plan & split queued work"),
        description: Cow::Borrowed(
            "Coordinates the Fleet run: plans the work, splits it into bounded tasks, and dispatches workers.",
        ),
    },
    Choice {
        label: Cow::Borrowed("scout"),
        summary: Cow::Borrowed("Read-first research"),
        description: Cow::Borrowed(
            "Research and evidence gathering. Reads and summarizes before anything is written.",
        ),
    },
    Choice {
        label: Cow::Borrowed("builder"),
        summary: Cow::Borrowed("Implements bounded changes"),
        description: Cow::Borrowed(
            "Implements changes strictly inside its assigned task scope; writes only what the slice needs.",
        ),
    },
    Choice {
        label: Cow::Borrowed("reviewer"),
        summary: Cow::Borrowed("Read-only review"),
        description: Cow::Borrowed(
            "Checks regressions, tests, and diffs. Read-only — it never writes.",
        ),
    },
    Choice {
        label: Cow::Borrowed("verifier"),
        summary: Cow::Borrowed("Runs focused validation"),
        description: Cow::Borrowed(
            "Runs targeted validation and reports receipts back to the orchestrator.",
        ),
    },
    Choice {
        label: Cow::Borrowed("consultant"),
        summary: Cow::Borrowed("Read-only second opinion"),
        description: Cow::Borrowed(
            "Short-lived, high-reasoning counsel for difficult decisions and overlooked risks. Read-only and shell-less.",
        ),
    },
    Choice {
        label: Cow::Borrowed("synthesizer"),
        summary: Cow::Borrowed("Reduce receipts to handoff"),
        description: Cow::Borrowed(
            "Turns worker receipts into bounded handoff state instead of raw transcript replay.",
        ),
    },
    Choice {
        label: Cow::Borrowed("general"),
        summary: Cow::Borrowed("General-purpose worker"),
        description: Cow::Borrowed(
            "A flexible worker with no specialized posture — use it when the task doesn't fit a named role.",
        ),
    },
    Choice {
        label: Cow::Borrowed("custom"),
        summary: Cow::Borrowed("Author a profile by hand"),
        description: Cow::Borrowed(
            "Define the posture yourself in a workspace agent TOML profile under .codewhale/agents/.",
        ),
    },
];

/// The `inherit` row shown first in the Model step (#3167). Concrete provider
/// models follow it, built per-run from EVERY configured provider's catalog
/// (#4093), so the user picks a real route — including cross-provider ones —
/// instead of an abstract class or only the active provider's models.
const MODEL_INHERIT: Choice = Choice {
    label: Cow::Borrowed("inherit"),
    summary: Cow::Borrowed("Same model as now"),
    description: Cow::Borrowed(
        "Use the operator's current route — provider, model, and reasoning included. Recommended default.",
    ),
};

const THINKING_CHOICES: &[Choice] = &[
    Choice {
        label: Cow::Borrowed("inherit"),
        summary: Cow::Borrowed("Same thinking as now"),
        description: Cow::Borrowed(
            "Reuse the operator's current reasoning setting for this worker. Recommended default.",
        ),
    },
    Choice {
        label: Cow::Borrowed("off"),
        summary: Cow::Borrowed("No extra thinking"),
        description: Cow::Borrowed(
            "Use for narrow lookups or mechanical work where speed matters.",
        ),
    },
    Choice {
        label: Cow::Borrowed("low"),
        summary: Cow::Borrowed("Small thinking budget"),
        description: Cow::Borrowed(
            "Use for bounded checks that still benefit from light reasoning.",
        ),
    },
    Choice {
        label: Cow::Borrowed("medium"),
        summary: Cow::Borrowed("Balanced thinking budget"),
        description: Cow::Borrowed("Use for normal implementation and review work."),
    },
    Choice {
        label: Cow::Borrowed("high"),
        summary: Cow::Borrowed("Deep thinking budget"),
        description: Cow::Borrowed("Use for harder design, debugging, and integration tasks."),
    },
    Choice {
        label: Cow::Borrowed("max"),
        summary: Cow::Borrowed("Maximum thinking budget"),
        description: Cow::Borrowed("Use for hard release, security, and root-cause work."),
    },
    Choice {
        label: Cow::Borrowed("auto"),
        summary: Cow::Borrowed("Let Codewhale choose"),
        description: Cow::Borrowed("Choose a thinking tier from the worker prompt at runtime."),
    },
];

#[derive(Debug, Clone)]
pub struct FleetSetupSnapshot {
    workspace: PathBuf,
    locale: crate::localization::Locale,
    /// Whether the active provider has a key or local runtime — gates the
    /// model-draft offer, mirroring the constitution card's `provider_ready`.
    provider_ready: bool,
    provider: String,
    model: String,
    reasoning: String,
    subagents_enabled: bool,
    max_subagents: usize,
    launch_concurrency: usize,
    max_admitted: usize,
    subagent_spawn_depth: u32,
    fleet_spawn_depth: u32,
    api_timeout_secs: u64,
    heartbeat_timeout_secs: u64,
    /// Lowercased roster member ids with their origin labels (built-in /
    /// config / project), so the wizard can say when a chosen role would
    /// override an existing roster member.
    roster_members: Vec<(String, String)>,
    /// Saved (file-backed) roster members keyed by lowercased id: where the
    /// file lives and the route it pins, so reopening a saved profile from
    /// `/fleet` starts from what is on disk instead of the wizard defaults.
    roster_details: Vec<RosterMemberDetail>,
    /// Whether project-scope profiles are enabled for this launch
    /// (`--no-project-config` disables them). When false, "This project" is
    /// offered disabled with that reason instead of writing a file nothing
    /// will load.
    project_profiles_enabled: bool,
    /// Resolved personal profile directory (`$CODEWHALE_HOME/agents`), or the
    /// reason it could not be resolved. Captured once at snapshot time so the
    /// wizard never re-reads the environment while painting and tests can
    /// point it at a temp dir.
    personal_profile_dir: Result<PathBuf, String>,
    /// `(exact provider id, model id, readiness label, selectable)` routes for a worker,
    /// drawn from ALL configured providers — not only the active one (#4093).
    /// Shown after `inherit` in the Model step so a Fleet worker can be pinned
    /// to a route independent of the parent/current provider. The provider id
    /// is a canonical built-in id or the exact named custom table key, not a
    /// display label — see [`cross_provider_model_routes`].
    available_models: Vec<(
        String,
        String,
        crate::provider_readiness::ResolvedProviderReadiness,
    )>,
}

/// A file-backed roster member as it exists on disk (project or personal).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RosterMemberDetail {
    id: String,
    scope: FleetProfileScope,
    source: PathBuf,
    provider: Option<String>,
    model: Option<String>,
    reasoning_effort: Option<String>,
}

impl FleetSetupSnapshot {
    #[must_use]
    pub fn from_app(app: &App, config: &Config) -> Self {
        let provider = app.effective_route_identity_display().0;
        let model = if app.auto_model {
            app.last_effective_model
                .as_deref()
                .map(|effective| format!("auto -> {effective}"))
                .unwrap_or_else(|| "auto".to_string())
        } else {
            app.model.clone()
        };
        let fleet_spawn_depth = config
            .fleet
            .as_ref()
            .map(|fleet| fleet.exec.max_spawn_depth)
            .unwrap_or_else(|| codewhale_config::FleetExecConfig::default().max_spawn_depth)
            .min(codewhale_config::MAX_SPAWN_DEPTH_CEILING);
        let roster =
            crate::fleet::roster::FleetRoster::load(&config.fleet_config(), &app.workspace);
        let roster_members = roster
            .members()
            .iter()
            .map(|member| (member.id.to_lowercase(), member.origin.to_string()))
            .collect();
        let roster_details = roster
            .members()
            .iter()
            .filter_map(|member| {
                let scope = match member.origin {
                    crate::fleet::roster::ProfileOrigin::Workspace => FleetProfileScope::Project,
                    crate::fleet::roster::ProfileOrigin::Personal => FleetProfileScope::Personal,
                    _ => return None,
                };
                Some(RosterMemberDetail {
                    id: member.id.to_lowercase(),
                    scope,
                    source: member.source.clone(),
                    provider: member.profile.provider.clone(),
                    model: member.profile.model.clone(),
                    reasoning_effort: member.profile.reasoning_effort.clone(),
                })
            })
            .collect();
        let active_route_readiness = crate::provider_readiness::resolve_for_model(
            config,
            app.api_provider,
            if app.auto_model { "auto" } else { &app.model },
            &app.provider_health,
        );

        Self {
            workspace: app.workspace.clone(),
            locale: app.ui_locale,
            provider_ready: active_route_readiness.can_attempt(),
            provider,
            model,
            reasoning: app.reasoning_effort_display_label(),
            subagents_enabled: config.subagents_enabled_for_provider(app.api_provider),
            max_subagents: config.max_subagents_for_provider(app.api_provider),
            launch_concurrency: config.launch_concurrency_for_provider(app.api_provider),
            max_admitted: config.max_admitted_subagents_for_provider(app.api_provider),
            subagent_spawn_depth: config.subagent_max_spawn_depth_for_provider(app.api_provider),
            fleet_spawn_depth,
            api_timeout_secs: config.subagent_api_timeout_secs_for_provider(app.api_provider),
            heartbeat_timeout_secs: config
                .subagent_heartbeat_timeout_secs_for_provider(app.api_provider),
            roster_members,
            roster_details,
            project_profiles_enabled: crate::fleet::roster::project_agent_profiles_enabled(),
            personal_profile_dir: crate::fleet::profile::personal_agent_profile_dir()
                .map_err(|err| format!("{err:#}")),
            available_models: cross_provider_model_routes(
                config,
                app.api_provider,
                &app.provider_health,
            ),
        }
    }
}

/// Build the `(canonical provider id, model id)` pairs selectable for a worker
/// from EVERY configured provider — not only the active one (#4093). Fleet
/// workers can be pinned to a route independent of the parent/current provider,
/// so the Model step must offer the same cross-provider catalog the model
/// picker does, instead of the active provider's models alone.
///
/// The provider id here is the exact non-secret configured route key. Built-ins
/// use their canonical id; named custom routes keep their table key so saved
/// Fleet profiles can rebuild the same child client.
/// Callers derive a human-readable label from it for UI text.
pub(super) fn cross_provider_model_routes(
    config: &Config,
    active: crate::config::ApiProvider,
    health: &crate::provider_readiness::ProviderReadinessSnapshot,
) -> Vec<(
    String,
    String,
    crate::provider_readiness::ResolvedProviderReadiness,
)> {
    let mut routes = Vec::new();
    let configured = crate::provider_lake::configured_providers(config, active);
    let legacy_custom_configured = configured.contains(&crate::config::ApiProvider::Custom);
    for provider in configured
        .into_iter()
        .filter(|provider| *provider != crate::config::ApiProvider::Custom)
    {
        append_provider_model_routes(
            &mut routes,
            config,
            active,
            provider,
            provider.as_str(),
            health,
        );
    }

    // `ApiProvider::Custom` is an enum class, not a route identity. Enumerate
    // every named custom table so a Fleet on custom A can still pin a worker
    // to custom B and persist B's exact client route.
    let mut custom_names = config
        .providers
        .as_ref()
        .map(|providers| providers.custom.keys().cloned().collect::<Vec<_>>())
        .unwrap_or_default();
    custom_names.sort();
    if custom_names.is_empty() && legacy_custom_configured {
        append_provider_model_routes(
            &mut routes,
            config,
            active,
            crate::config::ApiProvider::Custom,
            crate::config::ApiProvider::Custom.as_str(),
            health,
        );
    }
    for name in custom_names {
        let mut named_config = config.clone();
        named_config.provider = Some(name.clone());
        append_provider_model_routes(
            &mut routes,
            &named_config,
            active,
            crate::config::ApiProvider::Custom,
            &name,
            health,
        );
    }
    routes
}

fn append_provider_model_routes(
    routes: &mut Vec<(
        String,
        String,
        crate::provider_readiness::ResolvedProviderReadiness,
    )>,
    config: &Config,
    active: crate::config::ApiProvider,
    provider: crate::config::ApiProvider,
    provider_id: &str,
    health: &crate::provider_readiness::ProviderReadinessSnapshot,
) {
    // The bundled lake is only the baseline. A user may pin a valid
    // provider-specific preview or private deployment outside that catalog.
    let mut models = Vec::new();
    if let Some(model) = config
        .provider_config_for(provider)
        .and_then(|entry| entry.model.as_deref())
    {
        push_unique_model(&mut models, model);
    }
    if provider == active {
        let active_model = config.default_model();
        if !active_model.trim().eq_ignore_ascii_case("auto") {
            push_unique_model(&mut models, &active_model);
        }
    }
    for model in crate::provider_lake::models_for_provider(config, active, provider) {
        push_unique_model(&mut models, &model);
    }

    for model in models {
        let readiness =
            crate::provider_readiness::resolve_for_model(config, provider, &model, health);
        routes.push((provider_id.to_string(), model, readiness));
    }
}

fn push_unique_model(models: &mut Vec<String>, model: &str) {
    let model = model.trim();
    if !model.is_empty()
        && !models
            .iter()
            .any(|existing| existing.eq_ignore_ascii_case(model))
    {
        models.push(model.to_string());
    }
}

/// Human-readable label for a built-in provider id, falling back to an exact
/// named custom id verbatim.
pub(super) fn provider_display_label(provider_id: &str) -> String {
    crate::config::ApiProvider::parse(provider_id)
        .filter(|provider| provider.as_str() == provider_id)
        .map(|provider| provider.display_name().to_string())
        .unwrap_or_else(|| provider_id.to_string())
}

/// Which focused screen of the wizard is showing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Step {
    /// Pick the team role.
    Role,
    /// Review an inert role-to-model suggestion built from configured routes.
    Composition,
    /// Pick the model-routing class.
    Model,
    /// Choose where the profile is saved (this project or personal).
    Destination,
    /// Review the full posture and save.
    Review,
}

/// The two save destinations, in the order the Destination step lists them.
const DESTINATION_ORDER: [FleetProfileScope; 2] =
    [FleetProfileScope::Project, FleetProfileScope::Personal];

/// Resolved facts about one save destination, computed off the paint path
/// (on entering the Destination/Review steps and when the role changes).
#[derive(Debug, Clone, PartialEq, Eq)]
struct DestinationStatus {
    scope: FleetProfileScope,
    /// `None` when the destination can be written; otherwise the localized
    /// reason it is offered disabled.
    unavailable_reason: Option<String>,
    /// Exact file that saving would write.
    target: PathBuf,
    /// Whether `target` already exists (saving would replace it).
    target_exists: bool,
}

/// Which control on the Review step owns keyboard focus.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ReviewFocus {
    Save,
    ChangeDestination,
    Back,
}

impl ReviewFocus {
    const ORDER: [Self; 3] = [Self::Save, Self::ChangeDestination, Self::Back];

    fn next(self) -> Self {
        let idx = Self::ORDER.iter().position(|f| *f == self).unwrap_or(0);
        Self::ORDER[(idx + 1) % Self::ORDER.len()]
    }

    fn prev(self) -> Self {
        let idx = Self::ORDER.iter().position(|f| *f == self).unwrap_or(0);
        Self::ORDER[(idx + Self::ORDER.len() - 1) % Self::ORDER.len()]
    }
}

/// The workflow-owned request and its validated, deliberately unratified
/// proposal. Keeping the request beside the proposal lets the UI re-run the
/// workflow validator at the exact point where a human accepts a suggestion.
#[derive(Debug, Clone)]
struct CompositionAdvisory {
    request: FleetCompositionRequest,
    proposal: FleetCompositionProposal,
}

impl CompositionAdvisory {
    fn validated_route_for_role(
        &self,
        role: &str,
    ) -> Result<Option<(String, String)>, CompositionError> {
        let proposal =
            FleetCompositionProposal::validate(&self.request, self.proposal.suggestions.clone())?;
        Ok(proposal
            .suggestions
            .iter()
            .find(|suggestion| suggestion.role.eq_ignore_ascii_case(role))
            .map(|suggestion| (suggestion.provider.clone(), suggestion.model.clone())))
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CompositionDecision {
    Pending,
    Accepted,
    Edited,
    Rejected,
}

/// Per-row Fleet Model step interaction state.
///
/// Replaces the old `model_selectable: Vec<bool>` so a dormant external-consent
/// route can require explicit activation (#v092-fleet-routes-fix) while
/// genuinely unconfigured routes stay blocked with a reason.
#[derive(Debug, Clone, PartialEq, Eq)]
enum FleetModelRowState {
    Ready,
    NeedsActivation,
    Blocked { reason: String },
}

impl FleetModelRowState {
    fn from_readiness(readiness: &crate::provider_readiness::ResolvedProviderReadiness) -> Self {
        if readiness.requires_explicit_activation() {
            return Self::NeedsActivation;
        }
        if let Some(reason) = readiness.blocked_reason() {
            return Self::Blocked {
                reason: reason.into_owned(),
            };
        }
        if readiness.can_attempt() {
            return Self::Ready;
        }
        Self::Blocked {
            reason: readiness
                .blocked_reason()
                .map(std::borrow::Cow::into_owned)
                .unwrap_or_else(|| readiness.label().into_owned()),
        }
    }
}

/// Build the setup-time advisory from routes the wizard already resolved from
/// the operator's configured providers. The adapter is intentionally pure: it
/// sorts and de-duplicates the redacted provider/model pairs, assigns them to
/// the built-in roles in stable round-robin order, then asks the workflow
/// schema to validate every assignment against that exact pool.
fn deterministic_composition_advisory(
    available_models: &[(
        String,
        String,
        crate::provider_readiness::ResolvedProviderReadiness,
    )],
) -> Option<CompositionAdvisory> {
    let mut seen = BTreeSet::new();
    let mut pool: Vec<ConfiguredModel> = available_models
        .iter()
        // Do not recommend a route the Model step would refuse or require the
        // operator to activate first. Such rows remain available for explicit
        // human selection in the existing picker.
        .filter(|(_, _, readiness)| {
            FleetModelRowState::from_readiness(readiness) == FleetModelRowState::Ready
        })
        .filter_map(|(provider, model, _)| {
            let key = (provider.clone(), model.clone());
            seen.insert(key.clone())
                .then(|| ConfiguredModel::new(key.0, key.1, None))
        })
        .collect();
    pool.sort_by(|left, right| {
        left.provider
            .cmp(&right.provider)
            .then_with(|| left.model.cmp(&right.model))
    });

    let roles: Vec<CompositionRole> = ROLES
        .iter()
        // `custom` is an invitation to author a posture, not a semantic Fleet
        // role, so it stays on the manual Model path.
        .filter(|role| role.label != "custom")
        .map(|role| CompositionRole::new(role.label.to_string(), Some(&role.summary)))
        .collect();
    let request = FleetCompositionRequest::new(pool, roles).ok()?;
    let suggestions = request
        .roles
        .iter()
        .enumerate()
        .map(|(idx, role)| {
            let configured = &request.pool[idx % request.pool.len()];
            RoleSuggestion {
                role: role.role.clone(),
                provider: configured.provider.clone(),
                model: configured.model.clone(),
                reason: Some(
                    "Stable round-robin assignment from the configured model pool.".to_string(),
                ),
            }
        })
        .collect();
    let proposal = FleetCompositionProposal::validate(&request, suggestions).ok()?;
    Some(CompositionAdvisory { request, proposal })
}

pub struct FleetSetupView {
    snapshot: FleetSetupSnapshot,
    step: Step,
    role_idx: usize,
    model_idx: usize,
    thinking_idx: usize,
    profile_scope: FleetProfileScope,
    /// Whether the user has explicitly chosen (or a saved profile supplied) the
    /// save destination. Until then the header says the choice is still ahead
    /// instead of silently presenting a default as a decision.
    scope_decided: bool,
    /// Highlighted row on the Destination step (index into DESTINATION_ORDER).
    destination_idx: usize,
    /// Resolved destination facts for both scopes. Recomputed on entry to the
    /// Destination/Review steps and when the role (file name) changes; the
    /// draw path never touches the filesystem (#3908).
    destinations: Option<[DestinationStatus; 2]>,
    /// Focused control on the Review step (Tab/Shift-Tab/←/→ move it).
    review_focus: ReviewFocus,
    /// Replacing an existing file needs a second Enter on the save control.
    replace_armed: bool,
    /// One-line inline notice (e.g. why a model row cannot be selected).
    /// Cleared on the next navigation key.
    notice: Option<String>,
    review_scroll: usize,
    /// A model-drafted profile awaiting save (already sanitized and
    /// bounded by the untrusted gate). Cleared when the selection changes so
    /// a stale draft can never be saved against fresh answers.
    model_draft: Option<Box<crate::fleet::profile::FleetProfileDraft>>,
    /// Exact rendered TOML preview for `model_draft` (header comment + the
    /// deterministic bytes saving would persist). Rendered inline on the
    /// Review step — never in a separate pager (#4093): a standalone pager
    /// view owns its own `g`/`G` scroll bindings, which silently swallowed
    /// the save keypress and left users unable to save without first
    /// pressing Esc. Keeping the preview and the save control in the same
    /// view means the footer's `g`/Enter hints are never a lie.
    model_draft_preview: Option<String>,
    /// Model-step rows: `inherit` followed by one row per concrete model from
    /// every configured provider (#4093).
    model_choices: Vec<Choice>,
    /// `(provider, model)` aligned with `model_choices`. Index 0 is `inherit`
    /// (the active route); later rows pin a concrete, possibly cross-provider
    /// route. Drives the review/copy so a pinned route names its own provider.
    model_routes: Vec<(String, String)>,
    /// Interaction state for each aligned Model row. Distinguishes ready rows,
    /// dormant external-consent rows that need explicit activation, and
    /// genuinely blocked rows with a short reason.
    model_row_states: Vec<FleetModelRowState>,
    /// Typed filter for the Model step (#4639): substring match over
    /// provider and model id, so provider-heavy catalogs (e.g. OpenRouter)
    /// stay navigable without a provider→model drill-down.
    model_query: String,
    /// Whether the Model step's filter input is capturing keystrokes (`/`
    /// toggles it; Enter keeps the filter, Esc clears it).
    model_filter_active: bool,
    /// Pure workflow-schema proposal shown before the Model picker. It has no
    /// save, spawn, launch, or snapshot capability.
    composition: Option<CompositionAdvisory>,
    composition_decision: CompositionDecision,
    /// Selectable rows registered by the latest render. Keeping mouse geometry
    /// in the view gives the Fleet walkthrough the same row ownership as its
    /// keyboard path without coupling the host to this modal's layout.
    row_hitboxes: RefCell<Vec<(Rect, usize)>>,
}

impl FleetSetupView {
    /// Refresh row states from a freshly built snapshot while preserving the
    /// user's current selection position and draft state. Used after the host
    /// validates a dormant external-consent route so the same row becomes
    /// Ready without closing and reopening the modal.
    pub fn refresh_from_snapshot(&mut self, snapshot: FleetSetupSnapshot) {
        let old_step = self.step;
        let old_role_idx = self.role_idx;
        let old_model_idx = self.model_idx;
        let old_thinking_idx = self.thinking_idx;
        let old_profile_scope = self.profile_scope;
        let old_scope_decided = self.scope_decided;
        let old_destination_idx = self.destination_idx;
        let old_review_focus = self.review_focus;
        let old_model_query = self.model_query.clone();
        let old_model_filter_active = self.model_filter_active;
        let old_review_scroll = self.review_scroll;
        let old_model_draft = self.model_draft.clone();
        let old_model_draft_preview = self.model_draft_preview.clone();

        *self = Self::from_snapshot(snapshot);

        self.step = old_step;
        self.role_idx = old_role_idx;
        self.model_idx = old_model_idx.min(self.filtered_model_indices().len().saturating_sub(1));
        self.thinking_idx = old_thinking_idx;
        self.profile_scope = old_profile_scope;
        self.scope_decided = old_scope_decided;
        self.destination_idx = old_destination_idx;
        self.review_focus = old_review_focus;
        self.model_query = old_model_query;
        self.model_filter_active = old_model_filter_active;
        self.review_scroll = old_review_scroll;
        self.model_draft = old_model_draft;
        self.model_draft_preview = old_model_draft_preview;
        if self.step == Step::Composition && !self.has_composition_for_selected_role() {
            self.step = Step::Model;
        }
        if matches!(self.step, Step::Destination | Step::Review) {
            self.refresh_destinations();
        }
    }

    #[must_use]
    pub fn new(app: &App, config: &Config) -> Self {
        Self::from_snapshot(FleetSetupSnapshot::from_app(app, config))
    }

    /// Open setup for a role the operator already selected in `/fleet`.
    /// Unknown/custom roster roles map to the explicit custom authoring row;
    /// Left or Esc still exposes Role so the carried choice is never sticky.
    #[must_use]
    pub fn new_for_role(app: &App, config: &Config, role: &str) -> Self {
        Self::from_snapshot_for_role(FleetSetupSnapshot::from_app(app, config), role)
    }

    fn from_snapshot_for_role(snapshot: FleetSetupSnapshot, role: &str) -> Self {
        let mut view = Self::from_snapshot(snapshot);
        view.role_idx = ROLES
            .iter()
            .position(|choice| choice.label.eq_ignore_ascii_case(role.trim()))
            .unwrap_or(ROLES.len() - 1);
        view.step = Step::Model;
        // Reopening a SAVED member edits what is on disk: preselect its route,
        // thinking tier, and — most importantly — the scope it was saved in,
        // so "edit" can never quietly land in the other destination.
        let role_id = role.trim().to_ascii_lowercase();
        let saved = view
            .snapshot
            .roster_details
            .iter()
            .find(|detail| detail.id == role_id)
            .cloned();
        if let Some(saved) = saved {
            view.profile_scope = saved.scope;
            view.scope_decided = true;
            view.destination_idx = DESTINATION_ORDER
                .iter()
                .position(|scope| *scope == saved.scope)
                .unwrap_or(0);
            if let Some(model) = saved.model.as_deref() {
                let idx = view.model_routes.iter().position(|(provider, candidate)| {
                    candidate == model
                        && saved
                            .provider
                            .as_deref()
                            .is_none_or(|p| p.eq_ignore_ascii_case(provider))
                });
                if let Some(idx) = idx {
                    view.model_idx = idx;
                }
            }
            if let Some(effort) = saved.reasoning_effort.as_deref()
                && let Some(idx) = THINKING_CHOICES
                    .iter()
                    .position(|choice| choice.label.eq_ignore_ascii_case(effort))
            {
                view.thinking_idx = idx;
            }
        }
        view
    }

    fn from_snapshot(snapshot: FleetSetupSnapshot) -> Self {
        let mut model_choices = vec![MODEL_INHERIT];
        // `inherit` (index 0) maps to the active route; every later row pins a
        // concrete (provider, model) drawn from all configured providers.
        let mut model_routes = vec![(snapshot.provider.clone(), snapshot.model.clone())];
        let mut model_row_states = vec![FleetModelRowState::Ready];
        for (provider, model, readiness) in &snapshot.available_models {
            let provider_label = provider_display_label(provider);
            let readiness_summary = readiness.detail().map_or_else(
                || readiness.label().into_owned(),
                |detail| format!("{}: {detail}", readiness.label()),
            );
            // Capability badges from the existing catalog/registry owners
            // (#5038): shown in the word-wrapped detail pane so the picker
            // list stays narrow-terminal friendly. Unknown models honestly
            // omit the sentence instead of blocking selection.
            let capability_note = crate::fleet::capability_badges::resolve_route_capability_badges(
                Some(provider),
                model,
            )
            .map(|badges| format!(" Capabilities: {}.", badges.summary()))
            .unwrap_or_default();
            model_choices.push(Choice {
                label: Cow::Owned(model.clone()),
                summary: Cow::Owned(format!(
                    "Pin this model ({provider_label}) · {readiness_summary}"
                )),
                description: Cow::Owned(format!(
                    "Route this worker to {model} on {provider_label} instead of inheriting the session route.{capability_note}"
                )),
            });
            // Canonical provider id (not the display label above) — this is
            // what gets persisted into the saved profile (#4093).
            model_routes.push((provider.clone(), model.clone()));
            model_row_states.push(FleetModelRowState::from_readiness(readiness));
        }
        let composition = deterministic_composition_advisory(&snapshot.available_models);
        Self {
            snapshot,
            step: Step::Role,
            role_idx: 0,
            model_idx: 0,
            thinking_idx: 0,
            // Profiles authored for a person should follow that person across
            // repositories by default. Project scope remains one `s` away and
            // keeps higher roster precedence when explicitly selected.
            profile_scope: FleetProfileScope::Personal,
            scope_decided: false,
            destination_idx: DESTINATION_ORDER.len() - 1,
            destinations: None,
            review_focus: ReviewFocus::Save,
            replace_armed: false,
            notice: None,
            review_scroll: 0,
            model_draft: None,
            model_draft_preview: None,
            model_choices,
            model_routes,
            model_row_states,
            model_query: String::new(),
            model_filter_active: false,
            composition,
            composition_decision: CompositionDecision::Pending,
            row_hitboxes: RefCell::new(Vec::new()),
        }
    }

    /// Install a sanitized, bounded model draft. The exact TOML preview
    /// (returned here for the caller's status message) renders inline on the
    /// Review step — not in a separate pager — so the footer's `g`/Enter
    /// ratify hints stay true the instant the draft lands (#4093).
    pub fn install_model_draft(
        &mut self,
        mut draft: Box<crate::fleet::profile::FleetProfileDraft>,
        model_label: String,
        picked_route: Option<(String, String)>,
        reasoning_effort: Option<String>,
    ) -> (String, String) {
        // Re-inject the route the operator picked at `m`-press time (#4093). A
        // model draft comes from `from_untrusted_json`, which hard-sets
        // `provider: None` and echoes whatever `model` the model happened to
        // emit — so ratifying it verbatim would drop a concrete cross-provider
        // pick and persist the ambiguous, provider-scoped profile #4093 exists
        // to prevent. Pinning BOTH fields from the CARRIED route keeps the route
        // the user actually chose (the model only authored the prose), and is
        // immune to the selection changing while the async draft is in flight.
        // `inherit` (a `None` route) leaves `model`/`provider` untouched,
        // matching the deterministic Enter path.
        if let Some((provider, model)) = picked_route {
            draft.model = Some(model);
            draft.provider = Some(provider);
        }
        draft.reasoning_effort = reasoning_effort;
        let (title, header) = (
            tr(self.snapshot.locale, MessageId::FleetDraftTitle)
                .replace("{model_label}", &model_label),
            tr(self.snapshot.locale, MessageId::FleetDraftHeader)
                .replace("{name}", &draft.file_name())
                .replace("{model_label}", &model_label),
        );
        let content = format!(
            "{}{}",
            self.scope_preview_header(header),
            draft.render_toml()
        );
        self.model_draft = Some(draft);
        self.model_draft_preview = Some(content.clone());
        self.review_scroll = 0;
        (title, content)
    }

    /// The planner role chosen (drives the profile file name and `role_hint`).
    fn selected_role(&self) -> String {
        ROLES[self.role_idx.min(ROLES.len() - 1)].label.to_string()
    }

    fn has_composition_for_selected_role(&self) -> bool {
        let role = self.selected_role();
        self.composition.as_ref().is_some_and(|advisory| {
            advisory
                .proposal
                .suggestions
                .iter()
                .any(|suggestion| suggestion.role.eq_ignore_ascii_case(&role))
        })
    }

    /// Re-validate the entire proposal against its original explicit pool,
    /// then return the selected role's route. An out-of-pool proposal never
    /// reaches `model_idx`, even if the in-memory advisory were corrupted.
    fn validated_composition_route(&self) -> Option<(String, String)> {
        self.composition
            .as_ref()?
            .validated_route_for_role(&self.selected_role())
            .ok()?
    }

    fn select_model_route(&mut self, route: &(String, String)) -> bool {
        let Some(idx) = self
            .model_routes
            .iter()
            .position(|candidate| candidate == route)
        else {
            return false;
        };
        self.model_query.clear();
        self.model_filter_active = false;
        self.model_idx = idx;
        true
    }

    fn accept_composition(&mut self) -> ViewAction {
        let Some(route) = self.validated_composition_route() else {
            return ViewAction::None;
        };
        if !self.select_model_route(&route) {
            return ViewAction::None;
        }
        self.composition_decision = CompositionDecision::Accepted;
        // Accepting a suggestion still routes through the Destination step:
        // where the file lives is a human decision, not part of the advisory.
        self.step = Step::Destination;
        self.refresh_destinations();
        ViewAction::None
    }

    fn edit_composition(&mut self) -> ViewAction {
        let Some(route) = self.validated_composition_route() else {
            return ViewAction::None;
        };
        if !self.select_model_route(&route) {
            return ViewAction::None;
        }
        self.composition_decision = CompositionDecision::Edited;
        self.step = Step::Model;
        ViewAction::None
    }

    fn reject_composition(&mut self) -> ViewAction {
        self.composition_decision = CompositionDecision::Rejected;
        self.step = Step::Model;
        ViewAction::None
    }

    /// Copy note when the chosen role would override an existing roster
    /// member of the same id (e.g. "overrides built-in reviewer"). A saved
    /// profile shadows lower roster layers rather than adding a new member.
    fn roster_override_note(&self) -> Option<String> {
        self.override_note_for_scope(self.profile_scope)
    }

    /// Precedence consequence of saving the selected role into `scope`, given
    /// what the roster already contains for that id. Returns `None` when the
    /// id is new everywhere.
    fn override_note_for_scope(&self, scope: FleetProfileScope) -> Option<String> {
        let role = self.selected_role().to_lowercase();
        let locale = self.snapshot.locale;
        let (id, origin) = self
            .snapshot
            .roster_members
            .iter()
            .find(|(id, _)| *id == role)?;
        let has_project_copy = self
            .snapshot
            .roster_details
            .iter()
            .any(|d| d.id == role && d.scope == FleetProfileScope::Project);
        let has_personal_copy = self
            .snapshot
            .roster_details
            .iter()
            .any(|d| d.id == role && d.scope == FleetProfileScope::Personal);
        Some(match scope {
            FleetProfileScope::Personal if has_project_copy => {
                tr(locale, MessageId::FleetDestOverridesProject).replace("{id}", id)
            }
            FleetProfileScope::Project if has_personal_copy => {
                tr(locale, MessageId::FleetDestOverridesPersonal).replace("{id}", id)
            }
            _ => tr(locale, MessageId::FleetDestOverridesBuiltIn)
                .replace("{origin}", origin)
                .replace("{id}", id),
        })
    }

    /// Localized "This project" / "Personal" label for a scope.
    fn scope_label(&self, scope: FleetProfileScope) -> String {
        tr(
            self.snapshot.locale,
            match scope {
                FleetProfileScope::Project => MessageId::FleetDestProjectLabel,
                FleetProfileScope::Personal => MessageId::FleetDestPersonalLabel,
            },
        )
        .into_owned()
    }

    fn destination_for(&self, scope: FleetProfileScope) -> Option<&DestinationStatus> {
        self.destinations
            .as_ref()
            .and_then(|all| all.iter().find(|d| d.scope == scope))
    }

    /// The header chip: where the file will be written, or that the choice is
    /// still ahead. Visible on every step so the destination is never a
    /// surprise on the last screen.
    fn saves_to_line(&self) -> String {
        let locale = self.snapshot.locale;
        if !self.scope_decided {
            return tr(locale, MessageId::FleetSavesToUndecided).into_owned();
        }
        let path = self
            .destination_for(self.profile_scope)
            .map(|d| d.target.display().to_string())
            .unwrap_or_else(|| self.projected_target(self.profile_scope));
        tr(locale, MessageId::FleetSavesToChip)
            .replace("{scope}", &self.scope_label(self.profile_scope))
            .replace("{path}", &path)
    }

    /// Best-effort target path without touching the filesystem (used before
    /// `refresh_destinations` has run for the current role).
    fn projected_target(&self, scope: FleetProfileScope) -> String {
        let file = format!("{}.toml", profile_file_stem(&self.selected_role()));
        match scope {
            FleetProfileScope::Project => self
                .snapshot
                .workspace
                .join(crate::fleet::profile::WORKSPACE_AGENT_PROFILE_DIR)
                .join(file)
                .display()
                .to_string(),
            FleetProfileScope::Personal => match &self.snapshot.personal_profile_dir {
                Ok(dir) => dir.join(file).display().to_string(),
                Err(_) => format!("{}/{file}", scope.display_dir()),
            },
        }
    }

    /// The label of the primary Review action — it names its effect.
    fn save_action_label(&self) -> String {
        let locale = self.snapshot.locale;
        let exists = self
            .destination_for(self.profile_scope)
            .is_some_and(|d| d.target_exists);
        if exists && self.replace_armed {
            let file = self
                .destination_for(self.profile_scope)
                .and_then(|d| {
                    d.target
                        .file_name()
                        .map(|f| f.to_string_lossy().into_owned())
                })
                .unwrap_or_default();
            return tr(locale, MessageId::FleetActionConfirmReplace).replace("{file}", &file);
        }
        tr(
            locale,
            match (self.profile_scope, exists) {
                (FleetProfileScope::Project, false) => MessageId::FleetActionSaveProject,
                (FleetProfileScope::Personal, false) => MessageId::FleetActionSavePersonal,
                (FleetProfileScope::Project, true) => MessageId::FleetActionReplaceProject,
                (FleetProfileScope::Personal, true) => MessageId::FleetActionReplacePersonal,
            },
        )
        .into_owned()
    }

    /// Whether the currently chosen destination can be written.
    fn selected_destination_available(&self) -> bool {
        self.destination_for(self.profile_scope)
            .is_none_or(|d| d.unavailable_reason.is_none())
    }

    /// The concrete model chosen for this worker, written to the profile
    /// `model` field. `None` means `inherit` (reuse the session route).
    fn selected_model(&self) -> Option<String> {
        self.selected_route().map(|(_, model)| model)
    }

    /// The concrete `(provider, model)` chosen for this worker — a pinned route
    /// independent of the parent/current provider (#4093) — or `None` when
    /// `inherit` is selected (reuse the session route).
    fn selected_route(&self) -> Option<(String, String)> {
        let real_idx = self.real_model_idx();
        if real_idx == 0 {
            return None;
        }
        self.model_routes.get(real_idx).cloned()
    }

    /// Indices into `model_choices` visible under the current typed filter
    /// (#4639). Empty query shows every row; otherwise substring match over
    /// provider id/label and model id.
    fn filtered_model_indices(&self) -> Vec<usize> {
        let query = self.model_query.trim().to_ascii_lowercase();
        if query.is_empty() {
            return (0..self.model_choices.len()).collect();
        }
        (0..self.model_choices.len())
            .filter(|idx| {
                let (provider, model) = &self.model_routes[*idx];
                model.to_ascii_lowercase().contains(&query)
                    || provider.to_ascii_lowercase().contains(&query)
                    || provider_display_label(provider)
                        .to_ascii_lowercase()
                        .contains(&query)
                    || (*idx == 0 && "inherit same current".contains(&query))
            })
            .collect()
    }

    /// Map the filtered highlight position back to the real `model_choices`
    /// index. Selection, persistence, and hitboxes all use the real index.
    fn real_model_idx(&self) -> usize {
        let filtered = self.filtered_model_indices();
        if filtered.is_empty() {
            return 0;
        }
        filtered[self.model_idx.min(filtered.len() - 1)]
    }

    fn selected_reasoning_effort(&self) -> Option<String> {
        if self.thinking_idx == 0 {
            return None;
        }
        THINKING_CHOICES
            .get(self.thinking_idx)
            .map(|choice| choice.label.to_string())
    }

    fn selected_thinking_label(&self) -> String {
        self.selected_reasoning_effort()
            .unwrap_or_else(|| format!("inherit ({})", self.snapshot.reasoning))
    }

    fn scope_preview_header(&self, header: String) -> String {
        header.replacen(PROFILE_DIR, self.profile_scope.display_dir(), 1)
    }

    /// Number of selectable rows on the current step (0 on the review step).
    fn step_len(&self) -> usize {
        match self.step {
            Step::Role => ROLES.len(),
            Step::Composition => 0,
            Step::Model => self.filtered_model_indices().len(),
            Step::Destination => DESTINATION_ORDER.len(),
            Step::Review => 0,
        }
    }

    fn move_up(&mut self) {
        match self.step {
            Step::Role => {
                self.role_idx =
                    crate::tui::list_nav::wrap_index(self.role_idx, self.step_len(), -1);
                self.discard_model_draft();
                self.composition_decision = CompositionDecision::Pending;
            }
            Step::Composition => {}
            Step::Model => {
                self.model_idx =
                    crate::tui::list_nav::wrap_index(self.model_idx, self.step_len(), -1);
                self.discard_model_draft();
                if self.composition_decision != CompositionDecision::Pending {
                    self.composition_decision = CompositionDecision::Edited;
                }
            }
            Step::Destination => {
                self.destination_idx =
                    crate::tui::list_nav::wrap_index(self.destination_idx, self.step_len(), -1);
            }
            Step::Review => self.review_scroll = self.review_scroll.saturating_sub(1),
        }
    }

    /// A draft is only valid for the answers it was requested against.
    fn discard_model_draft(&mut self) {
        self.model_draft = None;
        self.model_draft_preview = None;
    }

    fn move_down(&mut self) {
        match self.step {
            Step::Role => {
                self.role_idx = crate::tui::list_nav::wrap_index(self.role_idx, self.step_len(), 1);
                self.discard_model_draft();
                self.composition_decision = CompositionDecision::Pending;
            }
            Step::Composition => {}
            Step::Model => {
                self.model_idx =
                    crate::tui::list_nav::wrap_index(self.model_idx, self.step_len(), 1);
                self.discard_model_draft();
                if self.composition_decision != CompositionDecision::Pending {
                    self.composition_decision = CompositionDecision::Edited;
                }
            }
            Step::Destination => {
                self.destination_idx =
                    crate::tui::list_nav::wrap_index(self.destination_idx, self.step_len(), 1);
            }
            Step::Review => self.review_scroll = self.review_scroll.saturating_add(1),
        }
    }

    /// Re-stat the profile directory. Called on the two transitions that can
    /// change the answer — entering Review, and toggling project/user scope —
    /// so the Review step never touches the filesystem while painting.
    fn refresh_destinations(&mut self) {
        let file = format!("{}.toml", profile_file_stem(&self.selected_role()));
        let statuses = DESTINATION_ORDER.map(|scope| {
            destination_status(
                scope,
                &self.snapshot.workspace,
                &self.snapshot.personal_profile_dir,
                &file,
                self.snapshot.project_profiles_enabled,
                self.snapshot.locale,
            )
        });
        self.destinations = Some(statuses);
        self.replace_armed = false;
    }

    /// Choose a destination explicitly (Destination step or roster preload).
    fn choose_destination(&mut self, scope: FleetProfileScope) {
        if self.profile_scope != scope {
            self.discard_model_draft();
        }
        self.profile_scope = scope;
        self.scope_decided = true;
        self.destination_idx = DESTINATION_ORDER
            .iter()
            .position(|s| *s == scope)
            .unwrap_or(0);
        self.replace_armed = false;
    }

    /// starter profile TOML the next save keypress would persist.
    fn advance(&mut self) -> ViewAction {
        match self.step {
            Step::Role => {
                self.step = Step::Model;
                ViewAction::None
            }
            Step::Composition => self.accept_composition(),
            Step::Model => {
                let idx = self.real_model_idx();
                match self.model_row_states.get(idx) {
                    Some(FleetModelRowState::Ready) => {
                        // Path: role → model → destination → review/save.
                        // Thinking defaults to inherit; adjust on review with `t`.
                        self.notice = None;
                        self.step = Step::Destination;
                        self.refresh_destinations();
                    }
                    Some(FleetModelRowState::NeedsActivation) => {
                        // Dormant external-consent route: explicit human
                        // selection must mint the read capability and validate
                        // only this exact provider/model. Hand off to the host
                        // so rendering stays I/O-free.
                        if let Some((provider_id, model)) = self.model_routes.get(idx)
                            && let Some(provider) = crate::config::ApiProvider::parse(provider_id)
                            && crate::tui::provider_picker::external_consent_target_for_provider(
                                provider,
                            )
                            .is_some()
                        {
                            return ViewAction::Emit(
                                ViewEvent::FleetSetupExternalConsentActivationRequested {
                                    provider_id: provider_id.clone(),
                                    model: model.clone(),
                                },
                            );
                        }
                    }
                    Some(FleetModelRowState::Blocked { reason }) => {
                        // Stay on the Model step, but say why Enter did nothing
                        // and where to fix it instead of failing silently.
                        self.notice = Some(
                            tr(self.snapshot.locale, MessageId::FleetModelRowBlockedNotice)
                                .replace("{reason}", reason),
                        );
                    }
                    None => {}
                }
                ViewAction::None
            }
            Step::Destination => {
                let scope =
                    DESTINATION_ORDER[self.destination_idx.min(DESTINATION_ORDER.len() - 1)];
                let available = self
                    .destination_for(scope)
                    .is_none_or(|d| d.unavailable_reason.is_none());
                if !available {
                    // A disabled destination never falls back to the other one.
                    return ViewAction::None;
                }
                self.choose_destination(scope);
                self.step = Step::Review;
                self.review_scroll = 0;
                self.review_focus = ReviewFocus::Save;
                self.refresh_destinations();
                ViewAction::None
            }
            Step::Review => self.activate_review_focus(),
        }
    }

    /// Enter on the Review step acts on the focused control.
    fn activate_review_focus(&mut self) -> ViewAction {
        match self.review_focus {
            ReviewFocus::Save => self.save_action(),
            ReviewFocus::ChangeDestination => {
                self.step = Step::Destination;
                self.refresh_destinations();
                ViewAction::None
            }
            ReviewFocus::Back => self.back(),
        }
    }

    /// The single save path for both the deterministic starter profile and a
    /// model-authored draft. Replacing an existing file requires a second
    /// press: the first arms the control and renames it; nothing is written
    /// until the second. An unavailable destination never saves.
    fn save_action(&mut self) -> ViewAction {
        if !self.scope_decided || !self.selected_destination_available() {
            return ViewAction::None;
        }
        let exists = self
            .destination_for(self.profile_scope)
            .is_some_and(|d| d.target_exists);
        if exists && !self.replace_armed {
            self.replace_armed = true;
            return ViewAction::None;
        }
        match self.model_draft.clone() {
            Some(draft) => ViewAction::EmitAndClose(ViewEvent::FleetProfileDraftCommitRequested {
                draft,
                scope: self.profile_scope,
            }),
            None => self.commit_starter_profile_action(),
        }
    }

    /// Step back toward the first screen. Returns `None` at the first step (the
    /// host closes the modal via Esc instead).
    fn back(&mut self) -> ViewAction {
        match self.step {
            Step::Role => ViewAction::None,
            Step::Composition => {
                self.step = Step::Model;
                ViewAction::None
            }
            Step::Model => {
                self.notice = None;
                self.step = Step::Role;
                ViewAction::None
            }
            Step::Destination => {
                self.step = Step::Model;
                ViewAction::None
            }
            Step::Review => {
                self.replace_armed = false;
                self.step = Step::Destination;
                self.refresh_destinations();
                ViewAction::None
            }
        }
    }

    /// Persist the deterministic starter profile directly from the Review
    /// summary. Unlike a model-authored draft, every field is derived from the
    /// structured choices already visible on this screen, so a second TOML
    /// ratification state adds no trust boundary.
    fn commit_starter_profile_action(&self) -> ViewAction {
        ViewAction::EmitAndClose(ViewEvent::FleetProfileDraftCommitRequested {
            draft: self.starter_profile_draft(),
            scope: self.profile_scope,
        })
    }

    /// Build a deterministic starter profile for the current role/model
    /// selection. The same save event persists this as model-drafted profiles,
    /// so duplicate-id checks and atomic writes stay in one host path.
    ///
    /// `provider` is seeded from whatever the user actually picked in the
    /// Model step (#4093) — a concrete route names its own provider
    /// explicitly, so the saved profile is never ambiguously scoped to
    /// whatever provider happens to be active at launch time. `inherit`
    /// carries no provider, matching its `model: None`.
    fn starter_profile_draft(&self) -> Box<crate::fleet::profile::FleetProfileDraft> {
        let role = &ROLES[self.role_idx.min(ROLES.len() - 1)];
        let route = self.selected_route();
        Box::new(crate::fleet::profile::FleetProfileDraft {
            id: profile_file_stem(&role.label),
            display_name: Some(role.label.to_string()),
            description: Some(format!("{} - {}", role.summary, role.description)),
            role_hint: role.label.to_string(),
            model_class_hint: None,
            model: route.as_ref().map(|(_, model)| model.clone()),
            provider: route.map(|(provider, _)| provider),
            reasoning_effort: self.selected_reasoning_effort(),
            instructions: Some(format!(
                "Role: {}. Work only within the assigned Fleet slice. Report concise evidence and stop when the assignment is complete. Do not widen permissions, trust, route configuration, or topology.",
                role.label
            )),
        })
    }

    /// The action hints for the current step's footer (wrapped by the shared
    /// footer renderer so they can never run off the modal edge).
    fn footer_hints(&self) -> Vec<ActionHint> {
        let mut hints = Vec::new();
        match self.step {
            Step::Role => {
                hints.push(ActionHint::new("↑/↓", "choose"));
                hints.push(ActionHint::new("Enter", "next"));
            }
            Step::Composition => {
                hints.push(ActionHint::new("a/Enter", "accept"));
                hints.push(ActionHint::new("e", "edit"));
                hints.push(ActionHint::new("r", "reject"));
                hints.push(ActionHint::new("", "back"));
            }
            Step::Model => {
                hints.push(ActionHint::new("↑/↓", "choose"));
                hints.push(ActionHint::new("/", "filter"));
                if self.has_composition_for_selected_role() {
                    hints.push(ActionHint::new("c", "suggest"));
                }
                hints.push(ActionHint::new("Enter", "next"));
                hints.push(ActionHint::new("", "back"));
            }
            Step::Destination => {
                hints.push(ActionHint::new("↑/↓", "choose"));
                hints.push(ActionHint::new("Enter/Space", "next"));
                hints.push(ActionHint::new("", "back"));
            }
            Step::Review => {
                hints.push(ActionHint::new("Tab", "focus"));
                hints.push(ActionHint::new("Enter", "activate"));
                hints.push(ActionHint::new("↑/↓", "scroll"));
                hints.push(ActionHint::new("t", "thinking"));
                if self.model_draft.is_some() {
                    hints.push(ActionHint::new("m", "redraft"));
                } else if self.snapshot.provider_ready {
                    hints.push(ActionHint::new("m", "model draft"));
                }
                hints.push(ActionHint::new("", "back"));
            }
        }
        // Esc is honest: it steps back everywhere except the first screen,
        // where it cancels the wizard.
        if self.step == Step::Role {
            hints.push(ActionHint::new("Esc", "cancel"));
        } else {
            hints.push(ActionHint::new("Esc", "back"));
        }
        hints
    }
}

impl ModalView for FleetSetupView {
    fn kind(&self) -> ModalKind {
        ModalKind::FleetSetup
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }

    fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction {
        match mouse.kind {
            MouseEventKind::ScrollUp => self.move_up(),
            MouseEventKind::ScrollDown => self.move_down(),
            MouseEventKind::Down(MouseButton::Left) => {
                let row = self.row_hitboxes.borrow().iter().find_map(|(rect, row)| {
                    rect.contains(ratatui::layout::Position::new(mouse.column, mouse.row))
                        .then_some(*row)
                });
                if let Some(row) = row {
                    match self.step {
                        Step::Role => {
                            self.role_idx = row.min(ROLES.len().saturating_sub(1));
                            self.composition_decision = CompositionDecision::Pending;
                        }
                        Step::Composition => {}
                        Step::Model => {
                            self.model_idx = row.min(self.step_len().saturating_sub(1));
                            if self.composition_decision != CompositionDecision::Pending {
                                self.composition_decision = CompositionDecision::Edited;
                            }
                        }
                        Step::Destination => {
                            self.destination_idx = row.min(DESTINATION_ORDER.len() - 1);
                            return ViewAction::None;
                        }
                        Step::Review => {}
                    }
                    self.discard_model_draft();
                }
            }
            _ => {}
        }
        ViewAction::None
    }

    fn handle_key(&mut self, key: KeyEvent) -> ViewAction {
        // Model-step filter input captures keystrokes while active (#4639).
        if self.step == Step::Model && self.model_filter_active {
            match key.code {
                KeyCode::Enter => {
                    self.model_filter_active = false;
                }
                KeyCode::Esc => {
                    self.model_filter_active = false;
                    self.model_query.clear();
                    self.model_idx = 0;
                }
                KeyCode::Backspace => {
                    self.model_query.pop();
                    self.model_idx = 0;
                    if self.composition_decision != CompositionDecision::Pending {
                        self.composition_decision = CompositionDecision::Edited;
                    }
                }
                KeyCode::Up => {
                    self.move_up();
                }
                KeyCode::Down => {
                    self.move_down();
                }
                KeyCode::Char(ch)
                    if !key.modifiers.intersects(
                        KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER,
                    ) =>
                {
                    self.model_query.push(ch);
                    self.model_idx = 0;
                    if self.composition_decision != CompositionDecision::Pending {
                        self.composition_decision = CompositionDecision::Edited;
                    }
                }
                _ => {}
            }
            return ViewAction::None;
        }
        // Any navigation key clears a one-shot notice; the notice is re-set
        // below when the same blocked action is attempted again.
        if !matches!(key.code, KeyCode::Null) {
            self.notice = None;
        }
        match key.code {
            KeyCode::Esc if self.step != Step::Role => self.back(),
            KeyCode::Esc => ViewAction::Close,
            KeyCode::Char('q') if self.step == Step::Role => ViewAction::Close,
            // Tab moves focus; it never changes where the file is written.
            KeyCode::Tab if self.step == Step::Review => {
                self.review_focus = self.review_focus.next();
                self.replace_armed = false;
                ViewAction::None
            }
            KeyCode::BackTab if self.step == Step::Review => {
                self.review_focus = self.review_focus.prev();
                self.replace_armed = false;
                ViewAction::None
            }
            KeyCode::Right | KeyCode::Char('l') if self.step == Step::Review => {
                self.review_focus = self.review_focus.next();
                self.replace_armed = false;
                ViewAction::None
            }
            KeyCode::Char(' ') if self.step == Step::Destination => self.advance(),
            KeyCode::Char(' ') if self.step == Step::Review => self.activate_review_focus(),
            KeyCode::Char('a') if self.step == Step::Composition => self.accept_composition(),
            KeyCode::Char('e') if self.step == Step::Composition => self.edit_composition(),
            KeyCode::Char('r') if self.step == Step::Composition => self.reject_composition(),
            KeyCode::Char('c')
                if self.step == Step::Model && self.has_composition_for_selected_role() =>
            {
                self.composition_decision = CompositionDecision::Pending;
                self.discard_model_draft();
                self.step = Step::Composition;
                ViewAction::None
            }
            KeyCode::Char('/') if self.step == Step::Model => {
                self.model_filter_active = true;
                ViewAction::None
            }
            KeyCode::Up | KeyCode::Char('k') => {
                self.move_up();
                ViewAction::None
            }
            KeyCode::Down | KeyCode::Char('j') => {
                self.move_down();
                ViewAction::None
            }
            // Secondary accelerator: jump to the Destination step. The primary
            // way to change the destination is the focused Review control.
            KeyCode::Char('s') if self.step == Step::Review => {
                self.replace_armed = false;
                self.step = Step::Destination;
                self.refresh_destinations();
                ViewAction::None
            }
            KeyCode::Char('t') if self.step == Step::Review => {
                self.thinking_idx = (self.thinking_idx + 1) % THINKING_CHOICES.len();
                self.discard_model_draft();
                ViewAction::None
            }
            KeyCode::Char('m') if self.step == Step::Review && self.snapshot.provider_ready => {
                let route = self.selected_route();
                ViewAction::Emit(ViewEvent::FleetProfileModelDraftRequested {
                    role: self.selected_role(),
                    model: route
                        .as_ref()
                        .map(|(_, model)| model.clone())
                        .unwrap_or_else(|| "inherit".to_string()),
                    // Carry the picked provider so the redrafted profile keeps
                    // the cross-provider route (#4093). `install_model_draft`
                    // re-injects it authoritatively from the wizard's current
                    // selection, but the event stays self-describing.
                    provider: route.map(|(provider, _)| provider),
                    reasoning_effort: self.selected_reasoning_effort(),
                    locale: self.snapshot.locale,
                })
            }
            KeyCode::Char('g') if self.step == Step::Review => {
                self.review_focus = ReviewFocus::Save;
                self.save_action()
            }
            KeyCode::Enter | KeyCode::Right | KeyCode::Char('l') => self.advance(),
            KeyCode::Left | KeyCode::Char('h') => self.back(),
            KeyCode::Home => {
                self.review_scroll = 0;
                ViewAction::None
            }
            KeyCode::PageUp => {
                self.review_scroll = self.review_scroll.saturating_sub(8);
                ViewAction::None
            }
            KeyCode::PageDown => {
                self.review_scroll = self.review_scroll.saturating_add(8);
                ViewAction::None
            }
            _ => ViewAction::None,
        }
    }

    fn render(&self, area: Rect, buf: &mut Buffer) {
        self.row_hitboxes.borrow_mut().clear();
        // Choice steps have a bounded list/detail body and should not expand
        // into a tall empty card on roomy terminals. Review is proof-dense and
        // scrollable, so it keeps the extra row budgeted for the footer gutter.
        let preferred_height = match self.step {
            Step::Role => 22,
            Step::Composition => 26,
            Step::Model => 23,
            Step::Destination => 22,
            Step::Review => 32,
        };
        let popup_area = centered_modal_area(area, 96, preferred_height, 60, 16);
        render_modal_surface(area, popup_area, buf);

        let step_no = match self.step {
            Step::Role => 1,
            Step::Composition => 2,
            Step::Model => 2,
            Step::Destination => 3,
            Step::Review => 4,
        };
        let block = Block::default()
            .title(Line::from(Span::styled(
                " Fleet setup — your agent team ",
                Style::default()
                    .fg(palette::WHALE_ACTION)
                    .add_modifier(Modifier::BOLD),
            )))
            .title_bottom(
                Line::from(Span::styled(
                    format!(" Step {step_no}/4 "),
                    Style::default().fg(palette::TEXT_MUTED),
                ))
                .alignment(ratatui::layout::Alignment::Right),
            )
            .borders(Borders::ALL)
            .border_style(Style::default().fg(palette::BORDER_COLOR))
            .style(Style::default().bg(palette::WHALE_BG))
            .padding(Padding::uniform(1));

        let inner = block.inner(popup_area);
        block.render(popup_area, buf);

        let hints = self.footer_hints();
        let content = render_modal_footer_with_gutter(inner, buf, &hints);

        // Header (title + subtitle + "Saves to" chip) above the step body.
        // In the Compact tier the subtitle is dropped so the chip survives.
        let header_rows = if content.height < 12 { 2 } else { 3 };
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Length(header_rows), Constraint::Min(1)])
            .split(content);
        self.render_header(chunks[0], buf);

        match self.step {
            Step::Role => {
                let mut context = vec![
                    "Fleet runs sub-agents that delegate work. Pick the role this team member should play; the saved profile carries it as its role_hint.".to_string(),
                ];
                if let Some(note) = self.roster_override_note() {
                    context.push(note);
                }
                render_choice_step(chunks[1], buf, &ROLES, self.role_idx, &context);
                register_choice_hitboxes(chunks[1], ROLES.len(), self.role_idx, &self.row_hitboxes);
            }
            Step::Destination => {
                self.render_destination(chunks[1], buf);
                register_choice_hitboxes(
                    chunks[1],
                    DESTINATION_ORDER.len(),
                    self.destination_idx,
                    &self.row_hitboxes,
                );
            }
            Step::Composition => self.render_composition(chunks[1], buf),
            Step::Model => {
                let filtered = self.filtered_model_indices();
                // Compact tier: the row summary and any notice matter more
                // than the long route description, which would push them
                // below the fold.
                let compact = chunks[1].height < 12;
                let filtered_choices: Vec<Choice> = filtered
                    .iter()
                    .map(|idx| {
                        let mut choice = self.model_choices[*idx].clone();
                        if compact {
                            choice.description = Cow::Borrowed("");
                        }
                        choice
                    })
                    .collect();
                let selected = self.model_idx.min(filtered.len().saturating_sub(1));
                let filter_line = if self.model_filter_active {
                    format!("Filter: {}▏ (Enter keep · Esc clear)", self.model_query)
                } else if !self.model_query.trim().is_empty() {
                    format!(
                        "Filter: {} ({} of {} rows · / edit)",
                        self.model_query,
                        filtered.len(),
                        self.model_choices.len()
                    )
                } else {
                    format!(
                        "Type / to filter {} routes by provider or model",
                        self.model_choices.len()
                    )
                };
                let mut context = Vec::new();
                if let Some(notice) = &self.notice {
                    context.push(notice.clone());
                }
                context.push(filter_line);
                context.push(format!(
                    "Current route: {} / {}  ·  reasoning {}",
                    self.snapshot.provider, self.snapshot.model, self.snapshot.reasoning
                ));
                context.push(match self.selected_model() {
                    Some(model) => format!("This worker will run on {model}."),
                    None => "This worker inherits your current route.".to_string(),
                });
                render_choice_step(chunks[1], buf, &filtered_choices, selected, &context);
                register_choice_hitboxes(
                    chunks[1],
                    filtered_choices.len(),
                    selected,
                    &self.row_hitboxes,
                );
            }
            Step::Review => self.render_review(chunks[1], buf),
        }
    }
}

impl FleetSetupView {
    fn render_header(&self, area: Rect, buf: &mut Buffer) {
        let (title, subtitle): (Cow<'static, str>, Cow<'static, str>) = match self.step {
            Step::Role => (
                Cow::Borrowed("Choose a team role"),
                Cow::Borrowed("Each Fleet member plays one role in the delegation."),
            ),
            Step::Composition => (
                Cow::Borrowed("Unratified composition suggestion"),
                Cow::Borrowed(
                    "Review the configured-pool assignments; nothing is saved or running.",
                ),
            ),
            Step::Model => (
                Cow::Borrowed("Choose a model"),
                Cow::Borrowed("Pick this worker's model, or inherit your current route."),
            ),
            Step::Destination => (
                Cow::Owned(tr(self.snapshot.locale, MessageId::FleetDestStepTitle).into_owned()),
                Cow::Owned(tr(self.snapshot.locale, MessageId::FleetDestStepSubtitle).into_owned()),
            ),
            Step::Review if self.model_draft.is_some() => (
                Cow::Borrowed("Save profile"),
                Cow::Borrowed(
                    "Exact TOML shown below; nothing is written until you activate the save control.",
                ),
            ),
            Step::Review => (
                Cow::Borrowed("Review & save"),
                Cow::Borrowed("Nothing is written until you activate the save control."),
            ),
        };
        let chip_style = Style::default().fg(palette::TEXT_MUTED);
        let mut lines = vec![Line::from(Span::styled(
            title.into_owned(),
            Style::default().fg(palette::WHALE_INFO).bold(),
        ))];
        if area.height >= 3 {
            lines.push(Line::from(Span::styled(
                subtitle.into_owned(),
                Style::default().fg(palette::TEXT_MUTED),
            )));
        }
        lines.push(Line::from(Span::styled(
            truncate_view_text(&self.saves_to_line(), usize::from(area.width)),
            chip_style,
        )));
        // No wrapping: each header row is one line, so the chip row is
        // always the last row and never pushed out by a long subtitle.
        Paragraph::new(lines).render(area, buf);
    }

    /// The Destination step: a focused two-option list (This project /
    /// Personal) with the exact resolved file, whether it will be replaced,
    /// and the precedence consequence, for the highlighted option.
    fn render_destination(&self, area: Rect, buf: &mut Buffer) {
        let locale = self.snapshot.locale;
        // Compact tier: keep the choice, the file, and the consequence; drop
        // the long explanation rather than clip the file line off-screen.
        let compact = area.height < 12;
        let workspace_name = self
            .snapshot
            .workspace
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| self.snapshot.workspace.display().to_string());
        let choices: Vec<Choice> = DESTINATION_ORDER
            .iter()
            .map(|scope| {
                let unavailable = self
                    .destination_for(*scope)
                    .and_then(|d| d.unavailable_reason.clone());
                let (label, summary, description) = match scope {
                    FleetProfileScope::Project => (
                        MessageId::FleetDestProjectLabel,
                        MessageId::FleetDestProjectSummary,
                        MessageId::FleetDestProjectDescription,
                    ),
                    FleetProfileScope::Personal => (
                        MessageId::FleetDestPersonalLabel,
                        MessageId::FleetDestPersonalSummary,
                        MessageId::FleetDestPersonalDescription,
                    ),
                };
                let _ = unavailable;
                Choice {
                    label: Cow::Owned(tr(locale, label).into_owned()),
                    summary: Cow::Owned(tr(locale, summary).into_owned()),
                    description: if compact {
                        Cow::Borrowed("")
                    } else {
                        Cow::Owned(tr(locale, description).replace("{workspace}", &workspace_name))
                    },
                }
            })
            .collect();
        let selected = self.destination_idx.min(DESTINATION_ORDER.len() - 1);
        let scope = DESTINATION_ORDER[selected];
        let mut context = Vec::new();
        match self.destination_for(scope) {
            Some(status) => {
                if let Some(reason) = &status.unavailable_reason {
                    context.push(
                        tr(locale, MessageId::FleetDestUnavailable).replace("{reason}", reason),
                    );
                }
                context.push(
                    tr(locale, MessageId::FleetDestPathLine)
                        .replace("{path}", &status.target.display().to_string()),
                );
                if status.target_exists {
                    context.push(
                        tr(locale, MessageId::FleetDestWillReplace)
                            .replace("{path}", &status.target.display().to_string()),
                    );
                }
            }
            None => context.push(
                tr(locale, MessageId::FleetDestPathLine)
                    .replace("{path}", &self.projected_target(scope)),
            ),
        }
        if let Some(note) = self.override_note_for_scope(scope) {
            context.push(note);
        }
        render_choice_step(area, buf, &choices, selected, &context);
    }

    fn render_composition(&self, area: Rect, buf: &mut Buffer) {
        let Some(advisory) = self.composition.as_ref() else {
            Paragraph::new("No configured model pool is available. Press e to choose manually.")
                .wrap(Wrap { trim: true })
                .render(area, buf);
            return;
        };
        let selected_role = self.selected_role();
        let mut lines = vec![
            Line::from(Span::styled(
                format!(
                    "{} · {}",
                    advisory.proposal.ratification.as_str().to_ascii_uppercase(),
                    advisory.proposal.advisory
                ),
                Style::default().fg(palette::STATUS_WARNING).bold(),
            )),
            Line::from(""),
        ];
        for suggestion in &advisory.proposal.suggestions {
            let selected = suggestion.role.eq_ignore_ascii_case(&selected_role);
            lines.push(Line::from(vec![
                Span::styled(
                    format!(
                        "{} {}",
                        crate::tui::glyphs::selection_marker(selected),
                        suggestion.role
                    ),
                    if selected {
                        menu_style::selected_row_style()
                    } else {
                        Style::default().fg(palette::TEXT_PRIMARY)
                    },
                ),
                Span::styled(
                    format!(
                        "{}/{}",
                        provider_display_label(&suggestion.provider),
                        suggestion.model
                    ),
                    Style::default().fg(palette::TEXT_MUTED),
                ),
            ]));
        }
        lines.extend([
            Line::from(""),
            Line::from(Span::styled(
                format!(
                    "Accept applies only the {selected_role} suggestion to this unsaved profile. Edit highlights it in the configured model picker; reject keeps your current selection."
                ),
                Style::default().fg(palette::TEXT_MUTED),
            )),
        ]);
        debug_assert_eq!(
            advisory.proposal.ratification,
            RatificationState::Unratified
        );
        Paragraph::new(lines)
            .wrap(Wrap { trim: true })
            .render(area, buf);
    }

    fn render_review(&self, area: Rect, buf: &mut Buffer) {
        if area.width == 0 || area.height == 0 {
            return;
        }
        // Row 1: the focused action controls. Row 2+: the scrollable summary.
        // Keeping the controls out of the scroll region means the save action
        // and its label are visible at every scroll offset and every size.
        let rows = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Length(2), Constraint::Min(1)])
            .split(area);
        self.render_review_actions(rows[0], buf);
        let body = rows[1];

        // A ratify-ready draft is on screen: show the exact TOML preview
        // inline, scrolled by the same `review_scroll` state, so the save
        // control in THIS view ratifies it directly — no separate pager in the
        // way to swallow the keypress (#4093).
        if let Some(preview) = self.model_draft_preview.as_deref() {
            render_scrollable_text(body, buf, preview, self.review_scroll);
            return;
        }

        let role = &ROLES[self.role_idx.min(ROLES.len() - 1)];
        let locale = self.snapshot.locale;
        let mut lines: Vec<Line> = Vec::new();
        let section = |lines: &mut Vec<Line>, label: &str, body: String| {
            lines.push(Line::from(Span::styled(
                label.to_string(),
                Style::default().fg(palette::WHALE_INFO).bold(),
            )));
            lines.push(Line::from(Span::styled(
                body,
                Style::default().fg(palette::TEXT_PRIMARY),
            )));
            lines.push(Line::from(""));
        };

        // "Saves to" comes first: it is the decision this screen exists to
        // confirm. Exact file, replace/create, precedence consequence.
        let mut saves_to = vec![format!(
            "{} · {}",
            self.scope_label(self.profile_scope),
            self.destination_for(self.profile_scope)
                .map(|d| d.target.display().to_string())
                .unwrap_or_else(|| self.projected_target(self.profile_scope))
        )];
        if let Some(status) = self.destination_for(self.profile_scope) {
            if let Some(reason) = &status.unavailable_reason {
                saves_to
                    .push(tr(locale, MessageId::FleetDestUnavailable).replace("{reason}", reason));
            } else if status.target_exists {
                saves_to.push(
                    tr(locale, MessageId::FleetDestWillReplace)
                        .replace("{path}", &status.target.display().to_string()),
                );
            }
        }
        if let Some(note) = self.roster_override_note() {
            saves_to.push(note);
        }
        section(
            &mut lines,
            &tr(locale, MessageId::FleetReviewSavesTo),
            saves_to.join("  ·  "),
        );
        section(
            &mut lines,
            "Role",
            format!("{}{}", role.label, role.summary),
        );
        section(
            &mut lines,
            "Model",
            // The picked route's OWN provider, not the parent/current
            // session's — a cross-provider pin must never be misreported as
            // running on the active provider (#4093).
            match self.selected_route() {
                Some((provider, model)) => {
                    let readiness = self
                        .snapshot
                        .available_models
                        .iter()
                        .find(|(candidate_provider, candidate_model, _)| {
                            candidate_provider == &provider && candidate_model == &model
                        })
                        .map(|(_, _, readiness)| readiness.label().into_owned())
                        .unwrap_or_else(|| {
                            if self.snapshot.provider_ready {
                                "ready".to_string()
                            } else {
                                "needs action".to_string()
                            }
                        });
                    format!(
                        "{model}  ·  provider {}  ·  {readiness}",
                        provider_display_label(&provider)
                    )
                }
                None => format!(
                    "inherit  ·  route {} / {}  ·  {}",
                    self.snapshot.provider,
                    self.snapshot.model,
                    if self.snapshot.provider_ready {
                        "ready"
                    } else {
                        "needs action"
                    }
                ),
            },
        );
        match self.composition_decision {
            CompositionDecision::Accepted => section(
                &mut lines,
                "Composition",
                "Accepted the configured-pool suggestion for this role. It remains unsaved until you save this profile; no Fleet was launched or changed.".to_string(),
            ),
            CompositionDecision::Edited => section(
                &mut lines,
                "Composition",
                "Edited the suggestion in the configured model picker. This review is the only save boundary.".to_string(),
            ),
            CompositionDecision::Rejected => section(
                &mut lines,
                "Composition",
                "Rejected the suggestion and kept the manually selected route. Nothing was saved or launched by the advisory.".to_string(),
            ),
            CompositionDecision::Pending => {}
        }
        section(&mut lines, "Thinking", self.selected_thinking_label());
        section(
            &mut lines,
            "Auth & readiness",
            if self.snapshot.provider_ready {
                "Active route can be attempted with the current credentials.".to_string()
            } else {
                "Active route is not ready — fix auth/readiness before relying on this profile at runtime.".to_string()
            },
        );
        section(
            &mut lines,
            "Permissions",
            "Inherit the parent envelope and narrow only. Children cannot widen approval, trust, or secrets, and required approvals stay on.".to_string(),
        );
        section(
            &mut lines,
            "Tools",
            "Read tools by default; write tools for builders within scope; shell stays policy-gated; artifacts and receipts stay inspectable.".to_string(),
        );
        section(
            &mut lines,
            "Workspace & org",
            format!(
                "{} · sub-agents {} ({} concurrent, {} launch slots, {} admitted) · recursion agent {} / fleet {} (ceiling {})",
                self.snapshot.workspace.display(),
                if self.snapshot.subagents_enabled {
                    "enabled"
                } else {
                    "disabled"
                },
                self.snapshot.max_subagents,
                self.snapshot.launch_concurrency,
                self.snapshot.max_admitted,
                self.snapshot.subagent_spawn_depth,
                self.snapshot.fleet_spawn_depth,
                codewhale_config::MAX_SPAWN_DEPTH_CEILING,
            ),
        );
        section(&mut lines, "Review policy", self.review_policy_summary());

        // `scroll` offsets by *visual* (post-wrap) rows, so the bound must count
        // wrapped rows — not logical lines — or the bottom sections become
        // unreachable. Estimate each line's wrapped height from its display
        // width; an over-estimate is harmless (scroll clamps at the real end).
        let wrap_width = usize::from(body.width).max(1);
        let visual_rows: usize = lines
            .iter()
            .map(|line| line.width().div_ceil(wrap_width).max(1))
            .sum();
        let max_scroll = visual_rows.saturating_sub(usize::from(body.height).max(1));
        let scroll = self.review_scroll.min(max_scroll);
        Paragraph::new(lines)
            .wrap(Wrap { trim: true })
            .scroll((scroll as u16, 0))
            .render(body, buf);
    }

    /// The Review step's focused control row: [Save…] [Change destination]
    /// [Back]. The focused control is drawn with the canonical selection style
    /// and the `▸` marker; a disabled save control (unavailable destination)
    /// is dimmed and named with the reason on the "Saves to" line.
    fn render_review_actions(&self, area: Rect, buf: &mut Buffer) {
        let locale = self.snapshot.locale;
        let save_enabled = self.scope_decided && self.selected_destination_available();
        let controls: [(ReviewFocus, String, bool); 3] = [
            (ReviewFocus::Save, self.save_action_label(), save_enabled),
            (
                ReviewFocus::ChangeDestination,
                tr(locale, MessageId::FleetActionChangeDestination).into_owned(),
                true,
            ),
            (
                ReviewFocus::Back,
                tr(locale, MessageId::FleetActionBack).into_owned(),
                true,
            ),
        ];
        let mut spans: Vec<Span> = Vec::new();
        for (focus, label, enabled) in controls {
            let focused = focus == self.review_focus;
            let text = format!(
                "{} {} ",
                crate::tui::glyphs::selection_marker(focused),
                label
            );
            let style = match (focused, enabled) {
                (true, true) => menu_style::selected_row_style(),
                (true, false) => menu_style::disabled_selected_row_style(),
                (false, true) => Style::default().fg(palette::TEXT_PRIMARY),
                (false, false) => Style::default().fg(palette::TEXT_MUTED).dim(),
            };
            spans.push(Span::styled(text, style));
            spans.push(Span::raw(" "));
        }
        Paragraph::new(vec![Line::from(spans), Line::from("")])
            .wrap(Wrap { trim: true })
            .render(area, buf);
    }

    fn review_policy_summary(&self) -> String {
        format!(
            "Workers run without a token cap by default · {}s api, {}s heartbeat. Launch with Fleet → exec; /fleet workers (or /subagents) shows sub-agents in the current interactive session; /fleet status and codewhale fleet status both read the persistent .codewhale/fleet.jsonl ledger.",
            self.snapshot.api_timeout_secs, self.snapshot.heartbeat_timeout_secs
        )
    }
}

/// Render wrapped, line-scrolled plain text (the ratify-ready draft TOML
/// preview) into `area`, clamping `scroll` to the real wrapped-row bound the
/// same way [`FleetSetupView::render_review`]'s summary does — an
/// over-estimate of wrapped height is harmless (scroll clamps at the end).
fn render_scrollable_text(area: Rect, buf: &mut Buffer, text: &str, scroll: usize) {
    let lines: Vec<Line> = text
        .lines()
        .map(|line| Line::from(line.to_string()))
        .collect();
    let wrap_width = usize::from(area.width).max(1);
    let visual_rows: usize = lines
        .iter()
        .map(|line| line.width().div_ceil(wrap_width).max(1))
        .sum();
    let max_scroll = visual_rows.saturating_sub(usize::from(area.height).max(1));
    let scroll = scroll.min(max_scroll);
    Paragraph::new(lines)
        .wrap(Wrap { trim: true })
        .scroll((scroll as u16, 0))
        .render(area, buf);
}

/// Render a wizard choice step: a list of selectable identifiers on the left and
/// a wrapped detail pane (summary + description + context) on the right. Stacks
/// vertically when the body is too narrow for two columns so nothing truncates.
fn render_choice_step(
    area: Rect,
    buf: &mut Buffer,
    choices: &[Choice],
    selected: usize,
    context: &[String],
) {
    if area.width == 0 || area.height == 0 {
        return;
    }

    let (list_area, detail_area) = if area.width >= CHOICE_TWO_COLUMN_MIN_WIDTH {
        let cols = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Length(CHOICE_LIST_WIDTH),
                Constraint::Min(CHOICE_DETAIL_MIN_WIDTH),
            ])
            .split(area);
        (cols[0], cols[1])
    } else {
        let list_height = (choices.len() as u16).min(area.height.saturating_sub(1).max(1));
        let rows = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Length(list_height), Constraint::Min(1)])
            .split(area);
        (rows[0], rows[1])
    };

    // List: labels are identifiers, so a `▸`-marked single line each is safe.
    let list_width = usize::from(list_area.width);
    let visible = choices.len().min(usize::from(list_area.height));
    let row_start = choice_window_start(choices.len(), selected, visible);
    let mut list_lines: Vec<Line> = Vec::with_capacity(visible);
    for (idx, choice) in choices.iter().enumerate().skip(row_start).take(visible) {
        let is_selected = idx == selected;
        let pointer = format!("{} ", crate::tui::glyphs::selection_marker(is_selected));
        let style = if is_selected {
            menu_style::selected_row_style()
        } else {
            Style::default().fg(palette::TEXT_PRIMARY)
        };
        list_lines.push(Line::from(Span::styled(
            truncate_view_text(&format!("{pointer}{}", choice.label), list_width),
            style,
        )));
    }
    Paragraph::new(list_lines).render(list_area, buf);

    // Detail: summary + wrapped description + wrapped context, all word-wrapped.
    let choice = &choices[selected.min(choices.len().saturating_sub(1))];
    let mut detail_lines: Vec<Line> = vec![Line::from(Span::styled(
        choice.summary.clone(),
        Style::default().fg(palette::WHALE_ACTION).bold(),
    ))];
    // An empty description (compact tiers drop the long explanation so the
    // decisive facts stay on screen) leaves no orphan blank rows behind.
    if !choice.description.is_empty() {
        detail_lines.push(Line::from(""));
        detail_lines.push(Line::from(Span::styled(
            choice.description.clone(),
            Style::default().fg(palette::TEXT_PRIMARY),
        )));
    }
    if !context.is_empty() {
        detail_lines.push(Line::from(""));
        for entry in context {
            detail_lines.push(Line::from(Span::styled(
                entry.clone(),
                Style::default().fg(palette::TEXT_MUTED),
            )));
        }
    }
    Paragraph::new(detail_lines)
        .wrap(Wrap { trim: true })
        .render(detail_area, buf);
}

/// Register exactly the list column/stack rows painted by
/// [`render_choice_step`]. The detail pane intentionally owns no hitboxes.
fn register_choice_hitboxes(
    area: Rect,
    choice_count: usize,
    selected: usize,
    hitboxes: &RefCell<Vec<(Rect, usize)>>,
) {
    if area.width == 0 || area.height == 0 || choice_count == 0 {
        return;
    }
    let list_area = if area.width >= CHOICE_TWO_COLUMN_MIN_WIDTH {
        Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Length(CHOICE_LIST_WIDTH),
                Constraint::Min(CHOICE_DETAIL_MIN_WIDTH),
            ])
            .split(area)[0]
    } else {
        let list_height = (choice_count as u16).min(area.height.saturating_sub(1).max(1));
        Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Length(list_height), Constraint::Min(1)])
            .split(area)[0]
    };
    let visible = choice_count.min(usize::from(list_area.height));
    let row_start = choice_window_start(choice_count, selected, visible);
    let mut rows = hitboxes.borrow_mut();
    rows.extend((0..visible).map(|visible_idx| {
        let choice_idx = row_start + visible_idx;
        (
            Rect::new(
                list_area.x,
                list_area.y.saturating_add(visible_idx as u16),
                list_area.width,
                1,
            ),
            choice_idx,
        )
    }));
}

fn choice_window_start(total: usize, selected: usize, visible: usize) -> usize {
    if total <= visible || visible == 0 {
        return 0;
    }
    selected
        .saturating_add(1)
        .saturating_sub(visible)
        .min(total.saturating_sub(visible))
}

/// Resolve one save destination off the paint path: the exact target file,
/// whether it already exists, and — when it cannot be written — the localized
/// reason. A disabled destination is never silently swapped for the other.
fn destination_status(
    scope: FleetProfileScope,
    workspace: &Path,
    personal_dir: &Result<PathBuf, String>,
    file_name: &str,
    project_profiles_enabled: bool,
    locale: crate::localization::Locale,
) -> DestinationStatus {
    let dir: Result<PathBuf, String> = match scope {
        FleetProfileScope::Project => {
            Ok(workspace.join(crate::fleet::profile::WORKSPACE_AGENT_PROFILE_DIR))
        }
        FleetProfileScope::Personal => personal_dir.clone(),
    };
    let (target, mut unavailable_reason) = match dir {
        Ok(dir) => (dir.join(file_name), None),
        Err(err) => (
            PathBuf::from(scope.display_dir()).join(file_name),
            Some(tr(locale, MessageId::FleetDestReasonHomeUnavailable).replace("{error}", &err)),
        ),
    };
    if unavailable_reason.is_none() {
        match scope {
            FleetProfileScope::Project => {
                if !project_profiles_enabled {
                    unavailable_reason =
                        Some(tr(locale, MessageId::FleetDestReasonNoProjectConfig).into_owned());
                } else if !workspace.is_dir() {
                    unavailable_reason = Some(
                        tr(locale, MessageId::FleetDestReasonWorkspaceMissing)
                            .replace("{path}", &workspace.display().to_string()),
                    );
                }
            }
            FleetProfileScope::Personal => {}
        }
    }
    if unavailable_reason.is_none()
        && let Some(parent) = target.parent()
        && parent.exists()
        && !parent.is_dir()
    {
        unavailable_reason = Some(
            tr(locale, MessageId::FleetDestReasonWorkspaceMissing)
                .replace("{path}", &parent.display().to_string()),
        );
    }
    let target_exists = unavailable_reason.is_none() && target.is_file();
    DestinationStatus {
        scope,
        unavailable_reason,
        target,
        target_exists,
    }
}

/// Sanitize a planner role label into a safe TOML file stem.
fn profile_file_stem(role: &str) -> String {
    let stem: String = role
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
        .collect();
    let stem = stem.trim_matches('-').to_ascii_lowercase();
    if stem.is_empty() {
        "custom".to_string()
    } else {
        stem
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tui::views::ViewStack;
    use crossterm::event::KeyModifiers;
    use unicode_width::UnicodeWidthStr;

    const BLOCKER_SIZES: [(u16, u16); 5] = [(80, 24), (89, 50), (100, 30), (120, 32), (160, 40)];

    fn snapshot() -> FleetSetupSnapshot {
        FleetSetupSnapshot {
            workspace: PathBuf::from("/tmp/codewhale-test-workspace"),
            locale: crate::localization::Locale::En,
            provider_ready: true,
            provider: "DeepSeek".to_string(),
            model: "deepseek-v4-pro".to_string(),
            reasoning: "Auto".to_string(),
            subagents_enabled: true,
            max_subagents: 8,
            launch_concurrency: 3,
            max_admitted: 20,
            subagent_spawn_depth: 3,
            fleet_spawn_depth: 3,
            api_timeout_secs: 120,
            heartbeat_timeout_secs: 300,
            roster_members: crate::fleet::roster::FleetRoster::built_ins_only()
                .members()
                .iter()
                .map(|member| (member.id.to_lowercase(), member.origin.to_string()))
                .collect(),
            roster_details: Vec::new(),
            project_profiles_enabled: true,
            personal_profile_dir: Ok(test_personal_dir()),
            available_models: vec![
                (
                    "deepseek".to_string(),
                    "deepseek-v4-pro".to_string(),
                    crate::provider_readiness::ResolvedProviderReadiness::SavedUnchecked,
                ),
                (
                    "deepseek".to_string(),
                    "deepseek-v4-flash".to_string(),
                    crate::provider_readiness::ResolvedProviderReadiness::SavedUnchecked,
                ),
            ],
        }
    }

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    /// A hermetic personal profile dir shared by the fixture snapshot, so no
    /// test reads the developer's real `$CODEWHALE_HOME/agents`.
    fn test_personal_dir() -> PathBuf {
        static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
        DIR.get_or_init(|| tempfile::tempdir().expect("personal dir"))
            .path()
            .join("agents")
    }

    fn sample_draft() -> Box<crate::fleet::profile::FleetProfileDraft> {
        let crate::fleet::profile::UntrustedProfileParse::Drafted(draft) =
            crate::fleet::profile::FleetProfileDraft::from_untrusted_json(
                r#"{"id":"reviewer","role_hint":"reviewer","description":"Reviews diffs.","instructions":"Read. Report. Stop."}"#,
            )
        else {
            panic!("sample draft should parse");
        };
        draft
    }

    /// #5038: the Model step's detail pane carries capability badges for
    /// known catalog models and honestly omits them for unknown models, so
    /// stale/absent data never blocks selection.
    #[test]
    fn model_step_detail_shows_capability_badges_for_known_models_only() {
        let mut snap = snapshot();
        snap.available_models.push((
            "deepseek".to_string(),
            "totally-made-up-model-xyz".to_string(),
            crate::provider_readiness::ResolvedProviderReadiness::SavedUnchecked,
        ));
        let view = FleetSetupView::from_snapshot(snap);

        let known = view
            .model_choices
            .iter()
            .find(|choice| choice.label == "deepseek-v4-pro")
            .expect("known catalog model row");
        assert!(
            known.description.contains("Capabilities:"),
            "{}",
            known.description
        );
        assert!(
            known.description.contains("1M ctx"),
            "{}",
            known.description
        );
        assert!(
            known.description.contains("catalog"),
            "catalog-backed rows must name catalog provenance: {}",
            known.description
        );

        let unknown = view.model_choices.last().expect("appended unknown row");
        assert_eq!(unknown.label, "totally-made-up-model-xyz");
        assert!(
            !unknown.description.contains("Capabilities:"),
            "{}",
            unknown.description
        );
        // The unknown row stays selectable; absence of data is not a block.
        assert_eq!(
            view.model_row_states.last(),
            Some(&FleetModelRowState::Ready)
        );
    }

    #[test]
    fn provider_display_label_preserves_case_colliding_custom_ids() {
        assert_eq!(provider_display_label("deepseek"), "DeepSeek");
        assert_eq!(provider_display_label("CUSTOM"), "CUSTOM");
        assert_eq!(provider_display_label("OPENAI"), "OPENAI");
    }

    fn to_review(view: &mut FleetSetupView) {
        view.handle_key(key(KeyCode::Enter)); // Role -> Model
        view.handle_key(key(KeyCode::Enter)); // Model -> Destination
        assert_eq!(view.step, Step::Destination);
        view.handle_key(key(KeyCode::Enter)); // Destination (Personal) -> Review
        assert_eq!(view.step, Step::Review);
    }

    /// Rendered text with all whitespace and box borders removed, so a phrase
    /// or path that wrapped across rows (temp-dir paths vary in length per
    /// platform and CI runner) still compares as one token.
    fn squashed(text: &str) -> String {
        text.chars()
            .filter(|c| !c.is_whitespace() && !matches!(c, '' | '' | '' | '' | '|'))
            .collect()
    }

    fn contains_wrapped(text: &str, needle: &str) -> bool {
        squashed(text).contains(&squashed(needle))
    }

    fn rendered_text(view: &FleetSetupView, w: u16, h: u16) -> String {
        let area = Rect::new(0, 0, w, h);
        let mut buf = Buffer::empty(area);
        view.render(area, &mut buf);
        (0..h)
            .map(|y| {
                (0..w)
                    .map(|x| buf[(x, y)].symbol().to_string())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    fn workspace_snapshot(workspace: &Path) -> FleetSetupSnapshot {
        FleetSetupSnapshot {
            workspace: workspace.to_path_buf(),
            ..snapshot()
        }
    }

    // ------------------------------------------------------------------
    // Save-scope redesign: destination step, review actions, no silent writes.
    // ------------------------------------------------------------------

    #[test]
    fn destination_step_sits_between_model_and_review_and_names_the_exact_file() {
        let temp = tempfile::tempdir().expect("temp workspace");
        let mut view = FleetSetupView::from_snapshot(workspace_snapshot(temp.path()));
        view.handle_key(key(KeyCode::Down)); // scout
        view.handle_key(key(KeyCode::Enter)); // -> Model
        view.handle_key(key(KeyCode::Enter)); // inherit -> Destination
        assert_eq!(view.step, Step::Destination);
        assert!(
            !view.scope_decided,
            "nothing is decided until the user picks"
        );
        let text = rendered_text(&view, 120, 32);
        assert!(text.contains("Where should this profile live?"), "{text}");
        assert!(text.contains("This project"), "{text}");
        assert!(text.contains("Personal"), "{text}");
        assert!(text.contains("Step 3/4"), "{text}");
        // The highlighted (Personal) row shows its resolved file.
        let personal = test_personal_dir().join("scout.toml");
        assert!(
            text.contains("File:") && text.contains("agents"),
            "resolved file must be visible: {text}"
        );
        assert_eq!(view.destinations.as_ref().unwrap()[1].target, personal);
        // Up -> This project shows the workspace file.
        view.handle_key(key(KeyCode::Up));
        let text = rendered_text(&view, 120, 32);
        let project = temp.path().join(PROFILE_DIR).join("scout.toml");
        assert!(!text.contains("Will replace"), "{text}");
        assert_eq!(view.destinations.as_ref().unwrap()[0].target, project);
    }

    #[test]
    fn header_chip_says_where_it_saves_on_every_step_once_decided() {
        let temp = tempfile::tempdir().expect("temp workspace");
        let mut view = FleetSetupView::from_snapshot(workspace_snapshot(temp.path()));
        let text = rendered_text(&view, 120, 32);
        assert!(text.contains("Saves to: choose in step 3"), "{text}");
        view.handle_key(key(KeyCode::Enter));
        view.handle_key(key(KeyCode::Enter));
        view.handle_key(key(KeyCode::Up)); // This project
        view.handle_key(key(KeyCode::Enter)); // -> Review
        assert_eq!(view.step, Step::Review);
        assert!(view.scope_decided);
        assert_eq!(view.profile_scope, FleetProfileScope::Project);
        let text = rendered_text(&view, 120, 32);
        assert!(text.contains("Saves to: This project"), "{text}");
        assert!(text.contains("Save to this project"), "{text}");
        // Going back keeps the decided destination visible while revising.
        view.handle_key(key(KeyCode::Esc)); // -> Destination
        view.handle_key(key(KeyCode::Esc)); // -> Model
        assert_eq!(view.step, Step::Model);
        let text = rendered_text(&view, 120, 32);
        assert!(text.contains("Saves to: This project"), "{text}");
    }

    #[test]
    fn switching_destination_preserves_role_model_and_thinking() {
        let temp = tempfile::tempdir().expect("temp workspace");
        let mut view = FleetSetupView::from_snapshot(workspace_snapshot(temp.path()));
        view.handle_key(key(KeyCode::Down));
        view.handle_key(key(KeyCode::Down)); // builder
        view.handle_key(key(KeyCode::Enter));
        view.handle_key(key(KeyCode::Down)); // deepseek-v4-pro
        view.handle_key(key(KeyCode::Enter)); // -> Destination
        view.handle_key(key(KeyCode::Up)); // This project
        view.handle_key(key(KeyCode::Enter)); // -> Review
        view.handle_key(key(KeyCode::Char('t'))); // thinking: off
        let role = view.selected_role();
        let route = view.selected_route();
        let thinking = view.thinking_idx;
        assert_eq!(view.profile_scope, FleetProfileScope::Project);
        // Change destination via the focused control, pick Personal.
        view.handle_key(key(KeyCode::Tab));
        assert_eq!(view.review_focus, ReviewFocus::ChangeDestination);
        assert_eq!(
            view.profile_scope,
            FleetProfileScope::Project,
            "Tab never changes scope"
        );
        view.handle_key(key(KeyCode::Enter));
        assert_eq!(view.step, Step::Destination);
        view.handle_key(key(KeyCode::Down));
        view.handle_key(key(KeyCode::Char(' ')));
        assert_eq!(view.step, Step::Review);
        assert_eq!(view.profile_scope, FleetProfileScope::Personal);
        assert_eq!(view.selected_role(), role);
        assert_eq!(view.selected_route(), route);
        assert_eq!(view.thinking_idx, thinking);
        let text = rendered_text(&view, 120, 32);
        assert!(text.contains("Save as Personal profile"), "{text}");
    }

    #[test]
    fn existing_target_is_announced_and_needs_a_second_enter_to_replace() {
        let temp = tempfile::tempdir().expect("temp workspace");
        let dir = temp.path().join(PROFILE_DIR);
        std::fs::create_dir_all(&dir).expect("dir");
        std::fs::write(dir.join("manager.toml"), "id = \"manager\"\n").expect("existing");
        let mut view = FleetSetupView::from_snapshot(workspace_snapshot(temp.path()));
        view.handle_key(key(KeyCode::Enter)); // manager
        view.handle_key(key(KeyCode::Enter)); // inherit -> Destination
        view.handle_key(key(KeyCode::Up)); // This project
        let text = rendered_text(&view, 120, 32);
        assert!(
            contains_wrapped(&text, "Will replace the existing file"),
            "{text}"
        );
        view.handle_key(key(KeyCode::Enter)); // -> Review
        let text = rendered_text(&view, 120, 32);
        assert!(contains_wrapped(&text, "Replace in this project"), "{text}");
        assert!(
            contains_wrapped(&text, "Will replace the existing file"),
            "{text}"
        );
        // First Enter arms; nothing is emitted.
        let action = view.handle_key(key(KeyCode::Enter));
        assert!(
            matches!(action, ViewAction::None),
            "first Enter must not save"
        );
        assert!(view.replace_armed);
        let text = rendered_text(&view, 120, 32);
        assert!(
            text.contains("Press Enter again to replace manager.toml"),
            "{text}"
        );
        // Moving focus disarms.
        view.handle_key(key(KeyCode::Tab));
        assert!(!view.replace_armed);
        view.handle_key(key(KeyCode::BackTab));
        view.handle_key(key(KeyCode::Enter)); // arm again
        let action = view.handle_key(key(KeyCode::Enter)); // confirm
        let ViewAction::EmitAndClose(ViewEvent::FleetProfileDraftCommitRequested { draft, scope }) =
            action
        else {
            panic!("second Enter saves");
        };
        assert_eq!(scope, FleetProfileScope::Project);
        assert_eq!(draft.id, "manager");
    }

    #[test]
    fn project_destination_is_disabled_with_a_reason_and_never_falls_back() {
        let temp = tempfile::tempdir().expect("temp workspace");
        let mut view = FleetSetupView::from_snapshot(FleetSetupSnapshot {
            project_profiles_enabled: false,
            ..workspace_snapshot(temp.path())
        });
        view.handle_key(key(KeyCode::Enter));
        view.handle_key(key(KeyCode::Enter)); // -> Destination
        view.handle_key(key(KeyCode::Up)); // This project (disabled)
        let text = rendered_text(&view, 120, 32);
        assert!(
            text.contains("Not available: project profiles are disabled"),
            "{text}"
        );
        let action = view.handle_key(key(KeyCode::Enter));
        assert!(matches!(action, ViewAction::None));
        assert_eq!(
            view.step,
            Step::Destination,
            "disabled destination does not advance"
        );
        assert!(!view.scope_decided);
        assert_eq!(
            view.profile_scope,
            FleetProfileScope::Personal,
            "no silent fallback either way: the scope is untouched"
        );
        // Personal still works.
        view.handle_key(key(KeyCode::Down));
        view.handle_key(key(KeyCode::Enter));
        assert_eq!(view.step, Step::Review);
        assert_eq!(view.profile_scope, FleetProfileScope::Personal);
    }

    #[test]
    fn precedence_consequences_are_stated_for_both_destinations() {
        let temp = tempfile::tempdir().expect("temp workspace");
        let project_source = temp.path().join(PROFILE_DIR).join("scout.toml");
        let mut snap = workspace_snapshot(temp.path());
        snap.roster_members.retain(|(id, _)| id != "scout");
        snap.roster_members
            .push(("scout".to_string(), "project".to_string()));
        snap.roster_details.push(RosterMemberDetail {
            id: "scout".to_string(),
            scope: FleetProfileScope::Project,
            source: project_source,
            provider: Some("deepseek".to_string()),
            model: Some("deepseek-v4-flash".to_string()),
            reasoning_effort: None,
        });
        let mut view = FleetSetupView::from_snapshot(snap);
        view.handle_key(key(KeyCode::Down)); // scout
        view.handle_key(key(KeyCode::Enter));
        view.handle_key(key(KeyCode::Enter)); // -> Destination (Personal highlighted)
        let text = rendered_text(&view, 120, 32);
        assert!(text.contains("already has a"), "{text}");
        view.handle_key(key(KeyCode::Up)); // This project
        let text = rendered_text(&view, 120, 32);
        assert!(!text.contains("already has a"), "{text}");
        assert!(text.contains("Replaces the project"), "{text}");
    }

    #[test]
    fn reopening_a_saved_member_preloads_its_scope_and_route() {
        let temp = tempfile::tempdir().expect("temp workspace");
        let mut snap = workspace_snapshot(temp.path());
        snap.roster_members.retain(|(id, _)| id != "scout");
        snap.roster_members
            .push(("scout".to_string(), "project".to_string()));
        snap.roster_details.push(RosterMemberDetail {
            id: "scout".to_string(),
            scope: FleetProfileScope::Project,
            source: temp.path().join(PROFILE_DIR).join("scout.toml"),
            provider: Some("deepseek".to_string()),
            model: Some("deepseek-v4-flash".to_string()),
            reasoning_effort: Some("high".to_string()),
        });
        let view = FleetSetupView::from_snapshot_for_role(snap, "scout");
        assert_eq!(view.step, Step::Model);
        assert!(view.scope_decided);
        assert_eq!(view.profile_scope, FleetProfileScope::Project);
        assert_eq!(
            view.selected_route(),
            Some(("deepseek".to_string(), "deepseek-v4-flash".to_string()))
        );
        assert_eq!(view.selected_reasoning_effort().as_deref(), Some("high"));
        let text = rendered_text(&view, 120, 32);
        assert!(text.contains("Saves to: This project"), "{text}");
    }

    #[test]
    fn blocked_model_row_explains_why_enter_did_nothing() {
        let mut snap = snapshot();
        snap.available_models = vec![(
            "xai".to_string(),
            "grok-4.5".to_string(),
            crate::provider_readiness::ResolvedProviderReadiness::MissingKey,
        )];
        let mut view = FleetSetupView::from_snapshot(snap);
        view.handle_key(key(KeyCode::Enter)); // -> Model
        view.model_idx = 1;
        view.handle_key(key(KeyCode::Enter));
        assert_eq!(view.step, Step::Model);
        assert!(
            view.notice
                .as_deref()
                .is_some_and(|n| n.contains("Not selectable"))
        );
        let text = rendered_text(&view, 120, 32);
        assert!(text.contains("Not selectable"), "{text}");
        view.handle_key(key(KeyCode::Down));
        assert!(view.notice.is_none(), "navigation clears the notice");
    }

    #[test]
    fn q_only_cancels_from_the_first_step_and_esc_is_back_elsewhere() {
        let mut view = FleetSetupView::from_snapshot(snapshot());
        view.handle_key(key(KeyCode::Enter)); // -> Model
        assert!(matches!(
            view.handle_key(key(KeyCode::Char('q'))),
            ViewAction::None
        ));
        assert_eq!(view.step, Step::Model);
        assert!(matches!(
            view.handle_key(key(KeyCode::Esc)),
            ViewAction::None
        ));
        assert_eq!(view.step, Step::Role);
        assert!(matches!(
            view.handle_key(key(KeyCode::Char('q'))),
            ViewAction::Close
        ));
        let hints = view.footer_hints();
        assert!(hints.iter().any(|h| h.key == "Esc" && h.label == "cancel"));
    }

    #[test]
    fn destination_and_review_stay_readable_at_60x16_80x24_and_120x32() {
        let temp = tempfile::tempdir().expect("temp workspace");
        for (w, h) in [(60u16, 16u16), (80, 24), (120, 32)] {
            let mut view = FleetSetupView::from_snapshot(workspace_snapshot(temp.path()));
            view.handle_key(key(KeyCode::Enter));
            view.handle_key(key(KeyCode::Enter)); // -> Destination
            let text = rendered_text(&view, w, h);
            assert!(text.contains("This project"), "{w}x{h}: {text}");
            assert!(text.contains("Personal"), "{w}x{h}: {text}");
            assert!(text.contains("File:"), "{w}x{h}: {text}");
            assert!(text.contains("Saves to:"), "{w}x{h}: {text}");
            view.handle_key(key(KeyCode::Up));
            view.handle_key(key(KeyCode::Enter)); // -> Review
            let text = rendered_text(&view, w, h);
            assert!(text.contains("Save to this project"), "{w}x{h}: {text}");
            assert!(text.contains("Saves to: This project"), "{w}x{h}: {text}");
            for line in text.lines() {
                assert!(
                    unicode_width::UnicodeWidthStr::width(line) <= usize::from(w),
                    "{w}x{h}: overflow: {line}"
                );
            }
        }
    }

    fn open_composition(view: &mut FleetSetupView) {
        view.handle_key(key(KeyCode::Enter)); // Role -> Model
        assert_eq!(view.step, Step::Model);
        view.handle_key(key(KeyCode::Char('c')));
        assert_eq!(view.step, Step::Composition);
    }

    #[test]
    fn composition_is_deterministic_unratified_and_pool_bounded() {
        let first = FleetSetupView::from_snapshot(snapshot());
        let second = FleetSetupView::from_snapshot(snapshot());
        let first = first.composition.expect("configured pool advisory");
        let second = second.composition.expect("configured pool advisory");

        assert_eq!(first.proposal, second.proposal);
        assert_eq!(first.proposal.ratification, RatificationState::Unratified);
        assert!(!first.proposal.is_actionable());
        assert_eq!(
            first.request.pool_keys(),
            vec![
                "deepseek/deepseek-v4-flash".to_string(),
                "deepseek/deepseek-v4-pro".to_string(),
            ]
        );
        for suggestion in &first.proposal.suggestions {
            assert!(
                first
                    .request
                    .pool_contains(&suggestion.provider, &suggestion.model),
                "{suggestion:?} escaped the configured pool"
            );
        }

        let rendered = render_through_stack(
            || {
                let mut view = FleetSetupView::from_snapshot(snapshot());
                open_composition(&mut view);
                view
            },
            120,
            40,
        )
        .join("\n");
        assert!(rendered.contains("UNRATIFIED"), "{rendered}");
        assert!(rendered.contains("Suggestion only"), "{rendered}");
        assert!(rendered.contains("a/Enter accept"), "{rendered}");
        assert!(rendered.contains("e edit"), "{rendered}");
        assert!(rendered.contains("r reject"), "{rendered}");
    }

    #[test]
    fn composition_accept_edit_and_reject_keep_the_existing_save_boundary() {
        let mut accepted = FleetSetupView::from_snapshot(snapshot());
        open_composition(&mut accepted);
        let expected = accepted
            .validated_composition_route()
            .expect("selected role suggestion");
        assert!(matches!(
            accepted.handle_key(key(KeyCode::Char('a'))),
            ViewAction::None
        ));
        assert_eq!(accepted.step, Step::Destination);
        accepted.handle_key(key(KeyCode::Enter)); // Destination -> Review
        assert_eq!(accepted.step, Step::Review);
        assert_eq!(accepted.composition_decision, CompositionDecision::Accepted);
        assert_eq!(accepted.selected_route().as_ref(), Some(&expected));
        let ViewAction::EmitAndClose(ViewEvent::FleetProfileDraftCommitRequested { draft, .. }) =
            accepted.handle_key(key(KeyCode::Enter))
        else {
            panic!("only the existing review save path may persist an accepted suggestion");
        };
        assert_eq!(
            (draft.provider.as_deref(), draft.model.as_deref()),
            (Some(expected.0.as_str()), Some(expected.1.as_str()))
        );

        let mut edited = FleetSetupView::from_snapshot(snapshot());
        open_composition(&mut edited);
        let suggested = edited
            .validated_composition_route()
            .expect("selected role suggestion");
        assert!(matches!(
            edited.handle_key(key(KeyCode::Char('e'))),
            ViewAction::None
        ));
        assert_eq!(edited.step, Step::Model);
        assert_eq!(edited.composition_decision, CompositionDecision::Edited);
        assert_eq!(edited.selected_route().as_ref(), Some(&suggested));

        let mut rejected = FleetSetupView::from_snapshot(snapshot());
        open_composition(&mut rejected);
        assert!(rejected.selected_route().is_none());
        assert!(matches!(
            rejected.handle_key(key(KeyCode::Char('r'))),
            ViewAction::None
        ));
        assert_eq!(rejected.step, Step::Model);
        assert_eq!(rejected.composition_decision, CompositionDecision::Rejected);
        assert!(rejected.selected_route().is_none());
    }

    #[test]
    fn composition_acceptance_revalidates_and_rejects_an_out_of_pool_route() {
        let mut view = FleetSetupView::from_snapshot(snapshot());
        open_composition(&mut view);
        let advisory = view.composition.as_mut().expect("advisory");
        let manager = advisory
            .proposal
            .suggestions
            .iter_mut()
            .find(|suggestion| suggestion.role == "manager")
            .expect("manager suggestion");
        manager.provider = "unconfigured".to_string();
        manager.model = "outside-pool".to_string();
        assert!(matches!(
            advisory.validated_route_for_role("manager"),
            Err(CompositionError::ModelOutsidePool { .. })
        ));

        assert!(matches!(
            view.handle_key(key(KeyCode::Char('a'))),
            ViewAction::None
        ));
        assert_eq!(view.step, Step::Composition);
        assert_eq!(view.composition_decision, CompositionDecision::Pending);
        assert!(view.selected_route().is_none());
    }

    #[test]
    fn composition_does_not_suggest_a_blocked_configured_route() {
        let mut snap = snapshot();
        snap.available_models.push((
            "anthropic".to_string(),
            "blocked-model".to_string(),
            crate::provider_readiness::ResolvedProviderReadiness::SavedLastCheckFailed {
                category: crate::error_taxonomy::ErrorCategory::Authentication,
                message: "auth failed".to_string(),
            },
        ));
        let view = FleetSetupView::from_snapshot(snap);
        let advisory = view.composition.expect("ready pool still composes");
        assert!(!advisory.request.pool_contains("anthropic", "blocked-model"));
        assert!(
            advisory
                .proposal
                .suggestions
                .iter()
                .all(|suggestion| suggestion.model != "blocked-model")
        );
    }

    #[test]
    fn review_step_m_requests_model_draft_with_current_answers() {
        let mut view = FleetSetupView::from_snapshot(snapshot());
        to_review(&mut view);

        let action = view.handle_key(key(KeyCode::Char('m')));
        let ViewAction::Emit(ViewEvent::FleetProfileModelDraftRequested {
            role,
            model,
            provider,
            reasoning_effort,
            locale,
        }) = action
        else {
            panic!("expected model draft request");
        };
        assert!(!role.is_empty());
        assert!(!model.is_empty());
        // Default selection is `inherit` (model_idx 0), which carries no
        // concrete provider route.
        assert_eq!(provider, None);
        assert_eq!(reasoning_effort, None);
        assert_eq!(locale, crate::localization::Locale::En);
    }

    #[test]
    fn m_redraft_preserves_a_cross_provider_pick_regression_4093() {
        // #4093 BLOCKER 2 regression: a cross-provider route pick followed by an
        // `m` model-assisted redraft must STILL persist the picked provider. A
        // model draft comes from `from_untrusted_json`, which hard-sets
        // `provider: None` (and can echo any model). Without re-injection the
        // ratified profile would carry `model` with no `provider` — the exact
        // ambiguous, provider-scoped profile #4093 removes.
        //
        // The active/session provider is DeepSeek; the picked route is a
        // GLM model on Zai — a genuinely different provider than the parent.
        let mut snap = snapshot();
        snap.provider = "DeepSeek".to_string();
        snap.model = "deepseek-v4-pro".to_string();
        snap.available_models = vec![(
            "zai".to_string(),
            "glm-5.2".to_string(),
            crate::provider_readiness::ResolvedProviderReadiness::SavedUnchecked,
        )];
        let mut view = FleetSetupView::from_snapshot(snap);

        // Role step: keep the first role. Model step: inherit(0), then the one
        // cross-provider row (1) -> pick it. Then advance to Review.
        view.handle_key(key(KeyCode::Enter)); // Role -> Model
        view.handle_key(key(KeyCode::Down)); // -> the zai/glm-5.2 row
        assert_eq!(
            view.selected_route(),
            Some(("zai".to_string(), "glm-5.2".to_string()))
        );
        view.handle_key(key(KeyCode::Enter)); // Model -> Destination
        view.handle_key(key(KeyCode::Enter)); // Destination -> Review
        assert_eq!(view.step, Step::Review);
        while view.selected_reasoning_effort().as_deref() != Some("max") {
            view.handle_key(key(KeyCode::Char('t')));
        }

        // `m` requests a draft and carries the picked cross-provider route.
        let action = view.handle_key(key(KeyCode::Char('m')));
        let ViewAction::Emit(ViewEvent::FleetProfileModelDraftRequested {
            model,
            provider,
            reasoning_effort,
            ..
        }) = action
        else {
            panic!("expected model draft request");
        };
        assert_eq!(model, "glm-5.2");
        assert_eq!(provider.as_deref(), Some("zai"));
        assert_eq!(reasoning_effort.as_deref(), Some("max"));

        // The host reconstructs the picked route from the event exactly as
        // `handle_fleet_profile_model_draft` does, and carries it to
        // `install_model_draft` (immune to the selection changing mid-draft).
        let picked_route = provider.map(|provider| (provider, model.clone()));

        // The model returns a draft that (as always) has provider: None — the
        // untrusted gate strips any provider a model tries to smuggle.
        let drafted = sample_draft();
        assert_eq!(drafted.provider, None);

        // Installing it re-injects the picked route, so the ratified draft keeps
        // BOTH the provider and the model the user actually chose, plus the
        // captured thinking tier.
        let (_title, content) = view.install_model_draft(
            drafted,
            "GLM-5.2".to_string(),
            picked_route,
            reasoning_effort,
        );
        let ratified = view.model_draft.as_deref().expect("draft installed");
        assert_eq!(ratified.provider.as_deref(), Some("zai"));
        assert_eq!(ratified.model.as_deref(), Some("glm-5.2"));
        assert_eq!(ratified.reasoning_effort.as_deref(), Some("max"));

        // The rendered TOML the ratify keypress would persist names the provider
        // explicitly — never a provider-scoped ambiguity.
        assert!(content.contains("provider = \"zai\""), "{content}");
        assert!(content.contains("model = \"glm-5.2\""), "{content}");
        assert!(content.contains("reasoning_effort = \"max\""), "{content}");

        // And ratifying commits exactly that route.
        let action = view.handle_key(key(KeyCode::Char('g')));
        let ViewAction::EmitAndClose(ViewEvent::FleetProfileDraftCommitRequested { draft, scope }) =
            action
        else {
            panic!("expected ratify commit event");
        };
        assert_eq!(scope, FleetProfileScope::Personal);
        assert_eq!(draft.provider.as_deref(), Some("zai"));
        assert_eq!(draft.model.as_deref(), Some("glm-5.2"));
        assert_eq!(draft.reasoning_effort.as_deref(), Some("max"));
    }

    #[test]
    fn model_step_filter_narrows_large_catalogs_by_provider_and_model() {
        let mut snap = snapshot();
        // Simulate an OpenRouter-scale catalog: many rows from one provider.
        for i in 0..120 {
            snap.available_models.push((
                "openrouter".to_string(),
                format!("vendor/model-{i:03}"),
                crate::provider_readiness::ResolvedProviderReadiness::SavedUnchecked,
            ));
        }
        snap.available_models.push((
            "openrouter".to_string(),
            "z-ai/glm-5-turbo".to_string(),
            crate::provider_readiness::ResolvedProviderReadiness::SavedUnchecked,
        ));
        let mut view = FleetSetupView::from_snapshot(snap);
        // Role → Model.
        view.handle_key(key(KeyCode::Enter));
        let full_len = view.step_len();
        assert!(full_len > 120, "unfiltered shows the whole catalog");

        // `/` opens the filter; typing narrows by model id substring.
        view.handle_key(key(KeyCode::Char('/')));
        for ch in "glm".chars() {
            view.handle_key(key(KeyCode::Char(ch)));
        }
        assert_eq!(view.step_len(), 1, "only the glm row survives the filter");
        let route = view.selected_route().expect("filtered selection resolves");
        assert_eq!(
            route,
            ("openrouter".to_string(), "z-ai/glm-5-turbo".to_string())
        );

        // Provider substring filters too.
        view.handle_key(key(KeyCode::Esc));
        view.handle_key(key(KeyCode::Char('/')));
        for ch in "deepseek".chars() {
            view.handle_key(key(KeyCode::Char(ch)));
        }
        // inherit's route IS the active DeepSeek route, so it matches too.
        assert_eq!(
            view.step_len(),
            3,
            "deepseek rows plus the inherit (active deepseek route) match"
        );

        // Enter keeps the filter but releases the input; Esc in filter clears.
        view.handle_key(key(KeyCode::Enter));
        assert!(!view.model_filter_active);
        assert_eq!(view.step_len(), 3);
        view.handle_key(key(KeyCode::Char('/')));
        view.handle_key(key(KeyCode::Esc));
        assert_eq!(
            view.step_len(),
            full_len,
            "clearing restores the full catalog"
        );
    }

    #[test]
    fn review_saves_starter_or_ratifies_installed_model_draft() {
        let mut view = FleetSetupView::from_snapshot(snapshot());
        to_review(&mut view);

        // A structured starter draft is save-ready from the summary.
        let action = view.handle_key(key(KeyCode::Char('g')));
        let ViewAction::EmitAndClose(ViewEvent::FleetProfileDraftCommitRequested { draft, scope }) =
            action
        else {
            panic!("expected starter commit event");
        };
        assert_eq!(scope, FleetProfileScope::Personal);
        assert_eq!(draft.id, "manager");

        let mut view = FleetSetupView::from_snapshot(snapshot());
        to_review(&mut view);
        let (title, content) =
            view.install_model_draft(sample_draft(), "GLM-5.2".to_string(), None, None);
        assert!(title.contains("GLM-5.2"));
        assert!(content.contains("id = \"reviewer\""), "{content}");
        assert!(content.contains("Nothing is saved until"), "{content}");

        let action = view.handle_key(key(KeyCode::Char('g')));
        let ViewAction::EmitAndClose(ViewEvent::FleetProfileDraftCommitRequested { draft, scope }) =
            action
        else {
            panic!("expected ratify commit event");
        };
        assert_eq!(scope, FleetProfileScope::Personal);
        assert_eq!(draft.id, "reviewer");
    }

    #[test]
    fn changing_answers_discards_a_stale_draft() {
        let mut view = FleetSetupView::from_snapshot(snapshot());
        to_review(&mut view);
        let _ = view.install_model_draft(sample_draft(), "GLM-5.2".to_string(), None, None);
        assert!(view.model_draft.is_some());

        // Back to the role step and change the selection: the draft no
        // longer matches the answers and must not survive to ratification.
        view.handle_key(key(KeyCode::Left)); // Review -> Destination
        view.handle_key(key(KeyCode::Left)); // Destination -> Model
        view.handle_key(key(KeyCode::Left)); // Model -> Role
        assert_eq!(view.step, Step::Role);
        view.handle_key(key(KeyCode::Down));
        assert!(view.model_draft.is_none());

        to_review(&mut view);
        let action = view.handle_key(key(KeyCode::Char('g')));
        let ViewAction::EmitAndClose(ViewEvent::FleetProfileDraftCommitRequested { draft, .. }) =
            action
        else {
            panic!("expected fresh deterministic starter");
        };
        assert_eq!(draft.id, "scout");
    }

    #[test]
    fn arrows_move_within_step_and_enter_advances() {
        let mut view = FleetSetupView::from_snapshot(snapshot());
        assert_eq!(view.step, Step::Role);

        view.handle_key(key(KeyCode::Down));
        assert_eq!(view.role_idx, 1);

        view.handle_key(key(KeyCode::Enter));
        assert_eq!(view.step, Step::Model);

        view.handle_key(key(KeyCode::Down));
        assert_eq!(view.model_idx, 1);

        view.handle_key(key(KeyCode::Enter));
        assert_eq!(view.step, Step::Destination);
        view.handle_key(key(KeyCode::Enter));
        assert_eq!(view.step, Step::Review);

        // `t` cycles thinking on the review step without an extra wizard screen.
        view.handle_key(key(KeyCode::Char('t')));
        assert_eq!(view.thinking_idx, 1);

        // Left steps back through the wizard.
        view.handle_key(key(KeyCode::Left));
        assert_eq!(view.step, Step::Destination);
        view.handle_key(key(KeyCode::Left));
        assert_eq!(view.step, Step::Model);
        view.handle_key(key(KeyCode::Left));
        assert_eq!(view.step, Step::Role);
    }

    #[test]
    fn roster_role_handoff_starts_at_model_and_can_return_to_role() {
        let mut via_left = FleetSetupView::from_snapshot_for_role(snapshot(), "consultant");
        assert_eq!(via_left.step, Step::Model);
        assert_eq!(via_left.selected_role(), "consultant");
        assert!(matches!(
            via_left.handle_key(key(KeyCode::Left)),
            ViewAction::None
        ));
        assert_eq!(via_left.step, Step::Role);
        assert_eq!(via_left.selected_role(), "consultant");

        let mut via_esc = FleetSetupView::from_snapshot_for_role(snapshot(), "reviewer");
        assert_eq!(via_esc.step, Step::Model);
        assert_eq!(via_esc.selected_role(), "reviewer");
        assert!(matches!(
            via_esc.handle_key(key(KeyCode::Esc)),
            ViewAction::None
        ));
        assert_eq!(via_esc.step, Step::Role);
        assert_eq!(via_esc.selected_role(), "reviewer");

        let custom = FleetSetupView::from_snapshot_for_role(snapshot(), "domain-expert");
        assert_eq!(custom.step, Step::Model);
        assert_eq!(custom.selected_role(), "custom");
    }

    #[test]
    fn esc_steps_back_then_cancels_from_role() {
        let mut view = FleetSetupView::from_snapshot(snapshot());
        view.handle_key(key(KeyCode::Enter)); // -> Model
        let action = view.handle_key(key(KeyCode::Esc));
        assert!(matches!(action, ViewAction::None));
        assert_eq!(view.step, Step::Role);
        let action = view.handle_key(key(KeyCode::Esc));
        assert!(matches!(action, ViewAction::Close));
    }

    #[test]
    fn mouse_selects_rows_and_wheel_matches_keyboard_navigation() {
        let mut view = FleetSetupView::from_snapshot(snapshot());
        let area = Rect::new(0, 0, 120, 40);
        let mut buf = Buffer::empty(area);
        view.render(area, &mut buf);
        let (rect, row) = view.row_hitboxes.borrow()[2];

        view.handle_mouse(MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column: rect.x,
            row: rect.y,
            modifiers: KeyModifiers::NONE,
        });
        assert_eq!(row, 2);
        assert_eq!(view.role_idx, 2);

        view.handle_mouse(MouseEvent {
            kind: MouseEventKind::ScrollDown,
            column: rect.x,
            row: rect.y,
            modifiers: KeyModifiers::NONE,
        });
        assert_eq!(view.role_idx, 3);
        view.handle_mouse(MouseEvent {
            kind: MouseEventKind::ScrollUp,
            column: rect.x,
            row: rect.y,
            modifiers: KeyModifiers::NONE,
        });
        assert_eq!(view.role_idx, 2);
    }

    #[test]
    fn compact_choice_window_keeps_deep_selection_visible_and_clickable() {
        let mut view = FleetSetupView::from_snapshot(snapshot());
        view.role_idx = ROLES.len() - 1;
        let area = Rect::new(0, 0, 80, 16);
        let mut buf = Buffer::empty(area);
        view.render(area, &mut buf);
        let rendered = (0..area.height)
            .map(|y| {
                (0..area.width)
                    .map(|x| buf[(x, y)].symbol())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n");

        assert!(rendered.contains("▸ custom"), "{rendered}");
        assert!(
            view.row_hitboxes
                .borrow()
                .iter()
                .any(|(_, idx)| *idx == ROLES.len() - 1),
            "selected row needs an aligned mouse hitbox"
        );
    }

    /// #3908: destination facts (exists/is_dir) are computed on the
    /// transitions that can change them — never per paint.
    #[test]
    fn review_destinations_are_cached_on_transitions_not_recomputed_per_paint() {
        let mut view = FleetSetupView::from_snapshot(snapshot());
        assert!(
            view.destinations.is_none(),
            "nothing is stat-ed before the user reaches the Destination step"
        );

        view.advance(); // Role -> Model
        view.advance(); // Model -> Destination
        assert_eq!(view.step, Step::Destination);
        let on_entry = view
            .destinations
            .clone()
            .expect("entering Destination must populate the cached statuses");
        view.advance(); // Destination -> Review
        assert_eq!(view.step, Step::Review);

        // Painting repeatedly must not change the cached value — that is the
        // whole point — and must not panic on the cached-read path.
        let area = Rect::new(0, 0, 80, 24);
        for _ in 0..3 {
            let mut buf = Buffer::empty(area);
            view.render(area, &mut buf);
        }
        assert_eq!(view.destinations.as_ref(), Some(&on_entry));
    }

    #[test]
    fn destination_status_reports_new_file_replace_and_disabled_reasons() {
        let temp = tempfile::tempdir().expect("temp workspace");
        let personal = Ok(temp.path().join("home-agents"));
        let fresh = destination_status(
            FleetProfileScope::Project,
            temp.path(),
            &personal,
            "reviewer.toml",
            true,
            crate::localization::Locale::En,
        );
        assert_eq!(
            fresh.target,
            temp.path().join(PROFILE_DIR).join("reviewer.toml")
        );
        assert!(!fresh.target_exists);
        assert!(fresh.unavailable_reason.is_none());

        let profile_dir = temp.path().join(PROFILE_DIR);
        std::fs::create_dir_all(&profile_dir).expect("profile dir");
        std::fs::write(profile_dir.join("reviewer.toml"), "id = \"reviewer\"\n")
            .expect("existing profile");
        let existing = destination_status(
            FleetProfileScope::Project,
            temp.path(),
            &personal,
            "reviewer.toml",
            true,
            crate::localization::Locale::En,
        );
        assert!(
            existing.target_exists,
            "the exact target file is detected, not a dir count"
        );

        let disabled = destination_status(
            FleetProfileScope::Project,
            temp.path(),
            &personal,
            "reviewer.toml",
            false,
            crate::localization::Locale::En,
        );
        assert!(
            disabled
                .unavailable_reason
                .as_deref()
                .is_some_and(|r| r.contains("--no-project-config")),
            "{disabled:?}"
        );

        let missing = destination_status(
            FleetProfileScope::Project,
            &temp.path().join("does-not-exist"),
            &personal,
            "reviewer.toml",
            true,
            crate::localization::Locale::En,
        );
        assert!(missing.unavailable_reason.is_some(), "{missing:?}");
    }

    #[test]
    fn one_enter_from_review_saves_starter_profile_for_selection() {
        let mut view = FleetSetupView::from_snapshot(snapshot());
        // Role: manager(0) scout(1) builder(2) -> builder.
        view.handle_key(key(KeyCode::Down));
        view.handle_key(key(KeyCode::Down));
        view.handle_key(key(KeyCode::Enter)); // -> Model
        // Model: inherit(0) deepseek-v4-pro(1) -> deepseek-v4-pro.
        view.handle_key(key(KeyCode::Down));
        view.handle_key(key(KeyCode::Enter)); // Model -> Destination
        view.handle_key(key(KeyCode::Enter)); // Destination -> Review
        assert_eq!(view.step, Step::Review);
        while view.selected_reasoning_effort().as_deref() != Some("max") {
            view.handle_key(key(KeyCode::Char('t')));
        }

        // The Review summary is already the structured confirmation surface;
        // one Enter saves the deterministic starter without another state.
        let action = view.handle_key(key(KeyCode::Enter));
        let ViewAction::EmitAndClose(ViewEvent::FleetProfileDraftCommitRequested { draft, scope }) =
            action
        else {
            panic!("expected one-Enter starter save");
        };
        let content = draft.render_toml();
        assert!(content.contains("id = \"builder\""));
        assert!(content.contains("role_hint = \"builder\""));
        assert!(content.contains("model = \"deepseek-v4-pro\""));
        assert!(content.contains("reasoning_effort = \"max\""));
        // A concrete cross-provider route pin names its own provider
        // explicitly (#4093) — the saved profile must not be ambiguously
        // scoped to whatever provider happens to be active at launch time.
        assert!(content.contains("provider = \"deepseek\""), "{content}");
        for forbidden in ["base_url", "api_key"] {
            assert!(
                !content.contains(forbidden),
                "starter profile must not carry {forbidden}: {content}"
            );
        }

        assert_eq!(scope, FleetProfileScope::Personal);
        assert_eq!(draft.id, "builder");
        assert_eq!(draft.role_hint, "builder");
        assert_eq!(draft.model.as_deref(), Some("deepseek-v4-pro"));
        assert_eq!(draft.provider.as_deref(), Some("deepseek"));
        assert_eq!(draft.reasoning_effort.as_deref(), Some("max"));
    }

    #[test]
    fn review_defaults_to_personal_and_can_switch_to_project() {
        let temp = tempfile::tempdir().expect("temp workspace");
        let mut view = FleetSetupView::from_snapshot(workspace_snapshot(temp.path()));
        to_review(&mut view);

        assert_eq!(view.profile_scope, FleetProfileScope::Personal);
        // `s` is a secondary accelerator back to the Destination step; the
        // destination itself is chosen with a focused control, never toggled
        // silently.
        view.handle_key(key(KeyCode::Char('s')));
        assert_eq!(view.step, Step::Destination);
        assert_eq!(
            view.profile_scope,
            FleetProfileScope::Personal,
            "s alone changes nothing"
        );
        view.handle_key(key(KeyCode::Up)); // This project
        view.handle_key(key(KeyCode::Enter));
        assert_eq!(view.step, Step::Review);
        assert_eq!(view.profile_scope, FleetProfileScope::Project);

        let action = view.handle_key(key(KeyCode::Enter));
        let ViewAction::EmitAndClose(ViewEvent::FleetProfileDraftCommitRequested { draft, scope }) =
            action
        else {
            panic!("expected project profile save event");
        };
        assert_eq!(scope, FleetProfileScope::Project);
        let rendered = draft.render_toml();
        assert!(rendered.contains("id = \"manager\""), "{rendered}");
    }

    #[test]
    fn inherit_selection_starter_draft_carries_no_provider() {
        // `inherit` (no concrete route pin) must never carry a provider —
        // there's no explicit route to name (#4093).
        let mut view = FleetSetupView::from_snapshot(snapshot());
        to_review(&mut view);
        let action = view.handle_key(key(KeyCode::Enter));
        let ViewAction::EmitAndClose(ViewEvent::FleetProfileDraftCommitRequested { draft, .. }) =
            action
        else {
            panic!("expected inherit starter save");
        };
        assert_eq!(draft.model, None);
        assert_eq!(draft.provider, None);
        assert_eq!(draft.reasoning_effort, None);
        let content = draft.render_toml();
        assert!(!content.contains("provider"), "{content}");
        assert!(!content.contains("reasoning_effort"), "{content}");
    }

    #[test]
    fn role_and_review_steps_note_roster_overrides() {
        // "reviewer" collides with the built-in roster member; the
        // role step context and review Role section must both say so.
        let mut view = FleetSetupView::from_snapshot(snapshot());
        for _ in 0..3 {
            view.handle_key(key(KeyCode::Down));
        }
        assert_eq!(view.selected_role(), "reviewer");
        assert_eq!(
            view.roster_override_note().as_deref(),
            Some("Replaces the built-in 'reviewer' role in the roster.")
        );

        let role_step = render_through_stack(
            || {
                let mut v = FleetSetupView::from_snapshot(snapshot());
                for _ in 0..3 {
                    v.handle_key(key(KeyCode::Down));
                }
                v
            },
            120,
            40,
        )
        .join("\n");
        assert!(
            contains_wrapped(&role_step, "Replaces the built-in 'reviewer'"),
            "{role_step}"
        );

        let review = render_through_stack(
            || {
                let mut v = FleetSetupView::from_snapshot(snapshot());
                for _ in 0..3 {
                    v.handle_key(key(KeyCode::Down));
                }
                v.step = Step::Review;
                v
            },
            120,
            40,
        )
        .join("\n");
        assert!(
            contains_wrapped(&review, "Replaces the built-in 'reviewer'"),
            "{review}"
        );

        // "custom" also matches a built-in roster member.
        let mut custom_view = FleetSetupView::from_snapshot(snapshot());
        for _ in 0..8 {
            custom_view.handle_key(key(KeyCode::Down));
        }
        assert_eq!(custom_view.selected_role(), "custom");
        assert_eq!(
            custom_view.roster_override_note().as_deref(),
            Some("Replaces the built-in 'custom' role in the roster.")
        );
    }

    #[test]
    fn default_selection_targets_manager_inherit() {
        let view = FleetSetupView::from_snapshot(snapshot());
        let draft = view.starter_profile_draft();
        assert_eq!(draft.file_name(), "manager.toml");
        assert_eq!(draft.role_hint, "manager");
        assert!(draft.model.is_none());
        assert!(draft.model_class_hint.is_none());
        assert!(
            draft
                .instructions
                .as_deref()
                .is_some_and(|text| text.contains("assigned Fleet slice"))
        );
    }

    #[test]
    fn fleet_model_rows_keep_failed_provider_visible_with_reason() {
        let mut snap = snapshot();
        snap.available_models = vec![(
            "zai".to_string(),
            "glm-5.2".to_string(),
            crate::provider_readiness::ResolvedProviderReadiness::SavedLastCheckFailed {
                category: crate::error_taxonomy::ErrorCategory::Authentication,
                message: "auth failed".to_string(),
            },
        )];
        let mut view = FleetSetupView::from_snapshot(snap);
        assert_eq!(view.model_choices.len(), 2);
        assert!(
            view.model_choices[1]
                .summary
                .contains("last check failed (authentication)")
        );
        assert!(view.model_choices[1].summary.contains("auth failed"));
        assert_eq!(
            view.model_routes[1],
            ("zai".to_string(), "glm-5.2".to_string())
        );
        assert!(matches!(
            &view.model_row_states[1],
            FleetModelRowState::Blocked { reason } if reason == "auth failed"
        ));
        view.step = Step::Model;
        view.model_idx = 1;
        assert!(matches!(
            view.handle_key(key(KeyCode::Enter)),
            ViewAction::None
        ));
        assert_eq!(view.step, Step::Model);
    }

    #[test]
    fn fleet_invalid_route_stays_visible_but_cannot_advance() {
        let mut snap = snapshot();
        snap.available_models = vec![(
            "zai".to_string(),
            "broken-model".to_string(),
            crate::provider_readiness::ResolvedProviderReadiness::InvalidRoute,
        )];
        let mut view = FleetSetupView::from_snapshot(snap);
        view.step = Step::Model;
        view.model_idx = 1;

        assert!(view.model_choices[1].summary.contains("invalid route"));
        assert!(matches!(
            view.handle_key(key(KeyCode::Enter)),
            ViewAction::None
        ));
        assert_eq!(view.step, Step::Model);
    }

    #[test]
    fn fleet_includes_saved_model_outside_bundled_catalog() {
        let providers = crate::config::ProvidersConfig {
            openrouter: crate::config::ProviderConfig {
                api_key: Some("openrouter-test-key".to_string()),
                model: Some("acme/private-preview".to_string()),
                ..Default::default()
            },
            ..Default::default()
        };
        let config = Config {
            provider: Some("openrouter".to_string()),
            providers: Some(providers),
            ..Default::default()
        };

        let routes = cross_provider_model_routes(
            &config,
            crate::config::ApiProvider::Openrouter,
            &crate::provider_readiness::ProviderReadinessSnapshot::default(),
        );

        assert!(routes.iter().any(|(provider, model, readiness)| {
            provider == "openrouter" && model == "acme/private-preview" && readiness.can_attempt()
        }));
        assert_eq!(
            routes
                .iter()
                .filter(|(provider, model, _)| {
                    provider == "openrouter" && model == "acme/private-preview"
                })
                .count(),
            1,
            "saved models must not be duplicated when the catalog later learns them"
        );
    }

    #[test]
    fn fleet_routes_and_saved_draft_keep_exact_named_custom_provider() {
        let mut custom = std::collections::HashMap::new();
        for (name, base_url, model) in [
            ("custom-a", "http://127.0.0.1:18181/v1", "model-a"),
            ("custom-b", "http://127.0.0.1:18182/v1", "model-b"),
        ] {
            custom.insert(
                name.to_string(),
                crate::config::ProviderConfig {
                    kind: Some("openai-compatible".to_string()),
                    base_url: Some(base_url.to_string()),
                    model: Some(model.to_string()),
                    api_key: Some("local-test-key".to_string()),
                    ..Default::default()
                },
            );
        }
        let config = Config {
            provider: Some("custom-a".to_string()),
            providers: Some(crate::config::ProvidersConfig {
                custom,
                ..Default::default()
            }),
            ..Default::default()
        };
        let routes = cross_provider_model_routes(
            &config,
            crate::config::ApiProvider::Custom,
            &crate::provider_readiness::ProviderReadinessSnapshot::default(),
        );
        assert!(
            routes
                .iter()
                .any(|(provider, model, _)| { provider == "custom-a" && model == "model-a" })
        );
        assert!(
            routes
                .iter()
                .any(|(provider, model, _)| { provider == "custom-b" && model == "model-b" })
        );
        assert!(!routes.iter().any(|(provider, _, _)| provider == "custom"));

        let mut view = FleetSetupView::from_snapshot(FleetSetupSnapshot {
            available_models: routes,
            provider: "custom-a".to_string(),
            model: "model-a".to_string(),
            ..snapshot()
        });
        let route = view
            .model_routes
            .iter()
            .find(|(provider, model)| provider == "custom-b" && model == "model-b")
            .cloned()
            .expect("custom B route selectable while A is active");
        let draft = sample_draft();
        let (_, rendered) =
            view.install_model_draft(draft, "model-b".to_string(), Some(route), None);
        assert!(rendered.contains("provider = \"custom-b\""), "{rendered}");
    }

    #[test]
    fn fleet_routes_keep_legacy_literal_custom_without_named_tables() {
        let config = Config {
            provider: Some("custom".to_string()),
            base_url: Some("http://127.0.0.1:18080/v1".to_string()),
            api_key: Some("local-test-key".to_string()),
            default_text_model: Some("legacy-custom-model".to_string()),
            ..Default::default()
        };

        let routes = cross_provider_model_routes(
            &config,
            crate::config::ApiProvider::Custom,
            &crate::provider_readiness::ProviderReadinessSnapshot::default(),
        );

        assert!(
            routes.iter().any(|(provider, model, readiness)| {
                provider == "custom"
                    && model == "legacy-custom-model"
                    && matches!(
                        readiness,
                        crate::provider_readiness::ResolvedProviderReadiness::LocalUnchecked
                    )
                    && readiness.can_attempt()
            }),
            "{routes:?}"
        );
    }

    #[test]
    fn role_step_keeps_list_and_detail_separate_at_80_columns() {
        let rows = render_through_stack(|| FleetSetupView::from_snapshot(snapshot()), 80, 24);
        let text = rows.join("\n");

        let manager_row = rows
            .iter()
            .position(|row| row.contains("▸ manager"))
            .expect("manager row should render");
        let custom_row = rows
            .iter()
            .position(|row| row.contains("  custom"))
            .expect("custom row should render");
        let summary_row = rows
            .iter()
            .position(|row| row.contains("Plan & split queued work"))
            .expect("selected role summary should render");
        let description_row = rows
            .iter()
            .position(|row| row.contains("Coordinates the Fleet run"))
            .expect("selected role description should render");

        assert!(
            manager_row < custom_row,
            "expected the full role list before details:\n{text}"
        );
        assert!(
            custom_row < summary_row,
            "selected summary must not share a row with role names:\n{text}"
        );
        assert!(
            custom_row < description_row,
            "selected description must render below the list:\n{text}"
        );
        for row in &rows[manager_row..=custom_row] {
            assert!(
                !row.contains("Plan & split queued work")
                    && !row.contains("Coordinates the Fleet run")
                    && !row.contains("Fleet runs sub-agents"),
                "role list row contains detail copy at 80 columns: {row:?}\n{text}"
            );
        }
    }

    const BLEED_FILL: &str = "\u{e000}";

    fn render_through_stack(view_at: impl Fn() -> FleetSetupView, w: u16, h: u16) -> Vec<String> {
        let area = Rect::new(0, 0, w, h);
        let mut buf = Buffer::empty(area);
        for y in 0..h {
            for x in 0..w {
                // A private-use glyph that no rendered copy or temp path can
                // contain, so bleed-through detection cannot false-positive
                // on a path like `/Volumes/VIXinSSD/...`.
                buf[(x, y)].set_symbol(BLEED_FILL);
            }
        }
        let mut stack = ViewStack::new();
        stack.push(view_at());
        stack.render(area, &mut buf);
        (0..h)
            .map(|y| {
                (0..w)
                    .map(|x| buf[(x, y)].symbol().to_string())
                    .collect::<String>()
            })
            .collect()
    }

    #[test]
    fn fleet_setup_is_usable_and_opaque_at_blocker_sizes() {
        // Exercise each step so all three screens are validated at every size.
        type Builder = (&'static str, fn() -> FleetSetupView);
        let builders: [Builder; 3] = [
            ("role", || FleetSetupView::from_snapshot(snapshot())),
            ("model", || {
                let mut v = FleetSetupView::from_snapshot(snapshot());
                v.step = Step::Model;
                v
            }),
            ("review", || {
                let mut v = FleetSetupView::from_snapshot(snapshot());
                v.step = Step::Review;
                v
            }),
        ];

        for (label, make) in builders {
            for (w, h) in BLOCKER_SIZES {
                let rows = render_through_stack(make, w, h);
                let text = rows.join("\n");

                // No bleed-through anywhere in the composited frame.
                assert!(
                    !text.contains(BLEED_FILL),
                    "{label} {w}x{h}: background bleed-through"
                );
                // Some action label is always visible.
                assert!(text.contains("Esc"), "{label} {w}x{h}: missing footer");
                // The first impression communicates Fleet = agent team.
                assert!(
                    text.contains("agent team"),
                    "{label} {w}x{h}: missing framing"
                );
                // No row overflows the frame width.
                for (y, row) in rows.iter().enumerate() {
                    assert!(
                        UnicodeWidthStr::width(row.trim_end()) <= w as usize,
                        "{label} {w}x{h}: row {y} overflows: {row:?}"
                    );
                }
            }
        }
    }

    #[test]
    fn review_at_cursor_size_keeps_content_and_actions_apart() {
        let rows = render_through_stack(
            || {
                let mut view = FleetSetupView::from_snapshot(snapshot());
                view.step = Step::Review;
                view
            },
            89,
            50,
        );
        let popup = centered_modal_area(Rect::new(0, 0, 89, 50), 96, 31, 60, 16);
        let review_row = rows
            .iter()
            .position(|row| row.contains("Review & save"))
            .expect("review heading");
        let review_col = rows[review_row]
            .chars()
            .position(|ch| ch == 'R')
            .expect("review heading column") as u16;
        assert!(
            review_col >= popup.x.saturating_add(2),
            "body copy must not touch the popup border: {:?}",
            rows[review_row]
        );

        let action_row = rows
            .iter()
            .rposition(|row| row.contains("Esc"))
            .expect("footer Esc action");
        let footer_row = rows[..=action_row]
            .iter()
            .rposition(|row| row.contains("scroll"))
            .expect("footer shortcut row");
        assert!(footer_row > 0);
        let gutter = rows[footer_row - 1]
            .chars()
            .skip(usize::from(popup.x.saturating_add(1)))
            .take(usize::from(popup.width.saturating_sub(2)))
            .collect::<String>();
        assert!(
            gutter.trim().is_empty(),
            "review body needs a quiet row before the action rail: {gutter:?}"
        );
    }

    #[test]
    fn choice_steps_at_cursor_size_stay_content_sized() {
        for (step, expected_height) in [(Step::Role, 22usize), (Step::Model, 23usize)] {
            let rows = render_through_stack(
                || {
                    let mut view = FleetSetupView::from_snapshot(snapshot());
                    view.step = step;
                    view
                },
                89,
                50,
            );
            let top = rows
                .iter()
                .position(|row| row.contains("Fleet setup — your agent team"))
                .expect("fleet setup title");
            let bottom = rows
                .iter()
                .rposition(|row| row.contains("Step "))
                .expect("fleet setup step receipt");
            assert_eq!(
                bottom - top + 1,
                expected_height,
                "choice card should follow its content instead of filling the 89x50 frame"
            );
        }
    }

    #[test]
    fn review_lists_model_permissions_tools_and_profile_availability() {
        // Top of the review: the leading sections are visible without scrolling.
        let top = render_through_stack(
            || {
                let mut v = FleetSetupView::from_snapshot(snapshot());
                v.step = Step::Review;
                v
            },
            120,
            40,
        )
        .join("\n");
        for section in [
            "Saves to",
            "Role",
            "Model",
            "Auth & readiness",
            "Permissions",
        ] {
            assert!(top.contains(section), "review missing section: {section}");
        }
        // The destination line names the scope and the exact file; the
        // permission posture stays governed by the sections below it.
        assert!(top.contains("Personal · "), "{top}");
        assert!(top.contains("agents"), "{top}");
        assert!(top.contains("Inherit the parent envelope"), "{top}");

        // The review is intentionally scrollable; scrolling to the bottom reveals
        // the workspace/org execution policy, review policy, and honest save note.
        let bottom = render_through_stack(
            || {
                let mut v = FleetSetupView::from_snapshot(snapshot());
                v.step = Step::Review;
                v.review_scroll = 999; // clamps to max in render
                v
            },
            120,
            40,
        )
        .join("\n");
        for needle in [
            "Tools",
            "Workspace",
            "Review policy",
            "Save as Personal profile",
        ] {
            assert!(bottom.contains(needle), "scrolled review missing: {needle}");
        }

        let policy = FleetSetupView::from_snapshot(snapshot()).review_policy_summary();
        for truth in [
            "current interactive session",
            "codewhale fleet status",
            ".codewhale/fleet.jsonl",
        ] {
            assert!(policy.contains(truth), "review policy missing: {truth}");
        }
        assert!(
            !policy.contains("inspects the ledger"),
            "the interactive status command must not claim to inspect the durable ledger: {policy}"
        );
    }

    #[test]
    fn dormant_external_consent_row_requires_activation() {
        let mut snap = snapshot();
        snap.available_models = vec![(
            "openai-codex".to_string(),
            "gpt-5.6-sol".to_string(),
            crate::provider_readiness::ResolvedProviderReadiness::ExternalConsentPendingSelection,
        )];
        let view = FleetSetupView::from_snapshot(snap);
        assert!(
            view.model_choices[1]
                .summary
                .contains("external consent · select to check")
        );
        assert!(matches!(
            view.model_row_states[1],
            FleetModelRowState::NeedsActivation
        ));
    }

    #[test]
    fn enter_on_dormant_external_consent_emits_activation_event() {
        let mut snap = snapshot();
        snap.available_models = vec![(
            "openai-codex".to_string(),
            "gpt-5.6-terra".to_string(),
            crate::provider_readiness::ResolvedProviderReadiness::ExternalConsentPendingSelection,
        )];
        let mut view = FleetSetupView::from_snapshot(snap);
        view.handle_key(key(KeyCode::Enter)); // Role -> Model
        view.handle_key(key(KeyCode::Down)); // inherit -> codex row
        assert_eq!(
            view.selected_route(),
            Some(("openai-codex".to_string(), "gpt-5.6-terra".to_string()))
        );
        let action = view.handle_key(key(KeyCode::Enter));
        let ViewAction::Emit(ViewEvent::FleetSetupExternalConsentActivationRequested {
            provider_id,
            model,
        }) = action
        else {
            panic!("expected external-consent activation request, got {action:?}");
        };
        assert_eq!(provider_id, "openai-codex");
        assert_eq!(model, "gpt-5.6-terra");
        assert_eq!(
            view.step,
            Step::Model,
            "stays on Model step until host validates"
        );
    }

    #[test]
    fn refresh_from_snapshot_makes_activated_row_ready() {
        let mut snap = snapshot();
        snap.available_models = vec![(
            "xai".to_string(),
            "grok-4.5".to_string(),
            crate::provider_readiness::ResolvedProviderReadiness::ExternalConsentPendingSelection,
        )];
        let mut view = FleetSetupView::from_snapshot(snap);
        view.handle_key(key(KeyCode::Enter)); // Role -> Model
        view.handle_key(key(KeyCode::Down)); // xai row
        assert!(matches!(
            view.model_row_states[1],
            FleetModelRowState::NeedsActivation
        ));

        // Simulate the host validating the route and rebuilding the snapshot:
        // the same row is now Ready.
        let mut refreshed = snapshot();
        refreshed.available_models = vec![(
            "xai".to_string(),
            "grok-4.5".to_string(),
            crate::provider_readiness::ResolvedProviderReadiness::Ready,
        )];
        view.refresh_from_snapshot(refreshed);

        assert!(matches!(
            view.model_row_states[1],
            FleetModelRowState::Ready
        ));
        // Selection and step are preserved.
        assert_eq!(view.step, Step::Model);
        assert_eq!(
            view.selected_route(),
            Some(("xai".to_string(), "grok-4.5".to_string()))
        );
    }

    #[test]
    fn blocked_row_cannot_advance() {
        let mut snap = snapshot();
        snap.available_models = vec![(
            "xai".to_string(),
            "grok-4.5".to_string(),
            crate::provider_readiness::ResolvedProviderReadiness::MissingKey,
        )];
        let mut view = FleetSetupView::from_snapshot(snap);
        view.step = Step::Model;
        view.model_idx = 1;
        assert!(matches!(
            &view.model_row_states[1],
            FleetModelRowState::Blocked { reason } if reason == "missing API key"
        ));
        assert!(matches!(
            view.handle_key(key(KeyCode::Enter)),
            ViewAction::None
        ));
        assert_eq!(view.step, Step::Model);
    }

    #[test]
    fn fleet_setup_includes_openai_codex_account_roster_with_dormant_consent() {
        let _env = crate::test_support::lock_test_env();
        let codex_home = tempfile::tempdir().expect("Codex home");
        let _home = crate::test_support::EnvVarGuard::set("CODEX_HOME", codex_home.path());
        std::fs::write(
            codex_home.path().join("models_cache.json"),
            serde_json::to_vec(&serde_json::json!({
                "fetched_at": chrono::Utc::now(),
                "models": [
                    { "slug": "gpt-5.6-sol", "priority": 1 },
                    { "slug": "gpt-5.6-terra", "priority": 2 },
                    { "slug": "gpt-5.6-luna", "priority": 3 }
                ]
            }))
            .expect("serialize cache"),
        )
        .expect("write cache");

        let mut config = crate::config::Config::default();
        config.providers = Some(crate::config::ProvidersConfig {
            openai_codex: crate::config::ProviderConfig {
                auth_mode: Some("oauth".to_string()),
                external_credentials: Some(
                    codewhale_config::ExternalCredentialConsentToml::read_only(
                        codewhale_config::ProviderKind::OpenaiCodex,
                        codewhale_config::ExternalCredentialSource::CodexCli,
                        codex_home.path().join("auth.json"),
                    ),
                ),
                ..Default::default()
            },
            ..Default::default()
        });

        let routes = cross_provider_model_routes(
            &config,
            crate::config::ApiProvider::Moonshot,
            &crate::provider_readiness::ProviderReadinessSnapshot::default(),
        );

        for model in ["gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna"] {
            assert!(
                routes.iter().any(|(provider, m, readiness)| {
                    provider == "openai-codex"
                        && m == model
                        && matches!(
                            readiness,
                            crate::provider_readiness::ResolvedProviderReadiness::ExternalConsentPendingSelection
                        )
                }),
                "missing dormant-consent Codex route for {model}: {routes:?}"
            );
        }
    }

    #[test]
    fn fleet_setup_includes_xai_grok_routes_with_dormant_consent() {
        let _env = crate::test_support::lock_test_env();
        let grok_home = tempfile::tempdir().expect("Grok home");
        let mut config = crate::config::Config::default();
        config.providers = Some(crate::config::ProvidersConfig {
            xai: crate::config::ProviderConfig {
                auth_mode: Some("oauth".to_string()),
                external_credentials: Some(
                    codewhale_config::ExternalCredentialConsentToml::read_only(
                        codewhale_config::ProviderKind::Xai,
                        codewhale_config::ExternalCredentialSource::GrokCli,
                        grok_home.path().join("grok-auth.json"),
                    ),
                ),
                ..Default::default()
            },
            ..Default::default()
        });

        let routes = cross_provider_model_routes(
            &config,
            crate::config::ApiProvider::Moonshot,
            &crate::provider_readiness::ProviderReadinessSnapshot::default(),
        );

        let xai_rows: Vec<_> = routes
            .iter()
            .filter(|(provider, _, _)| provider == "xai")
            .collect();
        assert!(
            !xai_rows.is_empty(),
            "xAI routes must be offered when Grok CLI consent is configured: {routes:?}"
        );
        assert!(
            xai_rows.iter().all(|(_, _, readiness)| {
                matches!(
                    readiness,
                    crate::provider_readiness::ResolvedProviderReadiness::ExternalConsentPendingSelection
                )
            }),
            "every xAI row must require explicit activation: {xai_rows:?}"
        );
    }
}