keyroost 0.13.0

Desktop GUI for managing hardware security keys: FIDO2, OATH, OpenPGP, PIV, and Token2 programmable TOTP tokens.
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
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106
24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126
24127
24128
24129
24130
24131
24132
24133
24134
24135
24136
24137
24138
24139
24140
24141
24142
24143
24144
24145
24146
24147
24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160
24161
24162
24163
24164
24165
24166
24167
24168
24169
24170
24171
24172
24173
24174
24175
24176
24177
24178
24179
24180
24181
24182
24183
24184
24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
24286
24287
24288
24289
24290
24291
24292
24293
24294
24295
24296
24297
24298
24299
24300
24301
24302
24303
24304
24305
24306
24307
24308
24309
24310
24311
24312
24313
24314
24315
24316
24317
24318
24319
24320
24321
24322
24323
24324
24325
24326
24327
24328
24329
24330
24331
24332
24333
24334
24335
24336
24337
24338
24339
24340
24341
24342
24343
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473
24474
24475
24476
24477
24478
24479
24480
24481
24482
24483
24484
24485
24486
24487
24488
24489
24490
24491
24492
24493
24494
24495
24496
24497
24498
24499
24500
24501
24502
24503
24504
24505
24506
24507
24508
24509
24510
24511
24512
24513
24514
24515
24516
24517
24518
24519
24520
24521
24522
24523
24524
24525
24526
24527
24528
24529
24530
24531
24532
24533
24534
24535
24536
24537
24538
24539
24540
24541
24542
24543
24544
24545
24546
24547
24548
24549
24550
24551
24552
24553
24554
24555
24556
24557
24558
24559
24560
24561
24562
24563
24564
24565
24566
24567
24568
24569
24570
24571
24572
24573
24574
24575
24576
24577
24578
24579
24580
24581
24582
24583
24584
24585
24586
24587
24588
24589
24590
24591
24592
24593
24594
24595
24596
24597
24598
24599
24600
24601
24602
24603
24604
24605
24606
24607
24608
24609
24610
24611
24612
24613
24614
24615
24616
24617
24618
24619
24620
24621
24622
24623
24624
24625
24626
24627
24628
24629
24630
24631
24632
24633
24634
24635
24636
24637
24638
24639
24640
24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
24661
24662
24663
24664
24665
24666
24667
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696
24697
24698
24699
24700
24701
24702
24703
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720
24721
24722
24723
24724
24725
24726
24727
24728
24729
24730
24731
24732
24733
24734
24735
24736
24737
24738
24739
24740
24741
24742
24743
24744
24745
24746
24747
24748
24749
24750
24751
24752
24753
24754
24755
24756
24757
24758
24759
24760
24761
24762
24763
24764
24765
24766
24767
24768
24769
24770
24771
24772
24773
24774
24775
24776
24777
24778
24779
24780
24781
24782
24783
24784
24785
24786
24787
24788
24789
24790
24791
24792
24793
24794
24795
24796
24797
24798
24799
24800
24801
24802
24803
24804
24805
24806
24807
24808
24809
24810
24811
24812
24813
24814
24815
24816
24817
24818
24819
24820
24821
24822
24823
24824
24825
24826
24827
24828
24829
24830
24831
24832
24833
24834
24835
24836
24837
24838
24839
24840
24841
24842
24843
24844
24845
24846
24847
24848
24849
24850
24851
24852
24853
24854
24855
24856
24857
24858
24859
24860
24861
24862
24863
24864
24865
24866
24867
24868
24869
24870
24871
24872
24873
24874
24875
24876
24877
24878
24879
24880
24881
24882
24883
24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
24898
24899
24900
24901
24902
24903
24904
24905
24906
24907
24908
24909
24910
24911
24912
24913
24914
24915
24916
24917
24918
24919
24920
24921
24922
24923
24924
24925
24926
24927
24928
24929
24930
24931
24932
24933
24934
24935
24936
24937
24938
24939
24940
24941
24942
24943
24944
24945
24946
24947
24948
24949
24950
24951
24952
24953
24954
24955
24956
24957
24958
24959
24960
24961
24962
24963
24964
24965
24966
24967
24968
24969
24970
24971
24972
24973
24974
24975
24976
24977
24978
24979
24980
24981
24982
24983
24984
24985
24986
24987
24988
24989
24990
24991
24992
24993
24994
24995
24996
24997
24998
24999
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
25010
25011
25012
25013
25014
25015
25016
25017
25018
25019
25020
25021
25022
25023
25024
25025
25026
25027
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044
25045
25046
25047
25048
25049
25050
25051
25052
25053
25054
25055
25056
25057
25058
25059
25060
25061
25062
25063
25064
25065
25066
25067
25068
25069
25070
25071
25072
25073
25074
25075
25076
25077
25078
25079
25080
25081
25082
25083
25084
25085
25086
25087
25088
25089
25090
25091
25092
25093
25094
25095
25096
25097
25098
25099
25100
25101
25102
25103
25104
25105
25106
25107
25108
25109
25110
25111
25112
25113
25114
25115
25116
25117
25118
25119
//! keyroost — desktop GUI for programming Token2 Molto2 / Molto2v2 tokens.
//!
//! Dark-themed by default, modeled loosely on Token2's PyQt5 layout: device
//! status across the top, slot list on the left, edit form on the right.

#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use std::time::{SystemTime, UNIX_EPOCH};

mod import_flow;
mod otp_pane;
#[cfg(feature = "qr")]
mod qrscan;
#[cfg(feature = "qr")]
mod screengrab;
mod settings;
mod ui;
use otp_pane::OtpState;
use settings::Settings;
use ui::device::{self, CapState, CapTab, Caps, Device, DeviceId, DeviceKind, DeviceView};
use ui::theme::{self, BtnKind, Mode, Palette};

use eframe::egui;
use keyroost_import::parse_otpauth;
use keyroost_proto::commands::{
    DisplayTimeout, HmacAlgo, OtpDigits, ProfileConfig, ProfilePublicData, TimeStep,
    DEFAULT_CUSTOMER_KEY,
};
use keyroost_transport::Token2ProgSession;
use keyroost_transport::{DeviceInfo, SeedDeleteOutcome, Session, TransportError};

use keyroost_ctap::client_pin::PinUvAuthToken;
use keyroost_ctap::cred_mgmt::{Credential, CredsMetadata, RelyingParty};
use keyroost_ctap::{AuthenticatorInfo, CtapHidDevice, InitResponse};

/// The version chip next to the wordmark in the top bar — the one place the
/// running app shows which version it is (#98). Compile-time, straight from
/// the workspace version, so it can never drift from the release.
const VERSION_LABEL: &str = concat!("v", env!("CARGO_PKG_VERSION"));

/// How the selected FIDO key is reached: over USB-HID (a `hidraw` path) or over
/// a PC/SC reader (NFC or contact, by reader name).
#[derive(Debug, Clone)]
enum FidoTarget {
    Hid(std::path::PathBuf),
    Pcsc(String),
}

/// The successful result of [`open_fido`]: the boxed CTAP transport, whether it
/// speaks CTAP2 (CBOR), and the HID `InitResponse` (HID only; `None` over PC/SC).
/// Aliased so the `open_fido` signature isn't `clippy::type_complexity`-complex.
type OpenFido = (
    Box<dyn keyroost_ctap::transport::CtapTransport>,
    bool,
    Option<InitResponse>,
);

/// A large-blob-write token for `pin`, obtained only after the change was
/// planned (and any certain refusal raised) from `before`. Getting the token
/// talks to the key, so the array is read again afterwards and the write is
/// refused unless it is still exactly `before`.
fn large_blob_write_token(
    dev: &mut impl keyroost_ctap::transport::CtapTransport,
    info: &keyroost_ctap::AuthenticatorInfo,
    pin: &str,
    before: &keyroost_ctap::large_blobs::LargeBlobArray,
) -> Result<keyroost_ctap::client_pin::PinUvAuthToken, String> {
    let token = keyroost_ctap::client_pin::get_pin_uv_auth_token(
        dev,
        pin,
        info,
        keyroost_ctap::client_pin::permissions::LARGE_BLOB_WRITE,
    )
    .map_err(|e| e.to_string())?;
    let now = keyroost_ctap::large_blobs::read(dev, info).map_err(|e| e.to_string())?;
    if now.raw_array() != before.raw_array() {
        return Err(
            "the key's large-blob storage changed while it was being unlocked \
                    \u{2014} nothing was written; reload and try again."
                .into(),
        );
    }
    Ok(token)
}

/// Borrow owned serials for the `keyroost_resolve` naming helpers.
fn serial_refs(serials: &[String]) -> Vec<&str> {
    serials.iter().map(String::as_str).collect()
}

/// The naming dialog's message for a key with no storage for its own name.
const KEY_NAME_NO_STORAGE: &str =
    "This key can't store a name on itself; save the name on this computer.";

/// The naming dialog's message for a name change the key refused or can't
/// hold. `used` is how many bytes the array uses now.
fn key_name_refusal(e: keyroost_ctap::device_label::LabelError, used: u64) -> String {
    use keyroost_ctap::device_label::LabelError;
    match e {
        LabelError::Unsupported => KEY_NAME_NO_STORAGE.into(),
        LabelError::NoPin => "This key has no FIDO PIN yet. Set one with \"Set a PIN\" in the \
                              FIDO2 tab, then save the name on the key."
            .into(),
        LabelError::TooLarge { size, max } => format!(
            "Not enough large-blob space for the name: it needs {} bytes, {} are free.",
            size.saturating_sub(used),
            max.saturating_sub(used)
        ),
        other => format!("Couldn't save the name on the key: {other}"),
    }
}

/// The naming dialog's message when the key's name changed after the dialog
/// opened: retrying the same dialog can't succeed, so it closes and rescans.
const KEY_NAME_STALE: &str = "The key's name changed since the naming field opened; nothing \
                              was changed. Open Rename again to try.";

/// The naming dialog's message when an on-key save needs the PIN typed.
const KEY_NAME_PIN_NEEDED: &str = "Enter the key's FIDO PIN to save the name on the key.";

/// What an on-key name save did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum KeyNameWrite {
    Written,
    /// The key already carried what was asked; nothing was written.
    AlreadySo,
}

/// Why an on-key name save didn't happen.
#[derive(Debug, Clone, PartialEq, Eq)]
enum KeyNameFailure {
    /// The name or array on the key changed since the dialog opened.
    Stale,
    Failed(String),
}

impl From<String> for KeyNameFailure {
    fn from(e: String) -> Self {
        KeyNameFailure::Failed(e)
    }
}

impl From<&str> for KeyNameFailure {
    fn from(e: &str) -> Self {
        KeyNameFailure::Failed(e.to_string())
    }
}

/// [`key_name_refusal`], with a changed array as [`KeyNameFailure::Stale`].
fn key_name_failure(e: keyroost_ctap::device_label::LabelError, used: u64) -> KeyNameFailure {
    match e {
        keyroost_ctap::device_label::LabelError::Changed => KeyNameFailure::Stale,
        e => KeyNameFailure::Failed(key_name_refusal(e, used)),
    }
}

/// Set (`Some`) or clear (`None`) the name stored on the key at `path`, the
/// way `keyroostctl name set --store key` does: open, getInfo, read, plan
/// (refusing what can't work before the PIN is used), PIN token, write only
/// over the array planned from, then read the name back. An empty `pin`
/// refuses only once planning found a write is needed. `expected` is the
/// name the dialog showed: a different name found now refuses, since the
/// question asked was about that one. Names read from keys are forgotten
/// around the write.
fn write_key_name(
    path: &std::path::Path,
    name: Option<&str>,
    expected: Option<&str>,
    pin: &str,
) -> Result<KeyNameWrite, KeyNameFailure> {
    use keyroost_ctap::device_label::{
        apply_label_plan, plan_label_change, random_nonce, read_label, DeviceLabel, LabelState,
        WRITER_KEYROOST,
    };
    let (mut dev, init) = CtapHidDevice::open(path).map_err(|e| e.to_string())?;
    if !init.supports_cbor() {
        return Err(KEY_NAME_NO_STORAGE.into());
    }
    let info = keyroost_ctap::get_info(&mut dev).map_err(|e| e.to_string())?;
    if info.option("largeBlobs") != Some(true) {
        return Err(KEY_NAME_NO_STORAGE.into());
    }
    let current = keyroost_ctap::large_blobs::read(&mut dev, &info).map_err(|e| e.to_string())?;
    let used = current.capacity(&info).used_bytes;
    let new = name.map(|l| DeviceLabel {
        label: l.to_string(),
        writer: Some(WRITER_KEYROOST.to_string()),
    });
    let plan = plan_label_change(&current, &info, new.as_ref(), random_nonce())
        .map_err(|e| key_name_failure(e, used))?;
    // An unreadable name on the key counts as none: only a readable one
    // other than the name the dialog showed is a change to refuse.
    let previous = plan
        .previous
        .as_ref()
        .map(|l| l.label.as_str())
        .filter(|l| keyroost_keyring::validate_name(l).is_ok());
    if previous != expected {
        return Err(KeyNameFailure::Stale);
    }
    if previous == name {
        return Ok(KeyNameWrite::AlreadySo); // nothing to write
    }
    // Asked for only now, so the certain refusals above come first.
    if pin.is_empty() {
        return Err(KEY_NAME_PIN_NEEDED.into());
    }
    let token = keyroost_ctap::client_pin::get_pin_uv_auth_token(
        &mut dev,
        pin,
        &info,
        keyroost_ctap::client_pin::permissions::LARGE_BLOB_WRITE,
    )
    .map_err(|e| format!("Couldn't unlock the key: {e}"))?;
    keyroost_resolve::with_key_names_forgotten(|| apply_label_plan(&mut dev, &info, &token, &plan))
        .map_err(|e| key_name_failure(e, used))?;
    let now = read_label(&mut dev, &info).map_err(|e| e.to_string())?;
    let kept = match (&now, name) {
        (LabelState::Present(l), Some(n)) => l.label == n,
        (LabelState::Absent, None) => true,
        _ => false,
    };
    if kept {
        Ok(KeyNameWrite::Written)
    } else {
        Err("The key didn't keep the change; try again."
            .to_string()
            .into())
    }
}

/// Record on this computer that the key with `serials` carries `name` (or,
/// for `None`, drop every record of it), after an on-key save. When the key
/// already carried the name (`written` false), keys.json is touched only if
/// that record is missing, as `keyroostctl name set` leaves it alone.
fn record_key_name(
    serials: &[String],
    name: Option<&str>,
    written: bool,
    meta: keyroost_keyring::RecordMeta,
) -> Result<(), String> {
    let mut k = keyroost_keyring::Keyring::load_default().map_err(|e| e.to_string())?;
    if let (false, Some(n)) = (written, name) {
        if device::has_key_record(&k, &serial_refs(serials), n) {
            return Ok(());
        }
    }
    match name {
        Some(n) => keyroost_resolve::set_key_name(
            &mut k,
            &serial_refs(serials),
            n,
            keyroost_keyring::NameStore::Key,
            meta,
        )
        .map_err(|e| e.to_string())?,
        None => {
            keyroost_resolve::clear_key_names(&mut k, &serial_refs(serials));
        }
    }
    k.save_default().map(|_| ()).map_err(|e| e.to_string())
}

/// Open a CTAP transport for `target`, returning the boxed transport, whether
/// it speaks CTAP2 (CBOR), and the HID `InitResponse` when available (HID only;
/// `None` over PC/SC, which has no INIT phase). The InitResponse carries the
/// firmware version shown on the hero for USB keys.
fn open_fido(target: &FidoTarget) -> Result<OpenFido, String> {
    match target {
        FidoTarget::Hid(path) => {
            let (dev, init) = CtapHidDevice::open(path).map_err(|e| e.to_string())?;
            let cbor = init.supports_cbor();
            Ok((Box::new(dev), cbor, Some(init)))
        }
        FidoTarget::Pcsc(reader) => {
            let dev =
                keyroost_transport::CtapPcscDevice::open(reader).map_err(|e| e.to_string())?;
            // After a successful FIDO applet SELECT we attempt CTAP2 regardless of
            // the exact version string (keys answer U2F_V2, FIDO_2_0, FIDO_2_1,
            // sometimes with trailing bytes). A genuinely U2F-only card will make
            // get_info return a clean CTAP error, which the caller surfaces —
            // rather than silently reporting "no CBOR" and leaving the UI idle.
            Ok((Box::new(dev), true, None))
        }
    }
}
use keyroost_hid::HidDevice;

const PROFILES: u8 = 100;

/// Error from an unlocked-session FIDO operation, carrying both a
/// human-readable message and whether it was a PIN / PIN-auth failure that
/// invalidated the session. Worker closures produce this so their completion
/// closures can decide (via [`App::fail_session_op`]) whether to auto-lock.
struct SessionOpError {
    message: String,
    relock: bool,
}

impl SessionOpError {
    /// A non-PIN failure (HID open, U2F-only device, etc.): never re-locks.
    fn msg(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            relock: false,
        }
    }

    /// Classify a CTAP error: PIN / PIN-auth codes (`0x31` / `0x33` / `0x34`)
    /// mark the session as invalidated so the caller re-locks.
    fn from_ctap(err: keyroost_ctap::CtapError) -> Self {
        Self {
            relock: err.is_pin_auth_error(),
            message: err.to_string(),
        }
    }

    /// Classify a boxed error from an op path that returns `Box<dyn Error>`
    /// (e.g. passkey delete/refresh). Downcasts to [`CtapError`](keyroost_ctap::CtapError) to recover the
    /// status byte; non-CTAP errors never re-lock.
    fn from_boxed(err: Box<dyn std::error::Error>) -> Self {
        match err.downcast::<keyroost_ctap::CtapError>() {
            Ok(ctap) => Self::from_ctap(*ctap),
            Err(other) => Self::msg(other.to_string()),
        }
    }
}

impl std::fmt::Display for SessionOpError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message)
    }
}

#[derive(Default)]
struct SecurityKeysState {
    /// CTAP info for the selected device, fetched lazily after selection.
    info: Option<AuthenticatorInfo>,
    init: Option<InitResponse>,
    /// User-facing error from the last enumeration / open / GetInfo call.
    error: Option<String>,
    /// Live PIN entry field (cleared after submit).
    pin_input: String,
    /// Active unlocked session: token + cached resident credentials.
    session: Option<UnlockedSession>,
    /// The device `session` was unlocked on. Follow-on operations (reload,
    /// delete, bio, large-blob writes) must obtain the session through
    /// `App::fido_session()`, which refuses it when this no longer matches
    /// the selection (KEY-012): the session retains the PIN, and a PIN
    /// cached for one key must never authorize work on another.
    session_device: Option<DeviceId>,
    /// Change-PIN modal state.
    change_pin: ChangePinDialog,
    /// Reset-confirmation modal state.
    reset: ResetDialog,
    /// Enrolled fingerprints, cached after a list. `None` until first read.
    fingerprints: Option<Vec<keyroost_ctap::Enrollment>>,
    /// Friendly-name buffer for the "enroll new fingerprint" field.
    fp_new_name: String,
    /// Shared live enroll progress, written by the worker after each captured
    /// sample and polled by the UI each frame to drive the wizard view.
    fp_progress: Option<std::sync::Arc<std::sync::Mutex<EnrollProgress>>>,
    /// Pending delete confirmation: the template id awaiting "Are you sure?".
    fp_confirm_delete: Option<Vec<u8>>,
    /// Inline rename editor: (template_id, new-name buffer).
    fp_rename: Option<(Vec<u8>, String)>,
    /// Pending advanced-config action awaiting typed confirmation + PIN.
    advanced: Option<AdvancedDialog>,
    /// Which sub-view of the FIDO2 tab is active (passkeys / fingerprints /
    /// settings), so the sections no longer stack in one long panel.
    subview: FidoSubview,
    /// Cached large-blob array, read on demand. `None` until first load.
    large_blobs: Option<keyroost_ctap::large_blobs::LargeBlobArray>,
    /// Capacity snapshot computed at load/reload time (needs the device's
    /// getInfo, which only the worker thread holds).
    lb_capacity: Option<keyroost_ctap::large_blobs::BlobCapacity>,
    /// Index of the entry currently expanded in the hex/ASCII viewer.
    lb_selected: Option<usize>,
    /// Pending "delete entry N" confirmation in the structured editor.
    lb_confirm_delete: Option<usize>,
    /// Pending "clear all storage" confirmation. Set by the first click on the
    /// destructive clear control; the confirmed click wipes every entry.
    lb_confirm_clear: bool,
    /// "Keep the key's name" in the clear confirmation; set when it opens
    /// ([`device::keep_name_default`]).
    lb_keep_name: bool,
    /// Status / result line for the last large-blob load or write.
    lb_status: Option<String>,
    /// Text buffer for the "add a note" field.
    lb_new_text: String,
    /// Whether the add-note composer is expanded (toggled by the Add button).
    lb_show_add: bool,
    /// Index of the note currently being edited inline, with its edit buffer.
    lb_editing: Option<usize>,
    lb_edit_text: String,
    /// Set once we've auto-loaded (or tried to) on first showing the Storage
    /// tab, so a failed read doesn't retry every frame. Reset when the selected
    /// device changes so a different key loads fresh.
    lb_autoloaded: bool,
    /// SSH certificates extracted by "Save certificate…", parked between the
    /// background decrypt job and the save dialog resolving, keyed by the
    /// request id its `FileTarget::SshCertSave` carries. A map rather than a
    /// single slot because nothing stops two save dialogs being open at once
    /// (the busy guard is released before the extract job's apply closure
    /// runs, and the dialogs are non-modal): with one shared slot the first
    /// dialog answered wrote whichever certificate happened to be parked.
    /// Empty when no save is in flight.
    ssh_cert_pending: std::collections::HashMap<u64, PendingSshCert>,
    /// Result line for the last "Save certificate…" action (extraction error,
    /// or the saved path plus the parsed cert summary). Shown in the Passkeys
    /// panel.
    ssh_cert_status: Option<String>,
}

#[derive(Default, Clone, Copy, Debug, PartialEq)]
enum FidoSubview {
    #[default]
    Passkeys,
    Fingerprints,
    Settings,
    LargeBlobs,
}

/// A pending `authenticatorConfig` action in the Advanced view. The action is
/// only dispatched once the user supplies the PIN (these commands need a token
/// with the AuthenticatorConfiguration permission) and, for irreversible ones,
/// confirms explicitly.
#[derive(Default)]
struct AdvancedDialog {
    action: AdvancedAction,
    /// PIN entry for this action (config needs its own permissioned token).
    pin_input: String,
    /// New minimum PIN length buffer (only for SetMinPin).
    min_pin_input: String,
    /// Whether to also force a PIN change (SetMinPin option).
    force_change: bool,
    /// The device the dialog was opened for. Apply is rejected — and the
    /// dialog dropped, wiping the PIN — when the selection has moved since
    /// (KEY-007): a PIN typed for one key must never be sent to another.
    device: Option<DeviceId>,
}

impl Drop for AdvancedDialog {
    /// Scrub the typed PIN when the dialog is torn down (e.g. on success, the
    /// dialog is replaced with `None`), matching the wipe-on-drop discipline of
    /// the other secret-bearing dialogs (ChangePinDialog, PivState).
    fn drop(&mut self) {
        wipe(&mut self.pin_input);
    }
}

#[derive(Default, Clone, Copy, PartialEq)]
enum AdvancedAction {
    #[default]
    None,
    ToggleAlwaysUv,
    SetMinPin,
    ForcePinChange,
    EnterpriseAttestation,
}

/// Live state of an in-progress fingerprint enrollment, shared between the
/// capture worker and the UI so the wizard can show per-sample progress.
#[derive(Clone)]
struct EnrollProgress {
    /// Total samples the sensor wants (from getFingerprintSensorInfo / begin).
    total: u64,
    /// Samples captured successfully so far.
    captured: u64,
    /// Human-readable status of the most recent sample (quality hint).
    last_message: String,
    /// Set when the flow finishes (Ok) or fails (Err message).
    done: Option<Result<(), String>>,
    /// Set by the UI's Cancel button; the worker checks it between samples,
    /// asks the device to cancel the current enrollment, and stops.
    cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
}

impl Default for EnrollProgress {
    fn default() -> Self {
        EnrollProgress {
            total: 0,
            captured: 0,
            last_message: "Touch the sensor to begin\u{2026}".into(),
            done: None,
            cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
        }
    }
}

/// State for the "reset key" confirmation. Reset wipes all credentials and the
/// PIN, so the user must type a confirmation word and then touch the key.
#[derive(Default)]
struct ResetDialog {
    open: bool,
    /// Typed confirmation (`reset` required to enable the button).
    confirm_input: String,
}

/// "Armed" reset: a FIDO authenticator only accepts a reset within ~10 s of
/// being powered on, which the plug-then-navigate-then-confirm flow can never
/// hit. So we confirm intent first, then watch for the user to unplug and
/// replug the key and fire the reset the instant it reconnects. Polled in
/// `update()` against the live FIDO HID list (no PC/SC, so it can't disturb
/// other cards).
struct ResetArm {
    /// The armed key's USB/HID serial, if it exposes one (SoloKeys / Nitrokey
    /// do; most YubiKeys don't). When present we track the key by serial, so it
    /// is recognised on re-insertion into *any* USB port, not just the same one.
    target_serial: Option<String>,
    /// The armed key's HID path at arm time. Used as the identity when there is
    /// no serial (`target_serial` is `None`): its disappearance is the "unplug"
    /// half of the dance, and a fresh path is treated as the re-insert.
    target_path: Option<std::path::PathBuf>,
    /// The armed key's *effective* serial from the resolver (USB serial, else
    /// the CCID-read YubiKey serial shown in the sidebar). In path mode this
    /// is the identity a re-inserted candidate must prove before the reset
    /// fires; without it (and without a HID serial) arming is refused —
    /// fail closed rather than reset the first same-model key (KEY-005).
    target_effective_serial: Option<String>,
    /// The armed key's USB vendor/product ids, captured at arm time. In path
    /// mode a fresh path must match these — so plugging in a *different*
    /// model while a reset is armed doesn't get it reset by mistake.
    target_ids: Option<(u16, u16)>,
    /// The selection the arm was set under. An armed ceremony belongs to one
    /// key, so every surface that speaks for it — the dialog's "now unplug the
    /// key" prompt above all — has to check that this is still the key on
    /// screen before saying anything.
    for_device: Option<DeviceId>,
    /// FIDO HID devices present at the previous poll, to diff against (path
    /// mode) — see [`HidIdentity`] for why this isn't a plain `Vec<PathBuf>`.
    prev_devices: Vec<HidIdentity>,
    /// True once the armed key has been unplugged; the next fresh insertion then
    /// fires the reset.
    saw_removal: bool,
}

/// One HID device's physical-connection identity at a poll, used to tell a
/// genuine reinsertion apart from a device that was there all along.
///
/// `/dev/hidrawN` paths are not proof of "the same still-connected device":
/// the kernel reuses a freed hidraw minor number, so an unplug immediately
/// followed by a replug can hand the reinserted key the very same path the
/// old one had (`hidraw0` -> disconnect -> `hidraw0` again), even though the
/// USB device number underneath it advanced (observed on hardware: `usb 1-3:
/// USB disconnect, device number 8` followed by `new full-speed USB device
/// number 9` — same `hidraw0`, different device). A path-only diff then reads
/// the reinserted key as "not fresh" — it's still in the previous snapshot by
/// that path — and the armed reset never fires; the touch prompt waits
/// forever for a replug the code already missed.
///
/// `usb_bus`/`usb_address` (sysfs `busnum`/`devnum`) are the kernel's own
/// per-attach counters, so they're what [`same_hid_connection`] compares
/// first. `hidapi` (macOS/Windows) doesn't expose USB topology, so identity
/// there falls back to the path — no better than before on those platforms,
/// but no worse either.
#[derive(Clone)]
struct HidIdentity {
    path: std::path::PathBuf,
    usb_bus: Option<u8>,
    usb_address: Option<u8>,
}

impl HidIdentity {
    fn of(d: &FidoHid) -> Self {
        HidIdentity {
            path: d.path.clone(),
            usb_bus: d.usb_bus,
            usb_address: d.usb_address,
        }
    }
}

/// Whether `a` and `b` are the same physical USB attach, for telling a
/// reinserted key apart from one that never left. Bus+address decide it when
/// both sides have them; otherwise this falls back to path equality, all the
/// hidapi backend can offer.
fn same_hid_connection(a: &HidIdentity, b: &HidIdentity) -> bool {
    match (a.usb_bus, a.usb_address, b.usb_bus, b.usb_address) {
        (Some(ab), Some(aa), Some(bb), Some(ba)) => ab == bb && aa == ba,
        _ => a.path == b.path,
    }
}

/// The device an open rename field is bound to, pinned when the field opens so
/// a background rescan can't retarget the save. See [`App::rename_target`].
#[derive(Clone)]
struct RenameTarget {
    /// The device's friendly name at open time, so the save removes the right
    /// old entry even if the live device's name has since changed.
    name_at_open: Option<String>,
    /// The row the field was opened on; completions of an on-key save act on
    /// the dialog only while it is still open for this row.
    device_id: DeviceId,
    /// Every serial the key may be recorded under ([`keyroost_resolve::row_serials`]),
    /// its own first (the device serial, not the reader-name serial). A
    /// device with no serial can't be named.
    serials: Vec<String>,
    /// The key's FIDO HID path at open time (an on-key save writes there).
    hid_path: Option<std::path::PathBuf>,
    /// How the key was named at open time.
    naming: keyroost_resolve::Naming,
    /// The places offered ([`device::store_choices`]).
    choices: Vec<device::NameStoreChoice>,
    /// The key has no large-blob storage (the dialog says so).
    lacks_storage: bool,
    /// The place picked in the dialog.
    store: device::NameStoreChoice,
    /// Why the last save didn't happen; the field stays open.
    error: Option<String>,
    /// A question awaiting an answer before an on-key save (replacing or
    /// removing the name the key carries), with the planned save.
    confirm: Option<(String, Option<String>)>,
    /// An on-key save is running.
    saving: bool,
    /// Display hints for the log line and the keys.json record.
    vendor: String,
    model: String,
}

/// The answer to the hero's offer to write a lost name back onto the key.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum WriteBack {
    Write,
    Forget,
    Dismiss,
}

struct UnlockedSession {
    token: PinUvAuthToken,
    metadata: CredsMetadata,
    /// Behind an `Arc`: the pane clones this every frame to escape the borrow
    /// of `self`, and credential lists (ids, user blobs) are not per-frame
    /// clone material.
    rps: std::sync::Arc<Vec<(RelyingParty, Vec<Credential>)>>,
    /// Enrolled fingerprints read at unlock (when the key supports bio), so the
    /// list shows immediately. `None` when bio is unsupported or the read failed.
    fingerprints: Option<Vec<keyroost_ctap::Enrollment>>,
    /// PIN retained for the unlocked session (wiped on lock). Bio writes
    /// (enroll/rename/delete) re-derive a fresh pinUvAuthToken per operation —
    /// the authenticator can invalidate a token after a UV-gated bio write, so
    /// reusing one across operations fails with PIN_AUTH_INVALID (0x33).
    pin: zeroize::Zeroizing<String>,
}

/// One FIDO HID device as the armed-reset poll sees it.
struct FidoHid {
    path: std::path::PathBuf,
    serial: Option<String>,
    ids: (u16, u16),
    /// USB bus/device-address of the underlying device (Linux sysfs backend
    /// only; `None` on the hidapi backend). Used by [`same_hid_connection`] to
    /// tell a reinserted key apart from a recycled `/dev/hidrawN` path.
    usb_bus: Option<u8>,
    usb_address: Option<u8>,
}

#[derive(Default)]
struct ChangePinDialog {
    /// Whether the inline PIN form is expanded.
    open: bool,
    old: String,
    new: String,
    /// Confirmation field for the new PIN — required for both setting a
    /// first-time PIN and changing an existing one (#79).
    confirm: String,
}

impl Drop for ChangePinDialog {
    /// Zeroize the typed PINs whenever the dialog is dropped — including the
    /// `= ChangePinDialog::default()` resets on cancel/success — so a typed
    /// (or mistyped) PIN doesn't linger in the buffer after the form closes.
    fn drop(&mut self) {
        wipe(&mut self.old);
        wipe(&mut self.new);
        wipe(&mut self.confirm);
    }
}

/// State for the OATH (TOTP) pane. The applet is driven over PC/SC, so a
/// "reader name" identifies the key rather than a hidraw path.
#[derive(Default)]
struct OathState {
    /// Credentials listed from the selected key, with their freshly-computed code.
    creds: Vec<OathRow>,
    /// Entries the card reported that could not be decoded (the listing is
    /// partial when non-zero) — surfaced so a reset isn't run against an
    /// inventory the user believes is complete.
    skipped: usize,
    /// True when the selected applet is password-protected and not yet unlocked.
    locked: bool,
    /// Password entry field (cleared after an unlock attempt).
    password_input: String,
    /// User-facing error/status from the last OATH operation.
    error: Option<String>,
    /// True once a list has been fetched for the current selection.
    loaded: bool,
    /// "Add credential" dialog state.
    add: OathAddDialog,
    /// Pending delete confirmation: the device the row was shown for and the
    /// credential name. Bound to a device so a confirmation opened for one
    /// key can neither render over nor delete from another (KEY-008).
    confirm_delete: Option<(DeviceId, String)>,
    /// Password accepted by the last successful unlock+list of the current
    /// selection. `password_input` is consumed (wiped) by every op's apply,
    /// so on-demand reads that happen much later — HOTP "Read code" — send
    /// this retained copy instead of an empty string (which could never
    /// unlock a protected applet and re-locked the pane every time).
    /// Cleared on selection change and on a rejected password.
    unlocked_password: Option<zeroize::Zeroizing<String>>,
    /// Pending applet-reset confirmation, bound to the device it was opened
    /// for (same KEY-008 posture as `confirm_delete`). Reset works without
    /// the password by design — it is the recovery for a forgotten one — so
    /// this is reachable from the locked view too.
    confirm_reset: Option<DeviceId>,
}

/// One credential row in the OATH pane: its stored name and the last code we
/// computed for it (empty until "Show code" / refresh).
struct OathRow {
    name: String,
    code: Option<String>,
    /// Counter-based credential: codes are computed only on explicit request
    /// (each computation advances the card's counter — a passive listing must
    /// not burn counter steps), and they don't expire, so no countdown ring.
    hotp: bool,
    /// The TOTP period the name implies (its `period/` prefix, else 30): the
    /// code is computed with it and the countdown ring runs on it.
    period: u32,
}

impl OathRow {
    fn new(name: String, code: Option<String>, hotp: bool) -> Self {
        let oath_type = if hotp {
            keyroost_oath::OathType::Hotp
        } else {
            keyroost_oath::OathType::Totp
        };
        let period = keyroost_oath::parse_name(&name, oath_type)
            .period
            .unwrap_or(30);
        OathRow {
            name,
            code,
            hotp,
            period,
        }
    }
}

/// "Add credential" modal state for the OATH pane. Open iff `open` is true; the
/// name + base32 **secret** + type/touch fields render *inside* the centered
/// `modal_window` (not inline in the pane) so the secret entry and its result
/// stay on-screen, mirroring the PIV/OpenPGP credential modals (issue #31).
/// `busy` shows the spinner while `provision_oath`'s job is in flight; `result`
/// is `None` until it completes, then `Ok(())` on success or `Err(message)` on
/// failure — both shown in the modal.
#[derive(Default)]
struct OathAddDialog {
    open: bool,
    name: String,
    /// Base32 secret (entered masked).
    secret: String,
    /// True = TOTP, false = HOTP.
    totp: bool,
    require_touch: bool,
    /// True while the provision op is in flight (spinner + Submit disabled).
    busy: bool,
    /// Outcome of the last provision op, shown in the modal.
    result: Option<Result<(), String>>,
}

impl OathAddDialog {
    /// A freshly-opened dialog: empty fields, TOTP default, no in-flight op.
    /// (No `..Default::default()` — the `Drop` impl forbids struct-update.)
    fn opened() -> Self {
        OathAddDialog {
            open: true,
            name: String::new(),
            secret: String::new(),
            totp: true,
            require_touch: false,
            busy: false,
            result: None,
        }
    }

    /// Client-side validation of the entered fields, mirroring the guards in
    /// `provision_oath` so the modal can reject bad input before dispatching.
    /// Returns the trimmed name + decoded secret on success, or an error message.
    fn validate(
        &self,
        family: keyroost_import::plan::OathFamily,
    ) -> Result<(String, Vec<u8>), String> {
        let name = self.name.trim().to_owned();
        if name.is_empty() {
            return Err("credential name is required".into());
        }
        // Past this length the key stops responding until it is unplugged,
        // so the name never reaches it (same check as `oath add`).
        if let Some(refusal) = family.name_refusal(&name) {
            return Err(refusal);
        }
        match keyroost_proto::codec::base32_decode(self.secret.trim()) {
            Ok(s) if !s.is_empty() => Ok((name, s)),
            Ok(_) => Err("secret is empty".into()),
            Err(e) => Err(format!("invalid base32 secret: {e}")),
        }
    }
}

// The form is replaced wholesale after submit; wipe the typed seed on drop.
impl Drop for OathAddDialog {
    fn drop(&mut self) {
        wipe(&mut self.secret);
    }
}

/// State for the OpenPGP pane. Like OATH, the applet is driven over PC/SC, so a
/// reader name identifies the card.
#[derive(Default)]
struct OpenPgpState {
    /// Last status read from the selected card.
    status: Option<keyroost_transport::OpenPgpStatus>,
    /// User-facing error from the last operation.
    error: Option<String>,
    /// Success/info line from the last write operation.
    notice: Option<String>,
    /// True once a status has been fetched for the current selection.
    loaded: bool,
    /// Admin PIN (PW3) entry, used for every write op. Cleared after use.
    admin_pin: String,
    /// Cardholder-name entry.
    name_input: String,
    /// Public-key-URL entry.
    url_input: String,
    /// The key (Signature / Decryption / Authentication) whose sub-tab is open.
    /// Every per-key action — generate on-card, import — targets this key, the
    /// same way the PIV pane's `selected_slot` drives its per-slot cards.
    selected_key: OpenPgpSlotSel,
    /// Algorithm chosen in the Generate-key modal for the selected slot.
    gen_alg: OpenPgpKeyAlgSel,
    /// The card's own Algorithm Information (`FA`) object, when it publishes
    /// one — feeds the Generate-key modal's algorithm choices. `None` means
    /// the card didn't publish one (pre-3.4 cards), not that it has none.
    supported: Option<keyroost_transport::AlgorithmInformation>,
    /// Path to an RSA key file for import-from-file (text-entered).
    import_path: String,
    /// Change-user-PIN (PW1) old/new entries. Cleared after use.
    user_pin_old: String,
    user_pin_new: String,
    /// Change-admin-PIN (PW3) old/new entries. Cleared after use.
    admin_pin_old: String,
    admin_pin_new: String,
    /// New user PIN for the unblock flow (reset retry counter); authorised by
    /// `admin_pin`. Cleared after use.
    unblock_new: String,
    /// "Use default admin PIN (PW3)" toggle in the credential modal: when set,
    /// the well-known factory default (`12345678`) fills `admin_pin` on Submit
    /// instead of whatever was typed. Reset per modal. (Most cards still on the
    /// factory PIN, so this saves typing during bring-up.)
    use_default_admin: bool,
    /// Credential-entry modal for the PIN changes + the admin-PIN-gated writes
    /// (open iff `Some`). The PW1/PW3 secret fields render *inside* this modal,
    /// not inline in the pane, so the entry and its result stay on-screen
    /// (issue #31). The non-secret parameters (name, URL, slot, file path) stay
    /// inline in the pane.
    cred_modal: Option<OpenPgpCredModal>,
}

impl OpenPgpState {
    /// Zeroize every PIN entry field. Called when the selection changes (a PIN
    /// typed for one card must not ride along to another) and on drop.
    fn wipe_secrets(&mut self) {
        wipe(&mut self.admin_pin);
        wipe(&mut self.user_pin_old);
        wipe(&mut self.user_pin_new);
        wipe(&mut self.admin_pin_old);
        wipe(&mut self.admin_pin_new);
        wipe(&mut self.unblock_new);
        self.use_default_admin = false;
    }
}

/// Which OpenPGP credential flow the modal is driving. The first three map 1:1
/// to the PIN operations (`change_openpgp_user_pin` / `change_openpgp_admin_pin`
/// / `unblock_openpgp_user_pin`); the rest are the admin-PIN (PW3)-gated writes
/// whose *secret* (the admin PIN) now lives in the modal while their non-secret
/// parameters (cardholder name, URL, slot, file path) stay inline in the pane.
/// The variant selects which secret fields the modal renders and which op
/// Submit dispatches to.
#[derive(Clone, Copy, PartialEq, Eq)]
enum OpenPgpCredKind {
    ChangeUserPin,
    ChangeAdminPin,
    UnblockUserPin,
    SetName,
    SetUrl,
    GenerateKey,
    GenerateImportKey,
    ImportKeyFile,
    Reset,
}

impl OpenPgpCredKind {
    /// Modal title, matching the FIDO/PIV dialogs' title style.
    fn title(self) -> &'static str {
        match self {
            OpenPgpCredKind::ChangeUserPin => "Change user PIN",
            OpenPgpCredKind::ChangeAdminPin => "Change admin PIN",
            OpenPgpCredKind::UnblockUserPin => "Unblock user PIN",
            OpenPgpCredKind::SetName => "Set cardholder name",
            OpenPgpCredKind::SetUrl => "Set public-key URL",
            OpenPgpCredKind::GenerateKey => "Generate key on-card",
            OpenPgpCredKind::GenerateImportKey => "Generate & import key",
            OpenPgpCredKind::ImportKeyFile => "Import key from file",
            OpenPgpCredKind::Reset => "Reset applet",
        }
    }
    /// Label for the modal's primary Submit button. Shorter than the title for
    /// the verbose flows so the button doesn't overflow.
    fn submit_label(self) -> &'static str {
        match self {
            OpenPgpCredKind::ChangeUserPin => "Change user PIN",
            OpenPgpCredKind::ChangeAdminPin => "Change admin PIN",
            OpenPgpCredKind::UnblockUserPin => "Unblock",
            OpenPgpCredKind::SetName => "Set name",
            OpenPgpCredKind::SetUrl => "Set URL",
            OpenPgpCredKind::GenerateKey => "Generate",
            OpenPgpCredKind::GenerateImportKey => "Generate & import",
            OpenPgpCredKind::ImportKeyFile => "Import",
            OpenPgpCredKind::Reset => "Reset applet",
        }
    }
    /// Spinner caption shown while this flow's op runs.
    fn busy_label(self) -> &'static str {
        match self {
            OpenPgpCredKind::ChangeUserPin => "Changing user PIN\u{2026}",
            OpenPgpCredKind::ChangeAdminPin => "Changing admin PIN\u{2026}",
            OpenPgpCredKind::UnblockUserPin => "Unblocking user PIN\u{2026}",
            OpenPgpCredKind::SetName => "Setting cardholder name\u{2026}",
            OpenPgpCredKind::SetUrl => "Setting public-key URL\u{2026}",
            OpenPgpCredKind::GenerateKey => "Generating key\u{2026}",
            OpenPgpCredKind::GenerateImportKey => "Generating & importing key\u{2026}",
            OpenPgpCredKind::ImportKeyFile => "Importing key from file\u{2026}",
            OpenPgpCredKind::Reset => "Resetting OpenPGP applet\u{2026}",
        }
    }
    /// In-modal success confirmation text. The key flows whose *detailed* result
    /// (the new fingerprint) still surfaces in the pane only need a generic
    /// confirmation here.
    fn success(self) -> &'static str {
        match self {
            OpenPgpCredKind::ChangeUserPin => "User PIN changed",
            OpenPgpCredKind::ChangeAdminPin => "Admin PIN changed",
            OpenPgpCredKind::UnblockUserPin => "User PIN unblocked",
            OpenPgpCredKind::SetName => "Cardholder name set",
            OpenPgpCredKind::SetUrl => "Public-key URL set",
            OpenPgpCredKind::GenerateKey => "Key generated",
            OpenPgpCredKind::GenerateImportKey => "Key generated and imported",
            OpenPgpCredKind::ImportKeyFile => "Key imported",
            OpenPgpCredKind::Reset => "Applet reset",
        }
    }
    /// True when this flow collects the *admin* PIN (PW3) — i.e. it shows the
    /// admin-PIN field and the "Use default admin PIN (PW3)" convenience toggle.
    /// The user-PIN change (PW1, self-authorising) and the reset (PIN-less) do
    /// not.
    fn needs_admin_pin(self) -> bool {
        matches!(
            self,
            OpenPgpCredKind::ChangeAdminPin
                | OpenPgpCredKind::UnblockUserPin
                | OpenPgpCredKind::SetName
                | OpenPgpCredKind::SetUrl
                | OpenPgpCredKind::GenerateKey
                | OpenPgpCredKind::GenerateImportKey
                | OpenPgpCredKind::ImportKeyFile
        )
    }
}

/// Live state of the OpenPGP credential-entry modal. Open iff
/// `OpenPgpState::cred_modal` is `Some`. Tracks the flow, whether its op is in
/// flight, and the op's result so the outcome is shown *in the modal* (issue
/// #31). `result` is `None` until the op completes, then `Ok(())` on success or
/// `Err(message)` on failure.
struct OpenPgpCredModal {
    kind: OpenPgpCredKind,
    busy: bool,
    result: Option<Result<(), String>>,
    /// The device the modal was opened for. Submit is rejected — and the
    /// modal closed — when the selection has moved since (KEY-013): the
    /// Reset flow needs no PIN, so this binding is the only thing standing
    /// between a stale modal and a factory reset of the wrong card.
    device: Option<DeviceId>,
}

impl OpenPgpCredModal {
    fn new(kind: OpenPgpCredKind, device: Option<DeviceId>) -> Self {
        OpenPgpCredModal {
            kind,
            busy: false,
            result: None,
            device,
        }
    }
}

/// The well-known OpenPGP Card factory-default admin PIN (PW3).
const OPENPGP_DEFAULT_ADMIN_PIN: &str = "12345678";

/// Inline new==confirm guard for the PIN-change flows, mirroring the op-level
/// backstop. Returns the error message when the two new entries diverge (and
/// the confirm field is non-empty). The admin-PIN-gated *writes* have no
/// new==confirm pair — they're validated by the ops' own client-side guards.
fn openpgp_cred_mismatch(pgp: &OpenPgpState, kind: OpenPgpCredKind) -> Option<&'static str> {
    // The OpenPGP PIN flows ask for old + new with no separate "confirm" field
    // (the original inline forms had none), so there is no mismatch to report.
    // The function exists to mirror the PIV modal's shape and to give a single
    // place to add a confirm guard later without touching the render path.
    let _ = (pgp, kind);
    None
}

/// Zeroize a secret-bearing text field (wipes the bytes, then leaves the
/// string empty — strictly better than `.clear()`, which only resets the
/// length and leaves the secret in the buffer).
fn wipe(s: &mut String) {
    use zeroize::Zeroize;
    s.zeroize();
}

/// Shared device-binding guard for background-job completions and modal
/// submissions. `captured` is the `DeviceId` recorded when the job was
/// dispatched (or the dialog/confirmation opened); `current` is the selection
/// now. The completion may act only when both exist and match — `None` on
/// either side fails closed, so an unbound completion can never act on
/// whatever happens to be selected. This is the one place the rule lives;
/// per-feature capture fields (Tasks: Molto session, FIDO session, advanced
/// dialog, OATH/OpenPGP confirmations) all route their decision through it.
///
/// Convention for users: dispatchers capture
/// `let for_device = self.selected_device.clone();` *before* `spawn_job`, and
/// the apply closure's first statement is
/// `if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) { return; }`.
fn completion_still_valid(captured: Option<&DeviceId>, current: Option<&DeviceId>) -> bool {
    matches!((captured, current), (Some(c), Some(now)) if c == now)
}

/// Whether a resident credential should offer the "Save certificate…" action.
/// True only for SSH relying parties (`ssh:*`) that also carry a largeBlob key:
/// the key is required to decrypt this credential's per-credential largeBlob
/// entry, so without one there is nothing an extract job could produce.
/// (Whether a certificate is *actually* stored is only knowable by reading the
/// device's largeBlob array — that stays in the background job, which reports
/// "no certificate stored" when the decrypt turns up nothing.)
fn ssh_cred_offers_cert(rp_id: &str, large_blob_key: Option<&[u8; 32]>) -> bool {
    rp_id.starts_with("ssh:") && large_blob_key.is_some()
}

/// One-line human summary of a parsed SSH certificate, shown beside the saved
/// path after "Save certificate…" succeeds.
fn ssh_cert_summary(info: &keyroost_ctap::ssh_cert::SshCertInfo) -> String {
    let kind = if info.cert_type == keyroost_ctap::ssh_cert::CERT_TYPE_USER {
        "user"
    } else {
        "host"
    };
    let principals = if info.principals.is_empty() {
        "(any)".to_string()
    } else {
        info.principals.join(", ")
    };
    format!(
        "{} ({kind}) \u{00b7} key id {} \u{00b7} principals {} \u{00b7} {}",
        info.key_type,
        info.key_id,
        principals,
        keyroost_ctap::ssh_cert::format_validity(info.valid_after, info.valid_before),
    )
}

/// Whether the user may override an `Unsupported` verdict for `extension`
/// ("Enable Anyway" below the Reset card; the CLI's `--force` is separate).
///
/// Only features the pane exposes as controls. Not overridable here:
/// - The internal reads GET METADATA, ATTEST and GET SLOT KEY STATUS: nothing
///   to switch on in the pane. "Enable Anyway" reaches GET METADATA and ATTEST
///   through the transport instead (`PivSessionState::set_send_unsupported_reads`,
///   set by `piv_cached_piv_session_state`), and the transport traces every
///   read the table skips or overrides.
/// - RESET (and the device-wide reset). It is potentially destructive, and a
///   one-click unlock would invite people to just try it. Reaching it means
///   deliberately exhausting the PIN and PUK retries first, so a failed
///   attempt on a device that turns out not to support it can leave the applet
///   locked with no way back — bricking the device. Unlocking a known-unsupported reset is
///   therefore left to the CLI's `--force`: the extra effort means only people
///   who know what they are doing take that path.
/// - Removing the management key outright (`MgmtAlgChoice::Delete`): that is
///   HID Crescendo's own command, not a feature another device might merely be
///   untested for.
///
/// For every other extension a device that really lacks the feature just
/// refuses the command and nothing changes.
///
/// Applied to the pane's controls. The transport's own gates keep resolving
/// from the real table, except that GET METADATA and ATTEST are sent anyway
/// for a key with "Enable Anyway" on (see above); the reset mechanism choice
/// is never overridden.
fn piv_user_overridable(extension: keyroost_piv::compat::PivExtension) -> bool {
    use keyroost_piv::compat::{MgmtAlgChoice, PivExtension};
    !matches!(
        extension,
        PivExtension::GetMetadata
            | PivExtension::Attest
            | PivExtension::GetSlotKeyStatus
            | PivExtension::Reset
            | PivExtension::ResetGlobal
            | PivExtension::ManagementKeyAlgorithm(MgmtAlgChoice::Delete)
    )
}

/// `gate` with "unsupported" downgraded to "unverified" when
/// [`piv_user_overridable`] allows it — the control works, with the same
/// warning an untested feature gets. Any other gate is returned unchanged.
fn piv_relax(
    extension: keyroost_piv::compat::PivExtension,
    gate: keyroost_piv::compat::FeatureGate,
) -> keyroost_piv::compat::FeatureGate {
    use keyroost_piv::compat::FeatureGate;
    match gate {
        FeatureGate::Unsupported if piv_user_overridable(extension) => FeatureGate::Unverified,
        other => other,
    }
}

/// How many user-facing PIV features keyroost's compatibility table lists as
/// unsupported on this device — the number the PIV card's "Compatibility
/// table" line shows. Counts only what "Ignore for this key" can actually
/// unlock (see `piv_user_overridable`), so RESET and HID
/// Crescendo's own commands never inflate it.
fn piv_compat_unsupported_count(
    fingerprint: keyroost_piv::fingerprint::AppletFingerprint,
    version: Option<&[u8]>,
    version_firmware: Option<&[u8]>,
) -> usize {
    use keyroost_piv::compat::{FeatureGate, MgmtAlgChoice, PivExtension};
    let mut features = vec![
        PivExtension::MoveKey,
        PivExtension::DeleteKey,
        PivExtension::PinManagementAuth,
        PivExtension::SetPinPukRetries,
        PivExtension::SetManagementKey,
        PivExtension::SlotPinPolicy,
        PivExtension::SlotTouchPolicy,
    ];
    features.extend(keyroost_piv::KeyAlg::ALL.map(PivExtension::SlotKeyAlgorithm));
    features.extend(
        [
            MgmtAlgChoice::TripleDes,
            MgmtAlgChoice::Aes128,
            MgmtAlgChoice::Aes192,
            MgmtAlgChoice::Aes256,
        ]
        .map(PivExtension::ManagementKeyAlgorithm),
    );
    features
        .into_iter()
        .filter(|&f| piv_user_overridable(f))
        .filter(|&f| {
            keyroost_piv::compat::resolve(f, fingerprint, version, version_firmware)
                == FeatureGate::Unsupported
        })
        .count()
}

/// Whether the FIDO Settings subview exists for the selected key.
/// authenticatorReset is a baseline CTAP2 command (present since CTAP 2.0),
/// so any key that answered getInfo with a CTAP2 version can be reset and
/// gets the tab; gating the tab on authenticatorConfig — a CTAP 2.1 feature —
/// hid the only reset path from CTAP 2.0-only keys (#81). The advanced
/// security-policy controls *inside* the tab stay gated on `authnrCfg`.
fn fido_settings_available(info: Option<&AuthenticatorInfo>) -> bool {
    info.is_some_and(|i| i.versions.iter().any(|v| v.starts_with("FIDO_2_")))
}

/// What `App::start_factory_reset_confirm` learned about the selected
/// device's PIV step before arming the confirm dialog — resolved one step
/// ahead of the dialog itself (fingerprinted the moment "Factory reset…" is
/// pressed, not deferred to when the reset actually runs), so
/// `factory_reset_confirm_summary` can describe exactly what that step will
/// do instead of hedging across every possibility. Mirrors
/// `keyroost_transport::PivResetPreview`, the same verdict the reset itself
/// resolves when it runs (`PivSession::factory_reset`, inside
/// `run_card_reset_step`) — fingerprinted again there rather than threaded
/// through from here: the two calls are only ever seconds apart and
/// `preview_factory_reset` costs no PIN/PUK attempt, so a fresh re-check is
/// cheap and can't go stale the way carrying this value forward could (the
/// confirm dialog can sit open for a while, or the key can be swapped and
/// swapped back — see `render_factory_reset_confirm`'s KEY-008 guard).
#[derive(Clone, Copy, PartialEq, Eq)]
enum FactoryResetPivPreview {
    /// The device's plan has no PIV step — nothing to fingerprint.
    NotOffered,
    /// The fingerprint attempt itself failed (no PC/SC reader for PIV,
    /// `PivSession::open` error, …) — the summary falls back to generic
    /// wording rather than blocking the whole confirm dialog on a
    /// diagnostic step's own failure.
    CheckFailed,
    /// The live verdict — `Unsupported` means neither reset mechanism is
    /// available, so `App::start_factory_reset_confirm` doesn't even plan a
    /// PIV step for this device (`keyroost_resolve::exclude_unresettable_piv`);
    /// `factory_reset_confirm_summary` never actually renders this variant's
    /// own text as a result (its `if plan.contains(&ResetStep::Piv)` guard
    /// skips the whole block), but it's still tracked here rather than
    /// folded into `NotOffered`/`CheckFailed` — those mean "nothing to say",
    /// this means "there was something to fingerprint, and the answer was
    /// no".
    Resolved(keyroost_transport::PivResetPreview),
}

/// Whether `piv_preview` says PIV can't be reset at all —
/// `App::render_factory_reset_confirm`/`App::run_factory_reset_gui` both
/// exclude [`keyroost_resolve::ResetStep::Piv`]
/// (`keyroost_resolve::exclude_unresettable_piv`) from the plan they rebuild
/// when this is true, rather than offering (or attempting) a step
/// `PivSession::factory_reset` would only refuse.
#[must_use]
fn factory_reset_piv_unresettable(preview: FactoryResetPivPreview) -> bool {
    matches!(
        preview,
        FactoryResetPivPreview::Resolved(keyroost_transport::PivResetPreview::Unsupported)
    )
}

/// State for the armed factory-reset confirm dialog: which device it's for
/// (KEY-008 — the dialog dies the instant the selection changes; see
/// `render_factory_reset_confirm`) and what's known about that device's PIV
/// step (see `FactoryResetPivPreview`).
#[derive(Clone)]
struct FactoryResetConfirmState {
    for_device: DeviceId,
    piv_preview: FactoryResetPivPreview,
    /// Whether `keyroost_transport::PivSession::global_reset_available`
    /// resolved true for this device: either `PivExtension::Reset` or
    /// `PivExtension::ResetGlobal` resolves something other than
    /// `Unsupported` (`Supported` or `Unverified`), *and*
    /// `PivQuirk::ResetNeedsManagementAuth` is set — today: every HID
    /// Crescendo fingerprint, C2300/C4000/Generic alike (see that method's
    /// doc for why `Generic` needs the OR, not just `ResetGlobal ==
    /// Supported`). The credential need this reflects comes from the quirk
    /// alone, not specifically from `ResetGlobal` — when true, the dialog
    /// shows the credential prompt (`App::factory_reset_mgmt_auth_field`)
    /// and `factory_reset_confirm_summary` says a credential is needed,
    /// regardless of which extension is the reason. Does **not** by itself
    /// decide whether `PivSession::factory_reset` ends up running the
    /// device-wide mechanism or the PIV-only one — `piv_preview` already
    /// carries that (see `FactoryResetPivPreview::Resolved`), so this crate
    /// doesn't track `reset_global_gate` separately any more.
    needs_reset_mgmt_auth: bool,
    /// This device's well-known factory-default management-key bytes, from
    /// the same fingerprint job that resolved `piv_preview`/
    /// `needs_reset_mgmt_auth`
    /// (`keyroost_transport::PivSession::default_management_key`). `None`
    /// when keyroost has no known default for this fingerprint/version —
    /// the same signal `App::piv_modal_mgmt_field` uses to disable its "Use
    /// default management key" checkbox rather than offer one that might be
    /// wrong. `App::factory_reset_mgmt_auth_field` mirrors that: disables
    /// the checkbox and shows the hex value in a tooltip only when this is
    /// `Some`.
    default_mgmt_key: Option<&'static [u8]>,
    /// [`keyroost_piv::compat::PivQuirk::ResetLongRunning`], from the same
    /// fingerprint job that resolved `piv_preview`/`needs_reset_mgmt_auth`/
    /// `default_mgmt_key` — `false` whenever that job never ran or never
    /// completed (`NotOffered`/`CheckFailed`), same as the other two fields
    /// default to their "nothing learned" value in those cases.
    /// `factory_reset_confirm_summary` appends
    /// [`keyroost_piv::compat::PivQuirk::RESET_LONG_RUNNING_HINT`] to the
    /// PIV note when this is set, same wording the PIV pane's "Reset applet"
    /// card and `keyroostctl piv reset` already show.
    reset_long_running: bool,
}

/// How the factory-reset confirm dialog's reset management-auth credential
/// prompt is currently resolved — the same three-way shape as
/// [`PivMgmtAuthMode`] (a typed field, a "use the well-known default"
/// convenience, or a PIN), kept as its own type because the credential
/// itself is a different one: whatever
/// [`keyroost_transport::PivSession::default_management_key`] resolves for
/// *this reset*, not necessarily the same value
/// [`PivMgmtAuthMode::Default`] resolves for a already-unlocked session's
/// other management operations (e.g. Generate Key) — the two happen to
/// coincide on HID Crescendo today (its only known default is its ACA
/// XAUTH key either way — see
/// [`keyroost_piv::compat::PivQuirk::Default9bManagementKey`]'s doc), but
/// nothing here assumes that holds for a future fingerprint.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
enum ResetMgmtAuthMode {
    /// Neither toggle ticked: `App::reset_mgmt_auth_input` holds a typed
    /// management-key hex string.
    #[default]
    Manual,
    /// "Use default management key":
    /// `FactoryResetConfirmState::default_mgmt_key`, resolved for the
    /// specific device this dialog is armed for.
    Default,
    /// "Use PIN": the ACA instance's own VERIFY PIN — not the standard PIV
    /// application PIN [`PivMgmtAuthMode::Pin`] means.
    Pin,
}

/// [`piv_mgmt_mode_after_toggle`]'s twin for [`ResetMgmtAuthMode`] — same
/// rule, different type: `mode_if_checked` if the click checked the box,
/// [`ResetMgmtAuthMode::Manual`] if it unchecked it, regardless of what
/// the mode held before.
#[must_use]
fn reset_mgmt_auth_mode_after_toggle(
    checked: bool,
    mode_if_checked: ResetMgmtAuthMode,
) -> ResetMgmtAuthMode {
    if checked {
        mode_if_checked
    } else {
        ResetMgmtAuthMode::Manual
    }
}

/// How the user authorized `PivSession::factory_reset`'s credential, when
/// `PivQuirk::ResetNeedsManagementAuth` means one is needed — the
/// factory-default management key, a typed management key, or a PIN for the
/// ACA's own VERIFY PIN reference (today's only real consumer of any of the
/// three is HID Crescendo's device-wide mechanism; a plain PIV reset needing
/// this same quirk would take the same shape, just via the standard PIV
/// management-key round instead — see `PivSession::factory_reset`'s doc).
/// Produced by `App::reset_mgmt_current_auth`, consumed by
/// `run_card_reset_step`'s `Piv` branch. Mirrors [`PivMgmtAuth`]'s shape for
/// the same reason that type exists — a single resolved form both the
/// dialog's validation and the worker job's actual call convert into
/// `keyroost_transport::CurrentMgmtAuth` the same way.
enum ResetMgmtAuth {
    Key(zeroize::Zeroizing<Vec<u8>>),
    Pin(zeroize::Zeroizing<String>),
}

/// The confirmation body for the Factory reset modal: what key, and exactly
/// which applets get wiped, with the two ceremonies that aren't a plain wipe
/// spelled out (PIV's actual precondition, per `piv_preview`; FIDO needs a
/// replug + touch).
fn factory_reset_confirm_summary(
    serial: &str,
    model: &str,
    plan: &[keyroost_resolve::ResetStep],
    piv_preview: FactoryResetPivPreview,
    needs_management_auth: bool,
    reset_long_running: bool,
) -> String {
    use keyroost_resolve::ResetStep;
    use keyroost_transport::{FactoryResetPlan, PivResetPreview};
    // `PivExtension::ResetGlobal` resolving `Supported` or `Unverified`
    // (`PivResetPreview::Global`) means the PIV step, if it runs, will take
    // at least one other applet down with it — the same device-wide
    // mechanism `StepOutcome::WipedGlobal` names post-hoc with
    // `PIV_GLOBAL_RESET_LABEL` once the reset has actually happened. Name it
    // the same way here, ahead of time, rather than letting the confirm
    // dialog undersell the PIV step as a bare "PIV".
    let piv_is_global = matches!(
        piv_preview,
        FactoryResetPivPreview::Resolved(PivResetPreview::Global)
    );
    let applets = plan
        .iter()
        .map(|s| match s {
            ResetStep::Piv if piv_is_global => keyroost_resolve::PIV_GLOBAL_RESET_LABEL,
            s => s.label(),
        })
        .collect::<Vec<_>>()
        .join(", ");
    let mut msg = format!(
        "Factory-reset {model} (serial {serial})?\n\nWipes: {applets}.\nEvery \
         credential, code, key, and PIN is erased. Each applet that completes \
         comes back in factory condition, ready to set up again."
    );
    if plan.contains(&ResetStep::Piv) {
        // Don't promise the key "stays fully usable" in the
        // `BurnPinPukThenReset` case: PIN/PUK are blocked on purpose there, so
        // a wipe that stops between the blocking and the RESET leaves PIV
        // locked until a reset finishes.
        let piv_note = match piv_preview {
            // Shouldn't happen — `start_factory_reset_confirm` always
            // fingerprints when the plan offers PIV — but fails into the same
            // wording `CheckFailed` gets rather than claim something about a
            // step that was never actually fingerprinted.
            FactoryResetPivPreview::NotOffered | FactoryResetPivPreview::CheckFailed => {
                "\n\nPIV: keyroost couldn't confirm this device's RESET support \
                 ahead of time. It will still attempt the standard path (block the \
                 PIN and PUK, then wipe) \u{2014} the report below the button says \
                 what actually happened."
            }
            // Unreachable via normal flow: `start_factory_reset_confirm`
            // drops `ResetStep::Piv` from the plan entirely whenever
            // `preview_factory_reset` resolves this (`exclude_unresettable_piv`),
            // so this whole block never runs for it. Kept for exhaustiveness
            // — empty string is the safe fallback if it's ever reached anyway
            // (e.g. a plan built before a fresh fingerprint changed the
            // answer).
            FactoryResetPivPreview::Resolved(PivResetPreview::Unsupported) => "",
            // The device-wide mechanism will run — nothing special to caveat
            // here: PIV just gets wiped along with the plan's other applets,
            // same as `BurnPinPukThenReset` below promises for the PIV-only
            // path, without that path's own PIN/PUK-blocking caveat (this
            // mechanism never touches either counter). The credential
            // sentence below covers the one thing worth calling out, when
            // the quirk applies.
            FactoryResetPivPreview::Resolved(PivResetPreview::Global) => "",
            // Also unreachable via normal flow, same reasoning as the
            // top-level `Unsupported` arm above — `preview_factory_reset` maps
            // `FactoryResetPlan::Unsupported` to the outer `PivResetPreview::
            // Unsupported`, never to `Piv(Unsupported)`.
            FactoryResetPivPreview::Resolved(PivResetPreview::Piv(
                FactoryResetPlan::Unsupported,
            )) => "",
            // Unlike `BurnPinPukThenReset` below, this authenticates once,
            // then sends RESET — a clean, atomic pass/fail with no
            // partial-blocking state the step report could reveal, so this
            // doesn't point at it the way the burn case does. The credential
            // sentence below (always shown alongside this arm, since
            // `NeedsManagementAuth` only resolves when the quirk applies)
            // says where the credential it authenticates with comes from.
            FactoryResetPivPreview::Resolved(PivResetPreview::Piv(
                FactoryResetPlan::NeedsManagementAuth,
            )) => {
                "\n\nPIV: this device resets via an authenticated management-key \
                 session \u{2014} keyroost authenticates with the credential \
                 entered below, then wipes."
            }
            // Also atomic, same reasoning as `NeedsManagementAuth` above: the
            // bare RESET attempt this case sends never touches the PIN or PUK
            // either, so it either wipes PIV outright or leaves it exactly as
            // it was — nothing partial for the step report to disambiguate.
            FactoryResetPivPreview::Resolved(PivResetPreview::Piv(
                FactoryResetPlan::Unverified,
            )) => {
                "\n\nPIV: keyroost's list has no RESET entry for this key, so it will \
                 try it without blocking the PIN and PUK first \u{2014} consult \
                 this device's own documentation for any precondition (commonly: \
                 the PIN and PUK both already blocked) and complete it manually if \
                 the attempt fails."
            }
            // The one case that isn't atomic: burning the PIN, then the PUK,
            // then sending RESET is three separate steps, and a failure
            // between any of them leaves PIV in a partial state this text
            // alone can't describe — hence pointing at the step report, unlike
            // every other case above.
            FactoryResetPivPreview::Resolved(PivResetPreview::Piv(
                FactoryResetPlan::BurnPinPukThenReset,
            )) => {
                "\n\nPIV: the PIN and PUK are intentionally blocked, then the applet \
                 is wiped (the standard reset path). If the wipe stops after the \
                 blocking, PIV stays locked until a reset finishes \u{2014} the \
                 report below the button says what state it's in."
            }
        };
        msg.push_str(piv_note);
        // `needs_management_auth` is `PivSession::global_reset_available`'s
        // boolean — `PivQuirk::ResetNeedsManagementAuth` applying, ANDed
        // with either `PivExtension::Reset` or `PivExtension::ResetGlobal`
        // not being a confirmed dead end. Whichever mechanism `piv_preview`
        // says will actually run (`Global` or `Piv(NeedsManagementAuth)`),
        // this same credential is what it needs, entered in the same field
        // (`App::factory_reset_mgmt_auth_field`) — so one sentence covers
        // both, rather than duplicating it into each arm above.
        if needs_management_auth {
            msg.push_str("\n\nResetting this device requires management auth, entered below.");
        }
        // `PivQuirk::ResetLongRunning` — same wording the PIV pane's "Reset
        // applet" card and `keyroostctl piv reset` already show, appended
        // here too so it isn't missed before the whole-device wipe starts.
        if reset_long_running {
            msg.push_str("\n\n");
            msg.push_str(keyroost_piv::compat::PivQuirk::RESET_LONG_RUNNING_HINT);
        }
    }
    if plan.contains(&ResetStep::Fido) {
        msg.push_str("\n\nFinishes with a step to unplug the key, plug it back in, and touch it.");
    }
    msg
}

/// One line of the factory-reset report pane.
///
/// Card applets resolve on the worker and arrive as finished
/// [`StepReport`](keyroost_resolve::StepReport)s. FIDO can't: its wipe is
/// handed to the armed reset dialog, which needs a replug and a touch, so its
/// row is seeded as `FidoPending` and only becomes a `Step` once that ceremony
/// answers. `StepOutcome` has no pending state — it lives in the shared
/// resolver crate the CLI consumes too — so the waiting state is modelled
/// here. Without this row a failed or abandoned FIDO finale left a report that
/// listed only the wiped card applets, reading as a completed whole-device
/// wipe while the passkeys and PIN were still on the key.
enum FactoryResetRow {
    /// A step that has answered, wiped or failed.
    Step(keyroost_resolve::StepReport),
    /// FIDO2 was in the plan and the replug + touch ceremony hasn't answered.
    FidoPending,
}

/// How a report line should be painted. Keeps the wording pure (testable
/// without a frame) while the renderer owns the palette lookup.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum RowTone {
    /// The step finished as asked.
    Done,
    /// Nothing went wrong, but the step hasn't happened yet.
    Waiting,
    /// The step wiped what it was supposed to, but something afterward
    /// still needs attention.
    Warn,
    /// The step did not wipe what it was supposed to.
    Bad,
    /// The step wasn't part of this run.
    Muted,
}

/// The text and tone for one factory-reset report line.
fn factory_reset_row_line(row: &FactoryResetRow) -> (String, RowTone) {
    use keyroost_resolve::StepOutcome;
    match row {
        FactoryResetRow::FidoPending => (
            // Route-neutral on purpose: a USB key finishes via the replug +
            // touch ceremony, a card in a reader resets in place after a
            // power cycle — the open reset dialog carries the specific
            // instructions for whichever this is.
            format!(
                "{}  not wiped yet \u{2014} finish the confirmation in the reset window",
                keyroost_resolve::ResetStep::Fido.label()
            ),
            RowTone::Waiting,
        ),
        FactoryResetRow::Step(r) => match &r.outcome {
            StepOutcome::Wiped => (format!("{}  wiped", r.step.label()), RowTone::Done),
            // Device-wide mechanism, not confined to PIV alone — name the
            // whole device instead of just the applet that triggered it.
            StepOutcome::WipedGlobal => (
                format!("{}  wiped", keyroost_resolve::PIV_GLOBAL_RESET_LABEL),
                RowTone::Done,
            ),
            StepOutcome::WipedWithWarning(e) => (
                format!("{}  wiped, but: {e}", r.step.label()),
                RowTone::Warn,
            ),
            StepOutcome::Failed(e) => (format!("{}  failed: {e}", r.step.label()), RowTone::Bad),
            StepOutcome::Skipped(reason) => (
                format!("{}  skipped: {reason}", r.step.label()),
                RowTone::Muted,
            ),
        },
    }
}

/// One-line factory-reset summary for the activity log: which steps wiped
/// cleanly, which wiped but left a follow-up warning, which failed (each
/// with its own reason), and which were skipped (each with its own reason)
/// — the same buckets `factory_reset_row_line` paints per-row in the
/// Overview pane, collapsed into one line so the activity log keeps a
/// permanent record of the run even after the pane's own report is
/// overwritten by the next one.
///
/// `StepOutcome::WipedWithWarning` counts toward *both* the "wiped" list
/// (the applet really was wiped — a reader scanning just that list must see
/// it there) and its own "warnings" list (the follow-up failure is real and
/// still needs its own line) — the one outcome that isn't confined to a
/// single bucket, matching what it actually is: a wipe that succeeded, with
/// a caveat.
fn factory_reset_report_summary(reports: &[keyroost_resolve::StepReport]) -> String {
    use keyroost_resolve::StepOutcome;
    let wiped: Vec<&str> = reports
        .iter()
        .filter(|r| {
            matches!(
                r.outcome,
                StepOutcome::Wiped | StepOutcome::WipedGlobal | StepOutcome::WipedWithWarning(_)
            )
        })
        .map(|r| match r.outcome {
            // Device-wide mechanism, not confined to PIV alone — name the
            // whole device instead of just the applet that triggered it.
            StepOutcome::WipedGlobal => keyroost_resolve::PIV_GLOBAL_RESET_LABEL,
            _ => r.step.label(),
        })
        .collect();
    let warnings: Vec<String> = reports
        .iter()
        .filter_map(|r| match &r.outcome {
            StepOutcome::WipedWithWarning(e) => Some(format!("{}: {e}", r.step.label())),
            _ => None,
        })
        .collect();
    let failed: Vec<String> = reports
        .iter()
        .filter_map(|r| match &r.outcome {
            StepOutcome::Failed(e) => Some(format!("{}: {e}", r.step.label())),
            _ => None,
        })
        .collect();
    let skipped: Vec<String> = reports
        .iter()
        .filter_map(|r| match &r.outcome {
            StepOutcome::Skipped(reason) => Some(format!("{}: {reason}", r.step.label())),
            _ => None,
        })
        .collect();
    let mut msg = format!(
        "wiped: {}",
        if wiped.is_empty() {
            "none".to_string()
        } else {
            wiped.join(", ")
        }
    );
    if !warnings.is_empty() {
        msg.push_str(&format!("; warnings: {}", warnings.join("; ")));
    }
    if !failed.is_empty() {
        msg.push_str(&format!("; failed: {}", failed.join("; ")));
    }
    if !skipped.is_empty() {
        msg.push_str(&format!("; skipped: {}", skipped.join("; ")));
    }
    msg
}

/// Fold the FIDO finale's outcome into the factory-reset report, replacing the
/// row seeded when the card sweep handed off. A FIDO reset that isn't part of
/// a factory-reset run (the standalone "Reset key" button) finds no FIDO row
/// and leaves the report untouched.
///
/// An already-answered FIDO row is replaced too, not just a pending one: the
/// report invites a retry after a failure, the retry runs against the same
/// selection (so nothing clears the report in between), and a row still
/// reading "failed" after a wipe that succeeded tells the user their passkeys
/// and PIN survived on a key that is actually empty. The latest outcome wins.
///
/// Only a caller that actually attempted the wipe may use this. Everything
/// else takes [`resolve_pending_fido_reset_row`].
///
/// Returns whether a row was actually found and replaced — `false` means this
/// wasn't part of a factory-reset run at all (a standalone "Reset key"), which
/// callers use to decide whether the finale is also worth a permanent
/// activity-log line rather than just an Overview-pane update (see
/// [`App::apply_factory_reset_sweep`]'s doc on why that permanent record
/// matters).
fn resolve_fido_reset_row(
    rows: &mut [FactoryResetRow],
    outcome: keyroost_resolve::StepOutcome,
) -> bool {
    if let Some(row) = rows.iter_mut().find(|r| match r {
        FactoryResetRow::FidoPending => true,
        FactoryResetRow::Step(r) => r.step == keyroost_resolve::ResetStep::Fido,
    }) {
        *row = FactoryResetRow::Step(keyroost_resolve::StepReport {
            step: keyroost_resolve::ResetStep::Fido,
            outcome,
        });
        true
    } else {
        false
    }
}

/// Resolve the FIDO row only while it is still waiting on the ceremony.
///
/// For callers that end a *dialog* rather than a wipe: cancelling the modal, or
/// refusing to arm it. They can't know whether the dialog they just closed was
/// the factory reset's finale or a standalone "Reset key" the user opened
/// afterwards — and the report survives both a tab switch and a replug, so a
/// stale one is still on screen. Overwriting an answered row from here turns a
/// finished "FIDO2 wiped" into "FIDO2 failed" the moment the user opens the
/// FIDO2 tab and backs out of the reset dialog, inviting them to repeat an
/// irreversible ceremony that already succeeded. A pending row is the only
/// evidence that this dialog owns the finale, so it is the only row these
/// callers may write.
///
/// Returns whether a pending row was actually found and resolved — `false`
/// covers both "no factory reset in flight" and "this row already answered",
/// neither of which is this dialog's finale to announce. `true` means this
/// really was the factory reset's FIDO step being decided just now, which
/// callers use to also give it a permanent activity-log line (see
/// [`resolve_fido_reset_row`]'s doc for why).
fn resolve_pending_fido_reset_row(
    rows: &mut [FactoryResetRow],
    outcome: keyroost_resolve::StepOutcome,
) -> bool {
    if let Some(row) = rows
        .iter_mut()
        .find(|r| matches!(r, FactoryResetRow::FidoPending))
    {
        *row = FactoryResetRow::Step(keyroost_resolve::StepReport {
            step: keyroost_resolve::ResetStep::Fido,
            outcome,
        });
        true
    } else {
        false
    }
}

/// Severity + activity-log line for a factory reset's FIDO finale outcome.
///
/// Callers reach here only after [`resolve_fido_reset_row`] or
/// [`resolve_pending_fido_reset_row`] confirms this really was the finale
/// being decided — otherwise the card sweep's own "factory reset finished"
/// line (written before the FIDO ceremony even starts, see
/// [`App::apply_factory_reset_sweep`]) is the only activity-log record of
/// the run, and never gets updated once FIDO's outcome is known. Reuses
/// [`factory_reset_row_line`]'s wording so the permanent log and the
/// Overview pane read as the same event.
fn factory_reset_fido_finale_log_line(
    outcome: &keyroost_resolve::StepOutcome,
) -> (Severity, String) {
    use keyroost_resolve::{ResetStep, StepOutcome, StepReport};
    let severity = match outcome {
        // `WipedGlobal` never actually reaches here in practice (its sole
        // producer is PIV, and this function is only ever called for
        // `ResetStep::Fido`), but the match has to stay exhaustive.
        StepOutcome::Wiped | StepOutcome::WipedGlobal => Severity::Ok,
        StepOutcome::WipedWithWarning(_) | StepOutcome::Skipped(_) => Severity::Warn,
        StepOutcome::Failed(_) => Severity::Err,
    };
    let (text, _tone) = factory_reset_row_line(&FactoryResetRow::Step(StepReport {
        step: ResetStep::Fido,
        outcome: outcome.clone(),
    }));
    (severity, format!("factory reset \u{2014} {text}"))
}

/// Render a `PivSession::factory_reset` failure for the report pane.
///
/// Only one of its paths — the PIN/PUK burn dance — blocks the PIN and then
/// the PUK on its way to RESET, so only there can a failure between the
/// blocking and the wipe leave a card that is locked but not erased. The
/// confirmation modal promises the report says which state the card is in,
/// so every failure from that path has to carry that.
///
/// The variants each of `factory_reset`'s other paths (device-wide
/// mechanism, authenticated management-key RESET, unverified bare RESET,
/// or an outright refusal before anything ran) can return already say so
/// themselves — none of them ever blocks a PIN or PUK, so appending the
/// burn-dance disclosure to them would be wrong. Only an error that could
/// have come from the burn dance (a transport error mid-loop, an unexpected
/// status word the PIN/PUK mapping renders as a bare APDU failure, a host
/// RNG failure) gets the disclosure appended.
///
/// The way out, when it applies, is to run the factory reset again, not the
/// single-applet PIV reset: a fault in the PUK loop leaves the PIN blocked
/// and the PUK *not* blocked, and the card refuses a plain RESET until both
/// are blocked.
fn piv_factory_reset_message(e: TransportError) -> String {
    match e {
        // None of these touched the PIN or PUK: `Unsupported`/
        // `NeedsManagementAuth` refuse before the burn sequence even starts
        // (see `PivSession::plan_factory_reset`), `UnverifiedFailed` is the
        // bare-RESET path that deliberately skips pre-blocking, and
        // `GlobalFailed`/`ManagementAuthFailed` are the device-wide and
        // authenticated-management-key mechanisms — neither has any
        // PIN/PUK-blocking step to have left half-done. The "PIV may now be
        // locked" caveat below would be actively wrong for any of these, so
        // they pass through as-is — each variant's own `Display` already
        // says what actually happened.
        TransportError::PivResetUnsupported
        | TransportError::PivResetNeedsManagementAuth
        | TransportError::PivResetUnverifiedFailed(_)
        | TransportError::PivResetForcedFailed(_)
        | TransportError::PivResetGlobalFailed(_)
        | TransportError::PivResetManagementAuthFailed(_)
        | TransportError::PivResetIncomplete(_)
        | TransportError::PivPukGuessAccepted => e.to_string(),
        other => format!(
            "{other} (the wipe blocks the PIN and PUK before erasing, so PIV may \
             now be locked but not wiped \u{2014} that is not bricked: run the \
             factory reset again to finish it)"
        ),
    }
}

/// Whether the PIV pane's "Reset applet" card should show its "Factory reset
/// supported →" link to the whole-device factory reset (Overview tab): true
/// when `reset_global_gate` — a *different* extension,
/// `PivExtension::ResetGlobal`, a device-wide reset directive that takes PIV
/// down with it alongside at least one other applet — resolves
/// [`keyroost_piv::compat::FeatureGate::Supported`] (an *unverified* alternative isn't something to
/// steer a user toward) AND `reset_gate` (`PivExtension::Reset`, the
/// PIV-only path) is anything other than [`keyroost_piv::compat::FeatureGate::Supported`] (a
/// known-good PIV-only path has nothing to redirect away from — this is the
/// "leave as-is" case).
fn piv_reset_global_alternative_available(
    reset_gate: keyroost_piv::compat::FeatureGate,
    reset_global_gate: keyroost_piv::compat::FeatureGate,
) -> bool {
    use keyroost_piv::compat::FeatureGate;
    reset_global_gate == FeatureGate::Supported && reset_gate != FeatureGate::Supported
}

/// Whether the Generate Key modal's "Policy other than `default` requires
/// YubiKey or compatible token." caveat still needs to be shown below the
/// PIN/touch policy combos: true unless *both* gates are confirmed
/// [`keyroost_piv::compat::FeatureGate::Supported`] — at that point the caveat is stale noise on a
/// device already known to handle non-default policies, and the per-row
/// warning marker / disabled-combo hover above already cover the
/// unverified/unsupported cases on their own.
fn piv_policy_caveat_hint_needed(
    pin_policy_gate: keyroost_piv::compat::FeatureGate,
    touch_policy_gate: keyroost_piv::compat::FeatureGate,
) -> bool {
    use keyroost_piv::compat::FeatureGate;
    pin_policy_gate != FeatureGate::Supported || touch_policy_gate != FeatureGate::Supported
}

/// Run one non-FIDO applet reset off the UI thread, mapping the result to a
/// [`StepOutcome`](keyroost_resolve::StepOutcome) so a single failure is
/// recorded rather than aborting the sweep (continue-on-error, matching the
/// CLI's `factory-reset`). FIDO is never routed here — it is handed to the
/// armed `ResetDialog` flow, which owns the replug + touch ceremony.
fn run_card_reset_step(
    step: keyroost_resolve::ResetStep,
    reader: Option<&str>,
    hid_path: Option<&std::path::Path>,
    reset_mgmt_auth: Option<&ResetMgmtAuth>,
) -> keyroost_resolve::StepOutcome {
    use keyroost_resolve::{ResetStep, StepOutcome};

    // PIV gets its own path, ahead of the shared closure below:
    // `PivSession::factory_reset` decides on its own, from a live fingerprint,
    // whether to run the device-wide mechanism, a PIV-only reset, or skip the
    // applet outright (RESET known-unsupported on both axes, or a
    // precondition — an authenticated management-key session — with no
    // credential supplied) rather than fail it, a distinction the shared
    // Ok/Err mapping the other steps share can't express. See
    // `piv_factory_reset_message` for why none of the "never touched PIN/PUK"
    // errors get its usual caveat appended.
    if step == ResetStep::Piv {
        return (|| -> Result<StepOutcome, String> {
            let name = reader.ok_or("no PC/SC reader for the PIV applet")?;
            let current = reset_mgmt_auth.map(|auth| match auth {
                ResetMgmtAuth::Key(key) => keyroost_transport::CurrentMgmtAuth::Key(key),
                ResetMgmtAuth::Pin(pin) => keyroost_transport::CurrentMgmtAuth::Pin(pin.as_bytes()),
            });
            keyroost_transport::PivSession::with_transaction(
                name,
                |s| -> Result<StepOutcome, TransportError> {
                    Ok(match s.factory_reset(current) {
                Ok(keyroost_transport::FactoryResetOutcome::Wiped) => StepOutcome::Wiped,
                // The device-wide mechanism ran cleanly -- more than just PIV
                // was wiped, so the report should say so rather than naming
                // only the applet that happened to trigger it.
                Ok(keyroost_transport::FactoryResetOutcome::WipedGlobal) => {
                    StepOutcome::WipedGlobal
                }
                // The device IS wiped -- only the courtesy XAUTH-key restore
                // (the device-wide mechanism's own follow-up) failed.
                // `WipedWithWarning`, not `Failed`: the wipe itself is done,
                // so this must count as wiped everywhere that's what's being
                // asked (the pane re-init below, the "N wiped" report), but
                // the restore failure is real and still needs its own line.
                Ok(keyroost_transport::FactoryResetOutcome::WipedKeyRestoreFailed) => {
                    StepOutcome::WipedWithWarning(
                        "restoring XAUTH key 1 to the factory-delivery value afterward failed \
                         \u{2014} it's left cleared instead. Set it manually (PIV \u{2192} \
                         Change management key) if you need it back."
                            .into(),
                    )
                }
                Err(
                    e @ (TransportError::PivResetUnsupported
                    | TransportError::PivResetNeedsManagementAuth),
                ) => StepOutcome::Skipped(e.to_string()),
                Err(e) => StepOutcome::Failed(piv_factory_reset_message(e)),
            })
                },
            )
            .map_err(|e: TransportError| e.to_string())
        })()
        .unwrap_or_else(StepOutcome::Failed);
    }

    let run = || -> Result<(), String> {
        match step {
            ResetStep::Oath => {
                let name = reader.ok_or("no PC/SC reader for the OATH applet")?;
                let mut s =
                    keyroost_transport::OathSession::open(name).map_err(|e| e.to_string())?;
                s.factory_reset().map_err(|e| e.to_string())?;
            }
            ResetStep::OpenPgp => {
                let name = reader.ok_or("no PC/SC reader for the OpenPGP applet")?;
                let mut s =
                    keyroost_transport::OpenPgpSession::open(name).map_err(|e| e.to_string())?;
                s.factory_reset().map_err(|e| e.to_string())?;
            }
            ResetStep::Piv => unreachable!("handled above, before this closure"),
            ResetStep::Token2Otp => {
                // The OTP applet lives on the FIDO HID node when present, else on
                // the PC/SC reader. Mirror the CLI's `HidThenReader` behavior:
                // try USB-HID first, and on an open failure fall back to the
                // SAME device's reader — some firmware botches the HID applet
                // probe while its CCID side works (#82). Without this fallback a
                // GUI factory reset reported OTP `Failed` where the CLI succeeds.
                let mut s = match (hid_path, reader) {
                    (Some(p), reader) => {
                        match keyroost_transport::Token2OtpSession::open_hid_path(p, false) {
                            Ok(s) => s,
                            Err(hid_err) => match reader {
                                Some(name) => {
                                    keyroost_transport::Token2OtpSession::open_pcsc_reader(
                                        name, false,
                                    )
                                    .map_err(|e| {
                                        format!(
                                            "USB-HID failed ({hid_err}); the same key's \
                                             reader also failed ({e})"
                                        )
                                    })?
                                }
                                None => return Err(hid_err.to_string()),
                            },
                        }
                    }
                    (None, Some(name)) => {
                        keyroost_transport::Token2OtpSession::open_pcsc_reader(name, false)
                            .map_err(|e| e.to_string())?
                    }
                    (None, None) => return Err("no transport for the OTP applet".to_string()),
                };
                s.erase_all().map_err(|e| e.to_string())?;
            }
            ResetStep::Fido => {}
        }
        Ok(())
    };
    match run() {
        Ok(()) => StepOutcome::Wiped,
        Err(e) => StepOutcome::Failed(e),
    }
}

/// Whether to render the Reset card *outside* the Settings subview: the key
/// is CTAP2 (so resettable) but not unlocked. authenticatorReset takes no
/// PIN, and its primary use case is recovering from a forgotten or blocked
/// PIN — the one state in which unlock is impossible — so hiding it behind
/// the unlock-gated tabs removed reset exactly when it was needed. Once
/// unlocked, the Settings tab owns the card and this stays false.
fn show_standalone_reset(unlocked: bool, info: Option<&AuthenticatorInfo>) -> bool {
    !unlocked && fido_settings_available(info)
}

/// The subview to actually render: the current pick when its tab is offered,
/// else the first offered tab. The pick persists across selection changes,
/// so switching from a key with a fingerprint sensor (or credential
/// management) to one without would otherwise leave the pane on a tab the
/// new key doesn't have.
fn snap_subview(current: FidoSubview, tabs: &[(FidoSubview, &str)]) -> FidoSubview {
    if tabs.iter().any(|(v, _)| *v == current) {
        current
    } else {
        tabs.first().map(|(v, _)| *v).unwrap_or_default()
    }
}

/// The capability tab to actually render: the current pick when `offered`
/// (the selected device's own `Device::tabs()`) still has it, else the
/// first offered tab, else `Overview` (`offered` empty — a Molto2 token,
/// which has no capability tabs at all). Same shape as [`snap_subview`], one
/// level up: a per-device remembered pick (`App::cap_tab_by_device`) can be
/// stale exactly the same way a persisted `FidoSubview` pick can — switching
/// from a key with PIV to one without would otherwise leave the pane on a
/// tab the new key doesn't have.
fn snap_cap_tab(current: CapTab, offered: &[CapTab]) -> CapTab {
    if offered.contains(&current) {
        current
    } else {
        offered.first().copied().unwrap_or_default()
    }
}

/// What getInfo says about PIN support. An absent `clientPin` option means
/// the key has no PIN feature at all (CTAP getInfo semantics) — a different
/// state from "getInfo not read yet", which the pane previously conflated
/// with it (PIN-less authenticators showed a permanent "Reading key…").
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum PinSupport {
    /// No getInfo yet (still loading, or the read failed).
    Unknown,
    /// The key does not support clientPin.
    Unsupported,
    /// clientPin supported, no PIN set yet.
    NotSet,
    /// A PIN is set.
    Set,
}

fn pin_support(info: Option<&AuthenticatorInfo>) -> PinSupport {
    match info {
        None => PinSupport::Unknown,
        Some(i) => match i.option("clientPin") {
            None => PinSupport::Unsupported,
            Some(false) => PinSupport::NotSet,
            Some(true) => PinSupport::Set,
        },
    }
}

/// Decide whether a freshly appeared FIDO HID device may receive an armed
/// reset. `target_*` describe the key the user armed; `cand_*` the device
/// that just appeared. Vendor/product ids must match when known, and then a
/// *stable* identity must match: the USB HID serial when both sides expose
/// one, else the resolver's effective (CCID-derived) serial. When neither
/// side offers a stable identity the answer is `false` — fail closed; being
/// the first same-model path to show up is not an identity (KEY-005).
fn reset_reinsert_matches(
    target_hid_serial: Option<&str>,
    target_effective_serial: Option<&str>,
    target_ids: Option<(u16, u16)>,
    cand_hid_serial: Option<&str>,
    cand_effective_serial: Option<&str>,
    cand_ids: (u16, u16),
) -> bool {
    if let Some(ids) = target_ids {
        if ids != cand_ids {
            return false;
        }
    }
    if let (Some(t), Some(c)) = (target_hid_serial, cand_hid_serial) {
        return t == c;
    }
    if let (Some(t), Some(c)) = (target_effective_serial, cand_effective_serial) {
        return t == c;
    }
    false
}

/// The password an OATH op should send: the freshly typed entry when there
/// is one, else the password retained from the last successful unlock of the
/// current selection (see `OathState::unlocked_password`). Falls back to
/// empty — correct for an unprotected applet.
fn oath_effective_password(oath: &OathState) -> zeroize::Zeroizing<String> {
    if !oath.password_input.is_empty() {
        return zeroize::Zeroizing::new(oath.password_input.clone());
    }
    oath.unlocked_password
        .clone()
        .unwrap_or_else(|| zeroize::Zeroizing::new(String::new()))
}

/// Purge egui's retained plaintext for a masked text widget.
///
/// egui keeps an undo history (`TextEditState.undoer`) holding real, unmasked
/// snapshots of everything typed into a field, for the whole process lifetime;
/// `.password(true)` only masks *display*. So wiping the caller's `String`
/// buffer is not enough — the secret is still recoverable from egui's own
/// memory until the undo history is cleared. This clears it. Safe to call every
/// frame and on a widget that was never typed into (it only touches that
/// widget's stored state, if any).
///
/// Limitation: egui's `clear_undoer` *replaces* the undoer, so the snapshot
/// `String`s are freed, not zeroized — the API gives no access to the stored
/// text, so the old bytes can linger in freed heap pages until reused. This
/// still removes the secret from egui's live, trivially-queryable state; it is
/// not (and cannot be, from outside egui) a memory-scrubbing guarantee.
fn clear_edit_undo(ctx: &egui::Context, id: egui::Id) {
    if let Some(mut state) = egui::TextEdit::load_state(ctx, id) {
        state.clear_undoer();
        egui::TextEdit::store_state(ctx, id, state);
    }
}

/// True when a text widget's retained undo state could still hold typed
/// plaintext, i.e. a scrub (`clear_edit_undo`) would actually remove
/// something. The probe is (default cursor, empty text): `has_undo` is false
/// only for an empty history or one whose single snapshot IS that empty
/// state — neither holds a secret. `has_redo` catches text typed and then
/// undone; `is_in_flux` catches text typed too recently to be committed.
fn edit_state_needs_scrub(state: &egui::text_edit::TextEditState) -> bool {
    let undoer = state.undoer();
    let probe = (egui::text::CCursorRange::default(), String::new());
    undoer.has_undo(&probe) || undoer.has_redo(&probe) || undoer.is_in_flux()
}

/// Draw-time guard for a secret field: while it isn't holding keyboard focus,
/// purge its undo history (see [`clear_edit_undo`]). Call immediately after
/// adding any `.password(true)` field, passing its [`egui::Response`].
///
/// This deliberately keys on `has_focus()` (a level) rather than
/// `lost_focus()` (an edge): a dialog dismissed while its field still has
/// focus (Esc, ✕ mid-typing) removes the widget before any lost-focus edge
/// can be observed, while its `TextEditState` — undo plaintext included —
/// persists for the process lifetime. The level-triggered form scrubs that
/// stale state on the reopened dialog's first unfocused frame, which the
/// edge form would miss. `edit_state_needs_scrub` skips the rewrite when the
/// history is provably empty, so the steady-state cost is one state load per
/// secret field per frame, no store.
fn guard_secret_field(ctx: &egui::Context, resp: &egui::Response) {
    if resp.has_focus() {
        return;
    }
    if let Some(state) = egui::TextEdit::load_state(ctx, resp.id) {
        if edit_state_needs_scrub(&state) {
            clear_edit_undo(ctx, resp.id);
        }
    }
}

/// The shared "Scan QR" button: a Default button with the QR glyph painted into
/// it. Returns `true` when clicked. Collapses the repeated
/// `button_with_icon` + `paint_qr_icon` block at every scan-QR call site.
#[cfg(feature = "qr")]
pub(crate) fn scan_qr_button(ui: &mut egui::Ui, p: &Palette) -> bool {
    let (resp, icon_center, fg) = theme::button_with_icon(ui, p, BtnKind::Default, "Scan QR", 14.0);
    paint_qr_icon(ui, icon_center, fg);
    resp.clicked()
}

/// Where an OpenPGP key import gets its key material. Mirrors the CLI's
/// `--generate` / `--in <FILE>` choice.
#[derive(Clone, Copy, PartialEq, Eq)]
enum ImportSource {
    /// Generate a fresh RSA-2048 key on the host.
    Generate,
    /// Load an RSA-2048 key from a file (PKCS#1/PKCS#8, PEM or DER).
    FromFile,
}

/// Which key slot a GUI generate targets. Mirrors the CLI's slot choice.
#[derive(Default, Clone, Copy, PartialEq, Eq)]
enum OpenPgpSlotSel {
    #[default]
    Sign,
    Decrypt,
    Auth,
}

impl OpenPgpSlotSel {
    fn to_crt(self) -> keyroost_transport::KeyCrt {
        match self {
            OpenPgpSlotSel::Sign => keyroost_transport::KeyCrt::Sign,
            OpenPgpSlotSel::Decrypt => keyroost_transport::KeyCrt::Decrypt,
            OpenPgpSlotSel::Auth => keyroost_transport::KeyCrt::Auth,
        }
    }
    fn label(self) -> &'static str {
        match self {
            OpenPgpSlotSel::Sign => "signature",
            OpenPgpSlotSel::Decrypt => "decryption",
            OpenPgpSlotSel::Auth => "authentication",
        }
    }
    /// Capitalized tab label for the sub-tab strip (mirrors PIV slot tabs).
    fn tab_label(self) -> &'static str {
        match self {
            OpenPgpSlotSel::Sign => "Signature",
            OpenPgpSlotSel::Decrypt => "Decryption",
            OpenPgpSlotSel::Auth => "Authentication",
        }
    }
    /// This key's raw algorithm attributes and fingerprint out of an
    /// `OpenPgpStatus`, so the per-key state line can read directly from the
    /// selected key.
    fn status_fields(self, st: &keyroost_transport::OpenPgpStatus) -> (&[u8], &[u8; 20]) {
        match self {
            OpenPgpSlotSel::Sign => (&st.sig_attrs, &st.fingerprint_sig),
            OpenPgpSlotSel::Decrypt => (&st.dec_attrs, &st.fingerprint_dec),
            OpenPgpSlotSel::Auth => (&st.aut_attrs, &st.fingerprint_aut),
        }
    }
}

/// OpenPGP key-generation algorithm selector: the slot's current algorithm
/// ("card default"), or an explicit one.
#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
enum OpenPgpKeyAlgSel {
    #[default]
    CardDefault,
    Alg(keyroost_transport::OpenPgpKeyAlg),
}

impl OpenPgpKeyAlgSel {
    fn to_alg(self) -> Option<keyroost_transport::OpenPgpKeyAlg> {
        match self {
            OpenPgpKeyAlgSel::CardDefault => None,
            OpenPgpKeyAlgSel::Alg(a) => Some(a),
        }
    }
    fn label(self) -> &'static str {
        match self {
            OpenPgpKeyAlgSel::CardDefault => "Card default",
            OpenPgpKeyAlgSel::Alg(a) => a.label(),
        }
    }
    /// The menu for `crt`'s slot: what the card lists in its Algorithm
    /// Information when it publishes one for that slot, else every algorithm
    /// that fits the slot — unknown means offer the surface and let the card
    /// answer, never a vendor table.
    fn choices(
        supported: Option<&keyroost_transport::AlgorithmInformation>,
        crt: keyroost_transport::KeyCrt,
    ) -> Vec<OpenPgpKeyAlgSel> {
        let mut out = vec![OpenPgpKeyAlgSel::CardDefault];
        let listed = supported.map(|i| i.key_algs(crt)).unwrap_or_default();
        if !listed.is_empty() {
            out.extend(listed.into_iter().map(OpenPgpKeyAlgSel::Alg));
        } else {
            out.extend(
                keyroost_transport::OpenPgpKeyAlg::ALL
                    .into_iter()
                    .filter(|a| a.attributes(crt).is_ok())
                    .map(OpenPgpKeyAlgSel::Alg),
            );
        }
        out
    }
}

/// Which credential-entry flow the PIV modal is currently driving. The first
/// three map 1:1 to the PIN/PUK operations (`piv_change_pin` / `piv_change_puk`
/// / `piv_unblock_pin`); the rest are the management-key-gated operations whose
/// *secrets* (management key and/or PIN) now live in the modal while their
/// non-secret parameters (slot, algorithm, file path, subject, …) stay inline
/// in the pane. The variant selects which secret fields the modal renders and
/// which op Submit dispatches to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PivCredKind {
    ChangePin,
    ChangePuk,
    UnblockPin,
    GenerateKey,
    ImportCert,
    SelfSign,
    RequestCsr,
    SetRetries,
    ChangeMgmtKey,
    DeleteCert,
    DeleteKey,
    MoveKey,
    NewChuid,
    /// Run every key self-test the selected slot's algorithm supports
    /// (decrypt / key-agree / sign, in that order). The PIN field is always
    /// optional — it's the user's choice whether to test with or without a
    /// PIN; no management key, and nothing on the card changes.
    SelfTest,
}

impl PivCredKind {
    /// Modal title, matching the FIDO dialogs' title style.
    fn title(self) -> &'static str {
        match self {
            PivCredKind::ChangePin => "Change PIN",
            PivCredKind::ChangePuk => "Change PUK",
            PivCredKind::UnblockPin => "Unblock PIN",
            PivCredKind::GenerateKey => "Generate key",
            PivCredKind::ImportCert => "Import certificate",
            PivCredKind::SelfSign => "Self-signed certificate",
            PivCredKind::RequestCsr => "Sign certificate request",
            PivCredKind::SetRetries => "Set retry counts",
            PivCredKind::ChangeMgmtKey => "Change management key",
            PivCredKind::DeleteCert => "Delete certificate",
            PivCredKind::DeleteKey => "Delete key",
            PivCredKind::MoveKey => "Move key",
            PivCredKind::NewChuid => "New CHUID",
            PivCredKind::SelfTest => "Key self-test",
        }
    }
    /// Label for the modal's primary Submit button. Shorter than the title for
    /// the verbose flows so the button doesn't overflow.
    fn submit_label(self) -> &'static str {
        match self {
            PivCredKind::GenerateKey => "Generate",
            PivCredKind::ImportCert => "Import",
            PivCredKind::SelfSign => "Create",
            PivCredKind::RequestCsr => "Sign & save",
            PivCredKind::SetRetries => "Set retry counts",
            PivCredKind::ChangeMgmtKey => "Change key",
            PivCredKind::DeleteCert => "Delete",
            PivCredKind::DeleteKey => "Delete",
            PivCredKind::MoveKey => "Move",
            PivCredKind::NewChuid => "Write",
            PivCredKind::SelfTest => "Run",
            _ => self.title(),
        }
    }
    /// Spinner caption shown while this flow's op runs (matches the busy label
    /// the underlying `spawn_job` op uses).
    fn busy_label(self) -> &'static str {
        match self {
            PivCredKind::ChangePin => "Changing PIV PIN\u{2026}",
            PivCredKind::ChangePuk => "Changing PUK\u{2026}",
            PivCredKind::UnblockPin => "Unblocking PIN\u{2026}",
            PivCredKind::GenerateKey => "Generating key\u{2026}",
            PivCredKind::ImportCert => "Importing certificate\u{2026}",
            PivCredKind::SelfSign => "Creating certificate\u{2026}",
            PivCredKind::RequestCsr => "Signing request\u{2026}",
            PivCredKind::SetRetries => "Setting retry counts\u{2026}",
            PivCredKind::ChangeMgmtKey => "Changing management key\u{2026}",
            PivCredKind::DeleteCert => "Deleting certificate\u{2026}",
            PivCredKind::DeleteKey => "Deleting key\u{2026}",
            PivCredKind::MoveKey => "Moving key\u{2026}",
            PivCredKind::NewChuid => "Writing a new CHUID\u{2026}",
            PivCredKind::SelfTest => "Running self-test\u{2026}",
        }
    }
    /// True when this flow collects the *current* management key (and therefore
    /// shows the "Use default management key" convenience toggle).
    fn needs_mgmt_key(self) -> bool {
        matches!(
            self,
            PivCredKind::GenerateKey
                | PivCredKind::ImportCert
                | PivCredKind::SelfSign
                | PivCredKind::SetRetries
                | PivCredKind::ChangeMgmtKey
                | PivCredKind::DeleteCert
                | PivCredKind::DeleteKey
                | PivCredKind::MoveKey
                | PivCredKind::NewChuid
        )
    }
    /// True for a flow that already collects a PIN of its own further down in
    /// the modal — `SelfSign`'s signing PIN, `SetRetries`' current PIN — for a
    /// reason unrelated to management auth. PIV has exactly one application
    /// PIN, so when `use_pin` is set on one of these,
    /// `piv_modal_mgmt_field` doesn't render a second PIN box asking for the
    /// same value twice: the dedicated field's PIN is reused directly for
    /// management auth too, in [`App::piv_current_mgmt_auth`].
    fn shares_pin_field(self) -> bool {
        matches!(self, PivCredKind::SelfSign | PivCredKind::SetRetries)
    }
}

/// Live state of the PIV credential-entry modal. Open iff `PivState::cred_modal`
/// is `Some`. Tracks the flow, whether its op is in flight, and the op's result
/// so the outcome is shown *in the modal* (issue #31 — feedback must not scroll
/// off-screen). `result` is `None` until the op completes, then `Ok(())` on
/// success or `Err(message)` on failure.
struct PivCredModal {
    kind: PivCredKind,
    busy: bool,
    result: Option<Result<(), String>>,
    /// A multi-line report shown under the success line: the per-operation
    /// pass list from a `SelfTest` run that fully passed (a failing run puts
    /// its report in `result`'s `Err` instead), or how a certificate import /
    /// self-signed certificate was stored when it was stored compressed.
    detail: Option<String>,
}

impl PivCredModal {
    fn new(kind: PivCredKind) -> Self {
        PivCredModal {
            kind,
            busy: false,
            result: None,
            detail: None,
        }
    }
}

/// How the management-key modal's "Use default management key" / "Use PIN"
/// toggles are currently resolved — one canonical field instead of two
/// independent `bool`s, so the two checkboxes can't drift into an
/// inconsistent combination (each is a pure view onto, and setter of, this
/// single value: checking one sets it to that variant; unchecking either
/// always returns to [`Self::Manual`], never leaves the other variant
/// standing from a stale toggle). [`Self::Manual`] — neither box ticked —
/// means "read the typed hex from `PivState::mgmt_key_input`", the ordinary
/// case this whole type exists to make unambiguous.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
enum PivMgmtAuthMode {
    /// Neither toggle is ticked: `PivState::mgmt_key_input` holds a typed
    /// management-key hex string.
    #[default]
    Manual,
    /// "Use default management key": the well-known factory default.
    Default,
    /// "Use PIN": `keyroost_piv::compat::PivExtension::PinManagementAuth`
    /// instead of a management key — see [`App::piv_current_mgmt_auth`].
    Pin,
}

/// What `PivState::mgmt_auth_mode` should become after one of the modal's
/// two toggle checkboxes is clicked: `mode_if_checked` if the click checked
/// it, `PivMgmtAuthMode::Manual` if the click unchecked it — unconditionally,
/// regardless of which variant `mgmt_auth_mode` held before. Factored out of
/// `App::piv_modal_mgmt_field` so this rule is unit-testable without an egui
/// context; it's also the fix for a real reported bug where two independent
/// `bool`s (one per checkbox), each resetting the other on check but not
/// consulting it on uncheck, could leave `mgmt_auth_mode`-equivalent state
/// stuck on a stale toggle after check-then-switch-then-uncheck.
#[must_use]
fn piv_mgmt_mode_after_toggle(checked: bool, mode_if_checked: PivMgmtAuthMode) -> PivMgmtAuthMode {
    if checked {
        mode_if_checked
    } else {
        PivMgmtAuthMode::Manual
    }
}

/// State for the PIV pane: a status snapshot plus the entry fields for the full
/// management surface (PIN/PUK, management key, key generation, certificate
/// import/export, reset), keyed by the selected device's reader name.
struct PivState {
    /// Last status read from the selected card.
    status: Option<keyroost_transport::PivStatus>,
    /// Per-slot detail, in canonical slot order, from the single
    /// [`keyroost_transport::PivSession::status_detailed`] call each refresh
    /// makes: the key algorithm (GET METADATA where authoritative, else a key
    /// generated this app run, else the slot certificate's
    /// SubjectPublicKeyInfo; `None` means no key in the slot, on any PIV
    /// card), and the certificate's Subject DN (`None` if the slot has no
    /// certificate or its DN failed to parse — degraded silently). Split out
    /// of [`keyroost_transport::PivSlotDetail`] into the shape the pane draws.
    slot_keys: Vec<(
        keyroost_piv::Slot,
        Option<keyroost_piv::KeyAlg>,
        Option<String>,
    )>,
    /// Per-slot PIN/touch policy, from the same `status_detailed` call that
    /// fills `slot_keys` (GET METADATA's policy bytes on firmware 5.3+, else
    /// the ATTEST certificate's key-policy extension on older firmware).
    /// `None` per-slot means unavailable: no YubiKey-compatible extensions
    /// answered, not necessarily an empty slot.
    slot_policies: Vec<(
        keyroost_piv::Slot,
        Option<(keyroost_piv::PinPolicy, keyroost_piv::TouchPolicy)>,
    )>,
    /// User-facing error from the last read/write.
    error: Option<String>,
    /// Success/info line from the last write operation.
    notice: Option<String>,
    /// True once a status has been fetched for the current selection.
    loaded: bool,
    /// Management key (hex) entered to authorize key-gen / cert-import /
    /// set-retries / management-key change. Cleared after use. Doubles as
    /// the PIN input when [`Self::mgmt_auth_mode`] is
    /// [`PivMgmtAuthMode::Pin`] and the flow has no dedicated PIN field of
    /// its own (see [`PivCredKind::shares_pin_field`]) — the same field,
    /// its label and hint swapped, rather than a second box. Only actually
    /// read when [`Self::mgmt_auth_mode`] is [`PivMgmtAuthMode::Manual`] or
    /// [`PivMgmtAuthMode::Pin`] — see that type's doc.
    mgmt_key_input: String,
    /// The management-key modal's "Use default management key" / "Use PIN"
    /// toggle state — see [`PivMgmtAuthMode`]. Reset per modal.
    mgmt_auth_mode: PivMgmtAuthMode,
    /// Change-PIN old/new/confirm entries. Cleared after use.
    pin_old: String,
    pin_new: String,
    pin_confirm: String,
    /// Change-PUK old/new/confirm entries. Cleared after use.
    puk_old: String,
    puk_new: String,
    puk_confirm: String,
    /// Unblock-PIN: PUK + new PIN entries. Cleared after use.
    unblock_puk: String,
    unblock_new_pin: String,
    /// PIN/PUK retry counts for set-retries, and the PIN that authorizes it.
    retries_pin: u8,
    retries_puk: u8,
    retries_pin_auth: String,
    /// The slot every key/certificate action targets. Chosen once by clicking a
    /// row in the status card (issue #31): the "Keys & certificates" section is
    /// slot-first now, so Generate / Create cert / Import / Export / Delete all
    /// act on this single selection instead of each carrying its own dropdown.
    selected_slot: PivSlotSel,
    /// Key-generation algorithm selector.
    gen_alg: keyroost_piv::KeyAlg,
    /// PIN/touch policy selectors in the Generate key modal. `Default`/
    /// `Default` (the initial selection) sends the plain PIV GENERATE
    /// ASYMMETRIC KEY PAIR APDU, with no policy tags, which is what every PIV
    /// card accepts; selecting anything else appends the Yubico extended
    /// policy tags (0xAA/0xAB), which only a YubiKey or compatible token
    /// honors. Reset per modal open.
    gen_pin_policy: keyroost_piv::PinPolicy,
    gen_touch_policy: keyroost_piv::TouchPolicy,
    /// Compression choice in the Import certificate and Self-signed
    /// certificate dialogs (the CLI's `--compress` / `--no-compress`).
    /// Reset to Automatic per modal open.
    cert_compression: PivCertCompressionSel,
    /// Certificate import file path.
    cert_path: String,
    /// Certificate export destination path.
    export_path: String,
    /// New management key (hex) + algorithm for a management-key rotation.
    new_mgmt_key_input: String,
    new_mgmt_alg: PivMgmtAlgSel,
    /// "Allow PIN unlock" checkbox in the management-key rotation dialog —
    /// whether the new key should also be stored PIN-protected (Yubico's
    /// `PivExtension::PinManagementAuth`; see
    /// `keyroost_transport::PivSession::set_management_key_pin_protected`).
    /// Reset to `false` per dialog open, same as `new_mgmt_key_input`; the
    /// row rendering this forces it to (effectively) `true` and disables
    /// editing on HID Crescendo, which unlocks management off the PIN
    /// already, with nothing to toggle — see the "Management key" row's own
    /// comment.
    new_mgmt_allow_pin_unlock: bool,
    /// Certificate creation: subject (bare name or full DN), validity, the PIN
    /// that authorizes the on-card signature, and the CSR destination.
    cert_subject: String,
    /// Validity period, entered as three counts that sum — years applied
    /// first, then months relative to that point, then a flat day count —
    /// fed to [`keyroost_piv::add_calendar_period`]. Mirrors `keyroostctl
    /// piv cert generate`'s combinable `--years`/`--months`/`--days` exactly.
    cert_valid_years: u32,
    cert_valid_months: u32,
    cert_valid_days: u32,
    /// Requested X.509 `keyUsage` for the certificate / CSR per device:slot
    /// (no usages means "Undefined": no extension written, and never
    /// critical), with the key algorithm it was last reconciled against (see
    /// [`reconcile_key_usage`]).
    cert_key_usage: std::collections::HashMap<
        (Option<DeviceId>, PivSlotSel),
        (
            keyroost_piv::x509::KeyUsageExt,
            Option<keyroost_piv::KeyAlg>,
        ),
    >,
    /// Device:slots whose Undefined was picked explicitly while the slot default
    /// is itself undefined (degraded for the key type), so the two entries can
    /// be told apart. Only consulted in that degraded case.
    cert_key_usage_explicit_undefined: std::collections::HashSet<(Option<DeviceId>, PivSlotSel)>,
    sign_pin: String,
    csr_path: String,
    /// New CHUID: validity, same three-field shape and default as
    /// `cert_valid_years`/`cert_valid_months`/`cert_valid_days`, fed to
    /// [`keyroost_piv::add_calendar_period`] +
    /// [`keyroost_piv::yyyymmdd_from_unix_secs`].
    chuid_valid_years: u32,
    chuid_valid_months: u32,
    chuid_valid_days: u32,
    /// New CHUID: the GUID input, hex (canonical `8-4-4-4-12` dashed form as
    /// pre-filled, but [`keyroost_piv::parse_guid_hex`] accepts plain hex
    /// too). Pre-filled with a fresh [`keyroost_transport::random_chuid_guid`]
    /// each time the dialog opens, refreshable there, and editable so the
    /// user can substitute their own.
    chuid_guid: String,
    /// Reset confirmation modal: typed-`reset` text (modal open iff `Some`).
    confirm_reset: Option<String>,
    /// True from the moment any PIV device job — status read, PIN/PUK/
    /// management-key change, key generate/import/delete/move, self-test,
    /// self-sign/CSR, CHUID write, reset, ... — queues via `spawn_piv_job`
    /// until that job's apply closure runs. The pane reads this once,
    /// wrapping everything except the slot tab strip (and the retired-slot
    /// rail) in a single `add_enabled_ui` (see `cap_piv`) — disabling every
    /// button/field in the applet-wide and per-slot cards for the duration
    /// without hooking into each one individually, while scrolling and slot
    /// selection stay live. Not `self.busy()`: that flips true for *any*
    /// queued job app-wide (an unrelated OATH or FIDO action among them),
    /// which would dim the PIV pane over device work that has nothing to do
    /// with the PIV applet.
    inflight: bool,
    /// Credential-entry modal for PIN/PUK changes + unblock (open iff `Some`).
    /// The PIN/PUK secret fields above render *inside* this modal, not inline in
    /// the pane, so the entry and its result stay on-screen (issue #31).
    cred_modal: Option<PivCredModal>,
    /// Chosen destination slot for the Move-key flow (empty until the user picks
    /// one in the modal's destination combo). Reset when the modal closes.
    move_dest: Option<keyroost_piv::Slot>,
    /// Lazily-read occupancy of the 20 retired slots (`slot -> has_key`), cached
    /// so expanding the section only probes the card once. `None` until read;
    /// invalidated after a move so the section re-reads on its next expand.
    retired_occupancy: Option<Vec<(keyroost_piv::Slot, keyroost_transport::SlotKeyPresence)>>,
}

// The pane is replaced wholesale on device switch (`self.piv =
// PivState::default()`); wiping on drop means the discarded fields don't
// leave PINs/keys in freed memory.
impl Drop for PivState {
    fn drop(&mut self) {
        wipe(&mut self.mgmt_key_input);
        self.mgmt_auth_mode = PivMgmtAuthMode::default();
        wipe(&mut self.pin_old);
        wipe(&mut self.pin_new);
        wipe(&mut self.pin_confirm);
        wipe(&mut self.puk_old);
        wipe(&mut self.puk_new);
        wipe(&mut self.puk_confirm);
        wipe(&mut self.unblock_puk);
        wipe(&mut self.unblock_new_pin);
        wipe(&mut self.retries_pin_auth);
        wipe(&mut self.new_mgmt_key_input);
        wipe(&mut self.sign_pin);
    }
}

impl Default for PivState {
    fn default() -> Self {
        PivState {
            status: None,
            slot_keys: Vec::new(),
            slot_policies: Vec::new(),
            error: None,
            notice: None,
            loaded: false,
            mgmt_key_input: String::new(),
            mgmt_auth_mode: PivMgmtAuthMode::default(),
            pin_old: String::new(),
            pin_new: String::new(),
            pin_confirm: String::new(),
            puk_old: String::new(),
            puk_new: String::new(),
            puk_confirm: String::new(),
            unblock_puk: String::new(),
            unblock_new_pin: String::new(),
            retries_pin: 3,
            retries_puk: 3,
            retries_pin_auth: String::new(),
            selected_slot: PivSlotSel::default(),
            gen_alg: keyroost_piv::KeyAlg::EccP256,
            gen_pin_policy: keyroost_piv::PinPolicy::Default,
            gen_touch_policy: keyroost_piv::TouchPolicy::Default,
            cert_compression: PivCertCompressionSel::Auto,
            cert_path: String::new(),
            export_path: String::new(),
            new_mgmt_key_input: String::new(),
            new_mgmt_alg: PivMgmtAlgSel::default(),
            new_mgmt_allow_pin_unlock: false,
            cert_subject: String::new(),
            cert_valid_years: 1,
            cert_valid_months: 0,
            cert_valid_days: 0,
            cert_key_usage: std::collections::HashMap::new(),
            cert_key_usage_explicit_undefined: std::collections::HashSet::new(),
            sign_pin: String::new(),
            csr_path: String::new(),
            chuid_valid_years: 1,
            chuid_valid_months: 0,
            chuid_valid_days: 0,
            chuid_guid: keyroost_transport::random_chuid_guid()
                .map(|g| keyroost_piv::format_guid(&g))
                .unwrap_or_default(),
            confirm_reset: None,
            inflight: false,
            cred_modal: None,
            move_dest: None,
            retired_occupancy: None,
        }
    }
}

/// PIV key-slot selector for the GUI controls.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
enum PivSlotSel {
    #[default]
    Auth,
    Sign,
    KeyMgmt,
    CardAuth,
    /// A Yubico retired key-management slot (n = 1..=20), selectable from the
    /// collapsible "Retired slots" section.
    Retired(u8),
}

impl PivSlotSel {
    fn to_slot(self) -> keyroost_piv::Slot {
        match self {
            PivSlotSel::Auth => keyroost_piv::Slot::Authentication,
            PivSlotSel::Sign => keyroost_piv::Slot::Signature,
            PivSlotSel::KeyMgmt => keyroost_piv::Slot::KeyManagement,
            PivSlotSel::CardAuth => keyroost_piv::Slot::CardAuthentication,
            PivSlotSel::Retired(n) => {
                keyroost_piv::Slot::retired(n).expect("PivSlotSel::Retired always holds 1..=20")
            }
        }
    }
    fn label(self) -> String {
        self.to_slot().label()
    }
}

/// The Compression dropdown in the Import certificate and Self-signed
/// certificate dialogs. Mirrors the CLI: Automatic = neither flag, Always =
/// `--compress`, Never = `--no-compress`.
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
enum PivCertCompressionSel {
    #[default]
    Auto,
    Always,
    Never,
}

impl PivCertCompressionSel {
    const ALL: [PivCertCompressionSel; 3] = [
        PivCertCompressionSel::Auto,
        PivCertCompressionSel::Always,
        PivCertCompressionSel::Never,
    ];
    fn label(self) -> &'static str {
        match self {
            PivCertCompressionSel::Auto => "Automatic (only if too large)",
            PivCertCompressionSel::Always => "Always",
            PivCertCompressionSel::Never => "Never",
        }
    }
    fn to_compression(self) -> keyroost_transport::CertCompression {
        use keyroost_transport::CertCompression;
        match self {
            PivCertCompressionSel::Auto => CertCompression::Auto,
            PivCertCompressionSel::Always => CertCompression::Always,
            PivCertCompressionSel::Never => CertCompression::Never,
        }
    }
}

/// Shown when Automatic compression had to store a certificate compressed;
/// the same note the CLI prints.
const PIV_AUTO_COMPRESSED_NOTE: &str = "The certificate did not fit on the card \
    uncompressed, so it was stored compressed (the PIV standard's gzip form). Most PIV \
    software reads compressed certificates, including Windows' built-in smart-card \
    driver in a community test; macOS's built-in PIV support has not been verified.";

/// The pane notice after a certificate was stored: `base`, the stored size
/// when compressed, and the Automatic note when that is why it was.
fn piv_cert_stored_notice(
    base: &str,
    compressed: bool,
    stored_len: usize,
    auto_compressed: bool,
) -> String {
    let mut s = base.to_owned();
    if compressed {
        s.push_str(&format!(
            " (stored compressed: {stored_len} bytes on the card)"
        ));
    }
    s.push('.');
    if auto_compressed {
        s.push(' ');
        s.push_str(PIV_AUTO_COMPRESSED_NOTE);
    }
    s
}

/// The dialog's success detail for a certificate stored compressed (one
/// line per paragraph); `None` when it was stored uncompressed.
fn piv_cert_stored_detail(
    compressed: bool,
    stored_len: usize,
    auto_compressed: bool,
) -> Option<String> {
    compressed.then(|| {
        let mut s = format!("Stored compressed: {stored_len} bytes on the card.");
        if auto_compressed {
            s.push('\n');
            s.push_str(PIV_AUTO_COMPRESSED_NOTE);
        }
        s
    })
}

/// With Compression set to Never, what to add to a "too large" refusal so
/// the user knows the dropdown can make it fit. `None` otherwise.
fn piv_cert_error_hint(e: &TransportError, choice: PivCertCompressionSel) -> Option<&'static str> {
    match e {
        TransportError::PivCertTooLarge {
            compressed_len: None,
            ..
        } if choice == PivCertCompressionSel::Never => {
            Some(" (set Compression to Automatic or Always)")
        }
        _ => None,
    }
}

/// The selected slot's state words: whether it holds a certificate (and
/// whether that is stored compressed or unreadable) or just a key, with the
/// key algorithm parenthesized after the state word it describes. A slot with
/// neither reads "empty" only when the card said it holds no key (`key`, the
/// transport's `SlotKeyPresence`); when keyroost can't tell, it says so. The
/// words match `keyroostctl piv info`'s.
fn piv_slot_state_text(
    cert_unreadable: Option<keyroost_transport::CertUnreadable>,
    cert_present: bool,
    cert_compressed: bool,
    alg: Option<keyroost_piv::KeyAlg>,
    key: keyroost_transport::SlotKeyPresence,
) -> String {
    // "key present" and "certificate present" both get the algorithm
    // parenthesized right after the state word they describe — for the
    // no-certificate case that's "key present (…), no certificate", not
    // "…, no certificate (…)": the algorithm belongs to the key, and
    // there's no certificate for it to trail.
    match (cert_unreadable, cert_present, alg) {
        // A certificate is there but won't decode: say so, rather than
        // "empty", which would invite overwriting it unawares.
        (Some(reason), _, _) => format!("certificate present but unreadable ({reason})"),
        (None, true, alg) => {
            let parts: Vec<&str> = alg
                .map(keyroost_piv::KeyAlg::label)
                .into_iter()
                .chain(cert_compressed.then_some("compressed"))
                .collect();
            if parts.is_empty() {
                "certificate present".to_string()
            } else {
                format!("certificate present ({})", parts.join(", "))
            }
        }
        (None, false, Some(a)) => format!("key present ({}), no certificate", a.label()),
        (None, false, None) => match key {
            keyroost_transport::SlotKeyPresence::Present => {
                "key present, no certificate".to_string()
            }
            keyroost_transport::SlotKeyPresence::NoKey => "empty".to_string(),
            _ => "no certificate (a key may be present)".to_string(),
        },
    }
}

/// A retired slot's state words, from the lazily-read `retired_occupancy`
/// cache (`None`: not read yet). Same rule as [`piv_slot_state_text`].
fn piv_retired_slot_state_text(key: Option<keyroost_transport::SlotKeyPresence>) -> String {
    match key {
        Some(keyroost_transport::SlotKeyPresence::Present) => "key present".to_string(),
        Some(keyroost_transport::SlotKeyPresence::NoKey) | None => "empty".to_string(),
        Some(_) => "no certificate (a key may be present)".to_string(),
    }
}

/// The retired-slot rail's hover text for one row.
fn piv_retired_slot_hover(label: &str, key: keyroost_transport::SlotKeyPresence) -> String {
    match key {
        keyroost_transport::SlotKeyPresence::Present => format!("{label} \u{00B7} holds a key"),
        keyroost_transport::SlotKeyPresence::NoKey => format!("{label} \u{00B7} empty"),
        _ => format!("{label} \u{00B7} no certificate (a key may be present)"),
    }
}

/// A PIV certificate-compression picker combo.
fn piv_cert_compression_combo(ui: &mut egui::Ui, id: &str, sel: &mut PivCertCompressionSel) {
    egui::ComboBox::from_id_salt(id)
        .selected_text(sel.label())
        .show_ui(ui, |ui| {
            for opt in PivCertCompressionSel::ALL {
                ui.selectable_value(sel, opt, opt.label());
            }
        });
}

// PIV key-generation algorithm selection uses `keyroost_piv::KeyAlg` directly
// (see `gen_alg` below) rather than a GUI-only wrapper enum — same pattern
// `gen_pin_policy`/`gen_touch_policy` already use for their domain types.
// `KeyAlg::ALL` lists every candidate for the combo
// (`piv_keyalg_combo`); which ones are actually selectable on the live device
// is a per-algorithm `keyroost_piv::compat::PivExtension::SlotKeyAlgorithm`
// gate, resolved where the combo is drawn, not baked into the selector type.

/// PIV management-key algorithm selector (for rotation). [`Self::Delete`] is
/// not an algorithm at all — HID Crescendo's ACA-only "management key" (see
/// [`keyroost_transport::CurrentMgmtAuth`]'s doc) can be deleted outright
/// instead of replaced, unlike a standard PIV management key, which is
/// mandatory — but it's still always offered, last, in [`Self::ALL`], on
/// every device, not only HID Crescendo: which options are actually
/// *selectable* on the live device is a per-choice
/// `keyroost_piv::compat::PivExtension::ManagementKeyAlgorithm` gate,
/// resolved where the combo is drawn (see `cap_piv`) and rendered as a
/// disabled entry rather than an omitted one — same split between "offered
/// set" and "live gate" that `KeyAlg`/`piv_keyalg_combo` already use for the
/// slot key-algorithm picker.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
enum PivMgmtAlgSel {
    #[default]
    Aes192,
    Aes128,
    Aes256,
    TripleDes,
    Delete,
}

impl PivMgmtAlgSel {
    /// `None` for [`Self::Delete`] — see this type's doc.
    fn to_alg(self) -> Option<keyroost_piv::MgmtAlg> {
        use keyroost_piv::MgmtAlg::*;
        match self {
            PivMgmtAlgSel::Aes192 => Some(Aes192),
            PivMgmtAlgSel::Aes128 => Some(Aes128),
            PivMgmtAlgSel::Aes256 => Some(Aes256),
            PivMgmtAlgSel::TripleDes => Some(TripleDes),
            PivMgmtAlgSel::Delete => None,
        }
    }
    /// This choice as a `keyroost_piv::compat::MgmtAlgChoice` — the argument
    /// [`keyroost_piv::compat::PivExtension::ManagementKeyAlgorithm`] gates on.
    /// A 1:1 mapping (unlike [`Self::to_alg`], `MgmtAlgChoice` has its own
    /// [`Self::Delete`]-equivalent variant, so this never returns `Option`).
    fn to_choice(self) -> keyroost_piv::compat::MgmtAlgChoice {
        use keyroost_piv::compat::MgmtAlgChoice;
        match self {
            PivMgmtAlgSel::Aes192 => MgmtAlgChoice::Aes192,
            PivMgmtAlgSel::Aes128 => MgmtAlgChoice::Aes128,
            PivMgmtAlgSel::Aes256 => MgmtAlgChoice::Aes256,
            PivMgmtAlgSel::TripleDes => MgmtAlgChoice::TripleDes,
            PivMgmtAlgSel::Delete => MgmtAlgChoice::Delete,
        }
    }
    fn label(self) -> &'static str {
        match self {
            PivMgmtAlgSel::Delete => "Delete",
            other => other
                .to_alg()
                .expect("every non-Delete variant has an algorithm")
                .label(),
        }
    }
    /// Every candidate for the management-key algorithm combo, in menu order
    /// — alphabetical by [`Self::label`] (`"3DES"`, `"AES-128"`, `"AES-192"`,
    /// `"AES-256"`), with [`Self::Delete`] last: it isn't a real algorithm
    /// name to sort alongside the rest (see this type's own doc), and
    /// `"Delete"` happens to sort after all four anyway. Offered identically
    /// on every device, standard PIV or HID Crescendo alike: which entries
    /// actually resolve selectable there is a live
    /// `keyroost_piv::compat::PivExtension::ManagementKeyAlgorithm` gate per
    /// candidate (see this type's own doc), not a difference in which
    /// candidates are listed. A standard device's mandatory management key
    /// has no delete mechanism keyroost implements, so `Delete` renders
    /// disabled there; HID Crescendo's ACA XAUTH key can be removed outright
    /// ([`keyroost_piv::fingerprint::hid_crescendo_aca_put_xauth_key_remove`]),
    /// so it's selectable there — same "list every candidate, gate each one
    /// live" shape `keyroost_piv::KeyAlg::ALL`/[`piv_keyalg_combo`] already
    /// use for the slot key-algorithm picker.
    ///
    /// Note `Self::ALL[0]` (`TripleDes`) is *not* [`Self::default`] (`Aes192`)
    /// — unlike before this was alphabetized, the two are no longer the same
    /// entry; see [`piv_mgmtalg_unsupported_fallback`]'s doc for where that
    /// used to matter.
    const ALL: [PivMgmtAlgSel; 5] = [
        PivMgmtAlgSel::TripleDes,
        PivMgmtAlgSel::Aes128,
        PivMgmtAlgSel::Aes192,
        PivMgmtAlgSel::Aes256,
        PivMgmtAlgSel::Delete,
    ];
}

/// A unit of work applied back to the [`App`] on the UI thread once a background
/// job finishes. Returned by the job closure and run inside `update()`.
type ApplyFn = Box<dyn FnOnce(&mut App) + Send>;
/// A background job: blocking device I/O that yields an [`ApplyFn`].
type Job = Box<dyn FnOnce() -> ApplyFn + Send>;

/// A single background worker thread. Device calls (CTAP / OATH over PC/SC) can
/// block for seconds — a touch-required credential or a 30s Reset window — so we
/// run them off the egui frame thread and apply their results back on the UI
/// thread. One thread keeps device access serialized (no concurrent card I/O).
struct Worker {
    job_tx: std::sync::mpsc::Sender<Job>,
    result_rx: std::sync::mpsc::Receiver<ApplyFn>,
}

impl Worker {
    /// `apdu_trace`: shared with the "APDU trace" checkbox in the activity
    /// log pane (see `App::activity_log`), read fresh at the start of every
    /// job rather than fixed at spawn time, so toggling it takes effect on
    /// the very next device operation. When on for a given job, that job's
    /// APDU trace is captured (see `keyroost_transport::trace`) and handed to
    /// its apply closure via `App::pending_trace`, for the next `log`/`log_bg`
    /// call inside it to attach. One capture per job — this thread runs jobs
    /// one at a time, start to finish, so "everything recorded between begin
    /// and take" is exactly "everything this job's device I/O did".
    fn spawn(
        ctx: egui::Context,
        apdu_trace: std::sync::Arc<std::sync::atomic::AtomicBool>,
    ) -> Self {
        let (job_tx, job_rx) = std::sync::mpsc::channel::<Job>();
        let (result_tx, result_rx) = std::sync::mpsc::channel::<ApplyFn>();
        std::thread::Builder::new()
            .name("keyroost-worker".into())
            .spawn(move || {
                while let Ok(job) = job_rx.recv() {
                    let debug = apdu_trace.load(std::sync::atomic::Ordering::Relaxed);
                    if debug {
                        keyroost_transport::trace::begin();
                    }
                    // A panicking job must not kill the worker: that would
                    // disconnect the result channel and wedge the busy guard
                    // (spawn_job would reject every future job forever). Catch
                    // it and deliver an error apply instead, so the frame loop
                    // still clears the busy bookkeeping and the thread lives on.
                    let apply = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)) {
                        Ok(apply) => apply,
                        Err(_) => Box::new(|app: &mut App| {
                            app.log(
                                Severity::Err,
                                "a background device operation panicked and was aborted; \
                                 re-plug the key if it stops responding",
                            );
                        }) as ApplyFn,
                    };
                    let apply = match debug.then(keyroost_transport::trace::take).flatten() {
                        Some(trace) if !trace.is_empty() => Box::new(move |app: &mut App| {
                            app.pending_trace = Some(trace);
                            apply(app);
                            app.pending_trace = None; // in case `apply` never logged
                        }) as ApplyFn,
                        _ => apply,
                    };
                    if result_tx.send(apply).is_err() {
                        break; // UI gone
                    }
                    ctx.request_repaint(); // wake the frame loop to apply it
                }
            })
            .expect("spawn worker thread");
        Worker { job_tx, result_rx }
    }
}

fn main() -> eframe::Result<()> {
    // KEYROOST_X11=1 forces the GUI onto X11/XWayland instead of native Wayland.
    // On some compositors — observed on KDE Plasma 6.7 / KWin (issue #48) — the
    // native Wayland window loses focus shortly after startup and then stops
    // receiving keyboard/text/IME events, while the same binary works under
    // XWayland. winit selects the Wayland backend whenever WAYLAND_DISPLAY is
    // set, so clearing it for our own process makes winit fall back to X11
    // (XWayland provides DISPLAY) — the same effect as launching with
    // `env -u WAYLAND_DISPLAY keyroost`, without pulling in a direct winit
    // dependency. No-op when Wayland wasn't in use. Done before any thread is
    // spawned (the worker starts inside run_native), so the env edit is safe.
    if std::env::var_os("KEYROOST_X11").is_some() {
        std::env::remove_var("WAYLAND_DISPLAY");
    }

    // Backs the "APDU trace" checkbox in the activity log pane (see
    // `App::activity_log`): shared with the worker thread so a toggle takes
    // effect on the very next device operation, off by default. Not a CLI
    // flag — this is a runtime setting the user flips from the pane, not
    // something decided once at launch.
    let apdu_trace = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));

    let options = eframe::NativeOptions {
        viewport: egui::ViewportBuilder::default()
            .with_inner_size([1180.0, 760.0])
            .with_min_inner_size([900.0, 560.0])
            .with_title("keyroost"),
        ..Default::default()
    };
    eframe::run_native(
        "keyroost",
        options,
        Box::new(|cc| {
            // Register IBM Plex Sans + JetBrains Mono so the redesign's type
            // weights resolve. (Vendored under assets/.)
            theme::install_fonts(&cc.egui_ctx);
            // Restore the persisted UI preferences (theme mode + accent +
            // colorblind + zoom) from our own settings.json, defaulting to the
            // refined dark + blue accent the prototype ships with. eframe's own
            // storage is off in this crate (no `persistence` feature), so
            // `App::save()` never fires — `settings::Settings` carries the
            // persistence instead. A missing/corrupt file yields defaults.
            let saved = Settings::load();
            let mode: Mode = saved.mode.into();
            // Clamp the accent index against the live accent count in case the
            // file predates an accent being removed.
            let accent_idx = saved.accent.min(Palette::ACCENTS.len() - 1);
            let colorblind = saved.colorblind;
            // `Settings::load` already clamps zoom; clamp again defensively.
            let zoom = theme::clamp_zoom(saved.zoom);
            Palette::new(mode, Palette::ACCENTS[accent_idx], colorblind).apply(&cc.egui_ctx, mode);
            // Watch for reader hotplug so already-plugged-in or newly-inserted
            // devices appear without a manual Refresh. The watcher only flags a
            // shared bit and wakes the frame loop; `update()` does the rescan.
            let devices_dirty = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
            let reader_watch = {
                let dirty = devices_dirty.clone();
                let egui_ctx = cc.egui_ctx.clone();
                keyroost_transport::ReaderWatcher::spawn(move || {
                    dirty.store(true, std::sync::atomic::Ordering::Relaxed);
                    egui_ctx.request_repaint();
                })
            };
            let app = App {
                mode,
                accent_idx,
                colorblind,
                zoom,
                // Seed the persistence baseline with exactly what we loaded so
                // the first `persist_settings()` doesn't re-write an unchanged
                // file. The sanitized values (clamped zoom / accent) are what we
                // actually hold, so record those.
                last_saved_settings: Some(Settings {
                    zoom,
                    mode: mode.into(),
                    accent: accent_idx,
                    colorblind,
                }),
                worker: Some(Worker::spawn(cc.egui_ctx.clone(), apdu_trace.clone())),
                egui_ctx: Some(cc.egui_ctx.clone()),
                devices_dirty,
                reader_watch: Some(reader_watch),
                mds: ui::mds::MdsDb::load_bundled(),
                apdu_trace,
                ..Default::default()
            };
            Ok(Box::new(app))
        }),
    )
}

#[derive(Default)]
struct App {
    /// Active PC/SC session, if any.
    session: Option<Session>,
    /// The device id `session` was opened for. A mutating op may only take
    /// the session while this still matches `selected_device` (KEY-004): the
    /// apply closures of Molto ops hand the session back unconditionally, so
    /// the binding — not the `Option` — is what keeps a session opened for
    /// key A from serving actions the user aims at key B.
    molto_session_device: Option<DeviceId>,
    /// Last device info read.
    info: Option<DeviceInfo>,
    /// Whether the session has been authenticated.
    authenticated: bool,
    /// Active single-profile programmable-token session, if any.
    prog_session: Option<keyroost_transport::Token2ProgSession>,
    /// Last programmable-token info read (serial + on-device UTC time).
    prog_info: Option<keyroost_token2prog::Info>,
    /// Whether the programmable-token session has been authenticated.
    prog_authenticated: bool,
    /// Form state for programming the prog token (seed + config inputs).
    /// `Zeroizing` so the typed seed is scrubbed on drop, matching the OTP
    /// dialogs' Drop-wipe (and it is also wiped on a successful burn).
    prog_seed_input: zeroize::Zeroizing<String>,
    prog_seed_hex: bool,
    prog_algo_sha256: bool,
    prog_step_60: bool,
    prog_timeout_idx: usize,
    /// Last burn result for the prog pane: (success, message). Shown inline.
    prog_status: Option<(bool, String)>,
    /// Per-field "show secret" toggles for password inputs, keyed by a stable
    /// id. Absent = masked (the default).
    secret_reveal: std::collections::HashMap<&'static str, bool>,
    /// Customer key text the user typed.
    customer_key_input: String,
    /// Treat customer_key_input as hex vs ASCII.
    customer_key_hex: bool,
    /// Currently selected Molto2 profile slot (0..PROFILES-1).
    slot: u8,
    /// Per-slot public blocks (title / occupancy / config) from the sweep
    /// that runs when the device is opened. `None` until the sweep has
    /// succeeded — the slot list then degrades to bare slot numbers.
    /// Indexed by slot; always 100 entries when `Some`.
    slot_meta: Option<Vec<ProfilePublicData>>,
    /// Draft of the form fields for `selected` (per-slot; cleared on slot switch).
    draft: Draft,
    /// Rolling log of operations (newest last).
    log: Vec<LogLine>,
    /// Backs the "APDU trace" checkbox in the activity log pane. Shared with
    /// the worker thread (see `Worker::spawn`), which reads it fresh at the
    /// start of every job — toggling the checkbox takes effect on the very
    /// next device operation, not just future app runs.
    apdu_trace: std::sync::Arc<std::sync::atomic::AtomicBool>,
    /// The APDU trace captured for the job whose result is being applied
    /// right now, if the checkbox was on and that job recorded anything.
    /// Consumed (and cleared) by the first `log`/`log_bg` call in the apply closure;
    /// `Worker::spawn` also clears it after the apply closure returns, so it
    /// never bleeds into an unrelated, later log line.
    pending_trace: Option<Vec<String>>,
    /// otpauth:// import dialog state.
    import_dialog: ImportDialog,
    /// Files waiting to be read, and the import dialog or notice showing.
    import_flow: import_flow::ImportFlow,
    /// Unified device list (physical keys + Molto2 tokens), most recent scan.
    devices: Vec<Device>,
    /// Selected device id — stable across refreshes so the pane doesn't jump
    /// when an *unrelated* key is plugged or unplugged.
    selected_device: Option<DeviceId>,
    /// Which capability pane is showing for the selected key.
    cap_tab: CapTab,
    /// Each device's own last-shown `cap_tab`, so switching to another
    /// device's tab and back doesn't reset the pane to Overview — only the
    /// *currently* selected device's pick lives in `cap_tab` at any moment;
    /// `on_device_selected` is what moves the outgoing device's pick in here
    /// and restores the incoming device's. A pick that's stale for its
    /// device (the device no longer offers that tab) is corrected at render
    /// time by `snap_cap_tab`, the same way `security_keys.subview` already
    /// self-heals for FIDO's own sub-tabs — so entries here are never
    /// pruned on device disappearance the way `piv_session_state` is: an
    /// invalid entry is harmless, `snap_cap_tab` just falls through it.
    cap_tab_by_device: std::collections::HashMap<DeviceId, CapTab>,
    /// Error from the last device enumeration, surfaced in the sidebar.
    devices_error: Option<String>,
    /// When set: the OTP code we placed on the clipboard and the time
    /// (now_secs_f64 epoch) to clear it — codes shouldn't sit in
    /// clipboard-manager history forever. Cleared conditionally: only if the
    /// clipboard still holds that exact code.
    clipboard_clear_at: Option<(String, f64)>,
    /// True once the first automatic device scan has been kicked off.
    scanned: bool,
    /// Sidebar filter text (filters the visible device list by vendor/model).
    filter: String,
    /// FIDO security-key view state (CTAP info, PIN session, errors).
    security_keys: SecurityKeysState,
    /// FIDO Metadata Service database (bundled, plus any refreshed download).
    mds: ui::mds::MdsDb,
    /// Cached icon texture for the selected device's AAGUID, with the AAGUID it
    /// was decoded for so we re-upload only when the device changes.
    mds_icon: Option<(String, egui::TextureHandle)>,
    /// Last TOTP window index seen while the On-device OTP tab was showing live
    /// codes. When the window rolls over, the codes have expired, so the pane
    /// auto-reloads. `None` until first observed.
    otp_last_window: Option<u64>,
    /// OATH (TOTP) view state.
    oath: OathState,
    /// OpenPGP view state.
    openpgp: OpenPgpState,
    /// PIV read-only status view state.
    piv: PivState,
    /// Per-device cache of [`keyroost_transport::PivSessionState`] — the
    /// applet identity, applet-specific byte cache, and in-session public-
    /// key cache a `PivSession` would otherwise have to re-resolve from
    /// scratch every single action (sessions are opened fresh per action,
    /// never kept alive across them). Every PIV action reads its device's
    /// entry (or an empty default, the first time) before spawning its job,
    /// hands it to `PivSession::with_cached_transaction`, and — once the job's session is
    /// done with whatever it went on to do — stores `PivSession::state()`
    /// back here, so the *next* action on the same device gets to skip
    /// re-probing identity, and the public-key cache (bridging "generate" to
    /// a later "sign a CSR with it" on cards without GET METADATA) survives
    /// switching to another device's tab and back, which it did not before
    /// this map existed. `with_cached_transaction`'s own validation (PC/SC presence
    /// bookkeeping, ATR, raw SELECT response) is what makes trusting a
    /// carried-over entry safe even though the physical card in a reader can
    /// change between two actions — see that method's doc. Keyed by
    /// [`DeviceId`], not reader name: pruned in lockstep with `devices`
    /// wherever a device disappears, so an unplugged key's cached identity
    /// doesn't linger indefinitely.
    piv_session_state: std::collections::HashMap<DeviceId, keyroost_transport::PivSessionState>,
    /// Keys the user chose to "ignore the compatibility table" for, this app
    /// run only (never persisted): features the table lists as unsupported
    /// become unverified — usable, with a warning — except RESET. Applied to
    /// every PIV session for the key via `piv_cached_piv_session_state`, and
    /// to the pane's own gates via `piv_gate`. The GUI's counterpart of the
    /// CLI's per-command `--force`.
    piv_compat_ignored: std::collections::HashSet<DeviceId>,
    /// Token2 on-device OTP (TOTP/HOTP) view state.
    otp: OtpState,
    /// Dark / light theme (persisted via eframe storage).
    mode: Mode,
    /// Accent index into `Palette::ACCENTS` (persisted).
    accent_idx: usize,
    /// Colorblind-safe palette (blue/vermillion status colors) — persisted.
    colorblind: bool,
    /// Whether the activity-log drawer is open.
    log_open: bool,
    /// Whether the activity log is popped out into its own OS window (viewport)
    /// instead of the docked bottom drawer. Set by the header's detach icon,
    /// cleared by "Reattach"; the window's own close button clears this *and*
    /// `log_open` (collapsing the log). Only meaningful while `log_open` is true.
    log_detached: bool,
    /// Open help topic id, or `None` when the popover is closed.
    help_open: Option<&'static str>,
    /// Anchor point (the clicked "?" button's left-bottom) for the popover.
    help_anchor: egui::Pos2,
    /// OATH "copied" flash: (credential name, expiry unix-secs). Cleared after.
    copied: Option<(String, f64)>,
    /// Whether the OATH pane has auto-attempted a read for the current selection
    /// (so a hard error doesn't retry every frame). Reset on selection change.
    oath_tried: bool,
    /// Same guard for the PIV pane's auto-read.
    piv_tried: bool,
    /// Same guard for the OTP pane's auto-read.
    otp_tried: bool,
    /// True while the Molto2 factory-reset confirmation is showing.
    molto_reset_confirm: bool,
    /// True while the per-slot seed-delete confirmation card is showing.
    molto_delete_confirm: bool,
    /// Friendly-name draft for the selected device.
    rename_input: String,
    /// The device the open rename field targets, pinned when the field opens:
    /// its serial and its name-at-open. The save writes against *this* serial,
    /// not whatever `selected_device` happens to be at save time — a background
    /// rescan (e.g. the Molto2's flapping CCID reader) can silently move the
    /// selection between open and save, and without this pin the new name would
    /// land on the wrong key.
    rename_target: Option<RenameTarget>,
    /// The FIDO PIN typed into the naming dialog for an on-key save (masked;
    /// wiped when the dialog closes and after every attempt).
    rename_pin: String,
    /// Rows whose "write the name back" offer was dismissed this session.
    write_back_dismissed: std::collections::HashSet<DeviceId>,
    /// Background worker for blocking device I/O. `None` only in tests.
    worker: Option<Worker>,
    /// Number of in-flight background jobs. While >0 the UI shows a spinner and
    /// disables actions that would issue overlapping device I/O.
    busy_jobs: u32,
    /// Human-readable description of what the worker is currently doing.
    busy_label: Option<String>,
    /// Set by the reader watcher on a PC/SC hotplug; consumed in `update()` to
    /// trigger a re-enumeration. Shared with the watcher thread.
    devices_dirty: std::sync::Arc<std::sync::atomic::AtomicBool>,
    /// While `Some`, a FIDO reset is armed and waiting for the key to be
    /// unplugged and plugged back in (see [`ResetArm`]).
    reset_arm: Option<ResetArm>,
    /// Pending whole-device factory-reset confirmation, bound to the device it
    /// was opened for (KEY-008 posture). None unless the modal is open.
    factory_reset_confirm: Option<FactoryResetConfirmState>,
    /// Validation error from the last "Yes, wipe this key" click on the
    /// factory-reset confirm dialog (e.g. bad hex in the reset management-auth
    /// credential field) — shown inline in that dialog, cleared on a fresh
    /// arm, a successful submit, or Cancel. Kept separate from `piv.error`:
    /// this error belongs to the confirm dialog, not the PIV pane, and must
    /// not leak into (or be clobbered by) that pane's own error state.
    factory_reset_confirm_error: Option<String>,
    /// Typed-`reset` text for the factory-reset confirm dialog's guard —
    /// mirrors `PivState::confirm_reset`/`typed_reset_modal`'s gate so both
    /// destructive-reset dialogs demand the same "type reset to confirm"
    /// ceremony before "Yes, wipe this key" arms. Cleared on arm, cancel, and
    /// successful submit alongside `factory_reset_confirm`/
    /// `factory_reset_confirm_error`.
    factory_reset_confirm_typed: String,
    /// Mode for the factory-reset confirm dialog's reset management-auth
    /// credential prompt (shown only when
    /// `FactoryResetConfirmState::needs_reset_mgmt_auth` is true). Lives on `App`,
    /// not inside `FactoryResetConfirmState`, for the same reason
    /// `PivState::mgmt_auth_mode` lives on `PivState` rather than inside
    /// whatever op is using it: it's user-typed UI state that must survive
    /// the confirm-arming round trip (fingerprinting runs as a background
    /// job in between) and be wiped explicitly on submit/cancel, not
    /// implicitly dropped with whatever state happened to be armed when it
    /// was typed.
    reset_mgmt_auth_mode: ResetMgmtAuthMode,
    /// Typed field backing `reset_mgmt_auth_mode`: a management-key hex
    /// string in `Manual` mode, a PIN in `Pin` mode. Wiped on submit and on
    /// dialog dismissal, same discipline as `PivState::mgmt_key_input`.
    reset_mgmt_auth_input: String,
    /// Live per-step report while a factory reset runs (empty when idle).
    factory_reset_report: Vec<FactoryResetRow>,
    /// Remaining scans in the current burst. A single scan races slow-to-
    /// register readers (the Molto2's CCID interface appears in pcscd a beat
    /// after the USB device), so startup and every hotplug schedule several
    /// staggered rescans instead of one.
    pending_scans: u8,
    /// When the next burst scan is due.
    next_scan_at: Option<std::time::Instant>,
    /// Background PC/SC hotplug watcher. `None` in tests / if it can't start.
    /// Held only to keep the thread alive; dropped on app exit.
    #[allow(dead_code)]
    reader_watch: Option<keyroost_transport::ReaderWatcher>,
    /// Result channel of the in-flight bulk-import stage (QR decode, vault
    /// decrypt, export parse). `Some` while one is running — these can take
    /// seconds (scrypt: minutes at the caps) and run on their own thread so
    /// they block neither the frame loop nor the device worker. One at a time.
    import_rx: Option<std::sync::mpsc::Receiver<ApplyFn>>,
    /// What the import thread is doing, for the dialog's progress row.
    import_label: Option<String>,
    /// Frame-loop handle for waking egui from helper threads. `None` in tests.
    egui_ctx: Option<egui::Context>,
    /// The `(mode, accent, colorblind)` triple whose Visuals are currently
    /// applied to the egui context — re-applied on change, not per frame.
    applied_theme: Option<(Mode, usize, bool)>,
    /// UI scale ("Text size", issue #42): egui's global zoom factor, which
    /// scales fonts AND painted symbols uniformly. Persisted via `settings.json`.
    /// `#[derive(Default)]` starts this at `0.0`; `theme::clamp_zoom` maps that
    /// (and any out-of-range value) back to 100%, so the default look is
    /// unchanged for existing users until they touch the control.
    zoom: f32,
    /// The zoom factor currently applied to the egui context — re-applied on
    /// change, not per frame (parallel to `applied_theme`).
    applied_zoom: Option<f32>,
    /// Slider preview while the "Text size" slider is actively dragged. The
    /// slider lives *inside* the UI it scales, so applying the zoom live during
    /// a drag would grow/shift the slider under the cursor and run the value
    /// away to the maximum (issue: slider runaway). Instead we stash the
    /// in-progress value here and keep the real `set_zoom_factor` untouched
    /// until the drag is released — see `text_size_control`. `None` means no
    /// drag in flight, so the readout/handle track the committed factor.
    zoom_pending: Option<f32>,
    /// Deadline for committing a +/− stepper preview (see `text_size_control`).
    /// The steppers stash their target in `zoom_pending` and set this; the zoom
    /// is applied once the user settles — pointer off the buttons, or this
    /// instant passes — so repeated clicks don't rescale the bar out from under
    /// the cursor mid-click. `None` when no stepper preview is pending.
    zoom_commit_at: Option<std::time::Instant>,
    /// The last `Settings` snapshot written to `settings.json` (or loaded at
    /// startup). `persist_settings()` compares the current UI state against
    /// this and only writes when something actually changed, so the disk isn't
    /// touched every frame. `None` until the first comparison.
    last_saved_settings: Option<Settings>,
    /// In-flight native file-chooser dialogs. rfd's xdg-portal backend is
    /// async, so each Browse…/Save… click spawns a helper thread that drives
    /// the dialog to completion and sends the chosen path back over a channel.
    /// `update()` drains this every frame and writes the path into the target
    /// field, so the picker never blocks the egui frame loop. One entry per
    /// open dialog; an entry is dropped once its result is consumed.
    pending_files: Vec<(
        FileTarget,
        std::sync::mpsc::Receiver<Option<std::path::PathBuf>>,
    )>,
    /// Monotonic id handed to each "Save certificate…" request so its dialog
    /// and its parked certificate stay paired. Never reset (not even on a
    /// selection change): an id must not be reused while a dialog opened for
    /// the previous key is still on screen.
    ssh_cert_next_id: u64,
}

/// Which path text field a resolved file-chooser result should populate. Keeps
/// the dialog plumbing generic — one helper, one drain loop, no per-field
/// duplication.
#[derive(Clone, PartialEq, Eq)]
enum FileTarget {
    /// OpenPGP "Import RSA-2048" key file (`openpgp.import_path`).
    OpenpgpImport,
    /// PIV "Sign & save CSR" destination (`piv.csr_path`).
    PivCsr,
    /// PIV "Import certificate" source file (`piv.cert_path`).
    PivCert,
    /// PIV "Export certificate" destination (`piv.export_path`).
    PivExport,
    /// Storage tab "Export…" destination for a large-blob entry. Carries the
    /// entry index so a second Export click (or a cancelled dialog) can never
    /// mismatch which entry a resolving dialog belongs to.
    LbExport(usize),
    /// Passkeys tab "Save certificate…" destination for an SSH credential's
    /// extracted cert. The cert text was decrypted by the background job and
    /// parked in `security_keys.ssh_cert_pending`; the resolving dialog writes
    /// it to the chosen path. Carries the request id that keys the parked
    /// certificate — same reason `LbExport` carries an index: two save dialogs
    /// can be open at once, and each must resolve to its own certificate.
    SshCertSave(u64),
    /// "Import file…" in a key's view: the picked file joins the import
    /// queue, remembering which view asked.
    ImportCodes(import_flow::Origin),
}

/// An SSH certificate extracted from a credential's largeBlob, waiting for the
/// user to pick a destination in the save dialog. `summary` is the parsed
/// one-line description shown next to the saved path on success.
struct PendingSshCert {
    cert_pub: String,
    summary: String,
}

/// Take the certificate a resolving "Save certificate…" dialog is for out of
/// the parked-certificate map. Keyed by the dialog's request id, so two saves
/// in flight each get their own certificate instead of racing for one slot;
/// `None` when this dialog's certificate is gone (the selection changed, so
/// `clear_device_state` dropped it).
fn take_pending_cert(
    pending: &mut std::collections::HashMap<u64, PendingSshCert>,
    id: u64,
) -> Option<PendingSshCert> {
    pending.remove(&id)
}

impl App {
    /// Spawn a native file-chooser for `target`. `save` picks the dialog kind
    /// (Save… vs open); `filters` is `(name, &[extensions])` rows for the
    /// type dropdown; `default_name` seeds the filename on save dialogs.
    ///
    /// rfd's portal backend is async, so the dialog runs on a throwaway thread
    /// (driven by `pollster::block_on`) and the result returns over a channel
    /// drained in `update()` — the egui frame thread is never blocked. The
    /// frame loop is woken via `request_repaint` once the user dismisses the
    /// dialog so the picked path lands without waiting for the next input event.
    fn spawn_file_dialog(
        &mut self,
        target: FileTarget,
        save: bool,
        filters: &[(&'static str, &'static [&'static str])],
        default_name: Option<&str>,
    ) {
        let (tx, rx) = std::sync::mpsc::channel();
        let owned_filters: Vec<(String, Vec<String>)> = filters
            .iter()
            .map(|(name, exts)| {
                (
                    (*name).to_owned(),
                    exts.iter().map(|e| (*e).to_owned()).collect(),
                )
            })
            .collect();
        let default_name = default_name.map(str::to_owned);
        let egui_ctx = self.egui_ctx.clone();
        std::thread::spawn(move || {
            let result = pollster::block_on(async move {
                let mut dialog = rfd::AsyncFileDialog::new();
                for (name, exts) in &owned_filters {
                    let ext_refs: Vec<&str> = exts.iter().map(String::as_str).collect();
                    dialog = dialog.add_filter(name, &ext_refs);
                }
                if let Some(name) = &default_name {
                    dialog = dialog.set_file_name(name);
                }
                let handle = if save {
                    dialog.save_file().await
                } else {
                    dialog.pick_file().await
                };
                handle.map(|h| h.path().to_path_buf())
            });
            let _ = tx.send(result);
            if let Some(ctx) = egui_ctx {
                ctx.request_repaint();
            }
        });
        self.pending_files.push((target, rx));
    }

    /// Drain any resolved file-chooser dialogs and write the picked path into
    /// the matching text field. A `None` result (the user cancelled) leaves the
    /// field untouched. Entries are removed once they resolve. Called once per
    /// frame from `update()`.
    fn drain_file_dialogs(&mut self) {
        let mut i = 0;
        while i < self.pending_files.len() {
            match self.pending_files[i].1.try_recv() {
                Ok(result) => {
                    let (target, _) = self.pending_files.remove(i);
                    if let Some(path) = result {
                        let text = path.display().to_string();
                        match target {
                            FileTarget::OpenpgpImport => self.openpgp.import_path = text,
                            // PIV cert file ops pick the path first, then act:
                            // CSR and import need a secret, so open their modal;
                            // export writes straight to the chosen path.
                            FileTarget::PivCsr => {
                                self.piv.csr_path = text;
                                self.piv_cred_modal_close();
                                self.piv.cred_modal =
                                    Some(PivCredModal::new(PivCredKind::RequestCsr));
                            }
                            FileTarget::PivCert => {
                                self.piv.cert_path = text;
                                self.piv_cred_modal_close();
                                self.piv.cred_modal =
                                    Some(PivCredModal::new(PivCredKind::ImportCert));
                            }
                            FileTarget::PivExport => {
                                self.piv.export_path = text;
                                self.piv_export_cert();
                            }
                            FileTarget::LbExport(idx) => {
                                use keyroost_ctap::large_blobs::EntryKind;
                                // The array may have been reloaded, cleared, or
                                // shrunk between the Export click and the dialog
                                // resolving — fail loudly instead of writing the
                                // wrong entry or silently doing nothing.
                                let entry = self
                                    .security_keys
                                    .large_blobs
                                    .as_ref()
                                    .and_then(|arr| arr.entry(idx));
                                self.security_keys.lb_status = Some(match entry {
                                    None => {
                                        format!("Export failed: entry {idx} no longer exists")
                                    }
                                    Some(entry) => {
                                        let bytes = match entry.classify() {
                                            EntryKind::SshCert { wire, .. } => {
                                                keyroost_ctap::ssh_cert::to_cert_pub(&wire)
                                                    .map(String::into_bytes)
                                            }
                                            _ => Some(entry.ciphertext.clone()),
                                        };
                                        match bytes {
                                            None => "Export failed: could not re-encode \
                                                     certificate"
                                                .into(),
                                            Some(bytes) => match std::fs::write(&path, &bytes) {
                                                Ok(()) => format!(
                                                    "Exported entry {idx} ({} bytes) to {text}",
                                                    bytes.len()
                                                ),
                                                Err(e) => format!("Export failed: {e}"),
                                            },
                                        }
                                    }
                                });
                            }
                            FileTarget::SshCertSave(id) => {
                                // The cert text was decrypted by the background
                                // job and parked under this dialog's id; take
                                // *that* one and write it to the chosen path.
                                let pending =
                                    take_pending_cert(&mut self.security_keys.ssh_cert_pending, id);
                                self.security_keys.ssh_cert_status = Some(match pending {
                                    None => "Save failed: no certificate was ready \
                                             to write"
                                        .to_string(),
                                    Some(pending) => {
                                        match std::fs::write(&path, pending.cert_pub.as_bytes()) {
                                            Ok(()) => format!(
                                                "Saved certificate to {text}\n{}",
                                                pending.summary
                                            ),
                                            Err(e) => format!("Save failed: {e}"),
                                        }
                                    }
                                });
                            }
                            FileTarget::ImportCodes(origin) => {
                                self.import_flow.enqueue([path], &origin);
                            }
                        }
                    } else {
                        // Cancelled: drop whatever payload was waiting on this
                        // dialog so it can't be written by a later one.
                        self.discard_file_target(target);
                    }
                }
                Err(std::sync::mpsc::TryRecvError::Empty) => i += 1,
                Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                    let (target, _) = self.pending_files.remove(i);
                    self.discard_file_target(target);
                }
            }
        }
    }

    /// Drop the payload a dialog was holding when it produced no path — the
    /// user cancelled, or the helper thread went away. Only save-certificate
    /// dialogs park anything; without this a cancelled save would leave the
    /// extracted certificate in the map for the rest of the session.
    fn discard_file_target(&mut self, target: FileTarget) {
        if let FileTarget::SshCertSave(id) = target {
            self.security_keys.ssh_cert_pending.remove(&id);
        }
    }
}

#[derive(Default)]
struct Draft {
    /// 1..=12 byte title.
    title: String,
    /// Base32-encoded TOTP secret.
    secret_base32: String,
    algorithm: AlgoChoice,
    digits: DigitsChoice,
    time_step: StepChoice,
    display_timeout: TimeoutChoice,
}

#[derive(Default, Clone, Copy, PartialEq, Eq)]
enum AlgoChoice {
    #[default]
    Sha1,
    Sha256,
}
impl AlgoChoice {
    fn to_proto(self) -> HmacAlgo {
        match self {
            AlgoChoice::Sha1 => HmacAlgo::Sha1,
            AlgoChoice::Sha256 => HmacAlgo::Sha256,
        }
    }
}

#[derive(Default, Clone, Copy, PartialEq, Eq)]
enum DigitsChoice {
    Four,
    #[default]
    Six,
    Eight,
    Ten,
}
impl DigitsChoice {
    fn to_proto(self) -> OtpDigits {
        match self {
            DigitsChoice::Four => OtpDigits::Four,
            DigitsChoice::Six => OtpDigits::Six,
            DigitsChoice::Eight => OtpDigits::Eight,
            DigitsChoice::Ten => OtpDigits::Ten,
        }
    }
}

#[derive(Default, Clone, Copy, PartialEq, Eq)]
enum StepChoice {
    #[default]
    S30,
    S60,
}
impl StepChoice {
    fn to_proto(self) -> TimeStep {
        match self {
            StepChoice::S30 => TimeStep::Seconds30,
            StepChoice::S60 => TimeStep::Seconds60,
        }
    }
}

#[derive(Default, Clone, Copy, PartialEq, Eq)]
enum TimeoutChoice {
    S15,
    #[default]
    S30,
    S60,
    S120,
}
impl TimeoutChoice {
    fn to_proto(self) -> DisplayTimeout {
        match self {
            TimeoutChoice::S15 => DisplayTimeout::Sec15,
            TimeoutChoice::S30 => DisplayTimeout::Sec30,
            TimeoutChoice::S60 => DisplayTimeout::Sec60,
            TimeoutChoice::S120 => DisplayTimeout::Sec120,
        }
    }
}

#[derive(Default)]
struct ImportDialog {
    open: bool,
    uri: String,
}

impl ImportDialog {
    /// Settle the dialog's open state after its window was drawn this frame.
    /// `window_open` is the copy egui's `[X]` close wrote to; `cancel_clicked` is the
    /// in-window Cancel button. A button must never write `open` directly from
    /// inside the window closure: the write-back of the stale `window_open`
    /// copy would undo it in the same frame (issue #170).
    fn settle_open(&mut self, window_open: bool, cancel_clicked: bool) {
        if self.open && !(window_open && !cancel_clicked) {
            self.close();
        }
    }

    /// Close the dialog and wipe the pasted URI, which carries the seed.
    fn close(&mut self) {
        self.open = false;
        wipe(&mut self.uri);
    }
}

struct LogLine {
    severity: Severity,
    kind: LogKind,
    text: String,
    /// The APDU trace behind this entry, captured on the worker thread while
    /// the "APDU trace" checkbox (see `App::activity_log`) was on. `None`
    /// with the checkbox off, for an entry with no device I/O behind it, or
    /// when a job recorded nothing. Printed in full under the entry —
    /// exactly the lines the CLI's own `--debug` would print.
    trace: Option<Vec<String>>,
}

#[derive(Clone, Copy)]
enum Severity {
    Info,
    Ok,
    Warn,
    Err,
}

/// Whether a log entry reports something the user directly asked for (a
/// button click that writes to, authenticates against, or otherwise acts on
/// a device) or something the app did on its own — a device scan, a status
/// sweep triggered by opening a tab or by selecting a device, a re-read that
/// follows a write to refresh the pane. Rendered with distinct weight (see
/// `App::activity_log`) so a quiet background poll never reads as though the
/// user had just done something.
#[derive(Clone, Copy, PartialEq, Eq)]
enum LogKind {
    User,
    Background,
}

/// Whether [`App::load_piv_status`] should reuse this device's cached
/// [`keyroost_transport::PivSessionState`] or force a from-scratch
/// resolution — independent of [`LogKind`]: how loudly a read is logged and
/// whether it trusts the cache are two separate questions. Today's sole
/// `Bypass` caller (the Refresh button) happens to also be the sole
/// `LogKind::User` caller, but that's a coincidence of what the button does,
/// not a rule tying the two together — a future caller is free to mix them
/// the other way.
#[derive(Clone, Copy, PartialEq, Eq)]
enum PivCache {
    /// Reuse this device's `piv_session_state` entry via
    /// [`keyroost_transport::PivSession::with_cached_transaction`] — the default for
    /// every unprompted read (first tab view, the re-read every write
    /// triggers): `with_cached_transaction`'s own checks already vouch for it, so
    /// there's no reason to distrust it just because nothing asked to.
    Reuse,
    /// Ignore whatever's cached and open via a plain
    /// [`keyroost_transport::PivSession::with_transaction`] — a real SELECT, a real
    /// fingerprint probe, no shortcuts, same as if this device had never
    /// been seen this app run. The result still gets stored back into
    /// `piv_session_state` afterward like any other read, so this doesn't
    /// leave the cache disabled going forward — it only forces *this* read
    /// to double-check it.
    Bypass,
}

impl App {
    /// Queue a blocking device job on the worker thread. `label` describes it for
    /// the busy indicator; `job` runs off-thread and returns a closure applied
    /// back to `self` on the UI thread. Falls back to running inline if there's
    /// no worker (tests).
    /// Returns `false` when the job was *not* queued (a job is already in
    /// flight, or the worker died). Callers that consumed user state to build
    /// the job — a typed PIN, a confirmed modal, a one-shot arm — must check
    /// the return and keep (or restore) that state on `false`, otherwise a
    /// click during a background read silently swallows the action.
    fn spawn_job<F>(&mut self, label: impl Into<String>, job: F) -> bool
    where
        F: FnOnce() -> ApplyFn + Send + 'static,
    {
        // Serialize device access: ignore a new job while one is in flight rather
        // than queueing overlapping card I/O behind a click the user can't see
        // landed. (A single worker thread would serialize anyway, but this also
        // stops a growing backlog of duplicate refreshes from rapid clicks.)
        if self.busy() {
            return false;
        }
        match &self.worker {
            Some(worker) => {
                self.busy_jobs += 1;
                self.busy_label = Some(label.into());
                if worker.job_tx.send(Box::new(job)).is_err() {
                    // Worker died; undo the bookkeeping so the UI doesn't hang.
                    self.busy_jobs -= 1;
                    self.busy_label = None;
                    return false;
                }
                true
            }
            None => {
                let apply = job();
                apply(self);
                true
            }
        }
    }

    /// Apply any finished background jobs. Called once per frame from `update()`.
    fn drain_worker(&mut self) {
        use std::sync::mpsc::TryRecvError;
        let mut applies: Vec<ApplyFn> = Vec::new();
        let mut disconnected = false;
        if let Some(w) = &self.worker {
            loop {
                match w.result_rx.try_recv() {
                    Ok(apply) => applies.push(apply),
                    Err(TryRecvError::Empty) => break,
                    Err(TryRecvError::Disconnected) => {
                        disconnected = true;
                        break;
                    }
                }
            }
        }
        for apply in applies {
            // Decrement *before* applying so an apply closure that chains another
            // job (e.g. refresh-readers → probe-lock) isn't blocked by the busy
            // guard in `spawn_job`.
            self.busy_jobs = self.busy_jobs.saturating_sub(1);
            if self.busy_jobs == 0 {
                self.busy_label = None;
            }
            apply(self);
        }
        if disconnected {
            // Last-resort safety net: jobs catch their own panics, so a dead
            // worker means the thread ended some other way. Clear the busy guard
            // so the UI can't wedge with an eternal spinner, then respawn a
            // worker so device actions keep working (falls back to inline
            // execution if there's no egui context, e.g. in tests).
            self.busy_jobs = 0;
            self.busy_label = None;
            let apdu_trace = self.apdu_trace.clone();
            self.worker = self
                .egui_ctx
                .clone()
                .map(|ctx| Worker::spawn(ctx, apdu_trace));
            self.log(
                Severity::Err,
                "the background worker stopped unexpectedly and was restarted",
            );
        }
    }

    /// True while any background device job is in flight.
    fn busy(&self) -> bool {
        self.busy_jobs > 0
    }

    /// True while a bulk-import stage runs on its own thread.
    fn import_busy(&self) -> bool {
        self.import_rx.is_some()
    }

    /// Run a bulk-import stage (QR decode / vault decrypt / export parse) on a
    /// dedicated thread. Not `spawn_job`: that queue serializes device I/O,
    /// and a multi-second scrypt must not park card operations behind it.
    fn run_import<F>(&mut self, label: impl Into<String>, job: F)
    where
        F: FnOnce() -> ApplyFn + Send + 'static,
    {
        if self.import_busy() {
            return;
        }
        let Some(ctx) = self.egui_ctx.clone() else {
            // Tests: no frame loop to wake; run inline.
            let apply = job();
            apply(self);
            return;
        };
        let (tx, rx) = std::sync::mpsc::channel::<ApplyFn>();
        let spawned = std::thread::Builder::new()
            .name("keyroost-import".into())
            .spawn(move || {
                let apply = job();
                if tx.send(apply).is_ok() {
                    ctx.request_repaint(); // wake the frame loop to apply it
                }
            });
        match spawned {
            Ok(_) => {
                self.import_rx = Some(rx);
                self.import_label = Some(label.into());
            }
            Err(e) => {
                self.import_thread_failed(format!("Couldn't start reading the file ({e})."));
            }
        }
    }

    /// Apply a finished bulk-import stage. Called once per frame from
    /// `update()`, alongside `drain_worker`.
    fn drain_import(&mut self) {
        let received = match &self.import_rx {
            Some(rx) => rx.try_recv(),
            None => return,
        };
        match received {
            Ok(apply) => {
                self.import_rx = None;
                self.import_label = None;
                apply(self);
            }
            Err(std::sync::mpsc::TryRecvError::Empty) => {}
            Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                // Import thread died (panicked) without sending a result.
                self.import_rx = None;
                self.import_label = None;
                self.import_thread_failed("Reading the file failed unexpectedly.".into());
            }
        }
    }

    /// Log something the user directly asked for: a write, an auth attempt,
    /// an export — anything that happened because of a specific click.
    /// Rendered at full weight (see `activity_log`). This is the visualization
    /// every explicit Molto2 action already used; every other module's
    /// explicit actions should log through this same entry point.
    fn log(&mut self, severity: Severity, text: impl Into<String>) {
        self.log_kind(severity, LogKind::User, text);
    }

    /// Log something the app did on its own — a device scan, a status sweep
    /// triggered by opening a tab or selecting a device, a re-read that
    /// follows a write to refresh the pane. Rendered muted (see
    /// `activity_log`) so it never competes visually with a user action.
    fn log_bg(&mut self, severity: Severity, text: impl Into<String>) {
        self.log_kind(severity, LogKind::Background, text);
    }

    fn log_kind(&mut self, severity: Severity, kind: LogKind, text: impl Into<String>) {
        // The activity log is device-centric: nearly every entry reports
        // something read from or done to the token currently in focus — a
        // status sweep, a write, an auth attempt. Prefix that token's display
        // name so the log stays legible when a session touches several keys.
        // Fleet-level lines (device-scan counts, "selection moved on" reset
        // notices) go through `log_global`, which skips the prefix.
        let text = match self.selected_device() {
            Some(d) => format!("{}: {}", d.title(), text.into()),
            None => text.into(),
        };
        self.push_log(severity, kind, text);
    }

    /// Log without the selected-token prefix `log_kind` adds — for entries that
    /// are about the device *fleet* or about a key that is no longer the
    /// selection (so its name would be the wrong one to show).
    fn log_global(&mut self, severity: Severity, kind: LogKind, text: impl Into<String>) {
        self.push_log(severity, kind, text.into());
    }

    fn push_log(&mut self, severity: Severity, kind: LogKind, text: String) {
        // The trace captured for whichever job's apply closure is running
        // right now (see `Worker::spawn`), if any — attached to the first log
        // line that closure produces, then consumed so a later, unrelated log
        // call in the same frame doesn't also claim it.
        let trace = self.pending_trace.take().filter(|t| !t.is_empty());
        self.log.push(LogLine {
            severity,
            kind,
            text,
            trace,
        });
        // Keep the log bounded; oldest entries are least interesting.
        if self.log.len() > 200 {
            let overflow = self.log.len() - 200;
            self.log.drain(0..overflow);
        }
    }

    fn customer_key_bytes(&self) -> Result<Vec<u8>, String> {
        if self.customer_key_input.is_empty() {
            return Ok(DEFAULT_CUSTOMER_KEY.to_vec());
        }
        if self.customer_key_hex {
            keyroost_proto::codec::hex_decode(&self.customer_key_input)
                .map_err(|e| format!("invalid customer key hex: {}", e))
        } else {
            Ok(self.customer_key_input.as_bytes().to_vec())
        }
    }

    /// Take the Molto2 session so a worker job can use it (the apply step
    /// hands it back). `None` — with the reason logged — when not connected;
    /// silently `None` while another job runs, so a click during a background
    /// read is dropped *before* any state is consumed.
    fn take_molto_session(&mut self) -> Option<Session> {
        if self.busy() {
            return None;
        }
        if !self.molto_session_usable() {
            // Session bound to a different device than the current selection
            // (e.g. a delayed open or hand-back landed after the user
            // switched keys). Never serve it; drop it instead (KEY-004).
            self.session = None;
            self.molto_session_device = None;
            self.log(Severity::Warn, "not connected");
            return None;
        }
        match self.session.take() {
            Some(s) => Some(s),
            None => {
                self.log(Severity::Warn, "not connected");
                None
            }
        }
    }

    /// True while the stored Molto2 session is bound to the current selection.
    fn molto_session_usable(&self) -> bool {
        completion_still_valid(
            self.molto_session_device.as_ref(),
            self.selected_device.as_ref(),
        )
    }

    fn authenticate(&mut self) {
        let key = match self.customer_key_bytes() {
            Ok(k) => zeroize::Zeroizing::new(k),
            Err(e) => {
                self.log(Severity::Err, e);
                return;
            }
        };
        let Some(mut s) = self.take_molto_session() else {
            return;
        };
        self.spawn_job("Authenticating\u{2026}", move || {
            let result = s.authenticate(&key);
            Box::new(move |app: &mut App| {
                app.session = Some(s);
                match result {
                    Ok(()) => {
                        app.authenticated = true;
                        app.import_auth_result(true);
                        app.log(Severity::Ok, "authenticated");
                    }
                    // The Display impl renders the tries-remaining count (or
                    // "unknown" when the card gave none).
                    Err(e @ TransportError::AuthFailed { .. }) => {
                        app.import_auth_result(false);
                        app.log(Severity::Err, e.to_string());
                    }
                    Err(e) => {
                        app.import_auth_result(false);
                        app.log(Severity::Err, format!("auth failed: {}", e));
                    }
                }
            })
        });
    }

    fn apply_draft(&mut self) {
        if !self.ensure_auth() {
            return;
        }
        let secret = match keyroost_proto::codec::base32_decode(&self.draft.secret_base32) {
            Ok(s) if !s.is_empty() && s.len() <= 63 => zeroize::Zeroizing::new(s),
            Ok(s) => {
                self.log(
                    Severity::Err,
                    format!("seed must decode to 1..=63 bytes (got {})", s.len()),
                );
                return;
            }
            Err(e) => {
                self.log(Severity::Err, format!("seed base32 invalid: {}", e));
                return;
            }
        };
        let title = self.draft.title.trim().to_owned();
        if title.is_empty() || title.len() > 12 {
            self.log(Severity::Err, "title must be 1..=12 bytes");
            return;
        }
        let cfg = ProfileConfig {
            display_timeout: self.draft.display_timeout.to_proto(),
            algorithm: self.draft.algorithm.to_proto(),
            digits: self.draft.digits.to_proto(),
            time_step: self.draft.time_step.to_proto(),
            utc_time: unix_now(),
        };
        let p = self.slot;
        let Some(mut s) = self.take_molto_session() else {
            return;
        };
        self.spawn_job(format!("Writing profile #{p}\u{2026}"), move || {
            let result = s
                .set_seed(p, &secret)
                .map_err(|e| format!("set_seed #{}: {}", p, e))
                .and_then(|()| {
                    s.set_title(p, &title)
                        .map_err(|e| format!("set_title #{}: {}", p, e))
                })
                .and_then(|()| {
                    s.set_config(p, &cfg)
                        .map_err(|e| format!("set_config #{}: {}", p, e))
                });
            let refreshed = result.is_ok().then(|| s.read_public_data(p).ok()).flatten();
            Box::new(move |app: &mut App| {
                app.session = Some(s);
                match result {
                    Ok(()) => {
                        // The seed now lives on the device; keeping it in the
                        // (masked) field for the app's lifetime is pure
                        // liability. Title/config drafts stay — convenient for
                        // programming a run of similar slots.
                        wipe(&mut app.draft.secret_base32);
                        if let (Some(meta), Some(block)) = (app.slot_meta.as_mut(), refreshed) {
                            if let Some(slot) = meta.get_mut(p as usize) {
                                *slot = block;
                            }
                        }
                        if app.slot_meta.is_none() {
                            app.resweep_slot_meta(LogKind::Background);
                        }
                        app.log(Severity::Ok, format!("profile #{} written", p));
                    }
                    Err(e) => app.log(Severity::Err, e),
                }
            })
        });
    }

    /// Write only the selected slot's title — no seed re-entry, no config.
    /// Needs auth (set_title is a secure command); the seed is untouched.
    fn apply_title_only(&mut self) {
        if !self.ensure_auth() {
            return;
        }
        let title = self.draft.title.trim().to_owned();
        if title.is_empty() || title.len() > 12 {
            self.log(Severity::Err, "title must be 1..=12 bytes");
            return;
        }
        let p = self.slot;
        let Some(mut s) = self.take_molto_session() else {
            return;
        };
        self.spawn_job(format!("Writing title on #{p}\u{2026}"), move || {
            let result = s
                .set_title(p, &title)
                .map_err(|e| format!("set_title #{}: {}", p, e));
            let refreshed = result.is_ok().then(|| s.read_public_data(p).ok()).flatten();
            Box::new(move |app: &mut App| {
                app.session = Some(s);
                match result {
                    Ok(()) => {
                        if let (Some(meta), Some(block)) = (app.slot_meta.as_mut(), refreshed) {
                            if let Some(slot) = meta.get_mut(p as usize) {
                                *slot = block;
                            }
                        }
                        if app.slot_meta.is_none() {
                            app.resweep_slot_meta(LogKind::Background);
                        }
                        app.log(Severity::Ok, format!("title written on slot #{}", p));
                    }
                    Err(e) => app.log(Severity::Err, e),
                }
            })
        });
    }

    /// Delete the selected slot's seed. Keyless on the wire (the device
    /// accepts it from any card holder); the GUI's gate is the confirm
    /// card. The stored title survives — the refreshed block shows it.
    fn delete_seed_selected(&mut self) {
        let p = self.slot;
        let Some(mut s) = self.take_molto_session() else {
            return;
        };
        self.spawn_job(format!("Deleting seed on #{p}\u{2026}"), move || {
            let result = s
                .delete_seed(p)
                .map_err(|e| format!("delete seed #{}: {}", p, e));
            let refreshed = result.is_ok().then(|| s.read_public_data(p).ok()).flatten();
            Box::new(move |app: &mut App| {
                app.session = Some(s);
                match result {
                    Ok(outcome) => {
                        if let (Some(meta), Some(block)) = (app.slot_meta.as_mut(), refreshed) {
                            if let Some(slot) = meta.get_mut(p as usize) {
                                *slot = block;
                            }
                        }
                        if app.slot_meta.is_none() {
                            app.resweep_slot_meta(LogKind::Background);
                        }
                        match outcome {
                            SeedDeleteOutcome::Deleted => app.log(
                                Severity::Ok,
                                format!("seed deleted from slot #{} (title kept)", p),
                            ),
                            SeedDeleteOutcome::AlreadyEmpty => {
                                app.log(Severity::Ok, format!("slot #{} was already empty", p))
                            }
                        }
                    }
                    Err(e) => app.log(Severity::Err, e),
                }
            })
        });
    }

    fn sync_time_selected(&mut self) {
        if !self.ensure_auth() {
            return;
        }
        let p = self.slot;
        let Some(mut s) = self.take_molto_session() else {
            return;
        };
        self.spawn_job("Syncing time\u{2026}", move || {
            let result = s.sync_time(p, unix_now());
            Box::new(move |app: &mut App| {
                app.session = Some(s);
                match result {
                    Ok(()) => app.log(Severity::Ok, format!("time synced on #{}", p)),
                    Err(e) => app.log(Severity::Err, format!("sync_time #{}: {}", p, e)),
                }
            })
        });
    }

    fn sync_time_all(&mut self) {
        if !self.ensure_auth() {
            return;
        }
        let Some(mut s) = self.take_molto_session() else {
            return;
        };
        // 100 slots × one APDU each — emphatically not frame-loop work.
        self.spawn_job("Syncing time on all profiles\u{2026}", move || {
            let mut ok = 0;
            let mut fail = 0;
            for p in 0..PROFILES {
                match s.sync_time(p, unix_now()) {
                    Ok(()) => ok += 1,
                    Err(_) => fail += 1,
                }
            }
            Box::new(move |app: &mut App| {
                app.session = Some(s);
                let sev = if fail == 0 {
                    Severity::Ok
                } else {
                    Severity::Warn
                };
                app.log(sev, format!("time-sync-all: {} ok, {} failed", ok, fail));
            })
        });
    }

    /// Scan a TOTP QR from the screen, then run the normal otpauth import to
    /// fill the Molto2 draft — reusing the same parse+fill path as paste-a-URI.
    #[cfg(feature = "qr")]
    fn molto_scan_qr(&mut self) {
        match qrscan::scan_screens_for_otpauth() {
            Ok(uri) => {
                self.import_dialog.uri = uri;
                self.import_otpauth();
            }
            Err(e) => self.log(Severity::Err, format!("scan QR: {e}")),
        }
    }

    fn import_otpauth(&mut self) {
        let uri = self.import_dialog.uri.trim().to_owned();
        let parsed = match parse_otpauth(&uri) {
            Ok(p) => p,
            Err(e) => {
                self.log(Severity::Err, format!("import: {}", e));
                return;
            }
        };
        // Push parsed fields into the draft so the user can review before pushing.
        self.draft.title = parsed.suggested_title();
        // Show the original base32 from the URI rather than re-encoding the bytes.
        self.draft.secret_base32 = uri
            .find("secret=")
            .map(|i| {
                let rest = &uri[i + 7..];
                let end = rest.find('&').unwrap_or(rest.len());
                rest[..end].to_owned()
            })
            .unwrap_or_default();
        self.draft.algorithm = match parsed.algorithm {
            HmacAlgo::Sha1 => AlgoChoice::Sha1,
            HmacAlgo::Sha256 => AlgoChoice::Sha256,
        };
        self.draft.digits = match parsed.digits {
            OtpDigits::Four => DigitsChoice::Four,
            OtpDigits::Six => DigitsChoice::Six,
            OtpDigits::Eight => DigitsChoice::Eight,
            OtpDigits::Ten => DigitsChoice::Ten,
        };
        self.draft.time_step = match parsed.time_step {
            TimeStep::Seconds30 => StepChoice::S30,
            TimeStep::Seconds60 => StepChoice::S60,
        };
        self.log(
            Severity::Info,
            format!(
                "imported draft for #{} from URI; review and click Write profile",
                self.slot
            ),
        );
        self.import_dialog.close();
    }

    fn factory_reset(&mut self) {
        let Some(mut s) = self.take_molto_session() else {
            return;
        };
        self.spawn_job("Requesting factory reset\u{2026}", move || {
            let result = s.factory_reset();
            Box::new(move |app: &mut App| {
                app.session = Some(s);
                match result {
                    Ok(()) => {
                        // The wipe lands only when the user presses the device
                        // button, and the token stays connected through it with
                        // no completion signal — so we can't re-read the cleared
                        // state. Drop the now-doomed titles rather than keep
                        // showing them; a reselect re-sweeps the blank device.
                        app.slot_meta = None;
                        app.log(
                            Severity::Warn,
                            "factory-reset requested. Confirm with the \u{25B2} button on the device; reselect it afterward to refresh the slot list.",
                        );
                    }
                    Err(e) => app.log(Severity::Err, format!("factory_reset: {}", e)),
                }
            })
        });
    }

    /// Re-read all 100 public blocks and replace the slot list. Recovers the
    /// metadata display when a write found no existing list to patch (the
    /// open-time sweep had failed, leaving `slot_meta` `None`). `kind` should
    /// be `User` when this runs because the user clicked "Refresh slots", and
    /// `Background` for every other caller — a write's own fallback re-sweep,
    /// or any future automatic trigger — so the activity log renders each the
    /// way it actually happened.
    fn resweep_slot_meta(&mut self, kind: LogKind) {
        let Some(mut s) = self.take_molto_session() else {
            return;
        };
        self.spawn_job("Refreshing slots\u{2026}", move || {
            let meta = (0..PROFILES)
                .map(|p| s.read_public_data(p))
                .collect::<Result<Vec<_>, _>>();
            Box::new(move |app: &mut App| {
                app.session = Some(s);
                match meta {
                    Ok(m) => {
                        app.log_kind(Severity::Ok, kind, format!("{} slots read", m.len()));
                        app.slot_meta = Some(m);
                    }
                    Err(e) => app.log_kind(Severity::Warn, kind, format!("slot refresh: {e}")),
                }
            })
        });
    }

    fn ensure_auth(&mut self) -> bool {
        if self.authenticated {
            return true;
        }
        self.log(
            Severity::Warn,
            "not authenticated; click Authenticate first",
        );
        false
    }

    /// Open the currently-selected hidraw device, run CTAPHID_INIT and
    /// authenticatorGetInfo, and cache the result. Blocks the UI briefly —
    /// CTAP GetInfo typically completes in a few milliseconds.
    fn fetch_selected_info(&mut self) {
        self.security_keys.info = None;
        self.security_keys.init = None;
        self.security_keys.error = None;
        let Some(target) = self.selected_fido_target() else {
            return;
        };
        // Tag the job with the device it reads — if the user switches devices
        // while it's in flight, the result must not be painted into the new
        // device's pane (or its row in the sidebar).
        let for_device = self.selected_device.clone();
        self.spawn_job("Reading key info\u{2026}", move || {
            // Off-thread: open the transport, run GetInfo. HID also yields an
            // InitResponse (firmware + CBOR capability); PC/SC (NFC/contact) has
            // no INIT phase, so we synthesize a minimal one and rely on GetInfo.
            let outcome = match open_fido(&target) {
                Ok((mut dev, cbor, init)) => {
                    let info = if cbor {
                        Some(keyroost_ctap::get_info(&mut dev).map_err(|e| e.to_string()))
                    } else {
                        None
                    };
                    Ok((init, info))
                }
                Err(e) => Err(format!("could not open key: {e}")),
            };
            // Back on the UI thread: store the results.
            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return; // selection changed mid-read; discard
                }
                match outcome {
                    Ok((init, info)) => {
                        // Surface the key's firmware on the hero (e.g. "fw 5.7.4")
                        // when we have an InitResponse (USB-HID); PC/SC has none.
                        if let Some(init) = init {
                            let fw = format!(
                                "{}.{}.{}",
                                init.device_major, init.device_minor, init.device_build
                            );
                            if let Some(id) = for_device.clone() {
                                if let Some(dev) = app.devices.iter_mut().find(|d| d.id == id) {
                                    dev.firmware = fw;
                                }
                            }
                            app.security_keys.init = Some(init);
                        }
                        match info {
                            Some(Ok(info)) => {
                                // Refine the model from the AAGUID (e.g. "YubiKey" ->
                                // "YubiKey 5 Series with NFC") on the read device.
                                if let Some(model) = ui::aaguid::model_for_aaguid(&info.aaguid) {
                                    if let Some(id) = for_device {
                                        if let Some(dev) =
                                            app.devices.iter_mut().find(|d| d.id == id)
                                        {
                                            dev.model = model.to_string();
                                        }
                                    }
                                }
                                app.security_keys.info = Some(info);
                            }
                            Some(Err(e)) => {
                                app.security_keys.error = Some(format!("GetInfo failed: {}", e))
                            }
                            None => {
                                // CBOR was reported unavailable and we never even
                                // attempted GetInfo. Record it as an error rather
                                // than leaving the pane spinning on "Reading key…"
                                // forever (the spinner re-fires while info is None).
                                app.security_keys.error = Some(
                                    "this key did not present a CTAP2 (FIDO2) interface over \
                                     the reader; only U2F was detected"
                                        .to_string(),
                                );
                            }
                        }
                    }
                    Err(e) => app.security_keys.error = Some(e),
                }
            })
        });
    }

    /// Open the selected hidraw, run the PIN exchange, and populate the
    /// session with metadata + credential listing. Errors land in
    /// `security_keys.error`.
    fn try_unlock(&mut self) {
        // Check busy *before* consuming the typed PIN — spawn_job would drop
        // the job (and the PIN with it) if a background read is in flight.
        if self.busy() {
            return;
        }
        let Some(target) = self.selected_fido_target() else {
            return;
        };
        let pin = std::mem::take(&mut self.security_keys.pin_input);
        if pin.is_empty() {
            self.security_keys.error = Some("PIN is empty".into());
            return;
        }
        let for_device = self.selected_device.clone();
        self.spawn_job("Unlocking\u{2026} (enter PIN / touch)", move || {
            let result = Self::open_and_unlock(&target, &pin).map_err(|e| e.to_string());
            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return; // selection changed mid-unlock; discard (drops the PIN)
                }
                match result {
                    Ok(sess) => {
                        // Surface fingerprints read during unlock so the list shows
                        // without a separate Reload.
                        app.security_keys.fingerprints = sess.fingerprints.clone();
                        app.security_keys.session = Some(sess);
                        app.security_keys.session_device = for_device.clone();
                        app.security_keys.error = None;
                    }
                    Err(e) => app.security_keys.error = Some(format!("unlock failed: {}", e)),
                }
            })
        });
    }

    fn open_and_unlock(
        target: &FidoTarget,
        pin: &str,
    ) -> Result<UnlockedSession, Box<dyn std::error::Error>> {
        let (mut dev, cbor, _init) = open_fido(target)?;
        if !cbor {
            return Err("device is U2F-only".into());
        }
        let info = keyroost_ctap::get_info(&mut dev)?;
        // Request credential-management permission, plus bio-enrollment when the
        // key supports it, so the one cached session token authorizes both
        // passkey management and fingerprint operations. Permissions are a
        // bitmask; only OR in BIO_ENROLLMENT when advertised, since asking for an
        // unsupported permission would make the whole unlock fail.
        let mut perms = keyroost_ctap::client_pin::permissions::CREDENTIAL_MANAGEMENT;
        if info.option("bioEnroll").is_some()
            || info.option("userVerificationMgmtPreview").is_some()
        {
            perms |= keyroost_ctap::client_pin::permissions::BIO_ENROLLMENT;
        }
        let token = keyroost_ctap::client_pin::get_pin_uv_auth_token(&mut dev, pin, &info, perms)?;
        // Hand the manager a clone and keep `token` for the cached session; the
        // token stays valid for the device session, so this avoids a redundant
        // second PIN/ECDH exchange just to rebuild it.
        let mut mgr =
            keyroost_ctap::cred_mgmt::CredentialManager::new(&mut dev, token.clone(), &info)?;
        let metadata = mgr.metadata()?;
        let parties = mgr.list_relying_parties()?;
        let mut rps = Vec::with_capacity(parties.len());
        for rp in parties {
            // A `None` hash marks an entry whose rpIdHash came back malformed:
            // list nothing rather than query against a wrong key.
            let creds = match rp.rp_id_hash {
                Some(hash) => mgr.list_credentials(&hash).unwrap_or_default(),
                None => Vec::new(),
            };
            rps.push((rp, creds));
        }
        // While the session is fresh, also read enrolled fingerprints (when the
        // key supports bio) so the Fingerprints list appears immediately without
        // a separate Reload. Best-effort: a failure here doesn't block unlock.
        let fingerprints = if info.option("bioEnroll").is_some()
            || info.option("userVerificationMgmtPreview").is_some()
        {
            let cmd_code = if info.option("bioEnroll").is_some() {
                keyroost_ctap::bio_enroll::CTAP2_BIO_ENROLLMENT
            } else {
                keyroost_ctap::bio_enroll::CTAP2_BIO_ENROLLMENT_PREVIEW
            };
            let mut bio =
                keyroost_ctap::bio_enroll::BioEnrollment::new(&mut dev, token.clone(), cmd_code);
            bio.enumerate().ok()
        } else {
            None
        };
        Ok(UnlockedSession {
            token,
            metadata,
            rps: std::sync::Arc::new(rps),
            fingerprints,
            pin: zeroize::Zeroizing::new(pin.to_owned()),
        })
    }

    /// The unlocked FIDO session, but only while it is still bound to the
    /// current selection (KEY-012). Every dispatcher that reuses the cached
    /// session/PIN must get it through here, not `security_keys.session`.
    fn fido_session(&self) -> Option<&UnlockedSession> {
        if completion_still_valid(
            self.security_keys.session_device.as_ref(),
            self.selected_device.as_ref(),
        ) {
            self.security_keys.session.as_ref()
        } else {
            None
        }
    }

    fn lock_session(&mut self) {
        self.security_keys.session = None;
        self.security_keys.session_device = None;
        wipe(&mut self.security_keys.pin_input);
    }

    /// Resolve a failed unlocked-session operation. When the underlying CTAP
    /// error is a PIN / PIN-auth failure (`0x31` / `0x33` / `0x34`) the key has
    /// invalidated the in-flight session, so we drop it and ask the user to
    /// unlock again. Any other failure keeps the existing behavior: surface the
    /// caller's contextual message. Auto-lock applies ONLY to operations that
    /// already hold a session — `try_unlock`'s own wrong-PIN handling is left
    /// untouched.
    fn fail_session_op(&mut self, err: &SessionOpError, context: &str) {
        if err.relock {
            self.lock_session();
            self.security_keys.error = Some(
                "the key re-locked (PIN or session changed) \u{2014} \
                 unlock again to continue."
                    .into(),
            );
        } else {
            self.security_keys.error = Some(format!("{context}: {err}"));
        }
    }

    fn refresh_credentials(&mut self) {
        // Check busy *before* taking the session — spawn_job would silently
        // drop the job, destroying the unlocked session (and its PIN token)
        // and logging the user out for clicking Reload at the wrong moment.
        if self.busy() {
            return;
        }
        let Some(target) = self.selected_fido_target() else {
            return;
        };
        if self.fido_session().is_none() {
            return; // no session, or one bound to a different device (KEY-012)
        }
        let Some(session) = self.security_keys.session.take() else {
            return;
        };
        let token = session.token;
        let pin = session.pin;
        let for_device = self.selected_device.clone();
        self.spawn_job("Refreshing credentials\u{2026}", move || {
            let result =
                Self::refresh_with_token(&target, token, pin).map_err(SessionOpError::from_boxed);
            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return; // selection changed mid-refresh; drop the session + PIN
                }
                match result {
                    Ok(fresh) => {
                        app.security_keys.session = Some(fresh);
                        app.security_keys.session_device = for_device.clone();
                    }
                    Err(e) => app.fail_session_op(&e, "refresh failed"),
                }
            })
        });
    }

    fn refresh_with_token(
        target: &FidoTarget,
        token: PinUvAuthToken,
        pin: zeroize::Zeroizing<String>,
    ) -> Result<UnlockedSession, Box<dyn std::error::Error>> {
        let (mut dev, _cbor, _init) = open_fido(target)?;
        let info = keyroost_ctap::get_info(&mut dev)?;
        let mut mgr =
            keyroost_ctap::cred_mgmt::CredentialManager::new(&mut dev, token.clone(), &info)?;
        let metadata = mgr.metadata()?;
        let parties = mgr.list_relying_parties()?;
        let mut rps = Vec::with_capacity(parties.len());
        for rp in parties {
            // A `None` hash marks an entry whose rpIdHash came back malformed:
            // list nothing rather than query against a wrong key.
            let creds = match rp.rp_id_hash {
                Some(hash) => mgr.list_credentials(&hash).unwrap_or_default(),
                None => Vec::new(),
            };
            rps.push((rp, creds));
        }
        Ok(UnlockedSession {
            token,
            metadata,
            rps: std::sync::Arc::new(rps),
            fingerprints: None,
            pin,
        })
    }

    /// Pick the bio-enrollment command byte from the cached AuthenticatorInfo.
    /// Mirrors the CLI helper: standard 0x09 when `bioEnroll` is advertised,
    /// else the preview 0x40.
    fn bio_cmd_code(&self) -> Option<u8> {
        let info = self.security_keys.info.as_ref()?;
        if info.option("bioEnroll").is_some() {
            Some(keyroost_ctap::bio_enroll::CTAP2_BIO_ENROLLMENT)
        } else if info.option("userVerificationMgmtPreview").is_some() {
            Some(keyroost_ctap::bio_enroll::CTAP2_BIO_ENROLLMENT_PREVIEW)
        } else {
            None
        }
    }

    /// Open the device, derive a FRESH bio pinUvAuthToken from the PIN, and run
    /// `f` with an armed BioEnrollment. A fresh token per operation is required:
    /// the authenticator can invalidate a token after a UV-gated bio write, so
    /// reusing the unlock token across operations fails with 0x33.
    fn with_fresh_bio<T>(
        target: &FidoTarget,
        pin: &str,
        f: impl FnOnce(
            &mut keyroost_ctap::bio_enroll::BioEnrollment<
                Box<dyn keyroost_ctap::transport::CtapTransport>,
            >,
        ) -> Result<T, SessionOpError>,
    ) -> Result<T, SessionOpError> {
        let (mut dev, cbor, _init) = open_fido(target).map_err(SessionOpError::msg)?;
        if !cbor {
            return Err(SessionOpError::msg("device is U2F-only"));
        }
        let info = keyroost_ctap::get_info(&mut dev).map_err(SessionOpError::from_ctap)?;
        let cmd_code = if info.option("bioEnroll").is_some() {
            keyroost_ctap::bio_enroll::CTAP2_BIO_ENROLLMENT
        } else if info.option("userVerificationMgmtPreview").is_some() {
            keyroost_ctap::bio_enroll::CTAP2_BIO_ENROLLMENT_PREVIEW
        } else {
            return Err(SessionOpError::msg(
                "key does not support fingerprint enrollment",
            ));
        };
        let token = keyroost_ctap::client_pin::get_pin_uv_auth_token(
            &mut dev,
            pin,
            &info,
            keyroost_ctap::client_pin::permissions::BIO_ENROLLMENT,
        )
        .map_err(SessionOpError::from_ctap)?;
        let mut bio = keyroost_ctap::bio_enroll::BioEnrollment::new(&mut dev, token, cmd_code);
        f(&mut bio)
    }

    /// Refresh the cached fingerprint list.
    fn refresh_fingerprints(&mut self) {
        if self.busy() {
            return;
        }
        let Some(target) = self.selected_fido_target() else {
            return;
        };
        let Some(session) = self.fido_session() else {
            self.security_keys.error = Some("unlock the key first".into());
            return;
        };
        let pin = session.pin.clone();
        let for_device = self.selected_device.clone();
        self.spawn_job("Reading fingerprints\u{2026}", move || {
            let result = Self::with_fresh_bio(&target, &pin, |bio| {
                bio.enumerate().map_err(SessionOpError::from_ctap)
            });
            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return; // selection changed mid-read; discard
                }
                match result {
                    Ok(list) => {
                        app.security_keys.fingerprints = Some(list);
                        app.security_keys.error = None;
                    }
                    Err(e) => app.fail_session_op(&e, "fingerprint list failed"),
                }
            })
        });
    }

    /// Enroll a new fingerprint end-to-end (begin + capture loop) on a worker.
    /// Writes live progress to a shared cell so the UI can show a wizard with
    /// per-sample quality feedback.
    fn enroll_fingerprint(&mut self) {
        if self.busy() {
            return;
        }
        let Some(target) = self.selected_fido_target() else {
            return;
        };
        let Some(session) = self.fido_session() else {
            self.security_keys.error = Some("unlock the key first".into());
            return;
        };
        let pin = session.pin.clone();
        let name = self.security_keys.fp_new_name.trim().to_owned();
        let name = if name.is_empty() { None } else { Some(name) };

        // Shared progress cell the worker updates and the UI polls each frame.
        let progress = std::sync::Arc::new(std::sync::Mutex::new(EnrollProgress::default()));
        // Pull out the cancel flag so the worker can poll it without locking the
        // whole progress mutex on every check.
        let cancel_flag = progress
            .lock()
            .map(|g| g.cancel.clone())
            .unwrap_or_default();
        self.security_keys.fp_progress = Some(progress.clone());

        let for_device = self.selected_device.clone();
        self.spawn_job("Enrolling fingerprint\u{2026}", move || {
            use keyroost_ctap::bio_enroll::sample_status_message;
            let result = (|| -> Result<Vec<keyroost_ctap::Enrollment>, SessionOpError> {
                let (mut dev, cbor, _init) = open_fido(&target).map_err(SessionOpError::msg)?;
                if !cbor {
                    return Err(SessionOpError::msg("device is U2F-only"));
                }
                // Wire the cooperative-cancel flag into the transport so a
                // capture blocked waiting for a touch aborts promptly (at the
                // next KEEPALIVE) when the user clicks Cancel.
                dev.set_cancel_flag(cancel_flag.clone());
                let info = keyroost_ctap::get_info(&mut dev).map_err(SessionOpError::from_ctap)?;
                let cmd_code = if info.option("bioEnroll").is_some() {
                    keyroost_ctap::bio_enroll::CTAP2_BIO_ENROLLMENT
                } else {
                    keyroost_ctap::bio_enroll::CTAP2_BIO_ENROLLMENT_PREVIEW
                };
                // Fresh bio token per enroll, derived from the session PIN.
                let token = keyroost_ctap::client_pin::get_pin_uv_auth_token(
                    &mut dev,
                    &pin,
                    &info,
                    keyroost_ctap::client_pin::permissions::BIO_ENROLLMENT,
                )
                .map_err(SessionOpError::from_ctap)?;
                let mut bio =
                    keyroost_ctap::bio_enroll::BioEnrollment::new(&mut dev, token, cmd_code);

                // Learn how many samples the sensor wants, for the progress bar.
                let total = bio
                    .sensor_info()
                    .map(|i| i.max_capture_samples)
                    .unwrap_or(0);

                let (template_id, mut status) =
                    bio.enroll_begin(None).map_err(SessionOpError::from_ctap)?;
                // captured = total - remaining (clamped), so the bar advances
                // even though the protocol reports "remaining".
                let update = |p: &std::sync::Mutex<EnrollProgress>,
                              total: u64,
                              remaining: u64,
                              msg: &str| {
                    if let Ok(mut g) = p.lock() {
                        g.total = total;
                        g.captured = total.saturating_sub(remaining);
                        g.last_message = msg.to_string();
                    }
                };
                update(
                    &progress,
                    total.max(status.remaining_samples + 1),
                    status.remaining_samples,
                    sample_status_message(status.last_sample_status),
                );

                while status.remaining_samples > 0 {
                    // The capture below blocks waiting for a touch, but the
                    // transport checks the cancel flag on every KEEPALIVE, so a
                    // cancel returns the "cancelled" error promptly. Map that to
                    // a device-side cancel + a clean exit.
                    match bio.enroll_capture_next(&template_id, None) {
                        Ok(s) => status = s,
                        Err(e) if e.to_string().contains("cancelled") => {
                            // Clear the flag first, otherwise the cancel command
                            // itself would be cancelled at its first KEEPALIVE.
                            cancel_flag.store(false, std::sync::atomic::Ordering::Relaxed);
                            let _ = bio.cancel_enrollment();
                            return Err(SessionOpError::msg("cancelled"));
                        }
                        Err(e) => return Err(SessionOpError::from_ctap(e)),
                    }
                    let total = total.max(status.remaining_samples + 1);
                    update(
                        &progress,
                        total,
                        status.remaining_samples,
                        sample_status_message(status.last_sample_status),
                    );
                }

                if let Some(n) = &name {
                    bio.set_friendly_name(&template_id, n)
                        .map_err(SessionOpError::from_ctap)?;
                }
                bio.enumerate().map_err(SessionOpError::from_ctap)
            })();

            // Mark the shared cell done (success or failure) for the UI.
            if let Ok(mut g) = progress.lock() {
                g.done = Some(result.as_ref().map(|_| ()).map_err(|e| e.message.clone()));
                if result.is_ok() {
                    g.last_message = "Fingerprint enrolled.".into();
                    g.captured = g.total;
                }
            }

            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return; // selection changed mid-enroll; the progress cell
                            // was already dropped + cancelled on selection change
                }
                match result {
                    Ok(list) => {
                        app.security_keys.fingerprints = Some(list);
                        app.security_keys.fp_new_name.clear();
                        app.security_keys.error = None;
                    }
                    Err(e) if e.message == "cancelled" => {
                        // User cancelled — dismiss the wizard without an error
                        // banner, and refresh the list so it reflects reality.
                        app.security_keys.fp_progress = None;
                        app.security_keys.error = None;
                        app.refresh_fingerprints();
                    }
                    Err(e) => app.fail_session_op(&e, "enroll failed"),
                }
                // Leave fp_progress in place briefly so the UI shows the final
                // "enrolled" state; it's cleared on the next user action.
            })
        });
    }

    /// Delete one fingerprint by template id, then refresh the list.
    fn delete_fingerprint(&mut self, template_id: Vec<u8>) {
        if self.busy() {
            return;
        }
        let Some(target) = self.selected_fido_target() else {
            return;
        };
        let Some(session) = self.fido_session() else {
            return;
        };
        let pin = session.pin.clone();
        let for_device = self.selected_device.clone();
        self.spawn_job("Deleting fingerprint\u{2026}", move || {
            let result = Self::with_fresh_bio(&target, &pin, |bio| {
                bio.remove_enrollment(&template_id)
                    .map_err(SessionOpError::from_ctap)?;
                bio.enumerate().map_err(SessionOpError::from_ctap)
            });
            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return; // selection changed mid-op; discard the stale completion
                }
                match result {
                    Ok(list) => app.security_keys.fingerprints = Some(list),
                    Err(e) => app.fail_session_op(&e, "delete failed"),
                }
            })
        });
    }

    /// Rename one fingerprint, then refresh the list.
    fn rename_fingerprint(&mut self, template_id: Vec<u8>, new_name: String) {
        if self.busy() {
            return;
        }
        let Some(target) = self.selected_fido_target() else {
            return;
        };
        let Some(session) = self.fido_session() else {
            return;
        };
        let pin = session.pin.clone();
        let for_device = self.selected_device.clone();
        self.spawn_job("Renaming fingerprint\u{2026}", move || {
            let result = Self::with_fresh_bio(&target, &pin, |bio| {
                bio.set_friendly_name(&template_id, &new_name)
                    .map_err(SessionOpError::from_ctap)?;
                bio.enumerate().map_err(SessionOpError::from_ctap)
            });
            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return; // selection changed mid-op; discard the stale completion
                }
                match result {
                    Ok(list) => app.security_keys.fingerprints = Some(list),
                    Err(e) => app.fail_session_op(&e, "rename failed"),
                }
            })
        });
    }

    /// Open the device and run `f` with a [`Configurator`](keyroost_ctap::config::Configurator) holding a fresh
    /// pinUvAuthToken that carries the AuthenticatorConfiguration permission.
    /// Mirrors `with_fresh_bio`; config commands need their own permissioned
    /// token, so they always take a PIN at action time.
    fn with_config<T>(
        target: &FidoTarget,
        pin: &str,
        f: impl FnOnce(
            &mut keyroost_ctap::config::Configurator<
                Box<dyn keyroost_ctap::transport::CtapTransport>,
            >,
        ) -> Result<T, SessionOpError>,
    ) -> Result<T, SessionOpError> {
        let (mut dev, cbor, _init) = open_fido(target).map_err(SessionOpError::msg)?;
        if !cbor {
            return Err(SessionOpError::msg("device is U2F-only"));
        }
        let info = keyroost_ctap::get_info(&mut dev).map_err(SessionOpError::from_ctap)?;
        if info.option("authnrCfg") != Some(true) {
            return Err(SessionOpError::msg(
                "this key does not support authenticatorConfig",
            ));
        }
        let token = keyroost_ctap::client_pin::get_pin_uv_auth_token(
            &mut dev,
            pin,
            &info,
            keyroost_ctap::client_pin::permissions::AUTHENTICATOR_CONFIGURATION,
        )
        .map_err(SessionOpError::from_ctap)?;
        let mut cfg = keyroost_ctap::config::Configurator::new(&mut dev, token, &info)
            .map_err(SessionOpError::from_ctap)?;
        f(&mut cfg)
    }

    /// Dispatch the pending Advanced action on a worker thread, then refresh the
    /// key's info so the view reflects the new state.
    fn run_advanced_action(&mut self) {
        if self.busy() {
            return;
        }
        let Some(dlg) = self.security_keys.advanced.as_ref() else {
            return;
        };
        let action = dlg.action;
        // Zeroizing so the worker closure's PIN copy is scrubbed when the job ends.
        let pin = zeroize::Zeroizing::new(dlg.pin_input.clone());
        let force_change = dlg.force_change;
        let min_pin = dlg.min_pin_input.trim().parse::<u32>().ok();
        let dlg_device = dlg.device.clone();

        // The dialog is bound to the device it opened for (KEY-007): if the
        // selection moved, the typed PIN must not be sent to the new key.
        // Dropping the dialog wipes the PIN (Drop impl).
        if !completion_still_valid(dlg_device.as_ref(), self.selected_device.as_ref()) {
            self.security_keys.advanced = None;
            self.security_keys.error = Some(
                "the selected key changed \u{2014} the settings change was cancelled; \
                 reopen it to retry"
                    .into(),
            );
            return;
        }

        let Some(target) = self.selected_fido_target() else {
            return;
        };

        // Validate inputs before spawning.
        if action == AdvancedAction::SetMinPin && min_pin.is_none() {
            self.security_keys.error = Some("Enter a whole number for the new minimum.".into());
            return;
        }
        if pin.is_empty() {
            self.security_keys.error = Some("Enter the device PIN to apply this change.".into());
            return;
        }

        let label = match action {
            AdvancedAction::ToggleAlwaysUv => "Updating always-UV\u{2026}",
            AdvancedAction::SetMinPin => "Setting minimum PIN length\u{2026}",
            AdvancedAction::ForcePinChange => "Requesting PIN change\u{2026}",
            AdvancedAction::EnterpriseAttestation => "Enabling enterprise attestation\u{2026}",
            AdvancedAction::None => return,
        };
        let for_device = self.selected_device.clone();
        self.spawn_job(label, move || {
            let result = Self::with_config(&target, &pin, |cfg| match action {
                AdvancedAction::ToggleAlwaysUv => {
                    cfg.toggle_always_uv().map_err(SessionOpError::from_ctap)
                }
                AdvancedAction::SetMinPin => cfg
                    .set_min_pin_length(min_pin, &[], force_change)
                    .map_err(SessionOpError::from_ctap),
                AdvancedAction::ForcePinChange => {
                    cfg.force_pin_change().map_err(SessionOpError::from_ctap)
                }
                AdvancedAction::EnterpriseAttestation => cfg
                    .enable_enterprise_attestation()
                    .map_err(SessionOpError::from_ctap),
                AdvancedAction::None => Ok(()),
            });
            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return; // selection changed mid-flight; discard
                }
                match result {
                    Ok(()) => {
                        app.security_keys.advanced = None;
                        app.security_keys.error = None;
                        // Re-read info so alwaysUv / minPinLength reflect the change.
                        app.fetch_selected_info();
                    }
                    Err(e) => {
                        // Drop the dialog on error too (KEY-007): a failed
                        // attempt must not keep the typed PIN alive for a
                        // retry against whatever is selected later.
                        app.security_keys.advanced = None;
                        app.fail_session_op(&e, "config change failed");
                    }
                }
            })
        });
    }

    fn delete_credential(&mut self, cred_id: Vec<u8>) {
        let Some(target) = self.selected_fido_target() else {
            return;
        };
        let Some(session) = self.fido_session() else {
            return;
        };
        let token = session.token.clone();
        // The refresh after delete needs its own token; clone for the chained op.
        let token_refresh = token.clone();
        let pin_refresh = session.pin.clone();
        let for_device = self.selected_device.clone();
        self.spawn_job("Deleting credential\u{2026}", move || {
            // Delete, then re-list in the same job so the UI updates atomically.
            let result = Self::try_delete(&target, token, &cred_id)
                .and_then(|()| Self::refresh_with_token(&target, token_refresh, pin_refresh))
                .map_err(SessionOpError::from_boxed);
            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return; // selection changed mid-delete; drop the refresh
                }
                match result {
                    Ok(fresh) => {
                        app.security_keys.session = Some(fresh);
                        app.security_keys.session_device = for_device.clone();
                        app.security_keys.error = None;
                    }
                    Err(e) => app.fail_session_op(&e, "delete failed"),
                }
            })
        });
    }

    fn try_delete(
        target: &FidoTarget,
        token: PinUvAuthToken,
        cred_id: &[u8],
    ) -> Result<(), Box<dyn std::error::Error>> {
        let (mut dev, _cbor, _init) = open_fido(target)?;
        let info = keyroost_ctap::get_info(&mut dev)?;
        let mut mgr = keyroost_ctap::cred_mgmt::CredentialManager::new(&mut dev, token, &info)?;
        mgr.delete(cred_id)?;
        Ok(())
    }

    /// Extract and save the OpenSSH certificate stored in an SSH credential's
    /// largeBlob. The credential's largeBlob key was captured from the unlocked
    /// session at click time (the GUI already enumerated it), so — unlike the
    /// CLI, which starts cold and rebuilds a CredentialManager to fetch the key —
    /// the job needs no PIN token: reading the world-readable largeBlob array
    /// takes the device but no auth. On success the parsed cert is parked in
    /// `ssh_cert_pending` under this request's id and a save dialog carrying
    /// the same id opens, defaulting to a path-safe `<rp-id>-cert.pub`
    /// filename. PIN only, no touch.
    ///
    /// The largeBlob key is carried `Zeroizing` so the copy moved into the job
    /// (and the one dropped on an early return) doesn't leave 32 bytes of key
    /// material in freed memory — same treatment as the typed PINs.
    fn save_ssh_cert(&mut self, rp_id: String, large_blob_key: zeroize::Zeroizing<[u8; 32]>) {
        let Some(target) = self.selected_fido_target() else {
            self.security_keys.ssh_cert_status = Some("No FIDO key selected.".into());
            return;
        };
        // Device-bound (KEY-012): only run while the unlocked session still
        // matches the current selection.
        if self.fido_session().is_none() {
            return;
        }
        // Pair this request with its dialog up front: a second "Save
        // certificate…" click gets its own id, so whichever dialog the user
        // answers first still writes its own certificate.
        let id = self.ssh_cert_next_id;
        self.ssh_cert_next_id = self.ssh_cert_next_id.wrapping_add(1);
        let for_device = self.selected_device.clone();
        self.spawn_job("Extracting certificate\u{2026}", move || {
            let result = Self::extract_ssh_cert(&target, &large_blob_key);
            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return; // selection changed mid-extract; discard the cert
                }
                match result {
                    Ok(pending) => {
                        app.security_keys.ssh_cert_pending.insert(id, pending);
                        app.security_keys.ssh_cert_status = None;
                        app.spawn_file_dialog(
                            FileTarget::SshCertSave(id),
                            true,
                            &[("SSH certificate", &["pub"]), ("All files", &["*"])],
                            Some(&keyroost_ctap::ssh_cert::default_cert_filename(&rp_id)),
                        );
                    }
                    Err(e) => app.security_keys.ssh_cert_status = Some(e),
                }
            })
        });
    }

    /// Open the device, read its largeBlob array, and decrypt this credential's
    /// certificate entry with `large_blob_key`. Returns the `-cert.pub` text plus
    /// a one-line parsed summary, or a human-readable error.
    fn extract_ssh_cert(
        target: &FidoTarget,
        large_blob_key: &[u8; 32],
    ) -> Result<PendingSshCert, String> {
        let (mut dev, cbor, _init) = open_fido(target)?;
        if !cbor {
            return Err("device is U2F-only; large blobs are not supported".into());
        }
        let info = keyroost_ctap::get_info(&mut dev).map_err(|e| e.to_string())?;
        if info.option("largeBlobs") != Some(true) {
            return Err("this key does not support the FIDO2 large-blob store".into());
        }
        // Read the world-readable array BEFORE any credential-management borrow —
        // matches the CLI's device-ownership ordering (see `enumerate_ssh_credentials`).
        let array = keyroost_ctap::large_blobs::read(&mut dev, &info).map_err(|e| e.to_string())?;
        let wire = keyroost_ctap::large_blobs::extract_cert_from_entries(large_blob_key, &array)
            .ok_or("no certificate is stored for this credential")?;
        let cert_pub = keyroost_ctap::ssh_cert::to_cert_pub(&wire)
            .ok_or("stored blob is not a valid OpenSSH certificate")?;
        // to_cert_pub already parsed the wire, so parse_wire here cannot fail;
        // fall back to a minimal label rather than erroring if it somehow does.
        let summary = keyroost_ctap::ssh_cert::parse_wire(&wire)
            .map(|info| ssh_cert_summary(&info))
            .unwrap_or_else(|| "OpenSSH certificate".to_string());
        Ok(PendingSshCert { cert_pub, summary })
    }

    fn submit_change_pin(&mut self) {
        // Check busy *before* consuming the typed PINs (see try_unlock).
        if self.busy() {
            return;
        }
        let Some(target) = self.selected_fido_target() else {
            return;
        };
        // Zeroizing so the in-use copies (moved into the job, and any dropped on
        // an early return below) don't leave the PIN in freed memory.
        let old = zeroize::Zeroizing::new(std::mem::take(&mut self.security_keys.change_pin.old));
        let new = zeroize::Zeroizing::new(std::mem::take(&mut self.security_keys.change_pin.new));
        let confirm =
            zeroize::Zeroizing::new(std::mem::take(&mut self.security_keys.change_pin.confirm));
        if old.is_empty() || new.is_empty() {
            self.security_keys.error = Some("both PIN fields are required".into());
            return;
        }
        // Same validation as set-PIN: catch a mistyped new PIN before it's
        // committed to the device (a typo here can lock the key — #79).
        if new.chars().count() < 4 {
            self.security_keys.error = Some("PIN must be at least 4 characters".into());
            return;
        }
        if *new != *confirm {
            self.security_keys.error = Some("the two PINs don't match".into());
            return;
        }
        self.spawn_job("Changing PIN\u{2026}", move || {
            let result = Self::try_change_pin(&target, &old, &new).map_err(|e| e.to_string());
            Box::new(move |app: &mut App| match result {
                Ok(()) => {
                    app.security_keys.change_pin.open = false;
                    app.security_keys.error = None;
                    // Force re-unlock with the new PIN.
                    app.lock_session();
                }
                Err(e) => app.security_keys.error = Some(format!("change PIN failed: {}", e)),
            })
        });
    }

    fn try_change_pin(
        target: &FidoTarget,
        old: &str,
        new: &str,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let (mut dev, _cbor, _init) = open_fido(target)?;
        keyroost_ctap::client_pin::change_pin(&mut dev, old, new)?;
        Ok(())
    }

    /// Set a first-time PIN on a key that has none (CTAP setPIN). Validates that
    /// the two entries match and meet the 4-char minimum, then re-reads info so
    /// the status flips to "PIN set".
    fn submit_set_pin(&mut self) {
        // Check busy *before* consuming the typed PINs (see try_unlock).
        if self.busy() {
            return;
        }
        let Some(target) = self.selected_fido_target() else {
            return;
        };
        let new = zeroize::Zeroizing::new(std::mem::take(&mut self.security_keys.change_pin.new));
        let confirm =
            zeroize::Zeroizing::new(std::mem::take(&mut self.security_keys.change_pin.confirm));
        if new.chars().count() < 4 {
            self.security_keys.error = Some("PIN must be at least 4 characters".into());
            return;
        }
        if *new != *confirm {
            self.security_keys.error = Some("the two PINs don't match".into());
            return;
        }
        self.spawn_job("Setting PIN\u{2026}", move || {
            let result = (|| -> Result<(), String> {
                let (mut dev, _cbor, _init) = open_fido(&target)?;
                keyroost_ctap::client_pin::set_pin(&mut dev, &new).map_err(|e| e.to_string())
            })();
            Box::new(move |app: &mut App| match result {
                Ok(()) => {
                    app.security_keys.change_pin = ChangePinDialog::default();
                    app.security_keys.error = None;
                    app.fetch_selected_info();
                }
                Err(e) => app.security_keys.error = Some(format!("set PIN failed: {e}")),
            })
        });
    }

    /// The transport descriptor for the selected FIDO key: a USB-HID path, or a
    /// PC/SC reader name (NFC or contact). Prefers HID when both are present (a
    /// USB key that also exposes a CCID interface).
    fn selected_fido_target(&self) -> Option<FidoTarget> {
        let d = self.selected_device()?;
        if let Some(p) = d.hid_path.clone() {
            return Some(FidoTarget::Hid(p));
        }
        if d.caps.has(Caps::FIDO2) {
            if let Some(r) = d.reader.clone() {
                return Some(FidoTarget::Pcsc(r));
            }
        }
        None
    }

    /// The selected key's USB-HID path, if any. Used only by the armed-reset
    /// hotplug tracker, which watches for a USB key being unplugged and
    /// replugged within the reset window — a USB-only concept (an NFC tap has no
    /// replug), so this intentionally returns `None` for reader-attached keys.
    fn selected_fido_hid_path(&self) -> Option<std::path::PathBuf> {
        self.selected_device().and_then(|d| d.hid_path.clone())
    }

    /// The reader to run an in-place card reset against — `Some` only for a
    /// FIDO2 device that is a card in a PC/SC reader with no USB-HID interface.
    ///
    /// The replug ceremony cannot work for such a device: there is nothing to
    /// unplug, no touch surface, and the arm's removal detector keys on a HID
    /// path the device does not have, so before this route existed the dialog
    /// simply polled forever (issue #84). A card gets the equivalent another
    /// way — PC/SC power-cycles it in the reader, which starts the same
    /// post-power-up window `authenticatorReset` must land in.
    ///
    /// A USB key that *also* exposes a CCID reader returns `None`: it has a
    /// real replug, and that ceremony's proof-of-possession is stronger than
    /// an in-place cycle, so it must not be bypassed just because a reader
    /// name is available.
    fn card_reset_reader(dev: Option<&keyroost_resolve::Device>) -> Option<String> {
        let d = dev?;
        if d.hid_path.is_none() && d.caps.has(Caps::FIDO2) {
            d.reader.clone()
        } else {
            None
        }
    }

    /// Fold a finished FIDO reset into the app, bound to the key the reset was
    /// dispatched for. Lifted out of `submit_reset_path`'s apply closure so the
    /// device-binding rule is exercisable without a key in hand; the guard is
    /// this function's first statement, which is what the closure's convention
    /// (see [`completion_still_valid`]) asks for.
    ///
    /// `for_device` is the selection at dispatch. The factory-reset report is
    /// app-global state that `on_device_selected` re-points at whatever key is
    /// selected now, so an unbound write paints one key's wipe under another
    /// key's name — the worst possible lie for this pane. A completion that
    /// outlives its selection is dropped, and said out loud in the log: the
    /// wipe did happen, and no report on screen can honestly show it.
    fn apply_reset_path_outcome(
        app: &mut App,
        for_device: Option<&DeviceId>,
        result: Result<(), String>,
    ) {
        if !completion_still_valid(for_device, app.selected_device.as_ref()) {
            // Selection changed mid-reset; don't paint A's outcome under B.
            let note = match &result {
                Ok(()) => "a security key finished its FIDO2 reset after the selection moved on \
                           \u{2014} its passkeys and PIN are wiped. The report on screen belongs \
                           to the key selected now, so it does not show that wipe."
                    .to_string(),
                Err(e) => format!(
                    "a security key's FIDO2 reset failed after the selection moved on \
                     \u{2014} its passkeys and PIN are still on it: {e}"
                ),
            };
            app.log(Severity::Warn, note);
            return;
        }
        match result {
            Ok(()) => {
                app.security_keys.session = None;
                app.security_keys.info = None;
                app.security_keys.error = None;
                // When this reset was a factory reset's finale, record it —
                // the Overview report is where the user is looking, and the
                // activity log, where the permanent record lives.
                let outcome = keyroost_resolve::StepOutcome::Wiped;
                if resolve_fido_reset_row(&mut app.factory_reset_report, outcome.clone()) {
                    let (severity, line) = factory_reset_fido_finale_log_line(&outcome);
                    app.log(severity, line);
                }
                // Re-read info so the PIN status reflects the wipe.
                app.fetch_selected_info();
            }
            Err(e) => {
                let msg = if e.contains("NOT_ALLOWED") || e.contains("0x30") {
                    "This key refused the reset. Most security keys (YubiKey \
                     included) only allow a FIDO reset within about 10 seconds \
                     of being plugged in. Unplug the key, plug it back in, then \
                     click \u{201C}Reset key\u{201D} again right away."
                        .to_string()
                } else {
                    format!("reset failed: {e}")
                };
                // `security_keys.error` is painted only in the FIDO2 and PIN
                // panes; a factory reset leaves the user on Overview, so the
                // failure has to land in the report too or the wipe looks
                // complete when the passkeys and PIN survived — and in the
                // activity log, so the permanent record doesn't stop at
                // whatever the card sweep alone finished with.
                let outcome = keyroost_resolve::StepOutcome::Failed(msg.clone());
                if resolve_fido_reset_row(&mut app.factory_reset_report, outcome.clone()) {
                    let (severity, line) = factory_reset_fido_finale_log_line(&outcome);
                    app.log(severity, line);
                }
                app.security_keys.error = Some(msg);
            }
        }
    }

    /// Wipe the FIDO key at `path` (authenticatorReset). Runs on the worker
    /// thread — the card needs a touch within ~30s, which the worker keeps off
    /// the UI frame. Used by the armed-reset flow, which targets the
    /// just-reconnected key rather than the (now stale) selection. On success
    /// the cached session and CTAP info are cleared.
    fn submit_reset_path(&mut self, path: std::path::PathBuf) -> bool {
        // The ceremony is device-bound like every other dispatcher: the key
        // being wiped is the one selected when the arm was set (selecting
        // another key disarms), and the outcome may only be written under that
        // selection.
        let for_device = self.selected_device.clone();
        self.spawn_job("Resetting key\u{2026} (touch now)", move || {
            let result = (|| -> Result<(), String> {
                // A just-replugged node (especially on a fresh port) can take a
                // moment to accept opens; retry briefly before giving up.
                let mut dev = None;
                for attempt in 0..10 {
                    match CtapHidDevice::open(&path) {
                        Ok((d, _)) => {
                            dev = Some(d);
                            break;
                        }
                        Err(e) if attempt == 9 => return Err(e.to_string()),
                        Err(_) => std::thread::sleep(std::time::Duration::from_millis(100)),
                    }
                }
                let mut dev = dev.ok_or_else(|| "could not open key".to_string())?;
                // Names read from keys before or during the write are stale.
                keyroost_resolve::with_key_names_forgotten(|| keyroost_ctap::reset(&mut dev))
                    .map_err(|e| e.to_string())
            })();
            Box::new(move |app: &mut App| {
                App::apply_reset_path_outcome(app, for_device.as_ref(), result)
            })
        })
    }

    /// Wipe the FIDO applet of a card sitting in `reader` (authenticatorReset,
    /// in place). The card analogue of [`Self::submit_reset_path`]: PC/SC
    /// power-cycles the card, which starts the post-power-up window the reset
    /// must land in, and the wipe is sent the moment the applet answers — no
    /// replug, no touch. Outcome lands through the same completion handler as
    /// the replug flow, so the factory-reset report and the FIDO2 pane both
    /// hear about it.
    fn submit_card_reset(&mut self, reader: String) -> bool {
        let for_device = self.selected_device.clone();
        self.spawn_job("Resetting card\u{2026}", move || {
            let result = (|| -> Result<(), String> {
                let mut dev = keyroost_transport::CtapPcscDevice::open_after_power_cycle(&reader)
                    .map_err(|e| e.to_string())?;
                // Names read from keys before or during the write are stale.
                keyroost_resolve::with_key_names_forgotten(|| keyroost_ctap::reset(&mut dev))
                    .map_err(|e| {
                        let s = e.to_string();
                        // Rewrite the refusal here, not in the shared handler: its
                        // NOT_ALLOWED advice ("unplug the key, plug it back in")
                        // is USB advice, and following it would eject the card
                        // for nothing.
                        if s.contains("NOT_ALLOWED") || s.contains("0x30") {
                            "the card refused the reset even straight after a power \
                         cycle. Some cards only accept a FIDO reset over NFC \
                         (contactless) rather than a contact reader \u{2014} \
                         try a contactless reader or the vendor's mobile app."
                                .to_string()
                        } else {
                            s
                        }
                    })
            })();
            Box::new(move |app: &mut App| {
                App::apply_reset_path_outcome(app, for_device.as_ref(), result)
            })
        })
    }

    fn selected_oath_reader(&self) -> Option<String> {
        self.selected_device().and_then(|d| d.reader.clone())
    }

    /// Off-thread helper: open `name` and unlock with `password` if protected.
    fn oath_open_unlock(
        name: &str,
        password: &str,
    ) -> Result<keyroost_transport::OathSession, TransportError> {
        let mut session = keyroost_transport::OathSession::open(name)?;
        if session.password_required() {
            session.unlock(password)?;
        }
        Ok(session)
    }

    /// Off-thread helper: list credentials and compute each current TOTP. Also
    /// returns how many undecodable entries the card holds (partial listing).
    fn oath_list_rows(
        session: &mut keyroost_transport::OathSession,
    ) -> Result<(Vec<OathRow>, usize), TransportError> {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        let listing = session.list()?;
        let mut rows = Vec::new();
        for c in listing.credentials {
            let hotp = matches!(c.oath_type, keyroost_oath::OathType::Hotp);
            // HOTP codes are never computed during a listing: the card
            // advances the credential's counter on every CALCULATE (the time
            // challenge is ignored), so a passive refresh would silently walk
            // the card out of the server's look-ahead window. The row shows a
            // "Read code" button instead.
            let mut row = OathRow::new(c.name, None, hotp);
            if !hotp {
                // A touch-required credential blocks until touched; fine off-thread.
                row.code = session
                    .calculate_totp(&row.name, now, row.period)
                    .ok()
                    .map(|otp| otp.code);
            }
            rows.push(row);
        }
        // Group without headers: live TOTP codes first, on-demand HOTP rows
        // after (stable — card order preserved within each group).
        rows.sort_by_key(|r| r.hotp);
        Ok((rows, listing.skipped))
    }

    /// Compute one HOTP code on explicit request and patch it into the row.
    /// Deliberately not part of the listing: each computation advances the
    /// card's counter.
    fn read_hotp_code(&mut self, name: &str) {
        self.oath.error = None;
        let Some(reader) = self.selected_oath_reader() else {
            self.oath.error = Some("no OATH key selected".into());
            return;
        };
        let cred = name.to_owned();
        // The listing already consumed (wiped) password_input, so this read
        // sends the retained accepted password — an empty string here could
        // never unlock a protected applet and re-locked the pane every time.
        let password = oath_effective_password(&self.oath);
        let for_device = self.selected_device.clone();
        self.spawn_job("Reading code\u{2026}", move || {
            let result = (|| -> Result<String, TransportError> {
                let mut session = Self::oath_open_unlock(&reader, &password)?;
                Ok(session.calculate_hotp(&cred)?.code)
            })();
            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return; // selection changed mid-read; discard
                }
                // The typed password is consumed whatever the outcome (mirrors
                // apply_oath_rows).
                wipe(&mut app.oath.password_input);
                match result {
                    Ok(code) => {
                        // This password worked (or none was needed): retain it,
                        // like a successful listing does.
                        app.oath.unlocked_password = Some(password);
                        if let Some(row) = app.oath.creds.iter_mut().find(|r| r.name == cred) {
                            row.code = Some(code);
                        }
                    }
                    Err(TransportError::OathPasswordRejected) => {
                        app.oath.unlocked_password = None;
                        app.oath.locked = true;
                        app.oath.error = Some("wrong OATH password".into());
                    }
                    Err(e) => app.oath.error = Some(e.to_string()),
                }
            })
        });
    }

    /// Store the outcome of an op that ends by (re)listing credentials.
    /// `password` is the password the op sent: on success it is retained in
    /// `unlocked_password` for later on-demand reads (HOTP "Read code" runs
    /// long after `password_input` was consumed); on a rejected password the
    /// retained copy is dropped too.
    fn apply_oath_rows(
        app: &mut App,
        result: Result<(Vec<OathRow>, usize), TransportError>,
        password: zeroize::Zeroizing<String>,
    ) {
        // The typed password is consumed whatever the outcome — success,
        // wrong-password, or a transport error must not leave it buffered for
        // an automatic retry against (potentially) a different key.
        wipe(&mut app.oath.password_input);
        // Mirror the outcome into the add modal when one is in flight (the
        // provision op routes through here), so success/error shows *in* the
        // dialog (issue #31) rather than only as a pane-level error line.
        let modal_busy = app.oath.add.open && app.oath.add.busy;
        match &result {
            Ok(_) if modal_busy => app.oath.add.result = Some(Ok(())),
            Err(TransportError::OathPasswordRejected) if modal_busy => {
                app.oath.add.result = Some(Err("wrong OATH password".into()));
            }
            Err(e) if modal_busy => app.oath.add.result = Some(Err(e.to_string())),
            _ => {}
        }
        if app.oath.add.open {
            app.oath.add.busy = false;
        }
        match result {
            Ok((rows, skipped)) => {
                // The applet accepted this password (or needed none): retain
                // it for on-demand reads against the same selection.
                app.oath.unlocked_password = Some(password);
                app.oath.creds = rows;
                app.oath.skipped = skipped;
                app.oath.loaded = true;
                app.oath.locked = false;
            }
            Err(TransportError::OathPasswordRejected) => {
                app.oath.unlocked_password = None;
                app.oath.locked = true;
                // The add modal already shows this; don't double-report when it
                // is the one that failed.
                if !modal_busy {
                    app.oath.error = Some("wrong OATH password".into());
                }
            }
            Err(e) => {
                // A transport error says nothing about the password; keep any
                // retained copy so a transient failure doesn't force a retype.
                if !modal_busy {
                    app.oath.error = Some(e.to_string());
                }
            }
        }
    }

    /// List credentials on the selected key, computing each current TOTP. Unlocks
    /// first with the entered password when the applet is protected.
    fn load_oath_creds(&mut self) {
        self.oath.error = None;
        let Some(name) = self.selected_oath_reader() else {
            self.oath.error = Some("no OATH key selected".into());
            return;
        };
        let password = oath_effective_password(&self.oath);
        let for_device = self.selected_device.clone();
        self.spawn_job("Reading OATH codes\u{2026}", move || {
            let result = Self::oath_open_unlock(&name, &password)
                .and_then(|mut session| Self::oath_list_rows(&mut session));
            Box::new(move |app: &mut App| {
                // Discard if the user switched devices while the read (which
                // can block on a touch) was in flight — device B's pane must
                // not show device A's codes.
                if completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    Self::apply_oath_rows(app, result, password);
                }
            })
        });
    }

    /// Provision the credential described by the add-dialog fields.
    fn provision_oath(&mut self) {
        self.oath.error = None;
        let Some(name) = self.selected_oath_reader() else {
            self.oath.error = Some("no OATH key selected".into());
            return;
        };
        // Validate before dispatch; the modal surfaces the reason on failure.
        let family = self
            .selected_device()
            .map_or(keyroost_import::plan::OathFamily::Other, |d| {
                keyroost_import::plan::OathFamily::from_vendor(&d.vendor, None)
            });
        let (cred_name, secret) = match self.oath.add.validate(family) {
            Ok((n, s)) => (n, zeroize::Zeroizing::new(s)),
            Err(e) => {
                self.oath.error = Some(e);
                return;
            }
        };
        let oath_type = if self.oath.add.totp {
            keyroost_oath::OathType::Totp
        } else {
            keyroost_oath::OathType::Hotp
        };
        let require_touch = self.oath.add.require_touch;
        let password = oath_effective_password(&self.oath);
        // The form stays open showing the spinner; it is wiped/closed on the
        // modal's Done (success) or Cancel/✕/Esc. Do not reset it here.
        let for_device = self.selected_device.clone();
        let vendor = self
            .selected_device()
            .map(|d| d.vendor.clone())
            .unwrap_or_default();
        self.spawn_job("Adding credential\u{2026}", move || {
            // Set when YubiKey 4 firmware 4.0–4.3.4 must not get this name
            // (the same check as `oath add` and the import plan).
            let mut refused: Option<String> = None;
            let result = (|| -> Result<(Vec<OathRow>, usize), TransportError> {
                let mut session = Self::oath_open_unlock(&name, &password)?;
                let family =
                    keyroost_import::plan::OathFamily::from_vendor(&vendor, session.version());
                if family.prefix_issue() {
                    let listing = session.list()?;
                    refused = family.prefix_refusal(
                        &cred_name,
                        listing.credentials.iter().map(|c| c.name.as_str()),
                    );
                    if refused.is_some() {
                        // Nothing sent; the list is refreshed as usual.
                        return Self::oath_list_rows(&mut session);
                    }
                }
                session.put(&keyroost_oath::PutParams {
                    name: &cred_name,
                    secret: &secret,
                    oath_type,
                    algorithm: keyroost_oath::Algorithm::Sha1,
                    digits: 6,
                    require_touch,
                    imf: 0,
                })?;
                Self::oath_list_rows(&mut session)
            })();
            Box::new(move |app: &mut App| {
                if completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    Self::apply_oath_rows(app, result, password);
                    if let Some(why) = refused.filter(|_| app.oath.add.open) {
                        app.oath.add.result = Some(Err(why));
                    }
                }
            })
        });
    }

    /// Delete the named credential (already confirmed).
    fn delete_oath(&mut self, name: &str) {
        self.oath.error = None;
        let Some(reader) = self.selected_oath_reader() else {
            self.oath.error = Some("no OATH key selected".into());
            return;
        };
        let cred_name = name.to_owned();
        let password = oath_effective_password(&self.oath);
        let for_device = self.selected_device.clone();
        self.spawn_job("Deleting credential\u{2026}", move || {
            let result = (|| -> Result<(Vec<OathRow>, usize), TransportError> {
                let mut session = Self::oath_open_unlock(&reader, &password)?;
                session.delete(&cred_name)?;
                Self::oath_list_rows(&mut session)
            })();
            Box::new(move |app: &mut App| {
                if completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    Self::apply_oath_rows(app, result, password);
                }
            })
        });
    }

    /// Close the "Add credential" modal, wiping the typed secret. (`OathAddDialog`
    /// also wipes on drop; the explicit reset here makes the close-path intent
    /// clear and mirrors the PIV/OpenPGP `*_cred_modal_close` helpers.)
    fn oath_add_modal_close(&mut self) {
        wipe(&mut self.oath.add.secret);
        self.oath.add = OathAddDialog::default();
    }

    /// Centered "New credential" modal: the name + base32 **secret** + type/touch
    /// fields live *inside* the shared `modal_window` chrome (not inline in the
    /// pane), so the secret entry and its result stay on-screen — matching the
    /// PIV/OpenPGP credential modals (issue #31). Submit dispatches the unchanged
    /// `provision_oath`; the outcome is mirrored back via `apply_oath_rows`. The
    /// secret is wiped on Done/Cancel/✕/Esc.
    fn render_oath_add_modal(&mut self, ctx: &egui::Context, p: &Palette) {
        if !self.oath.add.open {
            return;
        }
        let busy = self.oath.add.busy;
        let result = self.oath.add.result.clone();

        let mut want_submit = false;
        let mut want_close = false;

        let closed = Self::modal_window(ctx, p, "oath_add", "New credential", 300.0, |ui| {
            match &result {
                Some(Ok(())) => {
                    // Success: confirmation + a single Done that dismisses.
                    ui.label(
                        egui::RichText::new("\u{2713} Credential added")
                            .font(theme::f_sb(13.0))
                            .color(p.ok),
                    );
                    ui.add_space(16.0);
                    if theme::button(ui, p, BtnKind::Primary, "Done").clicked() {
                        want_close = true;
                    }
                }
                _ => {
                    // Entry form (also the path while busy / after an error so the
                    // user can retry without losing the dialog).
                    ui.horizontal(|ui| {
                        ui.add_sized(
                            [96.0, 22.0],
                            egui::Label::new(
                                egui::RichText::new("Name")
                                    .font(theme::f_reg(13.0))
                                    .color(p.txt2),
                            ),
                        );
                        ui.add(
                            egui::TextEdit::singleline(&mut self.oath.add.name)
                                .hint_text("issuer:account")
                                .desired_width(300.0),
                        );
                    });
                    ui.add_space(4.0);
                    secret_field(
                        ui,
                        p,
                        "Secret",
                        &mut self.oath.add.secret,
                        "base32 (behind the QR code)",
                        96.0,
                        300.0,
                    );
                    #[cfg(feature = "qr")]
                    {
                        ui.add_space(4.0);
                        ui.horizontal(|ui| {
                            ui.add_space(100.0);
                            if scan_qr_button(ui, p) {
                                self.oath_scan_qr();
                            }
                        });
                    }
                    ui.horizontal(|ui| {
                        ui.add_sized(
                            [96.0, 22.0],
                            egui::Label::new(
                                egui::RichText::new("Type")
                                    .font(theme::f_reg(13.0))
                                    .color(p.txt2),
                            ),
                        );
                        ui.selectable_value(&mut self.oath.add.totp, true, "TOTP");
                        ui.selectable_value(&mut self.oath.add.totp, false, "HOTP");
                    });
                    ui.add_space(4.0);
                    ui.checkbox(&mut self.oath.add.require_touch, "Require touch");
                    card_note(
                        ui,
                        p,
                        "The secret is sent to the key, not written to disk by keyroost.",
                    );

                    if let Some(Err(e)) = &result {
                        ui.add_space(6.0);
                        ui.colored_label(p.err, e);
                    }

                    ui.add_space(16.0);
                    ui.horizontal(|ui| {
                        if busy {
                            ui.add(egui::Spinner::new());
                            ui.label(
                                egui::RichText::new("Adding credential\u{2026}")
                                    .font(theme::f_reg(12.5))
                                    .color(p.txt2),
                            );
                        } else {
                            if theme::button(ui, p, BtnKind::Primary, "Add").clicked() {
                                want_submit = true;
                            }
                            ui.add_space(8.0);
                            if theme::button(ui, p, BtnKind::Default, "Cancel").clicked() {
                                want_close = true;
                            }
                        }
                    });
                }
            }
        });

        // ✕ / Esc / Cancel dismiss too, but never yank the dialog out from under
        // a running op (mirrors the PIV/OpenPGP modals' busy handling).
        if (closed || want_close) && !busy {
            self.oath_add_modal_close();
            return;
        }
        if want_submit && !busy {
            // Mark busy first so the modal shows the spinner this frame; the op
            // writes the outcome back via `apply_oath_rows`.
            self.oath.add.busy = true;
            self.oath.add.result = None;
            self.oath.error = None;
            self.provision_oath();
            // If the op didn't actually queue — the worker was busy (no error
            // set; retry on the next click) or a client-side guard rejected the
            // input and stored the reason in `oath.error` — unstick the modal and
            // surface the guard reason in the dialog rather than the pane.
            if !self.busy() {
                let guard_err = self.oath.error.take();
                self.oath.add.busy = false;
                if let Some(e) = guard_err {
                    self.oath.add.result = Some(Err(e));
                }
            }
        }
    }

    /// Modal confirmation before deleting a credential (irreversible). Bound
    /// to the device it was opened for: if the selection has moved the
    /// confirmation is dropped instead of rendered, and the dispatch is
    /// re-checked, so `delete_oath` can never open a different reader than
    /// the one the user confirmed against (KEY-008).
    fn render_oath_delete_confirm(&mut self, ctx: &egui::Context) {
        let Some((for_device, name)) = self.oath.confirm_delete.clone() else {
            return;
        };
        if !completion_still_valid(Some(&for_device), self.selected_device.as_ref()) {
            self.oath.confirm_delete = None;
            return;
        }
        let mut decision: Option<bool> = None;
        egui::Window::new("Delete credential?")
            .collapsible(false)
            .resizable(false)
            .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
            .show(ctx, |ui| {
                ui.label(format!(
                    "Permanently delete \u{201c}{name}\u{201d} from this key? \
                     This cannot be undone."
                ));
                ui.add_space(6.0);
                ui.horizontal(|ui| {
                    if ui.button("Delete").clicked() {
                        decision = Some(true);
                    }
                    if ui.button("Cancel").clicked() {
                        decision = Some(false);
                    }
                });
            });
        match decision {
            Some(true) => {
                self.oath.confirm_delete = None;
                self.delete_oath(&name);
            }
            Some(false) => self.oath.confirm_delete = None,
            None => {}
        }
    }

    /// Modal confirmation before factory-resetting the OATH applet. Same
    /// device binding as the delete confirmation (KEY-008): a stale
    /// confirmation is dropped, never rendered over the new selection.
    fn render_oath_reset_confirm(&mut self, ctx: &egui::Context) {
        let Some(for_device) = self.oath.confirm_reset.clone() else {
            return;
        };
        if !completion_still_valid(Some(&for_device), self.selected_device.as_ref()) {
            self.oath.confirm_reset = None;
            return;
        }
        let mut decision: Option<bool> = None;
        egui::Window::new("Reset OATH applet?")
            .collapsible(false)
            .resizable(false)
            .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
            .show(ctx, |ui| {
                ui.label(
                    "Permanently wipe EVERY authenticator credential on this key \
                     and clear its password? This cannot be undone.",
                );
                ui.add_space(6.0);
                ui.horizontal(|ui| {
                    if ui.button("Reset applet").clicked() {
                        decision = Some(true);
                    }
                    if ui.button("Cancel").clicked() {
                        decision = Some(false);
                    }
                });
            });
        match decision {
            Some(true) => {
                self.oath.confirm_reset = None;
                self.reset_oath_applet();
            }
            Some(false) => self.oath.confirm_reset = None,
            None => {}
        }
    }

    /// Factory-reset the OATH applet on the selected key. Opens WITHOUT
    /// unlocking — the applet's RESET requires no password (it is the
    /// recovery path for a forgotten one) — then rebuilds the pane state
    /// from scratch, which now shows an empty, unprotected applet.
    fn reset_oath_applet(&mut self) {
        self.oath.error = None;
        let Some(reader) = self.selected_oath_reader() else {
            self.oath.error = Some("no OATH key selected".into());
            return;
        };
        let for_device = self.selected_device.clone();
        self.spawn_job("Resetting OATH applet\u{2026}", move || {
            let result = (|| -> Result<(), TransportError> {
                let mut session = keyroost_transport::OathSession::open(&reader)?;
                session.factory_reset()
            })();
            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return;
                }
                match result {
                    Ok(()) => {
                        // Fresh state: the applet is now empty and unprotected;
                        // clearing oath_tried lets the pane re-list on its own.
                        app.oath = OathState::default();
                        app.oath_tried = false;
                    }
                    Err(e) => app.oath.error = Some(format!("reset failed: {e}")),
                }
            })
        });
    }

    /// The "Factory reset…" button's click handler: arms the confirm dialog
    /// for the selected device, but if its plan includes a PIV step,
    /// fingerprints PIV on the worker first — both `PivResetPreview`
    /// (`PivSession::preview_factory_reset` — read-only, no PIN/PUK attempt;
    /// tells the confirm dialog exactly which mechanism `factory_reset` will
    /// run, or that neither is available) and whether that mechanism needs a
    /// credential (`PivSession::global_reset_available`) — so the dialog's
    /// text can say exactly what will happen (or be skipped) instead of
    /// hedging across every possibility before the fact, and so it knows
    /// whether to show the credential prompt at all. Same verdict
    /// `PivSession::factory_reset` resolves again when the reset actually runs
    /// — see `FactoryResetPivPreview`'s doc for why that's a deliberate,
    /// cheap re-check rather than reused state (`needs_reset_mgmt_auth` itself,
    /// unlike `piv_preview`, IS carried forward into `run_factory_reset_gui`
    /// rather than re-fingerprinted — see that method's doc for why the two
    /// differ).
    ///
    /// A device with no PIV step arms immediately. A device with one arms
    /// only once the fingerprint job completes; a click while a job is
    /// already in flight silently drops (the button can simply be pressed
    /// again) — nothing user-typed is at stake here, unlike the callers
    /// `spawn_job`'s own doc warns about.
    fn start_factory_reset_confirm(&mut self) {
        let Some(dev) = self.selected_device().cloned() else {
            return;
        };
        self.factory_reset_confirm_typed.clear();
        let plan = keyroost_resolve::factory_reset_plan(dev.caps);
        if !plan.contains(&keyroost_resolve::ResetStep::Piv) {
            self.factory_reset_confirm = Some(FactoryResetConfirmState {
                for_device: dev.id,
                piv_preview: FactoryResetPivPreview::NotOffered,
                needs_reset_mgmt_auth: false,
                default_mgmt_key: None,
                reset_long_running: false,
            });
            return;
        }
        let Some(reader) = dev.reader.clone() else {
            // `Caps::PIV` says PIV should be reachable, but there's no PC/SC
            // reader to fingerprint it over (shouldn't happen in practice) —
            // arm with the same fallback wording an outright fingerprint
            // failure gets rather than get stuck offering nothing.
            self.factory_reset_confirm = Some(FactoryResetConfirmState {
                for_device: dev.id,
                piv_preview: FactoryResetPivPreview::CheckFailed,
                needs_reset_mgmt_auth: false,
                default_mgmt_key: None,
                reset_long_running: false,
            });
            return;
        };
        let for_device = dev.id;
        self.spawn_job("Checking PIV reset support\u{2026}", move || {
            let (preview, needs_reset_mgmt_auth, default_mgmt_key, reset_long_running) =
                keyroost_transport::PivSession::with_transaction(&reader, |s| {
                    // One fingerprint serves all four checks — see
                    // `PivSession::preview_factory_reset`/
                    // `global_reset_available`/`default_management_key`/
                    // `quirks`'s docs.
                    let preview = FactoryResetPivPreview::Resolved(s.preview_factory_reset());
                    Ok::<_, TransportError>((
                        preview,
                        s.global_reset_available(),
                        s.default_management_key(),
                        s.quirks()
                            .contains(&keyroost_piv::compat::PivQuirk::ResetLongRunning),
                    ))
                })
                .unwrap_or((
                    FactoryResetPivPreview::CheckFailed,
                    false,
                    None,
                    false,
                ));
            Box::new(move |app: &mut App| {
                if !completion_still_valid(Some(&for_device), app.selected_device.as_ref()) {
                    return;
                }
                app.factory_reset_confirm = Some(FactoryResetConfirmState {
                    for_device,
                    piv_preview: preview,
                    needs_reset_mgmt_auth,
                    default_mgmt_key,
                    reset_long_running,
                });
            })
        });
    }

    /// Confirm modal for the whole-device factory reset. Device-bound like
    /// `render_oath_reset_confirm`: it dies the instant the selection changes,
    /// so a confirmed wipe can only ever land on the key it was opened for
    /// (KEY-008). "Yes, wipe this key" starts the sequential reset job.
    fn render_factory_reset_confirm(&mut self, ctx: &egui::Context, p: &Palette) {
        let Some(FactoryResetConfirmState {
            for_device,
            piv_preview,
            needs_reset_mgmt_auth,
            default_mgmt_key,
            reset_long_running,
        }) = self.factory_reset_confirm.clone()
        else {
            return;
        };
        if !completion_still_valid(Some(&for_device), self.selected_device.as_ref()) {
            self.factory_reset_confirm = None;
            self.factory_reset_confirm_error = None;
            self.factory_reset_confirm_typed.clear();
            return;
        }
        let summary = match self.selected_device() {
            Some(dev) => {
                let mut plan = keyroost_resolve::factory_reset_plan(dev.caps);
                if factory_reset_piv_unresettable(piv_preview) {
                    keyroost_resolve::exclude_unresettable_piv(&mut plan);
                }
                factory_reset_confirm_summary(
                    &dev.serial,
                    &dev.model,
                    &plan,
                    piv_preview,
                    needs_reset_mgmt_auth,
                    reset_long_running,
                )
            }
            None => {
                self.factory_reset_confirm = None;
                self.factory_reset_confirm_error = None;
                self.factory_reset_confirm_typed.clear();
                return;
            }
        };
        let mut decision: Option<bool> = None;
        egui::Window::new("Factory reset this key?")
            .collapsible(false)
            .resizable(false)
            .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
            .show(ctx, |ui| {
                ui.label(summary);
                if needs_reset_mgmt_auth {
                    ui.add_space(8.0);
                    self.factory_reset_mgmt_auth_field(ui, p, default_mgmt_key);
                }
                if let Some(err) = &self.factory_reset_confirm_error {
                    ui.add_space(6.0);
                    ui.colored_label(p.err, err);
                }
                ui.add_space(8.0);
                ui.horizontal(|ui| {
                    ui.label("Type \u{201c}reset\u{201d} to confirm:");
                    ui.add(
                        egui::TextEdit::singleline(&mut self.factory_reset_confirm_typed)
                            .desired_width(120.0),
                    );
                });
                ui.add_space(8.0);
                let armed = self.factory_reset_confirm_typed.trim() == "reset";
                ui.horizontal(|ui| {
                    ui.add_enabled_ui(armed, |ui| {
                        if theme::button(ui, p, BtnKind::Danger, "Yes, wipe this key").clicked() {
                            decision = Some(true);
                        }
                    });
                    if ui.button("Cancel").clicked() {
                        decision = Some(false);
                    }
                });
            });
        match decision {
            Some(true) => {
                if self.run_factory_reset_gui() {
                    self.factory_reset_confirm = None;
                    self.factory_reset_confirm_error = None;
                    self.factory_reset_confirm_typed.clear();
                }
                // else: either a job is already in flight, or the entered
                // credential didn't validate (`factory_reset_confirm_error`
                // is now set) — either way keep the modal open so the
                // confirmed wipe isn't silently swallowed; the user can fix
                // the input or retry once the worker clears.
            }
            Some(false) => {
                self.factory_reset_confirm = None;
                self.factory_reset_confirm_error = None;
                self.factory_reset_confirm_typed.clear();
                wipe(&mut self.reset_mgmt_auth_input);
            }
            None => {}
        }
    }

    /// The factory-reset confirm dialog's management-auth credential prompt,
    /// shown whenever `FactoryResetConfirmState::needs_reset_mgmt_auth` is true —
    /// i.e. whenever `PivQuirk::ResetNeedsManagementAuth` applies.
    /// `PivSession::factory_reset` decides on its own, from the live
    /// fingerprint, which mechanism actually authenticates with what's typed
    /// here: HID Crescendo's ACA instance (today's only real consumer) or,
    /// on a fingerprint whose credential need is `PivExtension::Reset`
    /// alone, the standard PIV management-key round
    /// (`PivSession::authenticate_management_current`) — either way the same
    /// field, resolved into the same `keyroost_transport::CurrentMgmtAuth`.
    /// Same toggle-plus-field shape and wording as `App::piv_modal_mgmt_field`
    /// — "Use default management key" / "Use PIN" checkboxes, each a pure
    /// view onto (and setter of) `reset_mgmt_auth_mode`, plus the typed field
    /// underneath when neither is ticked or "Use PIN" is. `default_key` is
    /// `FactoryResetConfirmState::default_mgmt_key`, resolved for this
    /// device by the same fingerprint job that armed the dialog; mirroring
    /// `piv_modal_mgmt_field`, the checkbox is disabled — and reset back to
    /// `Manual` if it was already ticked when the device stopped offering
    /// one — whenever this is `None`, and shows the hex value in a tooltip
    /// when it's `Some`, rather than assuming HID's factory value the way
    /// this dialog used to. Unlike `piv_modal_mgmt_field`, there's no
    /// `PinManagementAuth`-style support gate on "Use PIN": both choices are
    /// always valid here, the only question is which credential the user has
    /// on hand.
    fn factory_reset_mgmt_auth_field(
        &mut self,
        ui: &mut egui::Ui,
        p: &Palette,
        default_key: Option<&'static [u8]>,
    ) {
        if default_key.is_none() && self.reset_mgmt_auth_mode == ResetMgmtAuthMode::Default {
            // Same rationale as `piv_modal_mgmt_field`'s reset: don't leave
            // the toggle checked for a default a device switch just took
            // away.
            self.reset_mgmt_auth_mode = ResetMgmtAuthMode::Manual;
        }
        ui.horizontal(|ui| {
            let mut is_default = self.reset_mgmt_auth_mode == ResetMgmtAuthMode::Default;
            let mut resp = ui.add_enabled(
                default_key.is_some(),
                egui::Checkbox::new(&mut is_default, "Use default management key"),
            );
            if let Some(key) = default_key {
                // Only on the enabled checkbox — a disabled one has no
                // applicable default to show.
                resp = resp.on_hover_text(format!("Default management key: {}", hex_lower(key)));
            }
            if resp.changed() {
                self.reset_mgmt_auth_mode =
                    reset_mgmt_auth_mode_after_toggle(is_default, ResetMgmtAuthMode::Default);
            }
            let mut is_pin = self.reset_mgmt_auth_mode == ResetMgmtAuthMode::Pin;
            if ui.checkbox(&mut is_pin, "Use PIN").changed() {
                self.reset_mgmt_auth_mode =
                    reset_mgmt_auth_mode_after_toggle(is_pin, ResetMgmtAuthMode::Pin);
            }
        });
        if self.reset_mgmt_auth_mode == ResetMgmtAuthMode::Default {
            return;
        }
        let use_pin = self.reset_mgmt_auth_mode == ResetMgmtAuthMode::Pin;
        let (label, hint) = if use_pin {
            ("PIN", "PIN")
        } else {
            // Deliberately not `piv_modal_mgmt_field`'s "hex (48/32/64
            // chars)": HID's ACA XAUTH key — the credential this actually
            // authenticates with on every fingerprint that needs this field
            // today — only ever supports TDES/AES-128 (8/16/24-byte keys),
            // never AES-256, unlike the standard PIV 0x9B round.
            ("Management key", "hex (16/32/48 chars)")
        };
        let mut reset_mgmt_rev = self
            .secret_reveal
            .get("reset-mgmt-auth")
            .copied()
            .unwrap_or(false);
        piv_secret_field(
            ui,
            p,
            label,
            &mut self.reset_mgmt_auth_input,
            &mut reset_mgmt_rev,
            hint,
            96.0,
            300.0,
        );
        self.secret_reveal.insert("reset-mgmt-auth", reset_mgmt_rev);
    }

    /// Resolve the credential the user entered for the factory reset's
    /// management-auth step: `FactoryResetConfirmState::default_mgmt_key`
    /// when "Use default management key" is ticked, a typed PIN with "Use
    /// PIN" ticked, otherwise the typed management-key hex. Mirrors
    /// `App::piv_current_mgmt_key`'s shape and error wording for the
    /// `Default` case (down to reusing the exact same "no known default"
    /// message) and `App::piv_current_mgmt_auth`'s role: the one call site
    /// both the dialog's validation and `run_factory_reset_gui` go through,
    /// so the resolution logic can't drift between the two.
    fn reset_mgmt_current_auth(&self) -> Result<ResetMgmtAuth, String> {
        match self.reset_mgmt_auth_mode {
            ResetMgmtAuthMode::Default => self
                .factory_reset_confirm
                .as_ref()
                .and_then(|c| c.default_mgmt_key)
                .map(|key| ResetMgmtAuth::Key(zeroize::Zeroizing::new(key.to_vec())))
                .ok_or_else(|| "This device has no known default management key.".to_string()),
            ResetMgmtAuthMode::Pin => Ok(ResetMgmtAuth::Pin(zeroize::Zeroizing::new(
                self.reset_mgmt_auth_input.clone(),
            ))),
            ResetMgmtAuthMode::Manual => {
                piv_mgmt_key_bytes(&self.reset_mgmt_auth_input).map(ResetMgmtAuth::Key)
            }
        }
    }

    /// Fold a finished card sweep into the app, bound to the key it ran
    /// against. Lifted out of `run_factory_reset_gui`'s apply closure for the
    /// same reason as [`App::apply_reset_path_outcome`]: the device-binding
    /// rule is the part worth testing, and it needs no key in hand.
    ///
    /// Every path through here logs a plain-language summary
    /// (`factory_reset_report_summary`: which steps wiped, failed, or were
    /// skipped, and why) — independent of `factory_reset_report` (the
    /// Overview pane's own live list, overwritten by the next run) and
    /// independent of any APDU trace. That `log`/`log_global` call is also
    /// what flushes a trace captured for this job: `App::push_log` is the
    /// sole consumer of `App::pending_trace` (see `Worker::spawn`'s doc), so
    /// a path through here that never logs would silently drop it — this
    /// function used to have exactly one such path (see the orphaned case
    /// below, which already logged, and the normal case, which didn't).
    ///
    /// The orphaned case is louder here than anywhere else in the file. By the
    /// time this runs, every card step has already been executed against the
    /// key the sweep was dispatched for — OATH, OpenPGP, PIV and the Token2 OTP
    /// applet are wiped or half-wiped whatever the selection now says.
    /// `reports` is the only record of that, and it carries the one line that
    /// tells "wiped" apart from "PIN and PUK blocked but not wiped" (PIV's
    /// failure text). Dropping it silently loses the difference, so an outcome
    /// that outlives its selection is said out loud in the log instead.
    fn apply_factory_reset_sweep(
        app: &mut App,
        for_device: Option<&DeviceId>,
        reports: Vec<keyroost_resolve::StepReport>,
        ends_in_fido: bool,
    ) {
        use keyroost_resolve::{ResetStep, StepOutcome};
        if !completion_still_valid(for_device, app.selected_device.as_ref()) {
            // Selection changed mid-sweep; don't paint A's outcome under B —
            // and deliberately don't open the FIDO dialog either, because
            // arming a wipe under the key on screen now is exactly what the
            // guard exists to prevent.
            let fido_txt = if ends_in_fido {
                format!(
                    " {} was left un-wiped \u{2014} the replug-and-touch ceremony never started.",
                    ResetStep::Fido.label()
                )
            } else {
                String::new()
            };
            app.log_global(
                Severity::Warn,
                LogKind::User,
                format!(
                    "a factory reset finished after the selection moved on \u{2014} {}.{fido_txt} \
                     Re-select that key to see its current state and finish the reset.",
                    factory_reset_report_summary(&reports)
                ),
            );
            return;
        }
        // Re-initialise each wiped applet's pane to a fresh, empty state
        // (mirrors the OATH reset apply), clearing its "tried" flag so the
        // pane re-lists on its own.
        for r in &reports {
            // `WipedGlobal` and `WipedWithWarning` count here too: the
            // applet itself really was wiped, either cleanly via the
            // device-wide mechanism or with a non-fatal follow-up (today:
            // PIV's courtesy XAUTH-key restore) that didn't go cleanly --
            // the pane's stale state still needs clearing either way.
            if matches!(
                r.outcome,
                StepOutcome::Wiped | StepOutcome::WipedGlobal | StepOutcome::WipedWithWarning(_)
            ) {
                match r.step {
                    ResetStep::Oath => {
                        app.oath = OathState::default();
                        app.oath_tried = false;
                    }
                    ResetStep::OpenPgp => {
                        app.openpgp = OpenPgpState::default();
                    }
                    // Fires regardless of which mechanism `PivSession::
                    // factory_reset` actually ran (device-wide or PIV-only) --
                    // `ResetStep::Piv` covers both; there's no separate step
                    // for the device-wide path any more.
                    ResetStep::Piv => {
                        app.piv = PivState::default();
                        app.piv_tried = false;
                    }
                    ResetStep::Token2Otp => {
                        app.otp = OtpState::default();
                        app.otp_tried = false;
                    }
                    ResetStep::Fido => {}
                }
            }
        }
        // Record the run in the activity log — independent of any APDU
        // trace: whether a factory reset ran, which applets it wiped, and
        // which steps failed or were skipped (and why). This is also the
        // call that flushes a captured APDU trace: `App::push_log` is the
        // sole consumer of `App::pending_trace` (see `Worker::spawn`'s doc),
        // so without a `log` call here, a trace captured for this whole job
        // had nowhere to attach and was silently discarded — this whole
        // function used to report only through `factory_reset_report`
        // (the Overview pane's own list), never through the activity log.
        // `WipedGlobal` counts as clean here (it's a full success, just via
        // a different mechanism), but deliberately not
        // `| StepOutcome::WipedWithWarning(_)`, unlike the pane-reinit loop
        // above: the applet is wiped either way, but a run with a warning
        // attached isn't a clean run, and `Severity::Warn` is what actually
        // gets that warning in front of the user.
        let severity = if reports
            .iter()
            .all(|r| matches!(r.outcome, StepOutcome::Wiped | StepOutcome::WipedGlobal))
        {
            Severity::Ok
        } else {
            Severity::Warn
        };
        app.log(
            severity,
            format!(
                "factory reset finished \u{2014} {}",
                factory_reset_report_summary(&reports)
            ),
        );
        app.factory_reset_report = reports.into_iter().map(FactoryResetRow::Step).collect();
        // Hand the FIDO finale to the tested armed-reset flow. Seed its
        // report row first: the ceremony can fail (no touch in time) or
        // be abandoned, and the pane must not read as a finished wipe
        // until FIDO actually answers — that outcome is routed to
        // `security_keys.error`, which the Overview tab never paints.
        if ends_in_fido {
            app.factory_reset_report.push(FactoryResetRow::FidoPending);
            app.security_keys.reset = ResetDialog {
                open: true,
                ..Default::default()
            };
        }
    }

    /// Run a whole-device factory reset: sweep every card applet in the shared
    /// plan off the UI thread (continue-on-error), record a per-step report,
    /// re-initialise the wiped panes, and — when the plan ends in FIDO — hand
    /// the finale to the existing armed `ResetDialog` (which owns the replug +
    /// touch ceremony), so no new FIDO logic is written here.
    ///
    /// If the armed `factory_reset_confirm` says a management-key credential
    /// is needed (`FactoryResetConfirmState::needs_reset_mgmt_auth` — set
    /// once, by `start_factory_reset_confirm`'s fingerprint, and carried
    /// forward rather than re-checked here): resolves the credential the user
    /// typed into the confirm dialog (`Self::reset_mgmt_current_auth`) and
    /// hands it to `run_card_reset_step`'s `Piv` branch, which passes it straight
    /// through to `PivSession::factory_reset` — that method decides on its own
    /// which mechanism actually consumes it (or, if neither `PivExtension::
    /// Reset` nor `ResetGlobal` is available, that it goes unused). Also
    /// excludes `ResetStep::Piv` from the plan entirely when
    /// `piv_preview` says neither mechanism is available at all
    /// (`factory_reset_piv_unresettable` /
    /// `keyroost_resolve::exclude_unresettable_piv`) — same decision
    /// `render_factory_reset_confirm` already made for the dialog text, made
    /// again here from the same stored `piv_preview` rather than a fresh
    /// fingerprint, for the reason the next paragraph gives.
    ///
    /// Unlike the individual PIV step's own fingerprint (deliberately
    /// re-run fresh every time it executes — see `FactoryResetPivPreview`'s
    /// doc), *what's in the plan* is decided once, when the dialog was
    /// armed, and not revisited here: re-deciding plan membership would need
    /// its own PC/SC round trip before this method could even build
    /// `card_steps`, which blocking-I/O-on-the-UI-thread this whole
    /// worker-job structure exists to avoid.
    ///
    /// An invalid credential returns `false` (same "keep the dialog open"
    /// signal a busy worker gives) with `factory_reset_confirm_error` set,
    /// instead of queuing a job that could only fail once it reached the
    /// card.
    fn run_factory_reset_gui(&mut self) -> bool {
        use keyroost_resolve::{ResetStep, StepReport};
        let Some(dev) = self.selected_device().cloned() else {
            return false;
        };
        let mut plan = keyroost_resolve::factory_reset_plan(dev.caps);
        let piv_preview = self
            .factory_reset_confirm
            .as_ref()
            .map(|c| c.piv_preview)
            .unwrap_or(FactoryResetPivPreview::NotOffered);
        if factory_reset_piv_unresettable(piv_preview) {
            keyroost_resolve::exclude_unresettable_piv(&mut plan);
        }
        if plan.is_empty() {
            return false;
        }
        let needs_reset_mgmt_auth = self
            .factory_reset_confirm
            .as_ref()
            .is_some_and(|c| c.needs_reset_mgmt_auth);
        let reset_mgmt_auth = if needs_reset_mgmt_auth {
            match self.reset_mgmt_current_auth() {
                Ok(auth) => Some(auth),
                Err(e) => {
                    self.factory_reset_confirm_error = Some(e);
                    return false;
                }
            }
        } else {
            None
        };
        self.factory_reset_confirm_error = None;
        // Capture the transport descriptors before going off-thread.
        let reader = dev.reader.clone();
        let hid_path = dev.hid_path.clone();
        let for_device = self.selected_device.clone();
        let ends_in_fido = plan.last() == Some(&ResetStep::Fido);
        // Card applets run on the worker; FIDO (if present) is left to the
        // armed ResetDialog after the card sweep completes.
        let card_steps: Vec<ResetStep> = plan
            .iter()
            .copied()
            .filter(|s| *s != ResetStep::Fido)
            .collect();
        // Clear any stale report so the pane shows this run's progress only.
        self.factory_reset_report.clear();
        self.spawn_job("Factory-resetting key\u{2026}", move || {
            let mut reports: Vec<StepReport> = Vec::new();
            for step in card_steps {
                let outcome = run_card_reset_step(
                    step,
                    reader.as_deref(),
                    hid_path.as_deref(),
                    reset_mgmt_auth.as_ref(),
                );
                reports.push(StepReport { step, outcome });
            }
            Box::new(move |app: &mut App| {
                wipe(&mut app.reset_mgmt_auth_input);
                App::apply_factory_reset_sweep(app, for_device.as_ref(), reports, ends_in_fido)
            })
        })
    }

    /// Reset confirmation: wiping a key is irreversible, so require the user to
    /// type `reset` before the button activates, then a physical touch.
    fn render_reset_dialog(&mut self, ctx: &egui::Context) {
        if !self.security_keys.reset.open {
            return;
        }
        let label = self
            .selected_device()
            .map(|d| match &d.name {
                Some(name) => name.clone(),
                None => format!("{} {}", d.vendor, d.model).trim().to_string(),
            })
            .unwrap_or_else(|| "this key".into());

        // A reset wipes credentials + the PIN but leaves the large-blob array
        // intact, so warn when this key supports it. Computed up front to avoid
        // borrowing `self` inside the window closure.
        let has_large_blobs = self
            .security_keys
            .info
            .as_ref()
            .and_then(|i| i.option("largeBlobs"))
            == Some(true);

        let mut window_open = true;
        let mut arm = false;
        let mut cancel = false;
        // A card in a reader takes the in-place route: power-cycle + immediate
        // reset, no replug and no touch. `None` for USB keys, which keep the
        // armed replug ceremony.
        let card_reader = Self::card_reset_reader(self.selected_device());
        // Device-scoped, not app-global: this dialog may belong to a different
        // key than the armed one, and telling the user to "unplug the key, then
        // plug it back in" under the wrong key's name invites a replug that
        // fires someone else's wipe.
        let waiting = self.reset_arm.as_ref().is_some_and(|arm| {
            completion_still_valid(arm.for_device.as_ref(), self.selected_device.as_ref())
        });
        egui::Window::new("Reset FIDO security key?")
            .collapsible(false)
            .resizable(false)
            .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
            .open(&mut window_open)
            .show(ctx, |ui| {
                ui.colored_label(
                    egui::Color32::from_rgb(220, 110, 110),
                    format!("This wipes ALL credentials and the PIN on {label}."),
                );
                ui.label("This cannot be undone.");
                if has_large_blobs {
                    ui.add_space(6.0);
                    let muted = egui::Color32::from_rgb(150, 150, 150);
                    ui.colored_label(
                        muted,
                        "Note: a reset does not erase large-blob storage. Open the Storage tab",
                    );
                    ui.colored_label(
                        muted,
                        "and use \u{201c}Clear all storage\u{201d} to wipe every entry there.",
                    );
                }
                ui.add_space(6.0);
                if waiting {
                    // Armed: the clock starts when the key is re-inserted, so we
                    // wait for the unplug/replug and fire the moment it returns.
                    ui.add_space(2.0);
                    ui.horizontal(|ui| {
                        ui.spinner();
                        ui.label(
                            egui::RichText::new("Now unplug the key, then plug it back in.")
                                .strong(),
                        );
                    });
                    ui.label("The reset is sent the instant it reconnects \u{2014} then the");
                    ui.label("key will blink. Touch it to finish the wipe.");
                    ui.add_space(6.0);
                    if ui.button("Cancel").clicked() {
                        cancel = true;
                    }
                } else {
                    if card_reader.is_some() {
                        ui.label("A key only accepts a reset just after power-up. This one");
                        ui.label("sits in a card reader, so there is nothing to unplug \u{2014}");
                        ui.label("the card is power-cycled in place and the wipe sent");
                        ui.label("immediately. Keep the card on the reader.");
                    } else {
                        ui.label("A key only accepts a reset within ~10 seconds of being");
                        ui.label("plugged in, so after you confirm you'll re-insert it.");
                    }
                    ui.add_space(6.0);
                    ui.horizontal(|ui| {
                        ui.label("Type \u{201c}reset\u{201d} to confirm:");
                        ui.add(
                            egui::TextEdit::singleline(&mut self.security_keys.reset.confirm_input)
                                .desired_width(120.0),
                        );
                    });
                    ui.add_space(6.0);
                    let ready = self.security_keys.reset.confirm_input.trim() == "reset";
                    let go_label = if card_reader.is_some() {
                        "Reset card"
                    } else {
                        "Arm reset"
                    };
                    ui.horizontal(|ui| {
                        if ui.add_enabled(ready, egui::Button::new(go_label)).clicked() {
                            arm = true;
                        }
                        if ui.button("Cancel").clicked() {
                            cancel = true;
                        }
                    });
                }
            });
        if arm {
            if let Some(reader) = card_reader {
                // In-place card route: the wipe runs now, on the worker, and
                // its outcome lands through the same completion handler the
                // replug flow uses. The dialog's job is done.
                self.security_keys.reset = ResetDialog::default();
                if !self.submit_card_reset(reader) {
                    // Worker busy — nothing was submitted, and the dialog just
                    // closed. A pending report row must not sit there implying
                    // a wipe is coming.
                    let msg = "not started \u{2014} another device operation is in \
                               progress. Retry from the FIDO2 pane once it finishes; \
                               the card was not touched."
                        .to_string();
                    let outcome = keyroost_resolve::StepOutcome::Failed(msg.clone());
                    if resolve_pending_fido_reset_row(
                        &mut self.factory_reset_report,
                        outcome.clone(),
                    ) {
                        let (severity, line) = factory_reset_fido_finale_log_line(&outcome);
                        self.log(severity, line);
                    }
                    self.security_keys.error = Some(msg);
                }
            } else {
                self.arm_fido_reset();
            }
        } else if cancel || !window_open {
            // Cancel button, or the window's [x] close.
            self.security_keys.reset = ResetDialog::default();
            self.reset_arm = None;
            // If this dialog was a factory reset's FIDO finale, say so in the
            // report rather than leaving a row that reads as still in progress
            // — and in the activity log, whose "factory reset finished" line
            // was written before this ceremony even started and never
            // otherwise learns how it ended.
            // Pending-only: a row that already answered belongs to an earlier
            // ceremony this cancel didn't undo (the report outlives the dialog),
            // and rewriting a completed wipe as "failed" asks for it again.
            let outcome = keyroost_resolve::StepOutcome::Failed(
                "cancelled \u{2014} the passkeys and PIN are still on this key".into(),
            );
            if resolve_pending_fido_reset_row(&mut self.factory_reset_report, outcome.clone()) {
                let (severity, line) = factory_reset_fido_finale_log_line(&outcome);
                self.log(severity, line);
            }
        }
    }

    /// Arm the reset: snapshot the current FIDO keys so the poll can tell when
    /// ours leaves and a fresh one arrives. Prefer the armed key's HID serial
    /// (port-independent), then the resolver's effective (CCID) serial; refuse
    /// to arm with neither — a replugged key we can't re-identify must not be
    /// matched by "first same-model path" (KEY-005).
    fn arm_fido_reset(&mut self) {
        self.arm_fido_reset_with(Self::fido_devices());
    }

    /// The arming decision, with the live device list supplied by the caller.
    ///
    /// Separated from [`Self::arm_fido_reset`] so it can be unit-tested without
    /// enumerating hardware. Enumeration is not free of side effects off Linux:
    /// `keyroost_hid::enumerate` reads sysfs there, but goes through `hidapi`
    /// on macOS and Windows, and on macOS that means IOKit from whatever thread
    /// the test harness happens to be on — which aborted the whole test process
    /// with SIGTRAP. A unit test also has no business depending on what is
    /// physically plugged into the machine running it.
    fn arm_fido_reset_with(&mut self, devices: Vec<FidoHid>) {
        let target_path = self.selected_fido_hid_path();
        let target = target_path
            .as_ref()
            .and_then(|p| devices.iter().find(|d| &d.path == p));
        let target_serial = target.and_then(|d| d.serial.clone());
        let target_ids = target.map(|d| d.ids);
        let target_effective_serial = self
            .selected_device()
            .map(|d| d.serial.clone())
            .filter(|s| !s.is_empty());
        if target_serial.is_none() && target_effective_serial.is_none() {
            self.security_keys.reset = ResetDialog::default();
            // Ending the dialog ends the ceremony behind it, exactly as Cancel
            // does. Reaching this branch with an arm already live is possible —
            // the dialog reverts to its confirm form whenever the arm's key is
            // no longer the selection, so "Arm reset" can be pressed a second
            // time — and saying "not armed" while the earlier arm keeps polling
            // is the one combination that wipes a key after telling the user
            // nothing would happen.
            self.reset_arm = None;
            let msg = "not armed \u{2014} this key exposes no serial to re-identify it by after \
                       a replug, so the armed reset can't safely target it. Run `keyroostctl \
                       fido reset --yes` within ~10 s of plugging the key in instead. If this \
                       is a card reached through a virtual FIDO device, skip the bridge: \
                       select the card's reader row and reset there \u{2014} a card resets in \
                       place, no replug."
                .to_string();
            self.log(Severity::Err, msg.clone());
            // The dialog just vanished and the log panel is collapsed by
            // default, so neither surface is guaranteed to be read. Land the
            // refusal where the user is looking as well: the report row
            // (Overview) when this was a factory reset's finale, and
            // `security_keys.error` (the FIDO2 pane the standalone Reset button
            // lives on) either way. Leaving the seeded row pending would ask
            // for a replug-and-touch ceremony that is never coming. Pending-only
            // for the same reason as the cancel branch: nothing was attempted
            // here, so an already-answered row is not this refusal's to rewrite.
            let outcome = keyroost_resolve::StepOutcome::Failed(msg.clone());
            if resolve_pending_fido_reset_row(&mut self.factory_reset_report, outcome.clone()) {
                let (severity, line) = factory_reset_fido_finale_log_line(&outcome);
                self.log(severity, line);
            }
            self.security_keys.error = Some(msg);
        } else {
            self.reset_arm = Some(ResetArm {
                target_serial,
                target_path,
                target_ids,
                target_effective_serial,
                for_device: self.selected_device.clone(),
                prev_devices: devices.iter().map(HidIdentity::of).collect(),
                saw_removal: false,
            });
        }
    }

    /// Current FIDO HID devices. No PC/SC. Cheap on Linux (a sysfs read), but
    /// not side-effect-free elsewhere: `keyroost_hid` uses `hidapi` on macOS
    /// and Windows, so this reaches IOKit / the Win32 HID stack. Keep it out of
    /// unit tests — take [`Self::arm_fido_reset_with`] and pass a list instead.
    fn fido_devices() -> Vec<FidoHid> {
        keyroost_hid::enumerate()
            .unwrap_or_default()
            .into_iter()
            .filter(HidDevice::is_fido)
            .map(|h| FidoHid {
                path: h.path,
                serial: h.serial_number,
                ids: (h.vendor_id, h.product_id),
                usb_bus: h.usb_bus,
                usb_address: h.usb_address,
            })
            .collect()
    }

    /// The resolver's stable identity for the FIDO HID device at `path`, read
    /// the same way `target_effective_serial` was captured at arm time: the
    /// full `keyroost_resolve` correlation (HID + PC/SC probe), not just a
    /// USB iSerialNumber or a YubiKey CCID serial.
    ///
    /// This used to call the former HID-only resolver
    /// (`keyroost_resolve::read_effective_serial`, removed once every front
    /// end moved onto the device model), which only ever resolved a HID
    /// `iSerialNumber` or — for `VID_YUBICO` specifically — a YubiKey CCID
    /// serial; every other card-derived serial
    /// (a Token2 PIN+/Bio3 key's OpenPGP-applet serial among them) made it
    /// return `Err` unconditionally. `target_effective_serial`, by contrast,
    /// comes from `self.selected_device()`, i.e. the *full* `correlate()`
    /// merge that `keyroost_resolve::enumerate()` runs — which pulls a
    /// serial from whichever applet a probed reader exposes, not only
    /// YubiKey's. So a serial-less Token2 FIDO+PGP key would arm (find a
    /// non-empty `target_effective_serial` from that merge) but could then
    /// never re-match on reinsertion (this function permanently returning
    /// `None` for it) — the reset dispatched at arm time was live, but the
    /// touch prompt never fires because `reset_reinsert_matches` never sees
    /// two `Some`s to compare. Matches the CLI's `fido_reset_after_replug`,
    /// which resolves the reinserted key from the same correlated device
    /// list for exactly this reason. Names stored on keys are not read here
    /// (`skip_key_names`), so the poll never talks CTAP to the key being
    /// reset.
    ///
    /// `None` when the device is gone or the identity can't be read *yet* (a
    /// just-replugged key's CCID interface takes a beat to register with
    /// pcscd) — callers retry on the next poll rather than guessing.
    fn fido_effective_serial(path: &std::path::Path) -> Option<String> {
        keyroost_resolve::enumerate_with(&keyroost_resolve::EnumerateOptions {
            skip_key_names: true,
            ..Default::default()
        })
        .unwrap_or_default()
        .into_iter()
        .find(|d| d.hid_path.as_deref() == Some(path))
        .map(|d| d.serial)
        .filter(|s| !s.is_empty())
    }

    /// Poll the live FIDO list while a reset is armed: once the armed key has
    /// been unplugged, fire the reset on its re-insertion (which the user
    /// does), inside the ~10 s window. Matches by HID serial when the key
    /// exposes one, else by the resolver's effective (CCID-read) serial; a
    /// fresh same-model path alone never fires the reset (KEY-005).
    fn poll_reset_arm(&mut self) {
        // Defence in depth. `on_device_selected` is the sole owner of ending an
        // armed ceremony, which means every path that moves the selection has
        // to route through it — one that forgets (the failed-scan path did)
        // leaves this poll firing an irreversible wipe for a key the UI has
        // moved off, with the dialog showing its un-armed confirm form (its
        // "now unplug the key" prompt is device-scoped for the same reason).
        // Cheaper to re-check the binding here than to rely on one owner.
        if !self.reset_arm.as_ref().is_some_and(|arm| {
            completion_still_valid(arm.for_device.as_ref(), self.selected_device.as_ref())
        }) {
            if self.reset_arm.take().is_some() {
                self.log_global(
                    Severity::Warn,
                    LogKind::User,
                    "the armed reset was cancelled \u{2014} the key it was armed for is no longer \
                     the one selected. Re-open \u{201C}Reset key\u{201D} on the key you want to \
                     wipe.",
                );
            }
            return;
        }
        let current = Self::fido_devices();
        let mut fire: Option<std::path::PathBuf> = None;
        if let Some(arm) = self.reset_arm.as_mut() {
            if let Some(target_serial) = arm.target_serial.clone() {
                // HID-serial mode: identity is port-independent.
                let here = current
                    .iter()
                    .find(|d| d.serial.as_deref() == Some(target_serial.as_str()));
                match here {
                    None => arm.saw_removal = true, // unplugged
                    Some(d) if arm.saw_removal => fire = Some(d.path.clone()),
                    Some(_) => {}
                }
            } else {
                // Effective-serial mode (no HID serial, e.g. most YubiKeys):
                // the armed path leaving is the unplug; a fresh *connection*
                // (see `HidIdentity` — not just a path unseen before, since a
                // hidraw minor number can be recycled straight back onto the
                // replugged key) is accepted as the re-insert only when its
                // stable identity matches the armed key's. The CCID probe
                // runs only for a model-matching fresh connection, and only
                // after removal.
                let present = |p: &std::path::PathBuf| current.iter().any(|d| &d.path == p);
                match &arm.target_path {
                    Some(t) if !present(t) => arm.saw_removal = true,
                    _ => {}
                }
                if arm.saw_removal {
                    fire = current
                        .iter()
                        .filter(|d| arm.target_ids.is_none() || arm.target_ids == Some(d.ids))
                        .filter(|d| {
                            let id = HidIdentity::of(d);
                            !arm.prev_devices.iter().any(|p| same_hid_connection(p, &id))
                        })
                        .find(|d| {
                            let cand_eff = Self::fido_effective_serial(&d.path);
                            reset_reinsert_matches(
                                arm.target_serial.as_deref(),
                                arm.target_effective_serial.as_deref(),
                                arm.target_ids,
                                d.serial.as_deref(),
                                cand_eff.as_deref(),
                                d.ids,
                            )
                        })
                        .map(|d| d.path.clone());
                }
            }
        }
        match fire {
            Some(path) => {
                // The replug window is one-shot. If the worker is mid-job the
                // submission is refused — keep the arm (and the stale
                // prev_devices, so the fresh connection still counts as new)
                // and let the next poll retry instead of silently losing the
                // reset.
                if self.submit_reset_path(path) {
                    self.reset_arm = None;
                    self.security_keys.reset = ResetDialog::default();
                }
            }
            None => {
                if let Some(arm) = self.reset_arm.as_mut() {
                    // Refresh the snapshot only until the unplug. After
                    // removal it must stay frozen: a fresh connection whose CCID
                    // serial isn't readable yet has to still count as fresh
                    // on the next poll, or the retry could never fire.
                    if !arm.saw_removal {
                        arm.prev_devices = current.iter().map(HidIdentity::of).collect();
                    }
                }
            }
        }
    }

    fn selected_openpgp_reader(&self) -> Option<String> {
        self.selected_device().and_then(|d| d.reader.clone())
    }

    /// Read the selected card's status on the worker thread.
    fn load_openpgp_status(&mut self) {
        self.openpgp.error = None;
        let Some(name) = self.selected_openpgp_reader() else {
            self.openpgp.error = Some("no OpenPGP card selected".into());
            return;
        };
        let for_device = self.selected_device.clone();
        self.spawn_job("Reading OpenPGP status\u{2026}", move || {
            let result = (|| -> Result<
                (
                    keyroost_transport::OpenPgpStatus,
                    Option<keyroost_transport::AlgorithmInformation>,
                ),
                TransportError,
            > {
                let mut session = keyroost_transport::OpenPgpSession::open(&name)?;
                let status = session.status()?;
                let supported = session.supported_algorithms().unwrap_or(None);
                Ok((status, supported))
            })();
            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return; // selection changed mid-read; discard
                }
                match result {
                    Ok((status, supported)) => {
                        app.openpgp.status = Some(status);
                        app.openpgp.supported = supported;
                        app.openpgp.loaded = true;
                    }
                    Err(e) => app.openpgp.error = Some(e.to_string()),
                }
            })
        });
    }

    /// Off-thread helper: open the card and verify the admin PIN (PW3). Shared by
    /// every write op so they all gate on PW3.
    fn openpgp_open_admin(
        name: &str,
        admin_pin: &str,
    ) -> Result<keyroost_transport::OpenPgpSession, TransportError> {
        let mut session = keyroost_transport::OpenPgpSession::open(name)?;
        session.verify_admin_pin(admin_pin.as_bytes())?;
        Ok(session)
    }

    /// Re-read status after a write and store it, surfacing `notice` on success.
    fn apply_openpgp_write(
        app: &mut App,
        result: Result<keyroost_transport::OpenPgpStatus, TransportError>,
        notice: String,
    ) {
        match result {
            Ok(status) => {
                app.openpgp.status = Some(status);
                app.openpgp.loaded = true;
                app.openpgp.error = None;
                app.openpgp.notice = Some(notice);
                wipe(&mut app.openpgp.admin_pin);
            }
            Err(e) => {
                app.openpgp.error = Some(e.to_string());
                wipe(&mut app.openpgp.admin_pin);
            }
        }
        Self::apply_openpgp_cred_result(app);
    }

    /// Mirror an OpenPGP write result into the credential modal so the outcome
    /// is shown in-modal (issue #31). Reads the pane status the apply closure
    /// just set: no error → `Ok(())`; an error → the message, with the modal
    /// kept open for a retry. `busy` always clears. No-op when the modal is
    /// closed (e.g. the flow was triggered some other way).
    fn apply_openpgp_cred_result(app: &mut App) {
        if let Some(m) = app.openpgp.cred_modal.as_mut() {
            m.busy = false;
            m.result = match &app.openpgp.error {
                Some(e) => Some(Err(e.clone())),
                None => Some(Ok(())),
            };
        }
    }

    /// The admin PIN (PW3) the modal's flows send: the typed `admin_pin`, or the
    /// well-known factory default when "Use default admin PIN (PW3)" is ticked.
    /// Mirrors the PIV `PivMgmtAuthMode::Default` convenience. Does not
    /// mutate state.
    fn openpgp_admin_pin_value(&self) -> String {
        if self.openpgp.use_default_admin {
            OPENPGP_DEFAULT_ADMIN_PIN.to_string()
        } else {
            self.openpgp.admin_pin.clone()
        }
    }

    /// Set the cardholder name (PW3-gated), then refresh status.
    fn set_openpgp_name(&mut self) {
        let Some(name) = self.selected_openpgp_reader() else {
            return;
        };
        let pin = zeroize::Zeroizing::new(self.openpgp_admin_pin_value());
        let value = self.openpgp.name_input.clone();
        self.openpgp.notice = None;
        self.spawn_job("Setting cardholder name…", move || {
            let result = (|| -> Result<keyroost_transport::OpenPgpStatus, TransportError> {
                let mut s = Self::openpgp_open_admin(&name, &pin)?;
                s.set_cardholder_name(value.as_bytes())?;
                s.status()
            })();
            Box::new(move |app: &mut App| {
                Self::apply_openpgp_write(app, result, "Cardholder name set.".into())
            })
        });
    }

    /// Set the public-key URL (PW3-gated), then refresh status.
    fn set_openpgp_url(&mut self) {
        let Some(name) = self.selected_openpgp_reader() else {
            return;
        };
        let pin = zeroize::Zeroizing::new(self.openpgp_admin_pin_value());
        let value = self.openpgp.url_input.clone();
        self.openpgp.notice = None;
        self.spawn_job("Setting public-key URL…", move || {
            let result = (|| -> Result<keyroost_transport::OpenPgpStatus, TransportError> {
                let mut s = Self::openpgp_open_admin(&name, &pin)?;
                s.set_url(value.as_bytes())?;
                s.status()
            })();
            Box::new(move |app: &mut App| {
                Self::apply_openpgp_write(app, result, "Public-key URL set.".into())
            })
        });
    }

    /// Generate + register a key in the selected slot (PW3-gated, destructive),
    /// then refresh status. May require a touch on the key.
    /// Returns `false` when the job couldn't be queued (worker busy) — the
    /// caller's confirm modal stays open so the confirmed click isn't lost.
    fn generate_openpgp_key(&mut self) -> bool {
        let Some(name) = self.selected_openpgp_reader() else {
            return true; // nothing to do; let the modal close
        };
        let pin = zeroize::Zeroizing::new(self.openpgp_admin_pin_value());
        let slot = self.openpgp.selected_key;
        let alg = self.openpgp.gen_alg.to_alg();
        let creation_time = unix_now();
        self.openpgp.notice = None;
        self.spawn_job("Generating key… (touch the key if it blinks)", move || {
            let result = (|| -> Result<(keyroost_transport::OpenPgpStatus, [u8; 20]), TransportError> {
                let mut s = Self::openpgp_open_admin(&name, &pin)?;
                let _ = s.generate_key(slot.to_crt(), alg)?;
                let fpr = s.register_key(slot.to_crt(), creation_time)?;
                Ok((s.status()?, fpr))
            })();
            Box::new(move |app: &mut App| {
                match result {
                    Ok((status, fpr)) => {
                        app.openpgp.status = Some(status);
                        app.openpgp.loaded = true;
                        app.openpgp.error = None;
                        app.openpgp.notice =
                            Some(format!("Generated {} key: {}", slot.label(), hex_lower(&fpr)));
                        wipe(&mut app.openpgp.admin_pin);
                    }
                    Err(e) => {
                        app.openpgp.error = Some(e.to_string());
                        wipe(&mut app.openpgp.admin_pin);
                    }
                }
                Self::apply_openpgp_cred_result(app);
            })
        })
    }

    /// Import a key into the selected slot (PW3-gated, destructive), then refresh
    /// status. The key material comes from host keygen or a file, obtained on the
    /// worker thread (keygen is slow). May require a touch on the key. Returns
    /// `false` when the job couldn't be queued (worker busy).
    fn import_openpgp_key(&mut self, source: ImportSource) -> bool {
        let Some(name) = self.selected_openpgp_reader() else {
            return true; // nothing to do; let the modal close
        };
        let pin = zeroize::Zeroizing::new(self.openpgp_admin_pin_value());
        let slot = self.openpgp.selected_key;
        let path = self.openpgp.import_path.clone();
        let creation_time = unix_now();
        self.openpgp.notice = None;
        let label = match source {
            ImportSource::Generate => "Generating & importing RSA-2048 key… (touch if it blinks)",
            ImportSource::FromFile => "Importing RSA key from file… (touch if it blinks)",
        };
        self.spawn_job(label, move || {
            // Obtain the key parts first (keygen / file parse on this worker
            // thread). Map every error to a String so success and the various
            // failure kinds (key, PIN, card) flow through one result channel.
            let result = (|| -> Result<(keyroost_transport::OpenPgpStatus, [u8; 20]), String> {
                let k = match source {
                    ImportSource::Generate => keyroost_rsakey::generate_2048(),
                    ImportSource::FromFile => {
                        keyroost_rsakey::load_from_file(std::path::Path::new(&path))
                    }
                }
                .map_err(|e| e.to_string())?;

                let mut s = Self::openpgp_open_admin(&name, &pin).map_err(|e| e.to_string())?;
                let parts = keyroost_transport::RsaPrivateKeyParts {
                    e: &k.e,
                    p: &k.p,
                    q: &k.q,
                    u: &k.u,
                    dp: &k.dp,
                    dq: &k.dq,
                    n: &k.n,
                };
                s.import_key(slot.to_crt(), &parts)
                    .map_err(|e| e.to_string())?;
                let fpr = s
                    .register_key(slot.to_crt(), creation_time)
                    .map_err(|e| e.to_string())?;
                let status = s.status().map_err(|e| e.to_string())?;
                Ok((status, fpr))
            })();
            Box::new(move |app: &mut App| {
                match result {
                    Ok((status, fpr)) => {
                        app.openpgp.status = Some(status);
                        app.openpgp.loaded = true;
                        app.openpgp.error = None;
                        app.openpgp.notice = Some(format!(
                            "Imported {} key: {}",
                            slot.label(),
                            hex_lower(&fpr)
                        ));
                        wipe(&mut app.openpgp.admin_pin);
                        app.openpgp.import_path.clear();
                    }
                    Err(e) => {
                        app.openpgp.error = Some(e);
                        wipe(&mut app.openpgp.admin_pin);
                    }
                }
                Self::apply_openpgp_cred_result(app);
            })
        })
    }

    /// Factory-reset the OpenPGP applet (destructive), then refresh status. No
    /// PIN needed — reset blocks the PINs itself. Returns `false` when the job
    /// couldn't be queued (worker busy).
    fn reset_openpgp(&mut self) -> bool {
        let Some(name) = self.selected_openpgp_reader() else {
            return true; // nothing to do; let the modal close
        };
        self.openpgp.notice = None;
        let for_device = self.selected_device.clone();
        self.spawn_job("Resetting OpenPGP applet…", move || {
            let result = (|| -> Result<keyroost_transport::OpenPgpStatus, TransportError> {
                let mut s = keyroost_transport::OpenPgpSession::open(&name)?;
                s.factory_reset()?;
                s.status()
            })();
            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return; // selection changed mid-reset; don't paint A's outcome under B
                }
                Self::apply_openpgp_write(
                    app,
                    result,
                    "OpenPGP applet reset; keys wiped, PINs back to defaults.".into(),
                )
            })
        })
    }

    /// Change the user PIN (PW1) from old to new, then refresh status. No admin
    /// PIN needed — CHANGE REFERENCE DATA carries the old PIN itself.
    fn change_openpgp_user_pin(&mut self) {
        let Some(name) = self.selected_openpgp_reader() else {
            return;
        };
        let old = zeroize::Zeroizing::new(self.openpgp.user_pin_old.clone());
        let new = zeroize::Zeroizing::new(self.openpgp.user_pin_new.clone());
        self.openpgp.notice = None;
        self.spawn_job("Changing user PIN\u{2026}", move || {
            let result = (|| -> Result<keyroost_transport::OpenPgpStatus, TransportError> {
                let mut s = keyroost_transport::OpenPgpSession::open(&name)?;
                s.change_user_pin(old.as_bytes(), new.as_bytes())?;
                s.status()
            })();
            Box::new(move |app: &mut App| {
                wipe(&mut app.openpgp.user_pin_old);
                wipe(&mut app.openpgp.user_pin_new);
                Self::apply_openpgp_write(app, result, "User PIN (PW1) changed.".into());
            })
        });
    }

    /// Change the admin PIN (PW3) from old to new, then refresh status.
    fn change_openpgp_admin_pin(&mut self) {
        let Some(name) = self.selected_openpgp_reader() else {
            return;
        };
        let old = zeroize::Zeroizing::new(self.openpgp.admin_pin_old.clone());
        let new = zeroize::Zeroizing::new(self.openpgp.admin_pin_new.clone());
        self.openpgp.notice = None;
        self.spawn_job("Changing admin PIN\u{2026}", move || {
            let result = (|| -> Result<keyroost_transport::OpenPgpStatus, TransportError> {
                let mut s = keyroost_transport::OpenPgpSession::open(&name)?;
                s.change_admin_pin(old.as_bytes(), new.as_bytes())?;
                s.status()
            })();
            Box::new(move |app: &mut App| {
                wipe(&mut app.openpgp.admin_pin_old);
                wipe(&mut app.openpgp.admin_pin_new);
                Self::apply_openpgp_write(app, result, "Admin PIN (PW3) changed.".into());
            })
        });
    }

    /// Unblock the user PIN (PW1): set it to a new value, authorised by the admin
    /// PIN (PW3). Recovers a card whose user PIN is blocked without a reset.
    fn unblock_openpgp_user_pin(&mut self) {
        let Some(name) = self.selected_openpgp_reader() else {
            return;
        };
        let admin = zeroize::Zeroizing::new(self.openpgp_admin_pin_value());
        let new = zeroize::Zeroizing::new(self.openpgp.unblock_new.clone());
        self.openpgp.notice = None;
        self.spawn_job("Unblocking user PIN\u{2026}", move || {
            let result = (|| -> Result<keyroost_transport::OpenPgpStatus, TransportError> {
                let mut s = keyroost_transport::OpenPgpSession::open(&name)?;
                s.reset_retry_counter(admin.as_bytes(), new.as_bytes())?;
                s.status()
            })();
            Box::new(move |app: &mut App| {
                wipe(&mut app.openpgp.unblock_new);
                Self::apply_openpgp_write(app, result, "User PIN (PW1) unblocked.".into());
            })
        });
    }

    /// The reset confirmation modal for the PIV pane.
    fn render_piv_confirms(&mut self, ctx: &egui::Context) {
        if typed_reset_modal(
            ctx,
            "Reset PIV applet?",
            "This wipes ALL PIV keys, certificates, and PINs.",
            &["Only works when the PIN and PUK are already blocked."],
            &mut self.piv.confirm_reset,
        ) && self.piv_reset()
        {
            self.piv.confirm_reset = None;
        }
    }
}

/// A typed-"reset" confirmation modal, shared by the OpenPGP and PIV panes.
/// `confirm` is the modal state (`Some(typed text)` = open). Returns `true`
/// when the user confirmed; the *caller* fires the action and closes the
/// modal only if the action was actually queued — a busy worker must not
/// swallow a confirmed destructive click.
fn typed_reset_modal(
    ctx: &egui::Context,
    title: &str,
    warning: &str,
    extra_lines: &[&str],
    confirm: &mut Option<String>,
) -> bool {
    let Some(typed) = confirm.clone() else {
        return false;
    };
    let mut do_it = false;
    let mut cancel = false;
    let mut window_open = true;
    let mut buf = typed;
    egui::Window::new(title)
        .collapsible(false)
        .resizable(false)
        .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
        .open(&mut window_open)
        .show(ctx, |ui| {
            ui.colored_label(egui::Color32::from_rgb(220, 110, 110), warning);
            for line in extra_lines {
                ui.label(*line);
            }
            ui.label("This cannot be undone.");
            ui.add_space(6.0);
            ui.horizontal(|ui| {
                ui.label("Type \u{201c}reset\u{201d} to confirm:");
                ui.add(egui::TextEdit::singleline(&mut buf).desired_width(120.0));
            });
            ui.add_space(6.0);
            ui.horizontal(|ui| {
                let armed = buf.trim() == "reset";
                if ui.add_enabled(armed, egui::Button::new("Reset")).clicked() {
                    do_it = true;
                }
                if ui.button("Cancel").clicked() {
                    cancel = true;
                }
            });
        });
    if do_it {
        true
    } else {
        if cancel || !window_open {
            *confirm = None;
        } else {
            *confirm = Some(buf);
        }
        false
    }
}

/// Lowercase hex of a byte slice.
fn hex_lower(bytes: &[u8]) -> String {
    keyroost_proto::codec::hex_encode(bytes)
}

/// Decode a management-key hex field into wipe-on-drop bytes.
fn piv_mgmt_key_bytes(hex: &str) -> Result<zeroize::Zeroizing<Vec<u8>>, String> {
    keyroost_proto::codec::hex_decode(hex.trim())
        .map(zeroize::Zeroizing::new)
        .map_err(|e| format!("management key is not valid hex: {}", e))
}

/// The well-known factory-default PIV/XAUTH management-key bytes for a
/// device fingerprinted as `fingerprint` at `version`/`firmware_version`, if
/// keyroost has one on record —
/// [`keyroost_piv::compat::PivQuirk::Default9bManagementKey`], read off
/// [`keyroost_piv::compat::resolve_quirks`]. `None` means keyroost has no
/// known default for this device (an unrecognised fingerprint, or one the
/// quirk table deliberately leaves unseeded) — the modal's "Use default
/// management key" convenience toggle
/// ([`App::piv_modal_mgmt_field`]) disables itself in that case rather than
/// offering a default it can't actually supply. The slice's length is
/// whatever that fingerprint's management-key algorithm actually takes — 16
/// bytes for AES-128, 24 for 3-DES/AES-192, 32 for AES-256 — never assume 24.
fn piv_default_mgmt_key(
    fingerprint: keyroost_piv::fingerprint::AppletFingerprint,
    version: Option<&[u8]>,
    firmware_version: Option<&[u8]>,
) -> Option<&'static [u8]> {
    keyroost_piv::compat::default_9b_management_key(&keyroost_piv::compat::resolve_quirks(
        fingerprint,
        version,
        firmware_version,
    ))
}

/// How the user authorized a PIV management operation — the standard
/// management key (typed or the well-known default), or a PIN for
/// `keyroost_piv::compat::PivExtension::PinManagementAuth`. Produced by
/// `App::piv_current_mgmt_auth`, consumed by `piv_authenticate`.
enum PivMgmtAuth {
    Key(zeroize::Zeroizing<Vec<u8>>),
    Pin(zeroize::Zeroizing<String>),
}

/// Unlock PIV management on an already-open session per `auth`: the standard
/// GET METADATA/GENERAL AUTHENTICATE round for `PivMgmtAuth::Key`, or
/// `PivSession::authenticate_management_via_pin` for `PivMgmtAuth::Pin`. The
/// single call site every management-gated PIV job in this module runs
/// through, so the two authorization paths stay in sync.
fn piv_authenticate(
    s: &mut keyroost_transport::PivSession<'_>,
    auth: &PivMgmtAuth,
) -> Result<(), TransportError> {
    match auth {
        PivMgmtAuth::Key(key) => {
            let alg = s.resolve_management_key_algorithm(key.len())?;
            s.authenticate_management(alg, key)
        }
        PivMgmtAuth::Pin(pin) => s.authenticate_management_via_pin(pin.as_bytes()),
    }
}

/// Full uppercase hex of a byte slice (no truncation), matching the
/// credential-details display.
/// Render a masked secret input with a trailing eye toggle. `revealed` is read
/// for the initial mask state and updated in place when the eye is clicked, so
/// the caller can keep the flag wherever it likes. Returns the TextEdit
/// response. The buffer text is shown in clear when `*revealed`.
pub(crate) fn secret_edit(
    ui: &mut egui::Ui,
    p: &Palette,
    buf: &mut String,
    revealed: &mut bool,
    hint: &str,
    width: f32,
) -> egui::Response {
    let mut resp = None;
    ui.horizontal(|ui| {
        let mut edit = egui::TextEdit::singleline(buf)
            .vertical_align(egui::Align::Center)
            .desired_width(width);
        if !*revealed {
            edit = edit.password(true);
        }
        if !hint.is_empty() {
            edit = edit.hint_text(hint);
        }
        resp = Some(ui.add_sized([width, 32.0], edit));
        // Eye toggle, painted (the UI font has no emoji glyphs). Open eye =
        // shown, slashed eye = hidden.
        let (irect, ir) = ui.allocate_exact_size(egui::vec2(26.0, 32.0), egui::Sense::click());
        let col = if ir.hovered() { p.txt } else { p.txt2 };
        let c = irect.center();
        paint_eye_icon(ui, c, col);
        if !*revealed {
            // Slash across the eye to signal the hidden state.
            ui.painter().line_segment(
                [
                    egui::pos2(c.x - 8.0, c.y + 5.0),
                    egui::pos2(c.x + 8.0, c.y - 5.0),
                ],
                egui::Stroke::new(1.3, col),
            );
        }
        if ir.hovered() {
            ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
        }
        if ir.clicked() {
            *revealed = !*revealed;
        }
        let _ = ir.on_hover_text(if *revealed { "Hide" } else { "Show" });
    });
    let resp = resp.unwrap();
    // Scrub egui's retained plaintext once the field is no longer focused, so a
    // wiped buffer leaves nothing recoverable from egui memory.
    guard_secret_field(ui.ctx(), &resp);
    resp
}

fn hex_full(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        s.push_str(&format!("{:02X}", b));
    }
    s
}

fn hex_short(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes.iter().take(8) {
        s.push_str(&format!("{:02x}", b));
    }
    if bytes.len() > 8 {
        s.push('…');
    }
    s
}

fn unix_now() -> u32 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs() as u32)
        .unwrap_or(0)
}

// --- Device-centric coordination (selection, theme, per-device loads) --------
impl App {
    /// The palette for the current theme + accent.
    fn palette(&self) -> Palette {
        Palette::new(
            self.mode,
            Palette::ACCENTS[self.accent_idx],
            self.colorblind,
        )
    }

    /// Persist the current UI preferences to `settings.json` — but only when
    /// something actually changed since the last write, so a per-change call
    /// site can fire freely without spamming the disk. Best-effort: a write
    /// failure is swallowed inside `Settings::save`, since a UI preference that
    /// won't persist must never crash the app. Called at the change points
    /// (theme toggle, accent pick, colorblind toggle, zoom commit) because
    /// eframe's own `save()` is disabled in this crate.
    fn persist_settings(&mut self) {
        let current = Settings {
            zoom: theme::clamp_zoom(self.zoom),
            mode: self.mode.into(),
            accent: self.accent_idx,
            colorblind: self.colorblind,
        };
        if self.last_saved_settings.as_ref() == Some(&current) {
            return;
        }
        current.save();
        self.last_saved_settings = Some(current);
    }

    /// The currently selected device, if the id still resolves to a present one.
    fn selected_device(&self) -> Option<&Device> {
        let id = self.selected_device.as_ref()?;
        self.devices.iter().find(|d| &d.id == id)
    }

    /// (Re)build the unified device list off-thread, then re-resolve selection.
    /// Queue a burst of staggered rescans (see `pending_scans`). The first runs
    /// as soon as the worker is free; the rest follow over the next few seconds
    /// so a slow-registering reader is caught without the user touching Refresh.
    fn schedule_scan_burst(&mut self) {
        self.pending_scans = 4;
        self.next_scan_at = None; // first scan is due immediately
    }

    fn refresh_devices(&mut self) {
        self.scanned = true;
        self.spawn_job("Scanning for devices\u{2026}", move || {
            let result = device::enumerate();
            Box::new(move |app: &mut App| match result {
                Ok(devices) => {
                    app.devices_error = None;
                    // Windows only needs `devices` mutable for the additive FIDO pass
                    // below; off-Windows the original binding flows through unchanged
                    // (a plain `let mut` here would be an unused-mut warning).
                    #[cfg(windows)]
                    let mut devices = devices;
                    // Windows non-admin: the FIDO2 capability is read from the HID
                    // usage page 0xF1D0, which a non-elevated process can't open
                    // (ERROR_ACCESS_DENIED). So FIDO access is detected separately
                    // via keyroost-winwebauthn (access-denied signal). This pass is
                    // strictly ADDITIVE — it never removes a resolved device — and
                    // is panic-isolated so an FFI fault can't empty the list.
                    //  * Multiprotocol keys already resolve (via PC/SC) — add the
                    //    FIDO2 cap so the tab appears.
                    //  * FIDO-only keys don't resolve at all — synthesize a minimal
                    //    device from the detected VID/PID.
                    // cap_fido2 then shows the "needs admin / use Windows settings"
                    // card for these.
                    #[cfg(windows)]
                    {
                        let fido_keys =
                            std::panic::catch_unwind(keyroost_winwebauthn::detect_fido_keys)
                                .unwrap_or_default();
                        if !fido_keys.is_empty() {
                            if devices.iter().any(|d| d.kind == DeviceKind::Key) {
                                for d in devices.iter_mut() {
                                    if d.kind == DeviceKind::Key && !d.caps.has(Caps::FIDO2) {
                                        d.caps.insert(Caps::FIDO2);
                                    }
                                }
                            } else {
                                for (i, k) in fido_keys.iter().enumerate() {
                                    let mut caps = Caps::default();
                                    caps.insert(Caps::FIDO2);
                                    let vid = k.vendor_id.unwrap_or(0);
                                    let pid = k.product_id.unwrap_or(0);
                                    let model = k
                                        .product
                                        .clone()
                                        .unwrap_or_else(|| "Security key".to_string());
                                    devices.push(Device {
                                        id: format!("winfido:{vid:04x}:{pid:04x}:{i}"),
                                        name: None,
                                        vendor: format!("{vid:04X}"),
                                        model,
                                        serial: String::new(),
                                        transport: "USB · FIDO HID (admin required)".into(),
                                        firmware: String::new(),
                                        caps,
                                        unverified: Caps::default(),
                                        kind: DeviceKind::Key,
                                        hid_path: None,
                                        reader: None,
                                        hid_serial: None,
                                        naming: Default::default(),
                                    });
                                }
                            }
                        }
                    }
                    // Keep the current selection if that device is still present;
                    // otherwise fall back to the first device.
                    let keep = app
                        .selected_device
                        .as_ref()
                        .filter(|id| devices.iter().any(|d| &d.id == *id))
                        .cloned();
                    let next = keep.or_else(|| devices.first().map(|d| d.id.clone()));
                    let changed = next != app.selected_device;
                    let previous = app.selected_device.clone();
                    app.selected_device = next;
                    // Surface duplicate-serial ambiguity (KEY-015): same-serial
                    // keys stay separately selectable (distinct #-suffixed ids),
                    // but naming can't disambiguate them, so tell the user.
                    app.devices_error = duplicate_serial_note(
                        devices
                            .iter()
                            .filter(|d| d.kind == DeviceKind::Key && !d.serial.is_empty())
                            .map(|d| d.serial.as_str()),
                    );
                    // Background: every scan funnels through here, whether it
                    // was kicked off by a hotplug event, the first-frame
                    // auto-scan, or a "Refresh"/"Scan for devices" click — the
                    // staggered burst that follows any of them (`pending_scans`)
                    // makes "which scan did the user actually ask for" moot in
                    // practice, so all of them log at the same, muted weight.
                    // keys.json unreadable, or names seen on keys not
                    // recorded: each shown once per session.
                    for w in keyroost_resolve::take_scan_warnings() {
                        app.log_global(Severity::Warn, LogKind::User, w);
                    }
                    app.log_global(
                        Severity::Info,
                        LogKind::Background,
                        format!(
                            "device scan: {} device{} found",
                            devices.len(),
                            if devices.len() == 1 { "" } else { "s" }
                        ),
                    );
                    app.devices = devices;
                    // A device that's genuinely gone shouldn't leave its
                    // cached PIV identity/pubkey data sitting in memory
                    // indefinitely. Prune here, against an actual fresh scan
                    // result, rather than on every selection change (nothing
                    // about switching *which* still-present device is
                    // selected implies any device disappeared) or on a
                    // failed scan (transient — doesn't mean the hardware
                    // actually went away, and wiping every entry over one
                    // pcscd hiccup would force a full re-fingerprint of
                    // everything on the next successful scan for no reason).
                    app.piv_session_state
                        .retain(|id, _| app.devices.iter().any(|d| &d.id == id));
                    if changed {
                        app.on_device_selected(previous);
                    }
                }
                Err(e) => {
                    app.log_global(
                        Severity::Warn,
                        LogKind::Background,
                        format!("device scan failed: {e}"),
                    );
                    App::apply_device_scan_failure(app, e);
                }
            })
        });
    }

    /// A scan that failed outright: no device list, and therefore no selection.
    /// Lifted out of `refresh_devices`'s apply closure so the teardown rule is
    /// exercisable without hardware.
    ///
    /// Clearing the selection here is a selection *change* like any other, and
    /// has to run the same teardown — `on_device_selected` is the sole owner of
    /// ending an armed FIDO ceremony, so assigning `None` directly left the arm
    /// live with nothing selected: the dialog (device-scoped) repaints its
    /// un-armed confirm form while the poll goes on watching for the replug,
    /// and every rescan path is suppressed while an arm exists, so the empty
    /// list could never recover on its own.
    fn apply_device_scan_failure(app: &mut App, error: String) {
        app.devices_error = Some(error);
        app.devices.clear();
        if let Some(previous) = app.selected_device.take() {
            // Same teardown as any other selection change. With nothing
            // selected it returns before dispatching any read.
            app.on_device_selected(Some(previous));
        }
    }

    /// Select a device by id (no-op if already selected).
    fn select_device(&mut self, id: DeviceId) {
        if self.selected_device.as_deref() == Some(id.as_str()) {
            return;
        }
        let previous = self.selected_device.replace(id);
        self.on_device_selected(previous);
    }

    /// Reset per-applet state for a new selection and kick off the cheap,
    /// no-touch reads (FIDO GetInfo; Molto2 session open). OATH/PGP/PIV reads
    /// stay deferred to their tab so selecting a key never triggers a surprise
    /// touch prompt. `previous` is the device id that was selected before
    /// this change (`None` if nothing was), needed only to save its
    /// `cap_tab` pick — everything else this resets is genuinely per-device
    /// UI/session state with nothing worth carrying forward under any id.
    fn on_device_selected(&mut self, previous: Option<DeviceId>) {
        if let Some(prev) = previous {
            self.cap_tab_by_device.insert(prev, self.cap_tab);
        }
        // The raw remembered pick, or `Overview` for a device seen for the
        // first time — `cap_tabs` corrects it at render time if it's stale
        // for this device (`snap_cap_tab`), so no need to consult
        // `self.devices` here just to pre-validate it.
        self.cap_tab = self
            .selected_device
            .as_ref()
            .and_then(|id| self.cap_tab_by_device.get(id))
            .copied()
            .unwrap_or_default();
        self.security_keys.info = None;
        self.security_keys.init = None;
        self.security_keys.session = None;
        self.security_keys.session_device = None;
        self.security_keys.error = None;
        // Large-blob state is per-key; drop it so the next key auto-loads fresh.
        self.security_keys.large_blobs = None;
        self.security_keys.lb_capacity = None;
        self.security_keys.lb_autoloaded = false;
        self.security_keys.lb_selected = None;
        self.security_keys.lb_editing = None;
        self.security_keys.lb_show_add = false;
        self.security_keys.lb_status = None;
        self.security_keys.lb_confirm_delete = None;
        self.security_keys.lb_confirm_clear = false;
        // SSH-cert extract state is per-key too (KEY-012): drop any parked certs
        // and the result line so a different key never shows the previous one's.
        // A dialog still open for the old key then resolves to "no certificate
        // was ready to write" rather than the new key's cert.
        self.security_keys.ssh_cert_pending.clear();
        self.security_keys.ssh_cert_status = None;
        // Fingerprint state is per-key: the cached list, the pending delete /
        // rename, the name draft, and a live enroll wizard must not carry
        // over (KEY-012). A running enroll worker is told to cancel; it
        // aborts at the next KEEPALIVE.
        self.security_keys.fingerprints = None;
        self.security_keys.fp_new_name.clear();
        self.security_keys.fp_confirm_delete = None;
        self.security_keys.fp_rename = None;
        if let Some(p) = self.security_keys.fp_progress.take() {
            if let Ok(g) = p.lock() {
                g.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
            }
        }
        self.oath.creds.clear();
        self.oath.skipped = 0;
        self.oath.loaded = false;
        self.oath.locked = false;
        self.oath.error = None;
        self.oath.unlocked_password = None;
        self.openpgp.status = None;
        self.openpgp.loaded = false;
        self.openpgp.error = None;
        self.openpgp.notice = None;
        self.openpgp.name_input.clear();
        self.openpgp.url_input.clear();
        self.openpgp.supported = None;
        self.openpgp.gen_alg = OpenPgpKeyAlgSel::CardDefault;
        self.piv = PivState::default();
        // Typed secrets must never survive a selection change — a PIN entered
        // for one key would otherwise be sent to another (the OATH pane even
        // auto-submits its password on tab open), silently burning retry
        // counters on the wrong device.
        wipe(&mut self.security_keys.pin_input);
        wipe(&mut self.security_keys.change_pin.old);
        wipe(&mut self.security_keys.change_pin.new);
        wipe(&mut self.security_keys.change_pin.confirm);
        self.security_keys.change_pin.open = false;
        // A pending advanced-config dialog (and its typed PIN — wiped by the
        // Drop impl) must not survive onto another key (KEY-007).
        self.security_keys.advanced = None;
        wipe(&mut self.oath.password_input);
        wipe(&mut self.oath.add.secret);
        wipe(&mut self.otp.add.secret);
        self.openpgp.wipe_secrets();
        // Destructive confirmations are per-device: a delete/reset dialog
        // opened for one key must not survive onto another (KEY-008/KEY-013).
        self.oath.confirm_delete = None;
        self.openpgp.cred_modal = None;
        self.security_keys.reset = ResetDialog::default();
        // …and so is the *armed* ceremony behind that dialog. An arm outlives
        // its dialog otherwise (nothing else clears it once the dialog is gone),
        // and it is entirely invisible: the poll keeps running, so replugging
        // the key it was armed for wipes it with the user looking at another
        // key — and the outcome would land in whatever report is on screen.
        // An armed ceremony must not outlive the selection it was armed for.
        if self.reset_arm.take().is_some() {
            self.log_global(
                Severity::Warn,
                LogKind::User,
                "the armed reset was cancelled \u{2014} selecting another key ends the ceremony. \
                 Re-open \u{201C}Reset key\u{201D} on the key you want to wipe.",
            );
        }
        self.factory_reset_report.clear();
        self.oath_tried = false;
        self.piv_tried = false;
        self.otp_tried = false;
        self.otp = OtpState::default();
        self.molto_reset_confirm = false;
        self.molto_delete_confirm = false;
        self.close_rename();
        self.authenticated = false;
        self.session = None;
        self.molto_session_device = None;
        self.info = None;
        self.slot_meta = None;

        let Some(dev) = self.selected_device().cloned() else {
            return;
        };
        match dev.kind {
            DeviceKind::Token => self.open_molto(),
            DeviceKind::ProgToken => self.open_prog(),
            DeviceKind::Key if dev.caps.has(Caps::FIDO2) => self.fetch_selected_info(),
            DeviceKind::Key => {}
        }
    }

    /// Open the selected Molto2 token's PC/SC session and read its info, so the
    /// dedicated token pane has a live handle.
    fn open_molto(&mut self) {
        let Some(reader) = self.selected_device().and_then(|d| d.reader.clone()) else {
            return;
        };
        // Tag the job with the device it opens — a delayed completion must
        // not repopulate the pane after the user switches keys (KEY-004).
        let for_device = self.selected_device.clone();
        self.spawn_job("Opening Molto2\u{2026}", move || {
            let result = (|| -> Result<(Session, DeviceInfo, Option<Vec<ProfilePublicData>>), TransportError> {
                let mut s = Session::open_named(&reader)?;
                let info = s.read_info()?;
                // Public-block sweep, one APDU per slot (~1-2 s). A failed sweep
                // degrades to the bare slot list; it must never block the open.
                let meta = (0..PROFILES)
                    .map(|p| s.read_public_data(p))
                    .collect::<Result<Vec<_>, _>>()
                    .ok();
                Ok((s, info, meta))
            })();
            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return; // user switched devices mid-open; drop the session
                }
                match result {
                    Ok((s, info, meta)) => {
                        // Background: this fires automatically whenever a
                        // Molto2 is selected, never from a click of the
                        // user's own — same treatment as the device scan
                        // that usually precedes it.
                        app.log_bg(Severity::Ok, format!("opened Molto2 {}", info.serial));
                        // Enumeration's gentle probe usually fills these already;
                        // refresh them here as a fallback in case that read failed.
                        if let Some(id) = for_device.clone() {
                            let named = keyroost_keyring::Keyring::load_default()
                                .ok()
                                .and_then(|k| k.local_name_for(&info.serial).map(str::to_owned));
                            if let Some(dev) = app.devices.iter_mut().find(|d| d.id == id) {
                                dev.serial = info.serial.clone();
                                if dev.name.is_none() {
                                    dev.name = named;
                                }
                            }
                        }
                        app.session = Some(s);
                        app.molto_session_device = for_device;
                        app.info = Some(info);
                        app.slot_meta = meta;
                        app.authenticated = false;
                    }
                    Err(e) => app.log_bg(Severity::Err, format!("open Molto2: {e}")),
                }
            })
        });
    }

    /// Open the selected programmable token's PC/SC session and read its info,
    /// so the pane can show the model, serial and on-device clock.
    fn open_prog(&mut self) {
        let Some(reader) = self.selected_device().and_then(|d| d.reader.clone()) else {
            return;
        };
        let for_device = self.selected_device.clone();
        self.spawn_job("Opening token\u{2026}", move || {
            let result =
                (|| -> Result<(Token2ProgSession, keyroost_token2prog::Info), TransportError> {
                    let mut s = Token2ProgSession::open_named(&reader)?;
                    let info = s.read_info()?;
                    Ok((s, info))
                })();
            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return; // user switched devices mid-open
                }
                match result {
                    Ok((s, info)) => {
                        app.log(
                            Severity::Ok,
                            format!("opened programmable token {}", info.serial),
                        );
                        app.prog_session = Some(s);
                        app.prog_info = Some(info);
                        app.prog_authenticated = false;
                    }
                    Err(e) => app.log(Severity::Err, format!("open token: {e}")),
                }
            })
        });
    }

    /// Same contract as `spawn_job` (returns whether the job actually
    /// queued), but also manages `PivState::inflight` for the job's
    /// lifetime: set the moment it queues, cleared as the very first thing
    /// the apply closure does — before whatever outcome-specific work `job`
    /// goes on to do, same ordering `piv_reset` used to hand-roll for
    /// `reset_inflight` alone. Every PIV device job (status read, PIN/PUK/
    /// management-key change, key generate/import/delete/move, self-test,
    /// self-sign/CSR, CHUID write, reset, ...) should queue through this
    /// rather than `spawn_job` directly, so `cap_piv`'s two
    /// `add_enabled_ui(!self.piv.inflight, ...)` wraps disable the pane for
    /// any of them uniformly instead of each call site managing its own flag.
    fn spawn_piv_job<F>(&mut self, label: impl Into<String>, job: F) -> bool
    where
        F: FnOnce() -> ApplyFn + Send + 'static,
    {
        let queued = self.spawn_job(label, move || {
            let apply = job();
            Box::new(move |app: &mut App| {
                app.piv.inflight = false;
                apply(app);
            }) as ApplyFn
        });
        if queued {
            self.piv.inflight = true;
        }
        queued
    }

    /// The selected device's cached [`keyroost_transport::PivSessionState`]
    /// (an empty, freshly-`Default`ed one the first time this device's PIV
    /// tab does anything), cloned for a background job to move into its
    /// `PivSession::with_cached_transaction` call — cloned rather than borrowed because
    /// the job runs off-thread and can't hold a reference into `App`. Every
    /// PIV action calls this before `spawn_piv_job` and passes the result
    /// through; see the `piv_session_state` field's doc for the full round
    /// trip.
    fn piv_cached_piv_session_state(&self) -> keyroost_transport::PivSessionState {
        let mut state: keyroost_transport::PivSessionState = self
            .selected_device
            .as_ref()
            .and_then(|id| self.piv_session_state.get(id))
            .cloned()
            .unwrap_or_default();
        // "Enable Anyway" also lets the transport send the internal reads
        // (GET METADATA, ATTEST) the table would otherwise skip for this key.
        state.set_send_unsupported_reads(self.piv_compat_ignored_selected());
        state
    }

    /// Whether the user chose to ignore the compatibility table for the
    /// selected key (see `piv_compat_ignored`).
    fn piv_compat_ignored_selected(&self) -> bool {
        self.selected_device
            .as_ref()
            .is_some_and(|id| self.piv_compat_ignored.contains(id))
    }

    /// The compatibility table's gate for `extension` on this device, relaxed
    /// ("unsupported" → "unverified", except RESET) when the user chose to
    /// ignore the table for the selected key. Every PIV control's gate goes
    /// through here rather than `compat::resolve` directly.
    fn piv_gate(
        &self,
        extension: keyroost_piv::compat::PivExtension,
        fingerprint: keyroost_piv::fingerprint::AppletFingerprint,
        version: Option<&[u8]>,
        version_firmware: Option<&[u8]>,
    ) -> keyroost_piv::compat::FeatureGate {
        let gate = keyroost_piv::compat::resolve(extension, fingerprint, version, version_firmware);
        if self.piv_compat_ignored_selected() {
            piv_relax(extension, gate)
        } else {
            gate
        }
    }

    /// Store `state` as `device`'s cached PIV session state. Called from a
    /// PIV job's apply closure with the device id captured *before* the job
    /// was spawned (not `self.selected_device` as it stands when the apply
    /// closure runs) — unlike `app.piv.status` and the rest of the pane's
    /// live display, which a stale completion must discard (see
    /// `completion_still_valid`), this map is keyed by device id and simply
    /// unused by whatever's currently on screen if the selection moved on,
    /// so there's nothing to guard: storing it is correct and worth doing
    /// even for a device the user has since switched away from, precisely
    /// so switching back to it later still finds it cached. A `None` device
    /// (nothing was selected when the job was captured) is a no-op.
    fn store_piv_session_state(
        &mut self,
        device: Option<DeviceId>,
        state: keyroost_transport::PivSessionState,
    ) {
        if let Some(id) = device {
            self.piv_session_state.insert(id, state);
        }
    }

    /// Split a job result that also carries the session's final
    /// [`keyroost_transport::PivSessionState`] into the plain
    /// `Result<PivStatus, TransportError>` [`Self::apply_piv_write`] expects,
    /// storing the state for `device` along the way (a no-op on `Err`: a
    /// job whose `PivSession::with_cached_transaction` failed outright, or that never
    /// got as far as producing a final state, has nothing to store). Shared
    /// by every simple PIN/PUK/management-key/retries write, which
    /// otherwise all repeat this same split.
    fn store_and_unwrap_piv_write(
        &mut self,
        device: Option<DeviceId>,
        result: Result<
            (
                keyroost_transport::PivStatus,
                keyroost_transport::PivSessionState,
            ),
            TransportError,
        >,
    ) -> Result<keyroost_transport::PivStatus, TransportError> {
        match result {
            Ok((status, state)) => {
                self.store_piv_session_state(device, state);
                Ok(status)
            }
            Err(e) => Err(e),
        }
    }

    /// [`Self::store_and_unwrap_piv_write`] for a certificate import or
    /// self-signed certificate job, which also returns what the import
    /// stored ([`keyroost_transport::CertImport`]).
    fn store_and_unwrap_piv_cert_write(
        &mut self,
        device: Option<DeviceId>,
        result: Result<
            (
                keyroost_transport::PivStatus,
                keyroost_transport::PivSessionState,
                keyroost_transport::CertImport,
            ),
            TransportError,
        >,
    ) -> Result<
        (
            keyroost_transport::PivStatus,
            keyroost_transport::CertImport,
        ),
        TransportError,
    > {
        let (result, stored) = match result {
            Ok((status, state, stored)) => (Ok((status, state)), Some(stored)),
            Err(e) => (Err(e), None),
        };
        let status = self.store_and_unwrap_piv_write(device, result)?;
        Ok((status, stored.expect("Ok result carries the CertImport")))
    }

    /// [`Self::load_piv_status_with_cache`] with `cache` fixed to
    /// [`PivCache::Reuse`] — the common case: every caller except the
    /// Refresh button wants this. See that method's doc for the full
    /// contract.
    fn load_piv_status(&mut self, kind: LogKind) {
        self.load_piv_status_with_cache(kind, PivCache::Reuse);
    }

    /// Read the selected card's read-only PIV status snapshot: status + every
    /// slot's algorithm/subject/policy. `kind` should be `User` only when
    /// this runs because the user clicked "Refresh" — the initial read when
    /// the PIV tab is first opened, and the re-read every write triggers
    /// afterwards to pick up what it changed, both pass `Background` so the
    /// activity log renders them the way they actually happened (see
    /// `LogKind`). `cache` governs the separate question of whether this
    /// read trusts `piv_session_state` at all — see [`PivCache`]. Callers
    /// that always want [`PivCache::Reuse`] (everyone but the Refresh
    /// button) can go through [`Self::load_piv_status`] instead, which
    /// fixes it for them. The activity log line itself distinguishes the two
    /// outcomes a `Reuse` read can have: "PIV status read (N slots)" when
    /// [`keyroost_transport::PivSession::touched_card`] says a live APDU
    /// actually reached the card, "PIV status cache validated" when every
    /// value came out of the reused state with none.
    fn load_piv_status_with_cache(&mut self, kind: LogKind, cache: PivCache) {
        self.piv.error = None;
        let Some(reader) = self.selected_oath_reader() else {
            return;
        };
        let for_device = self.selected_device.clone();
        let cached_state = match cache {
            PivCache::Reuse => Some(self.piv_cached_piv_session_state()),
            // A fresh read still honours "Enable Anyway": an empty state never
            // matches the card, so this resolves everything from scratch like
            // the plain path, but with the user's choice carried in.
            PivCache::Bypass => self.piv_compat_ignored_selected().then(|| {
                let mut fresh = keyroost_transport::PivSessionState::default();
                fresh.set_send_unsupported_reads(true);
                fresh
            }),
        };
        self.spawn_piv_job("Reading PIV status\u{2026}", move || {
            // One transport call gathers the snapshot and every slot's
            // algorithm / Subject DN / PIN-touch policy, reading each slot's
            // GET METADATA and certificate object exactly once. Doing this
            // pane-side with `slot_key_algorithm` + `read_certificate` +
            // `slot_policy` per slot re-read the certificate two or three
            // times and GET METADATA twice (`PivSession` keeps no read cache).
            // `with_cached_transaction` carries forward whatever keys generated earlier
            // this app run were already cached — including across a device
            // switch and back — so there's no need to reseed `remember_pubkey`
            // per slot the way a plain `with_transaction` would have required;
            // `PivCache::Bypass` forgoes that on purpose — see this
            // method's doc.
            let result = match cached_state {
                Some(cached) => {
                    keyroost_transport::PivSession::with_cached_transaction(&reader, cached, |s| {
                        let detailed = s.status_detailed();
                        // Read before `state()` so it reflects this call's
                        // own status_detailed() and nothing after — whether
                        // *any* of it needed a live APDU, or every value came
                        // out of the state `with_cached_transaction` carried
                        // in with no card round trip at all.
                        let touched_card = s.touched_card();
                        Ok::<_, TransportError>((detailed, s.state(), touched_card))
                    })
                }
                None => keyroost_transport::PivSession::with_transaction(&reader, |s| {
                    let detailed = s.status_detailed();
                    let touched_card = s.touched_card();
                    Ok::<_, TransportError>((detailed, s.state(), touched_card))
                }),
            };
            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return; // selection changed mid-read; discard
                }
                match result {
                    Ok((Ok(detailed), state, touched_card)) => {
                        app.store_piv_session_state(for_device.clone(), state);
                        let keyroost_transport::PivStatusDetailed { status, slots, .. } = detailed;
                        // `touched_card` false means every field above came
                        // out of the cache `with_cached_transaction` reused, with no
                        // live APDU at all — say so distinctly from an
                        // actual read, rather than implying this round trip
                        // hit the card when it didn't.
                        let message = if touched_card {
                            format!("PIV status read ({} slots)", slots.len())
                        } else {
                            "PIV status cache validated".to_string()
                        };
                        app.log_kind(Severity::Ok, kind, message);
                        app.piv.slot_keys = slots
                            .iter()
                            .map(|d| (d.slot, d.algorithm, d.subject.clone()))
                            .collect();
                        app.piv.slot_policies = slots.iter().map(|d| (d.slot, d.policy)).collect();
                        app.piv.status = Some(status);
                        app.piv.loaded = true;
                    }
                    Ok((Err(e), state, _touched_card)) => {
                        app.store_piv_session_state(for_device.clone(), state);
                        app.log_kind(Severity::Err, kind, format!("PIV status read: {e}"));
                        app.piv.error = Some(e.to_string());
                    }
                    Err(e) => {
                        app.log_kind(Severity::Err, kind, format!("PIV status read: {e}"));
                        app.piv.error = Some(e.to_string());
                    }
                }
            })
        });
    }

    /// Apply a PIV write result: on success store the notice and refreshed
    /// status; on error store the message. Shared by every PIV write action —
    /// also where every one of them logs, User-weight (the caller's `notice`
    /// already says what happened in plain terms; a click landed here to
    /// produce it).
    fn apply_piv_write(
        app: &mut App,
        result: Result<keyroost_transport::PivStatus, TransportError>,
        notice: String,
    ) {
        match result {
            Ok(status) => {
                app.log(Severity::Ok, notice.clone());
                app.piv.status = Some(status);
                app.piv.error = None;
                app.piv.notice = Some(notice);
                // Re-read so per-slot key algorithms (and anything the write
                // touched) reflect the new state without a manual Refresh —
                // background: it's a side-effect re-read, not the action the
                // user asked for (that's the log line just above).
                app.load_piv_status(LogKind::Background);
                // Any successful PIV write (delete, reset, move, ...) can change
                // retired-slot occupancy; drop the cache so the retired tab
                // re-reads fresh on its next open instead of showing stale
                // occupancy (see piv_move_key for the same invalidation).
                app.piv.retired_occupancy = None;
                // A retired-slot selection is stale once its occupancy cache is
                // dropped; snapping back to a
                // standard slot prevents acting on it with unknown occupancy —
                // notably the Generate overwrite guard, which would otherwise
                // see "unknown" as "empty" and skip its warning on a still-
                // occupied archived key.
                if matches!(app.piv.selected_slot, PivSlotSel::Retired(_)) {
                    app.piv.selected_slot = PivSlotSel::Auth;
                }
            }
            Err(e) => {
                app.log(Severity::Err, e.to_string());
                app.piv.notice = None;
                app.piv.error = Some(e.to_string());
            }
        }
    }

    /// Mirror a PIV PIN/PUK write result into the credential modal so the outcome
    /// is shown in-modal (issue #31). Reads the pane status `apply_piv_write` just
    /// set: success clears `busy` and records `Ok(())`; an error records the
    /// message and keeps the modal open for a retry. Cleared secrets on success
    /// are wiped by the op's apply closure regardless.
    fn apply_piv_cred_result(app: &mut App) {
        if let Some(m) = app.piv.cred_modal.as_mut() {
            m.busy = false;
            m.result = match &app.piv.error {
                Some(e) => Some(Err(e.clone())),
                None => Some(Ok(())),
            };
        }
    }

    /// [`Self::apply_piv_write`] + [`Self::apply_piv_cred_result`] for a
    /// certificate import or self-signed certificate: the notice (`base`
    /// plus how it was stored) and the dialog's detail mirror the CLI's
    /// output, and a too-large refusal under Never points at the dropdown.
    fn apply_piv_cert_write(
        app: &mut App,
        result: Result<
            (
                keyroost_transport::PivStatus,
                keyroost_transport::CertImport,
            ),
            TransportError,
        >,
        base: &str,
        choice: PivCertCompressionSel,
    ) {
        match result {
            Ok((status, stored)) => {
                let notice = piv_cert_stored_notice(
                    base,
                    stored.compressed,
                    stored.stored_len,
                    stored.auto_compressed,
                );
                Self::apply_piv_write(app, Ok(status), notice);
                if let Some(m) = app.piv.cred_modal.as_mut() {
                    m.detail = piv_cert_stored_detail(
                        stored.compressed,
                        stored.stored_len,
                        stored.auto_compressed,
                    );
                }
            }
            Err(e) => {
                let hint = piv_cert_error_hint(&e, choice);
                Self::apply_piv_write(app, Err(e), String::new());
                if let (Some(hint), Some(err)) = (hint, app.piv.error.as_mut()) {
                    err.push_str(hint);
                }
            }
        }
        Self::apply_piv_cred_result(app);
    }

    /// Change the PIV PIN. Validates new==confirm, runs off-thread, and surfaces
    /// the outcome both in the pane banner and in the credential modal.
    fn piv_change_pin(&mut self) {
        let Some(name) = self.selected_oath_reader() else {
            return;
        };
        if self.piv.pin_new != self.piv.pin_confirm {
            self.piv.notice = None;
            self.piv.error = Some("the two new PINs don't match".into());
            return;
        }
        let (old, new) = (self.piv.pin_old.clone(), self.piv.pin_new.clone());
        self.piv.notice = None;
        let for_device = self.selected_device.clone();
        let cached_state = self.piv_cached_piv_session_state();
        self.spawn_piv_job("Changing PIV PIN\u{2026}", move || {
            let result =
                keyroost_transport::PivSession::with_cached_transaction(&name, cached_state, |s| {
                    s.change_pin(old.as_bytes(), new.as_bytes())?;
                    let status = s.status()?;
                    Ok((status, s.state()))
                });
            Box::new(move |app: &mut App| {
                wipe(&mut app.piv.pin_old);
                wipe(&mut app.piv.pin_new);
                wipe(&mut app.piv.pin_confirm);
                let result = app.store_and_unwrap_piv_write(for_device, result);
                Self::apply_piv_write(app, result, "PIN changed.".into());
                Self::apply_piv_cred_result(app);
            })
        });
    }

    fn piv_change_puk(&mut self) {
        let Some(name) = self.selected_oath_reader() else {
            return;
        };
        if self.piv.puk_new != self.piv.puk_confirm {
            self.piv.notice = None;
            self.piv.error = Some("the two new PUKs don't match".into());
            return;
        }
        let (old, new) = (self.piv.puk_old.clone(), self.piv.puk_new.clone());
        self.piv.notice = None;
        let for_device = self.selected_device.clone();
        let cached_state = self.piv_cached_piv_session_state();
        self.spawn_piv_job("Changing PUK\u{2026}", move || {
            let result =
                keyroost_transport::PivSession::with_cached_transaction(&name, cached_state, |s| {
                    s.change_puk(old.as_bytes(), new.as_bytes())?;
                    let status = s.status()?;
                    Ok((status, s.state()))
                });
            Box::new(move |app: &mut App| {
                wipe(&mut app.piv.puk_old);
                wipe(&mut app.piv.puk_new);
                wipe(&mut app.piv.puk_confirm);
                let result = app.store_and_unwrap_piv_write(for_device, result);
                Self::apply_piv_write(app, result, "PUK changed.".into());
                Self::apply_piv_cred_result(app);
            })
        });
    }

    fn piv_unblock_pin(&mut self) {
        let Some(name) = self.selected_oath_reader() else {
            return;
        };
        let (puk, new) = (
            self.piv.unblock_puk.clone(),
            self.piv.unblock_new_pin.clone(),
        );
        self.piv.notice = None;
        let for_device = self.selected_device.clone();
        let cached_state = self.piv_cached_piv_session_state();
        self.spawn_piv_job("Unblocking PIN\u{2026}", move || {
            let result =
                keyroost_transport::PivSession::with_cached_transaction(&name, cached_state, |s| {
                    s.unblock_pin(puk.as_bytes(), new.as_bytes())?;
                    let status = s.status()?;
                    Ok((status, s.state()))
                });
            Box::new(move |app: &mut App| {
                wipe(&mut app.piv.unblock_puk);
                wipe(&mut app.piv.unblock_new_pin);
                let result = app.store_and_unwrap_piv_write(for_device, result);
                Self::apply_piv_write(app, result, "PIN unblocked and reset.".into());
                Self::apply_piv_cred_result(app);
            })
        });
    }

    /// [`piv_default_mgmt_key`] for the currently selected card's last-read
    /// status — `None` before any status has been read, or when this
    /// fingerprint/version carries no
    /// [`keyroost_piv::compat::PivQuirk::Default9bManagementKey`]. The one
    /// place both [`Self::piv_current_mgmt_key`] and
    /// [`Self::piv_modal_mgmt_field`]'s checkbox-enablement check resolve
    /// this, so the two can't disagree about whether a default is on offer.
    fn piv_current_default_mgmt_key(&self) -> Option<&'static [u8]> {
        let status = self.piv.status.as_ref()?;
        piv_default_mgmt_key(
            status.applet_fingerprint,
            status.version.as_deref(),
            status.version_firmware.as_deref(),
        )
    }

    /// Resolve the *current* management key the user authorized this op with:
    /// this device's well-known factory default when "Use default management
    /// key" is ticked, otherwise the hex they typed. Decoding errors are
    /// surfaced the same way the inline field's were; ticking the toggle on a
    /// device with no known default (which the checkbox should already be
    /// disabled for — see [`Self::piv_modal_mgmt_field`]) surfaces the same
    /// way rather than silently falling back to a guess.
    fn piv_current_mgmt_key(&self) -> Result<zeroize::Zeroizing<Vec<u8>>, String> {
        if self.piv.mgmt_auth_mode == PivMgmtAuthMode::Default {
            self.piv_current_default_mgmt_key()
                .map(|key| zeroize::Zeroizing::new(key.to_vec()))
                .ok_or_else(|| "This device has no known default management key.".to_string())
        } else {
            piv_mgmt_key_bytes(&self.piv.mgmt_key_input)
        }
    }

    /// Resolve how the user authorized `kind`'s management operation: the
    /// standard management key (default or typed — [`Self::piv_current_mgmt_key`])
    /// or, with "Use PIN" ticked, a PIN for
    /// `PivSession::authenticate_management_via_pin`. The PIN itself comes
    /// from `mgmt_key_input` normally, or — for a flow with a dedicated PIN
    /// field of its own (`PivCredKind::shares_pin_field`) — from that field
    /// directly, exactly the sequence [`piv_authenticate`] would run had the
    /// same PIN been typed into the management-key field instead: PIV has
    /// only one application PIN, so there's nothing to gain by asking twice.
    fn piv_current_mgmt_auth(&self, kind: PivCredKind) -> Result<PivMgmtAuth, String> {
        if self.piv.mgmt_auth_mode == PivMgmtAuthMode::Pin {
            let pin = if kind.shares_pin_field() {
                match kind {
                    PivCredKind::SelfSign => &self.piv.sign_pin,
                    PivCredKind::SetRetries => &self.piv.retries_pin_auth,
                    _ => unreachable!("shares_pin_field() covers exactly these two kinds"),
                }
            } else {
                &self.piv.mgmt_key_input
            };
            return Ok(PivMgmtAuth::Pin(zeroize::Zeroizing::new(pin.clone())));
        }
        self.piv_current_mgmt_key().map(PivMgmtAuth::Key)
    }

    fn piv_set_retries(&mut self) {
        let Some(name) = self.selected_oath_reader() else {
            return;
        };
        let mgmt = match self.piv_current_mgmt_auth(PivCredKind::SetRetries) {
            Ok(a) => a,
            Err(e) => {
                self.piv.error = Some(e);
                return;
            }
        };
        let pin = zeroize::Zeroizing::new(self.piv.retries_pin_auth.clone());
        let (pin_tries, puk_tries) = (self.piv.retries_pin, self.piv.retries_puk);
        self.piv.notice = None;
        let for_device = self.selected_device.clone();
        let cached_state = self.piv_cached_piv_session_state();
        self.spawn_piv_job("Setting PIV retry counts\u{2026}", move || {
            let result =
                keyroost_transport::PivSession::with_cached_transaction(&name, cached_state, |s| {
                    piv_authenticate(s, &mgmt)?;
                    s.verify_pin(pin.as_bytes())?;
                    s.set_pin_retries(pin_tries, puk_tries)?;
                    let status = s.status()?;
                    Ok((status, s.state()))
                });
            Box::new(move |app: &mut App| {
                wipe(&mut app.piv.mgmt_key_input);
                wipe(&mut app.piv.retries_pin_auth);
                let result = app.store_and_unwrap_piv_write(for_device, result);
                Self::apply_piv_write(
                    app,
                    result,
                    "Retry counts set; PIN/PUK reset to defaults.".into(),
                );
                Self::apply_piv_cred_result(app);
            })
        });
    }

    fn piv_generate_key(&mut self) {
        let Some(name) = self.selected_oath_reader() else {
            return;
        };
        let mgmt = match self.piv_current_mgmt_auth(PivCredKind::GenerateKey) {
            Ok(a) => a,
            Err(e) => {
                self.piv.error = Some(e);
                return;
            }
        };
        let slot = self.piv.selected_slot.to_slot();
        let alg = self.piv.gen_alg;
        let (pin_policy, touch_policy) = (self.piv.gen_pin_policy, self.piv.gen_touch_policy);
        self.piv.notice = None;
        let for_device = self.selected_device.clone();
        let cached_state = self.piv_cached_piv_session_state();
        self.spawn_piv_job("Generating key\u{2026} (touch if it blinks)", move || {
            let result = keyroost_transport::PivSession::with_cached_transaction(
                &name,
                cached_state,
                |s| -> Result<_, TransportError> {
                    piv_authenticate(s, &mgmt)?;
                    let pubkey = s.generate_key(slot, alg, pin_policy, touch_policy)?;
                    let status = s.status()?;
                    Ok((pubkey, status, s.state()))
                },
            );
            Box::new(move |app: &mut App| {
                wipe(&mut app.piv.mgmt_key_input);
                match result {
                    Ok((pubkey, status, state)) => {
                        app.log(
                            Severity::Ok,
                            format!("generated {} key in {}", alg.label(), slot.label()),
                        );
                        app.piv.status = Some(status);
                        app.piv.error = None;
                        // `generate_key` already remembered the new key in
                        // this session's own pubkey cache — see
                        // `PivSessionState::pubkey_cache`'s doc. Storing the
                        // updated state (rather than just discarding it) is
                        // what lets a later self-sign/CSR, or this same
                        // status refresh below, name the key on cards that
                        // don't answer GET METADATA — including after
                        // switching to another device's tab and back, which
                        // a bare per-job cache couldn't survive.
                        app.store_piv_session_state(for_device.clone(), state);
                        match keyroost_piv::spki::subject_public_key_info(&pubkey, alg) {
                            Ok(_) => {
                                app.piv.notice = Some(format!("Generated {} key.", alg.label()));
                            }
                            Err(e) => {
                                app.piv.notice = Some(format!(
                                    "Generated {} key (public-key encoding failed: {})",
                                    alg.label(),
                                    e
                                ));
                            }
                        }
                        // Re-read so the slot's "State:" line picks up the new
                        // key's algorithm immediately, same as every other PIV
                        // write (`apply_piv_write`) already does. This matters
                        // even more here than there: on firmware without GET
                        // METADATA, `slot_key_algorithm` has no certificate to
                        // fall back to yet (this slot didn't have one before
                        // generating and still doesn't), so without this
                        // refresh the pane would keep showing "empty" until
                        // some *other* write happened to trigger one.
                        app.load_piv_status(LogKind::Background);
                        // A retired slot's occupancy cache may now be stale
                        // (generation can target a retired slot); drop it so
                        // it re-reads fresh rather than keeping a cached
                        // "empty" for the slot just written to. Unlike
                        // `apply_piv_write`'s reset path, the selection itself
                        // stays put — the user is almost certainly about to
                        // look at (or self-sign/CSR) exactly the slot they
                        // just generated into.
                        app.piv.retired_occupancy = None;
                    }
                    Err(e) => {
                        app.log(Severity::Err, e.to_string());
                        app.piv.notice = None;
                        app.piv.error = Some(e.to_string());
                    }
                }
                Self::apply_piv_cred_result(app);
            })
        });
    }

    fn piv_import_cert(&mut self) {
        let Some(name) = self.selected_oath_reader() else {
            return;
        };
        let mgmt = match self.piv_current_mgmt_auth(PivCredKind::ImportCert) {
            Ok(a) => a,
            Err(e) => {
                self.piv.error = Some(e);
                return;
            }
        };
        let slot = self.piv.selected_slot.to_slot();
        let path = self.piv.cert_path.trim().to_owned();
        let choice = self.piv.cert_compression;
        self.piv.notice = None;
        let for_device = self.selected_device.clone();
        // `with_cached_transaction` restores the whole cached pubkey map (every slot, not
        // just this one) as part of resolving the session — see
        // `load_piv_status`/`piv_self_sign`'s docs for why a key generated
        // earlier this app run, including one that overwrote an older key
        // already loaded into this slot, has to be known before
        // `import_certificate`'s own key-match check
        // (`PivSession::reject_certificate_key_mismatch`) has anything to
        // compare against — without it, that check silently treats the
        // slot's key as unknowable and lets a stale certificate through even
        // when this app run knows better.
        let cached_state = self.piv_cached_piv_session_state();
        self.spawn_piv_job("Importing certificate\u{2026}", move || {
            let result = (|| -> Result<
                (
                    keyroost_transport::PivStatus,
                    keyroost_transport::PivSessionState,
                    keyroost_transport::CertImport,
                ),
                TransportError,
            > {
                let bytes = std::fs::read(&path).map_err(|_| {
                    TransportError::MalformedResponse("cannot read certificate file")
                })?;
                let der = cert_bytes_to_der(&bytes)
                    .ok_or(TransportError::MalformedResponse("file is not PEM or DER"))?;
                keyroost_transport::PivSession::with_cached_transaction(
                    &name,
                    cached_state,
                    |s| {
                        piv_authenticate(s, &mgmt)?;
                        let stored = s.import_certificate(slot, &der, choice.to_compression())?;
                        let status = s.status()?;
                        Ok((status, s.state(), stored))
                    },
                )
            })();
            Box::new(move |app: &mut App| {
                wipe(&mut app.piv.mgmt_key_input);
                let result = app.store_and_unwrap_piv_cert_write(for_device, result);
                Self::apply_piv_cert_write(app, result, "Certificate imported", choice);
            })
        });
    }

    /// Delete (clear) the certificate in the selected slot. The private
    /// key, if any, is left intact. Management-key authorized; works on every
    /// PIV card. Mirrors `piv_import_cert`'s shape: open → authenticate → call
    /// the transport method → re-read status (so the slot's cert state updates).
    fn piv_delete_cert(&mut self) {
        let Some(name) = self.selected_oath_reader() else {
            return;
        };
        let mgmt = match self.piv_current_mgmt_auth(PivCredKind::DeleteCert) {
            Ok(a) => a,
            Err(e) => {
                self.piv.error = Some(e);
                return;
            }
        };
        let slot = self.piv.selected_slot.to_slot();
        self.piv.notice = None;
        let for_device = self.selected_device.clone();
        let cached_state = self.piv_cached_piv_session_state();
        self.spawn_piv_job("Deleting certificate\u{2026}", move || {
            let result =
                keyroost_transport::PivSession::with_cached_transaction(&name, cached_state, |s| {
                    piv_authenticate(s, &mgmt)?;
                    s.clear_certificate(slot)?;
                    let status = s.status()?;
                    Ok((status, s.state()))
                });
            Box::new(move |app: &mut App| {
                wipe(&mut app.piv.mgmt_key_input);
                let result = app.store_and_unwrap_piv_write(for_device, result);
                Self::apply_piv_write(
                    app,
                    result,
                    format!("Certificate removed from {}.", slot.label()),
                );
                Self::apply_piv_cred_result(app);
            })
        });
    }

    /// Regenerate the "New CHUID" GUID input with a fresh random value —
    /// called when the dialog opens and by its "Refresh" button. Host-side
    /// only (no card I/O); leaves the field as-is on the vanishingly rare RNG
    /// failure rather than blanking a value the user may already be editing.
    fn piv_refresh_chuid_guid(&mut self) {
        if let Ok(guid) = keyroost_transport::random_chuid_guid() {
            self.piv.chuid_guid = keyroost_piv::format_guid(&guid);
        }
    }

    /// "Change management key"'s "Generate random key & Copy" link: fill `New
    /// key` with a fresh random key sized for `alg` and copy it to the
    /// clipboard. Host-side only (no card I/O); the field's prior contents
    /// are wiped, not just overwritten, same discipline as every other
    /// secret-bearing field this app clears. Auto-clears the clipboard after
    /// 45s like the OTP-code copy path, so the generated key doesn't sit in
    /// clipboard-manager history forever. Leaves the field as-is on the
    /// vanishingly rare RNG failure rather than blanking a value the user
    /// may already be editing. Reveals the field (same `secret_reveal` toggle
    /// its own eye icon uses) — the value just landed on the clipboard in
    /// plain text anyway, so hiding it in the field buys nothing and only
    /// stops the user checking what they generated.
    fn piv_generate_random_mgmt_key(&mut self, ctx: &egui::Context, alg: keyroost_piv::MgmtAlg) {
        let Ok(key) = keyroost_transport::random_management_key(alg) else {
            return;
        };
        let hex = hex_lower(&key);
        wipe(&mut self.piv.new_mgmt_key_input);
        self.piv.new_mgmt_key_input.push_str(&hex);
        ctx.copy_text(hex.clone());
        self.clipboard_clear_at = Some((hex, now_secs_f64() + 45.0));
        self.secret_reveal.insert("piv-new-mgmt-key", true);
    }

    /// Write a CHUID — the GUID from `chuid_guid` (a fresh random default,
    /// or whatever the user overwrote it with). Management-key authorized;
    /// applet-wide, not tied to any slot. Mirrors `piv_import_cert`'s shape:
    /// open \u{2192} authenticate \u{2192} call the transport method \u{2192} re-read status.
    /// Windows' PIV minidriver caches a card's contents by its CHUID's GUID,
    /// so this is what makes it notice a slot's certificate/key actually
    /// changed.
    fn piv_new_chuid(&mut self) {
        let Some(name) = self.selected_oath_reader() else {
            return;
        };
        let mgmt = match self.piv_current_mgmt_auth(PivCredKind::NewChuid) {
            Ok(a) => a,
            Err(e) => {
                self.piv.error = Some(e);
                return;
            }
        };
        let guid = match keyroost_piv::parse_guid_hex(&self.piv.chuid_guid) {
            Some(g) => g,
            None => {
                self.piv.error = Some(
                    "GUID must be 16 bytes of hex, dashes optional (e.g. \
                     aabbccdd-eeff-1122-3344-556677889900)"
                        .into(),
                );
                return;
            }
        };
        let expiration = keyroost_piv::yyyymmdd_from_unix_secs(keyroost_piv::add_calendar_period(
            u64::from(unix_now()),
            self.piv.chuid_valid_years,
            self.piv.chuid_valid_months,
            self.piv.chuid_valid_days,
        ));
        self.piv.notice = None;
        let for_device = self.selected_device.clone();
        let cached_state = self.piv_cached_piv_session_state();
        self.spawn_piv_job("Writing a new CHUID\u{2026}", move || {
            let result =
                keyroost_transport::PivSession::with_cached_transaction(&name, cached_state, |s| {
                    piv_authenticate(s, &mgmt)?;
                    s.new_chuid(&guid, &expiration)?;
                    let status = s.status()?;
                    Ok((status, s.state()))
                });
            Box::new(move |app: &mut App| {
                wipe(&mut app.piv.mgmt_key_input);
                let result = app.store_and_unwrap_piv_write(for_device, result);
                Self::apply_piv_write(app, result, "New CHUID written.".into());
                Self::apply_piv_cred_result(app);
            })
        });
    }

    /// Permanently delete (erase) the private key in the selected slot.
    /// Management-key authorized. DELETE KEY is a Yubico extension (fw 5.7+);
    /// the slot panel resolves `keyroost_piv::compat` into a three-way gate
    /// (enable / warn / dim), and an unsupported card refuses the APDU itself
    /// — the transport no longer version-gates.
    fn piv_delete_key(&mut self) {
        let Some(name) = self.selected_oath_reader() else {
            return;
        };
        let mgmt = match self.piv_current_mgmt_auth(PivCredKind::DeleteKey) {
            Ok(a) => a,
            Err(e) => {
                self.piv.error = Some(e);
                return;
            }
        };
        let slot = self.piv.selected_slot.to_slot();
        self.piv.notice = None;
        let for_device = self.selected_device.clone();
        let cached_state = self.piv_cached_piv_session_state();
        self.spawn_piv_job("Deleting key\u{2026}", move || {
            let result =
                keyroost_transport::PivSession::with_cached_transaction(&name, cached_state, |s| {
                    piv_authenticate(s, &mgmt)?;
                    s.delete_key(slot)?;
                    // `delete_key` already evicted this slot from the
                    // session's own pubkey cache — nothing left to do here
                    // beyond storing the updated state back.
                    let status = s.status()?;
                    Ok((status, s.state()))
                });
            Box::new(move |app: &mut App| {
                wipe(&mut app.piv.mgmt_key_input);
                let result = app.store_and_unwrap_piv_write(for_device, result);
                Self::apply_piv_write(app, result, format!("Key erased from {}.", slot.label()));
                Self::apply_piv_cred_result(app);
            })
        });
    }

    /// Relocate the selected slot's private key to the chosen destination slot
    /// (Yubico MOVE KEY). Mirrors `piv_delete_key`: management-key auth, then the
    /// move, then a status re-read. The source slot's certificate stays put.
    fn piv_move_key(&mut self) {
        let Some(name) = self.selected_oath_reader() else {
            return;
        };
        let mgmt = match self.piv_current_mgmt_auth(PivCredKind::MoveKey) {
            Ok(a) => a,
            Err(e) => {
                self.piv.error = Some(e);
                return;
            }
        };
        let src = self.piv.selected_slot.to_slot();
        let Some(dest) = self.piv.move_dest else {
            self.piv.error = Some("choose a destination slot".into());
            return;
        };
        self.piv.notice = None;
        let for_device = self.selected_device.clone();
        let cached_state = self.piv_cached_piv_session_state();
        self.spawn_piv_job("Moving key\u{2026}", move || {
            let result =
                keyroost_transport::PivSession::with_cached_transaction(&name, cached_state, |s| {
                    piv_authenticate(s, &mgmt)?;
                    // The key itself relocated, not just its reference —
                    // `move_key` already carries a cached entry along with it
                    // in the session's own pubkey cache, same as
                    // `PivSession::move_key`'s in-session cache always has.
                    s.move_key(src, dest)?;
                    let status = s.status()?;
                    Ok((status, s.state()))
                });
            Box::new(move |app: &mut App| {
                wipe(&mut app.piv.mgmt_key_input);
                let result = app.store_and_unwrap_piv_write(for_device, result);
                Self::apply_piv_write(
                    app,
                    result,
                    format!("Key moved from {} to {}.", src.label(), dest.label()),
                );
                // Retired occupancy changed (source and/or destination); drop
                // the cache so the retired tab re-reads on its next open.
                app.piv.retired_occupancy = None;
                // A retired-slot selection is stale once its occupancy cache is
                // dropped; snapping back to a
                // standard slot prevents acting on it with unknown occupancy —
                // notably the Generate overwrite guard, which would otherwise
                // see "unknown" as "empty" and skip its warning on a still-
                // occupied archived key.
                if matches!(app.piv.selected_slot, PivSlotSel::Retired(_)) {
                    app.piv.selected_slot = PivSlotSel::Auth;
                }
                Self::apply_piv_cred_result(app);
            })
        });
    }

    /// Lazily read which of the 20 retired slots hold a key (GET METADATA each),
    /// caching the result in `PivState::retired_occupancy`. Triggered once when
    /// the "Retired slots" section is expanded (or the move modal opens) rather
    /// than on every status refresh, keeping the common path to 4 slot reads.
    /// Returns whether the read was actually queued (mirrors `spawn_job`'s
    /// contract): `false` means no job is in flight, so callers must not act
    /// as though a load is pending.
    fn load_piv_retired_occupancy(&mut self) -> bool {
        let Some(reader) = self.selected_oath_reader() else {
            return false;
        };
        let for_device = self.selected_device.clone();
        let cached_state = self.piv_cached_piv_session_state();
        self.spawn_piv_job("Reading retired slots\u{2026}", move || {
            let result = keyroost_transport::PivSession::with_cached_transaction(
                &reader,
                cached_state,
                |s| {
                    let occupancy: Vec<_> = keyroost_piv::Slot::retired_all()
                        .into_iter()
                        .map(|slot| (slot, s.slot_key_presence(slot)))
                        .collect();
                    Ok::<_, TransportError>((occupancy, s.state()))
                },
            );
            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return; // selection changed mid-read; discard
                }
                match result {
                    Ok((v, state)) => {
                        app.store_piv_session_state(for_device.clone(), state);
                        // Background: this fires the first time the retired
                        // slots section is expanded, or the move-key modal is
                        // opened — neither is "the user asked to read retired
                        // occupancy", it's incidental to something else.
                        app.log_bg(
                            Severity::Ok,
                            format!("retired slot occupancy read ({} slots)", v.len()),
                        );
                        app.piv.retired_occupancy = Some(v);
                    }
                    Err(e) => {
                        app.log_bg(Severity::Warn, format!("retired slot occupancy: {e}"));
                        app.piv.error = Some(e.to_string());
                    }
                }
            })
        })
    }

    /// Whether the currently selected PIV slot already holds a private key.
    /// Thin wrapper over [`piv_slot_occupied`] reading the loaded caches; drives
    /// the Generate-key overwrite warning and the Import-cert replace note.
    fn piv_selected_occupied(&self) -> bool {
        piv_slot_occupied(
            self.piv.selected_slot,
            &self.piv.slot_keys,
            self.piv.retired_occupancy.as_deref(),
        )
    }

    /// [`piv_slot_occupancy`] for `slot`, reading the loaded caches and the
    /// last status read's per-slot key presence.
    fn piv_occupancy(&self, slot: keyroost_piv::Slot) -> PivOccupancy {
        let standard: Vec<_> = self
            .piv
            .status
            .as_ref()
            .map(|s| s.slots.iter().map(|sl| (sl.slot, sl.key)).collect())
            .unwrap_or_default();
        piv_slot_occupancy(
            slot,
            &self.piv.slot_keys,
            &standard,
            self.piv.retired_occupancy.as_deref(),
        )
    }

    /// The selected slot's `(PIN policy, touch policy)` from the last
    /// `status_detailed` read, or `None` when the card didn't report one.
    fn piv_selected_slot_policy(
        &self,
    ) -> Option<(keyroost_piv::PinPolicy, keyroost_piv::TouchPolicy)> {
        let sel = self.piv.selected_slot.to_slot();
        self.piv
            .slot_policies
            .iter()
            .find(|(s, _)| *s == sel)
            .and_then(|(_, pol)| *pol)
    }

    /// The selected slot's key algorithm (from the last `status_detailed`
    /// read) and whether it holds a certificate — the two facts the Test row
    /// gates its button on.
    fn piv_selected_test_target(&self) -> (Option<keyroost_piv::KeyAlg>, bool) {
        let sel = self.piv.selected_slot.to_slot();
        let entry = self.piv.slot_keys.iter().find(|(s, _, _)| *s == sel);
        let alg = entry.and_then(|(_, a, _)| *a);
        let has_cert = entry.is_some_and(|(_, _, dn)| dn.is_some())
            || self
                .piv
                .status
                .as_ref()
                .is_some_and(|st| st.slots.iter().any(|s| s.slot == sel && s.cert_present));
        (alg, has_cert)
    }

    /// Run every self-test the selected slot's key algorithm supports
    /// (decrypt, then key-agree, then sign): build a fixed challenge from the
    /// slot certificate's public key ([`keyroost_pivtest`]), run the
    /// private-key op on the card, and verify the reply against that public
    /// key. Read-only on the card — no write, no management key. The PIN
    /// field is always optional — it's the user's call whether to test with
    /// or without one, independent of the slot's (possibly misreported) PIN
    /// policy; the PIN is only sent to the card when the field is non-blank.
    /// Each operation's pass/fail is reported together.
    fn piv_self_test(&mut self) {
        let Some(name) = self.selected_oath_reader() else {
            return;
        };
        let pin = zeroize::Zeroizing::new(self.piv.sign_pin.clone());
        let slot = self.piv.selected_slot.to_slot();
        let want_touch = matches!(
            self.piv_selected_slot_policy().map(|(_, t)| t),
            Some(keyroost_piv::TouchPolicy::Always | keyroost_piv::TouchPolicy::Cached)
        );
        self.piv.notice = None;
        let label = if want_touch {
            "Running self-test\u{2026} \u{2014} touch the key"
        } else {
            "Running self-test\u{2026}"
        };
        let for_device = self.selected_device.clone();
        let cached_state = self.piv_cached_piv_session_state();
        self.spawn_piv_job(label, move || {
            let outcome = run_piv_self_test(&name, slot, pin.as_bytes(), cached_state);
            Box::new(move |app: &mut App| {
                wipe(&mut app.piv.sign_pin);
                let (all_ok, text) = match &outcome {
                    // Skipped ops don't count as failures.
                    Ok((results, _)) => (
                        !results.iter().any(|(_, r)| r.is_failure()),
                        keyroost_pivtest::format_report(results),
                    ),
                    Err(e) => (false, e.clone()),
                };
                if let Ok((_, state)) = outcome {
                    app.store_piv_session_state(for_device, state);
                }
                if all_ok {
                    app.log(
                        Severity::Ok,
                        format!("PIV self-test on {} passed", slot.label()),
                    );
                    app.piv.error = None;
                    app.piv.notice = Some(text.clone());
                } else {
                    app.log(
                        Severity::Err,
                        format!("PIV self-test on {} failed", slot.label()),
                    );
                    app.piv.notice = None;
                    app.piv.error = Some(text.clone());
                }
                if let Some(m) = app.piv.cred_modal.as_mut() {
                    m.detail = all_ok.then_some(text);
                }
                Self::apply_piv_cred_result(app);
            })
        });
    }

    /// Normalize the certificate-subject field: a bare name becomes `CN=name`;
    /// anything containing `=` is taken as a full distinguished name.
    fn piv_subject(&self) -> Option<String> {
        let s = self.piv.cert_subject.trim();
        if s.is_empty() {
            return None;
        }
        Some(if s.contains('=') {
            s.to_owned()
        } else {
            format!("CN={s}")
        })
    }

    /// The `keyUsage` extension chosen in the certificate section; `None` for
    /// "Undefined" (no extension).
    fn piv_requested_key_usage(&self) -> Option<keyroost_piv::x509::KeyUsageExt> {
        let key = (self.selected_device.clone(), self.piv.selected_slot);
        let ext = match self.piv.cert_key_usage.get(&key) {
            Some((ext, _)) => *ext,
            None => keyroost_piv::x509::piv_default_key_usage(
                self.piv.selected_slot.to_slot(),
                self.piv_selected_test_target().0,
            )
            .unwrap_or_default(),
        };
        Some(ext).filter(|e| !e.usages.is_empty())
    }

    /// The selected device:slot's key usage, created from the PIV default on
    /// first sight and reconciled with the slot key's current algorithm (an
    /// algorithm that is merely unknown right now changes nothing). Returns
    /// the extension, the algorithm in force, and the slot's PIV default.
    fn piv_sync_key_usage(
        &mut self,
    ) -> (
        keyroost_piv::x509::KeyUsageExt,
        Option<keyroost_piv::KeyAlg>,
        keyroost_piv::x509::KeyUsageExt,
    ) {
        let slot_sel = self.piv.selected_slot;
        let slot = slot_sel.to_slot();
        let seen = self.piv_selected_test_target().0;
        let key = (self.selected_device.clone(), slot_sel);
        let (ext, alg) = match self.piv.cert_key_usage.get(&key) {
            None => (
                keyroost_piv::x509::piv_default_key_usage(slot, seen).unwrap_or_default(),
                seen,
            ),
            Some((ext, old)) => match seen {
                Some(new) if *old != Some(new) => {
                    (reconcile_key_usage(slot, *ext, *old, new), Some(new))
                }
                _ => (*ext, *old),
            },
        };
        self.piv.cert_key_usage.insert(key, (ext, alg));
        let default = keyroost_piv::x509::piv_default_key_usage(slot, alg).unwrap_or_default();
        (ext, alg, default)
    }

    /// Create a self-signed certificate for the selected slot's key and store
    /// it in the slot (management key authorizes the import, PIN the signing).
    fn piv_self_sign(&mut self) {
        let Some(name) = self.selected_oath_reader() else {
            return;
        };
        let mgmt = match self.piv_current_mgmt_auth(PivCredKind::SelfSign) {
            Ok(a) => a,
            Err(e) => {
                self.piv.error = Some(e);
                return;
            }
        };
        let Some(subject) = self.piv_subject() else {
            self.piv.error = Some("enter a name for the certificate".into());
            return;
        };
        let pin = zeroize::Zeroizing::new(self.piv.sign_pin.clone());
        let slot = self.piv.selected_slot.to_slot();
        let years = self.piv.cert_valid_years;
        let months = self.piv.cert_valid_months;
        // Same "at least a day" floor `cert_days.max(1)` used before the
        // single field split into three: an all-zero combination would
        // otherwise produce a validity period that ends before it starts.
        let days = if years == 0 && months == 0 {
            self.piv.cert_valid_days.max(1)
        } else {
            self.piv.cert_valid_days
        };
        let choice = self.piv.cert_compression;
        let key_usage = self.piv_requested_key_usage();
        self.piv.notice = None;
        let for_device = self.selected_device.clone();
        // `with_cached_transaction` restores whatever the session's pubkey cache already
        // knew — including a key generated earlier this app run, on cards
        // where the freshly-opened session otherwise has no other way to
        // learn it (see `load_piv_status`'s doc).
        let cached_state = self.piv_cached_piv_session_state();
        self.spawn_piv_job(
            "Creating self-signed certificate\u{2026} (touch if it blinks)",
            move || {
                let result = keyroost_transport::PivSession::with_cached_transaction(
                    &name,
                    cached_state,
                    |s| {
                        piv_authenticate(s, &mgmt)?;
                        let now = unix_now();
                        let (_, stored) = s.self_signed_certificate(
                            slot,
                            &subject,
                            i64::from(now),
                            keyroost_piv::add_calendar_period(u64::from(now), years, months, days),
                            pin.as_bytes(),
                            choice.to_compression(),
                            key_usage,
                        )?;
                        let status = s.status()?;
                        Ok((status, s.state(), stored))
                    },
                );
                Box::new(move |app: &mut App| {
                    wipe(&mut app.piv.sign_pin);
                    wipe(&mut app.piv.mgmt_key_input);
                    let result = app.store_and_unwrap_piv_cert_write(for_device, result);
                    Self::apply_piv_cert_write(
                        app,
                        result,
                        &format!("Self-signed certificate stored in {}", slot.label()),
                        choice,
                    );
                })
            },
        );
    }

    /// Sign a PKCS#10 certificate request on the card and save it as PEM.
    fn piv_request_csr(&mut self) {
        let Some(name) = self.selected_oath_reader() else {
            return;
        };
        let Some(subject) = self.piv_subject() else {
            self.piv.error = Some("enter a name for the certificate request".into());
            return;
        };
        // The path comes from a native save dialog, which already handled its
        // own "replace existing file?" prompt — so no empty / clobber checks
        // here.
        let path = self.piv.csr_path.trim().to_owned();
        let pin = zeroize::Zeroizing::new(self.piv.sign_pin.clone());
        let slot = self.piv.selected_slot.to_slot();
        let key_usage = self.piv_requested_key_usage();
        self.piv.notice = None;
        let for_device = self.selected_device.clone();
        // See `piv_self_sign`: `with_cached_transaction` restores whatever the session's
        // pubkey cache already knew, including a key generated earlier this
        // app run.
        let cached_state = self.piv_cached_piv_session_state();
        self.spawn_piv_job(
            "Signing certificate request\u{2026} (touch if it blinks)",
            move || {
                let result = keyroost_transport::PivSession::with_cached_transaction(
                    &name,
                    cached_state,
                    |s| -> Result<_, TransportError> {
                        let pem = s.generate_csr(slot, &subject, pin.as_bytes(), key_usage)?;
                        std::fs::write(&path, pem.as_bytes()).map_err(|_| {
                            TransportError::MalformedResponse("cannot write destination file")
                        })?;
                        Ok(s.state())
                    },
                );
                Box::new(move |app: &mut App| {
                    wipe(&mut app.piv.sign_pin);
                    match result {
                        Ok(state) => {
                            app.store_piv_session_state(for_device, state);
                            app.log(
                                Severity::Ok,
                                format!("certificate request signed for {}", slot.label()),
                            );
                            app.piv.error = None;
                            app.piv.notice = Some("Certificate request signed and saved.".into());
                        }
                        Err(e) => {
                            app.log(Severity::Err, e.to_string());
                            app.piv.notice = None;
                            app.piv.error = Some(e.to_string());
                        }
                    }
                    Self::apply_piv_cred_result(app);
                })
            },
        );
    }

    fn piv_export_cert(&mut self) {
        let Some(name) = self.selected_oath_reader() else {
            return;
        };
        let slot = self.piv.selected_slot.to_slot();
        // The path comes from a native save dialog, which already handled its
        // own "replace existing file?" prompt — so no empty / clobber checks
        // here.
        let path = self.piv.export_path.trim().to_owned();
        self.piv.notice = None;
        let for_device = self.selected_device.clone();
        let cached_state = self.piv_cached_piv_session_state();
        self.spawn_piv_job("Exporting certificate\u{2026}", move || {
            let result = keyroost_transport::PivSession::with_cached_transaction(
                &name,
                cached_state,
                |s| -> Result<_, TransportError> {
                    let der =
                        s.read_certificate(slot)?
                            .ok_or(TransportError::MalformedResponse(
                                "slot holds no certificate",
                            ))?;
                    std::fs::write(&path, &der).map_err(|_| {
                        TransportError::MalformedResponse("cannot write destination file")
                    })?;
                    Ok((der.len(), s.state()))
                },
            );
            Box::new(move |app: &mut App| match result {
                Ok((n, state)) => {
                    app.store_piv_session_state(for_device, state);
                    app.log(
                        Severity::Ok,
                        format!("exported {}-byte certificate from {}", n, slot.label()),
                    );
                    app.piv.error = None;
                    app.piv.notice = Some(format!("Exported {}-byte DER certificate.", n));
                }
                Err(e) => {
                    app.log(Severity::Err, e.to_string());
                    app.piv.notice = None;
                    app.piv.error = Some(e.to_string());
                }
            })
        });
    }

    fn piv_change_management_key(&mut self) {
        let Some(name) = self.selected_oath_reader() else {
            return;
        };
        let old = match self.piv_current_mgmt_auth(PivCredKind::ChangeMgmtKey) {
            Ok(a) => a,
            Err(e) => {
                self.piv.error = Some(e);
                return;
            }
        };
        // "Delete" (HID Crescendo only — see `PivMgmtAlgSel`'s doc) needs no
        // new-key input at all: an empty key goes to the card instead,
        // deleting XAUTH key 1 rather than replacing it. Every other
        // selection reads/validates the typed hex as usual.
        let new = match self.piv.new_mgmt_alg.to_alg() {
            Some(new_alg) => {
                let new = match piv_mgmt_key_bytes(&self.piv.new_mgmt_key_input) {
                    Ok(b) => b,
                    Err(e) => {
                        self.piv.error = Some(e);
                        return;
                    }
                };
                if new.len() != new_alg.key_len() {
                    self.piv.error = Some(format!(
                        "new management key is {} bytes; {} needs {}",
                        new.len(),
                        new_alg.label(),
                        new_alg.key_len()
                    ));
                    return;
                }
                Some((new_alg, new))
            }
            None => None,
        };
        // Whether to also maintain PIN-protected management-key storage
        // (`set_management_key_pin_protected`'s steps 2a/2b) alongside the
        // key change itself, gated on `PivExtension::PinManagementAuth` the
        // same way the checkbox row above is — the GUI has no `--force`
        // override the way `keyroostctl` does, so a device known unable to
        // support it stays on plain `set_management_key`, leaving Admin
        // Data / the PIN-protected object untouched either way. HID
        // Crescendo resolves this `Supported` unconditionally, so it always
        // takes the maintenance path — its own no-op lives inside
        // `set_management_key_pin_protected` itself, not here.
        //
        // `pin_unlock_gate` is kept (not just the derived `maintain_pin_unlock`
        // bool) because the worker closure below needs it again, at a finer
        // grain, to decide whether a `PinProtectMaintenance::Ran` write
        // failure is a real error (`Supported`) or expected background noise
        // worth a warning instead (`Unverified` — the only other value
        // reachable here, since `Unsupported` already means
        // `maintain_pin_unlock` is false).
        let pin_unlock_gate = {
            use keyroost_piv::compat::PivExtension;
            let (piv_fp, piv_ver, piv_fw_ver) = self.piv.status.as_ref().map_or(
                (
                    keyroost_piv::fingerprint::AppletFingerprint::Generic,
                    None,
                    None,
                ),
                |s| {
                    (
                        s.applet_fingerprint,
                        s.version.as_deref(),
                        s.version_firmware.as_deref(),
                    )
                },
            );
            self.piv_gate(PivExtension::PinManagementAuth, piv_fp, piv_ver, piv_fw_ver)
        };
        let maintain_pin_unlock = !matches!(
            pin_unlock_gate,
            keyroost_piv::compat::FeatureGate::Unsupported
        );
        let allow_pin_unlock = self.piv.new_mgmt_allow_pin_unlock;
        self.piv.notice = None;
        let for_device = self.selected_device.clone();
        let cached_state = self.piv_cached_piv_session_state();
        self.spawn_piv_job("Changing management key\u{2026}", move || {
            let result =
                keyroost_transport::PivSession::with_cached_transaction(&name, cached_state, |s| {
                    piv_authenticate(s, &old)?;
                    // A HID Crescendo unit whose management key isn't a real
                    // PIV object runs its own self-contained unlock right
                    // before PUT XAUTH KEY (see `set_management_key`'s doc)
                    // rather than relying on the `piv_authenticate` call
                    // above still being in force — `current` carries the
                    // same credential again for that path; every other
                    // device ignores it.
                    let current = match &old {
                        PivMgmtAuth::Key(key) => keyroost_transport::CurrentMgmtAuth::Key(key),
                        PivMgmtAuth::Pin(pin) => {
                            keyroost_transport::CurrentMgmtAuth::Pin(pin.as_bytes())
                        }
                    };
                    let mut pin_unlock_warning = None;
                    match &new {
                        Some((new_alg, new_key)) if maintain_pin_unlock => {
                            match s.set_management_key_pin_protected(
                                current,
                                *new_alg,
                                new_key,
                                false,
                                allow_pin_unlock,
                            )? {
                                keyroost_transport::PinProtectMaintenance::NotApplicable
                                | keyroost_transport::PinProtectMaintenance::Ran {
                                    printed_data: Ok(()),
                                } => {}
                                keyroost_transport::PinProtectMaintenance::Ran {
                                    printed_data: Err(e),
                                } => {
                                    // `Supported` is a confirmed device — a
                                    // failure there is real and still fails
                                    // the whole job, same as before this
                                    // outcome existed. Anything less certain
                                    // (only `Unverified` reaches here, per
                                    // `maintain_pin_unlock`'s own doc above)
                                    // was never confirmed to support this
                                    // write at all, so it's downgraded to a
                                    // warning the apply closure logs instead.
                                    if pin_unlock_gate == keyroost_piv::compat::FeatureGate::Supported {
                                        return Err(e);
                                    }
                                    let action = if allow_pin_unlock { "enable" } else { "disable" };
                                    pin_unlock_warning = Some(format!(
                                        "Could not {action} PIN-protected management-key \
                                         storage ({e}). keyroost's list has no entry for \
                                         this on this key."
                                    ));
                                }
                            }
                        }
                        Some((new_alg, new_key)) => {
                            s.set_management_key(current, *new_alg, new_key, false)?;
                        }
                        None => s.delete_management_key_hid_crescendo(current)?,
                    }
                    let status = s.status()?;
                    Ok((status, s.state(), pin_unlock_warning))
                });
            Box::new(move |app: &mut App| {
                wipe(&mut app.piv.mgmt_key_input);
                wipe(&mut app.piv.new_mgmt_key_input);
                let (result, pin_unlock_warning) = match result {
                    Ok((status, state, warning)) => (Ok((status, state)), warning),
                    Err(e) => (Err(e), None),
                };
                // Reflects what actually happened, not just what was asked
                // for: a `pin_unlock_warning` means the PIN-protected-storage
                // write itself failed (downgraded to a warning, logged
                // separately below) even though the management key change
                // succeeded — the status line must not then go on to claim
                // that write also succeeded.
                let notice = match &new {
                    Some((new_alg, _)) => {
                        let base = format!("Management key changed to {}.", new_alg.label());
                        if !maintain_pin_unlock || pin_unlock_warning.is_some() {
                            base
                        } else if allow_pin_unlock {
                            format!("{base} PIN-protected management-key storage enabled.")
                        } else {
                            format!("{base} PIN-protected management-key storage disabled (if it was set).")
                        }
                    }
                    None => "Management key deleted.".to_string(),
                };
                let result = app.store_and_unwrap_piv_write(for_device, result);
                let succeeded = result.is_ok();
                Self::apply_piv_write(app, result, notice);
                if succeeded {
                    if let Some(w) = pin_unlock_warning {
                        app.log(Severity::Warn, w);
                    }
                }
                Self::apply_piv_cred_result(app);
            })
        });
    }

    /// Returns `false` when the job couldn't be queued (worker busy) — the
    /// caller's confirm modal stays open so the confirmed click isn't lost.
    fn piv_reset(&mut self) -> bool {
        let Some(name) = self.selected_oath_reader() else {
            return true; // nothing to do; let the modal close
        };
        self.piv.notice = None;
        let for_device = self.selected_device.clone();
        let cached_state = self.piv_cached_piv_session_state();
        let queued = self.spawn_piv_job("Resetting PIV applet\u{2026}", move || {
            let result =
                keyroost_transport::PivSession::with_cached_transaction(&name, cached_state, |s| {
                    // The PIV pane's "Reset applet" card collects no
                    // management-key/PIN credential of its own (unlike the
                    // Overview tab's whole-device factory reset) — nothing to
                    // pass here today; see `force_reset_if_known_supported`'s
                    // doc for why the parameter exists regardless.
                    //
                    // `force_reset_if_known_supported`/`reset` already
                    // rebuild this session's state from nothing internally
                    // (see `PivSession::refresh`'s doc) — wipes every slot,
                    // nothing cached survives it — so `s.state()` below is
                    // already the post-reset state; there's nothing left to
                    // clear by hand.
                    s.force_reset_if_known_supported(None, false)?;
                    let status = s.status()?;
                    Ok((status, s.state()))
                });
            Box::new(move |app: &mut App| {
                let result = app.store_and_unwrap_piv_write(for_device, result);
                Self::apply_piv_write(
                    app,
                    result,
                    "PIV application reset to factory defaults.".into(),
                );
            })
        });
        // `queued` still matters here beyond `spawn_piv_job`'s own bookkeeping:
        // a worker already busy means the confirm modal should stay open for
        // the caller to retry, rather than closing on a click that did nothing.
        queued
    }

    /// Apply the three rename-dialog actions shared by the security-key hero and
    /// the Molto2 hero: open the inline field, cancel it, or commit the name.
    /// The flags are collected during the `ui` closures (where `self` is already
    /// borrowed) and applied here afterwards.
    fn apply_rename_actions(&mut self, dev: &Device, open: bool, cancel: bool, save: bool) {
        if open {
            self.open_rename(dev, None);
        }
        if cancel {
            self.close_rename();
        }
        if save {
            self.save_device_name();
        }
    }

    /// Open the inline naming field on `dev`, prefilled with its name, or
    /// with `write_back` and "On this key" picked (the offer to write a lost
    /// name back).
    fn open_rename(&mut self, dev: &Device, write_back: Option<&str>) {
        if dev.serial.is_empty() {
            self.log(
                Severity::Warn,
                "this device exposes no serial, so it can't be named yet",
            );
            return;
        }
        let choices = device::store_choices(dev);
        let store = match write_back {
            Some(_) if choices.contains(&device::NameStoreChoice::Key) => {
                device::NameStoreChoice::Key
            }
            _ => device::default_store(dev),
        };
        self.rename_input = write_back
            .map(str::to_owned)
            .or_else(|| dev.naming.plain.clone())
            .or_else(|| dev.name.clone())
            .unwrap_or_default();
        wipe(&mut self.rename_pin);
        // Pin the target now, so the eventual save writes against this
        // device even if a background rescan moves the selection first.
        self.rename_target = Some(RenameTarget {
            name_at_open: dev.name.clone(),
            device_id: dev.id.clone(),
            serials: keyroost_resolve::row_serials(dev)
                .into_iter()
                .map(str::to_owned)
                .collect(),
            hid_path: dev.hid_path.clone(),
            naming: dev.naming.clone(),
            lacks_storage: device::lacks_key_storage(dev),
            choices,
            store,
            error: None,
            confirm: None,
            saving: false,
            vendor: dev.vendor.clone(),
            model: dev.model.clone(),
        });
    }

    /// Reset the inline-rename state (field closed, draft, PIN and pin cleared).
    fn close_rename(&mut self) {
        self.rename_input.clear();
        wipe(&mut self.rename_pin);
        self.rename_target = None;
        // The scan-burst loop stops scheduling repaints while a rename field
        // is open (see `update`); wake the loop once so a paused burst
        // resumes now instead of waiting for the next input event.
        if let Some(ctx) = &self.egui_ctx {
            ctx.request_repaint();
        }
    }

    /// Show `msg` in the open naming field, which stays open.
    fn rename_failed(&mut self, msg: impl Into<String>) {
        if let Some(t) = self.rename_target.as_mut() {
            t.error = Some(msg.into());
            t.saving = false;
        }
    }

    /// Whether an on-key save of the open naming field needs a typed PIN:
    /// it does unless the key's FIDO session is unlocked.
    fn rename_needs_pin(&self) -> bool {
        let Some(t) = &self.rename_target else {
            return false;
        };
        !(self.selected_device.as_ref() == Some(&t.device_id) && self.fido_session().is_some())
    }

    /// Persist (or clear) the friendly name for the device the rename field was
    /// opened against, keyed by the serial pinned at open time, where the
    /// dialog says ([`device::plan_name_save`]). Empty input removes the name
    /// wherever it lives. Writing against the *pinned* serial (not the live
    /// selection) is what keeps a mid-edit rescan from landing the name on the
    /// wrong key. Certain refusals come before any question or PIN use.
    fn save_device_name(&mut self) {
        let Some(target) = self.rename_target.clone() else {
            // No pinned target (e.g. the device had no serial at open); nothing
            // to write.
            self.close_rename();
            return;
        };
        if target.saving {
            return;
        }
        let name = self.rename_input.trim().to_owned();
        if !name.is_empty() {
            if let Err(e) = keyroost_keyring::validate_name(&name) {
                self.rename_failed(format!("Invalid name: {e}"));
                return; // keep the field open so the user can correct it
            }
        }
        let plan = match device::plan_name_save(&target.naming, target.store, &name) {
            Ok(p) => p,
            Err(why) => {
                self.rename_failed(why);
                return;
            }
        };
        match plan {
            device::NameSave::Unchanged => self.close_rename(),
            device::NameSave::Local(name) => self.save_name_locally(&target, name),
            device::NameSave::OnKey { name, question } => {
                // An empty PIN is checked by the worker after it plans, so a
                // certain refusal (no FIDO PIN on the key, no large-blob
                // storage, not enough space) shows before a PIN is asked for.
                if let Some(n) = &name {
                    match keyroost_keyring::Keyring::load_default() {
                        Ok(k)
                            if keyroost_resolve::name_held_elsewhere(
                                &k,
                                n,
                                &serial_refs(&target.serials),
                            ) =>
                        {
                            self.rename_failed(format!(
                                "Another key on this computer already has the name \"{n}\". \
                                 Pick another name, or clear that key's name first."
                            ));
                            return;
                        }
                        Ok(_) => {}
                        Err(e) => {
                            self.rename_failed(format!("Names not saved: {e}"));
                            return;
                        }
                    }
                }
                match question {
                    Some(q) => {
                        if let Some(t) = self.rename_target.as_mut() {
                            t.error = None;
                            t.confirm = Some((q, name));
                        }
                    }
                    None => self.start_key_name_write(name),
                }
            }
        }
    }

    /// The person answered the replace/remove question: save on the key.
    fn confirm_key_name_write(&mut self) {
        let Some(name) = self
            .rename_target
            .as_mut()
            .and_then(|t| t.confirm.take())
            .map(|(_, n)| n)
        else {
            return;
        };
        self.start_key_name_write(name);
    }

    /// Set (`Some`) or clear (`None`) the name on the key the open naming
    /// field is pinned to, in the background, then record it on this
    /// computer. The worker plans first and refuses what can't work before
    /// the PIN is used.
    fn start_key_name_write(&mut self, name: Option<String>) {
        let Some(target) = self.rename_target.clone() else {
            return;
        };
        let pin = if self.rename_needs_pin() {
            zeroize::Zeroizing::new(self.rename_pin.clone())
        } else {
            match self.fido_session() {
                Some(s) => s.pin.clone(),
                None => zeroize::Zeroizing::new(String::new()),
            }
        };
        wipe(&mut self.rename_pin);
        let Some(path) = target.hid_path.clone() else {
            self.rename_failed(KEY_NAME_NO_STORAGE);
            return;
        };
        let expected = match &target.naming.on_key {
            keyroost_resolve::KeyLabel::Present(l) => Some(l.clone()),
            _ => None,
        };
        let serials = target.serials.clone();
        let meta = keyroost_keyring::RecordMeta {
            source: keyroost_keyring::IdSource::default(),
            vendor: Some(target.vendor.to_ascii_lowercase()),
        };
        let device_id = target.device_id.clone();
        let old_display = target
            .name_at_open
            .clone()
            .unwrap_or_else(|| target.model.clone());
        let new_display = name.clone().unwrap_or_else(|| target.model.clone());
        let label = if name.is_some() {
            "Saving the name on the key\u{2026}"
        } else {
            "Removing the name from the key\u{2026}"
        };
        let queued = self.spawn_job(label, move || {
            let result =
                write_key_name(&path, name.as_deref(), expected.as_deref(), &pin).map(|w| {
                    let written = w == KeyNameWrite::Written;
                    (
                        w,
                        record_key_name(&serials, name.as_deref(), written, meta).err(),
                    )
                });
            drop(pin);
            Box::new(move |app: &mut App| {
                let open_here = completion_still_valid(
                    Some(&device_id),
                    app.rename_target.as_ref().map(|t| &t.device_id),
                );
                match result {
                    Ok((written, record_error)) => {
                        if written == KeyNameWrite::AlreadySo {
                            app.log_global(
                                Severity::Info,
                                LogKind::User,
                                format!("{new_display}: already so on the key; nothing changed"),
                            );
                        } else {
                            let what = if name.is_some() {
                                "name saved on the key"
                            } else {
                                "name removed from the key"
                            };
                            app.log_global(
                                Severity::Ok,
                                LogKind::User,
                                format!("{new_display}: {what}, was {old_display}"),
                            );
                        }
                        if let Some(e) = record_error {
                            app.log_global(
                                Severity::Warn,
                                LogKind::User,
                                format!(
                                    "{new_display}: this computer's record of the name \
                                     couldn't be saved: {e}"
                                ),
                            );
                        }
                        if open_here {
                            app.close_rename();
                        }
                        // The storage view's copy of the array is stale now.
                        if app.selected_device.as_ref() == Some(&device_id) {
                            app.security_keys.large_blobs = None;
                            app.security_keys.lb_autoloaded = false;
                        }
                        app.refresh_devices();
                    }
                    // Retrying the same dialog can't succeed: close it and
                    // rescan, so a reopened field shows the key's current name.
                    Err(KeyNameFailure::Stale) => {
                        app.log_global(
                            Severity::Warn,
                            LogKind::User,
                            format!("{old_display}: {KEY_NAME_STALE}"),
                        );
                        if open_here {
                            app.close_rename();
                        }
                        keyroost_resolve::forget_key_names();
                        app.refresh_devices();
                    }
                    Err(KeyNameFailure::Failed(e)) => {
                        if open_here {
                            app.rename_failed(e);
                        } else {
                            app.log_global(
                                Severity::Err,
                                LogKind::User,
                                format!("{old_display}: name not saved: {e}"),
                            );
                        }
                    }
                }
            })
        });
        if let Some(t) = self.rename_target.as_mut() {
            if queued {
                t.saving = true;
                t.error = None;
            } else {
                t.error = Some("Another operation is running; try again in a moment.".into());
            }
        }
    }

    /// Save (or clear) the name on this computer only.
    fn save_name_locally(&mut self, target: &RenameTarget, name: Option<String>) {
        // Never fall back to an empty registry here: saving it would replace
        // every name in a keys.json that merely failed to load.
        let mut keyring = match keyroost_keyring::Keyring::load_default() {
            Ok(k) => k,
            Err(e) => {
                self.rename_failed(format!("Names not saved: {e}"));
                return; // keep the field open; nothing was saved
            }
        };
        // A key without an explicit friendly name still shows one — its model
        // (see `DeviceView::title`). Resolving both sides of the change to a
        // concrete display name means one message covers rename, first naming
        // and clearing alike, with no special cases.
        let old_display = target
            .name_at_open
            .clone()
            .unwrap_or_else(|| target.model.clone());
        let cleared = name.is_none();
        let new_display = name.clone().unwrap_or_else(|| target.model.clone());
        match &name {
            // Clearing drops every record of the key.
            None => {
                keyroost_resolve::clear_key_names(&mut keyring, &serial_refs(&target.serials));
            }
            Some(n) => {
                if keyroost_resolve::name_held_elsewhere(&keyring, n, &serial_refs(&target.serials))
                {
                    self.rename_failed(format!(
                        "Another key on this computer already has the name \"{n}\". \
                         Pick another name, or clear that key's name first."
                    ));
                    return;
                }
                let meta = keyroost_keyring::RecordMeta {
                    source: keyroost_keyring::IdSource::default(),
                    vendor: Some(target.vendor.to_ascii_lowercase()),
                };
                if let Err(e) = keyroost_resolve::set_key_name(
                    &mut keyring,
                    &serial_refs(&target.serials),
                    n,
                    keyroost_keyring::NameStore::Computer,
                    meta,
                ) {
                    self.rename_failed(format!("Name not saved: {e}"));
                    return; // keep the field open; nothing was saved
                }
            }
        }
        match keyring.save_default() {
            // Name the before and after explicitly rather than leaning on the
            // usual selected-token prefix: the device list still holds the old
            // name here (the refresh below is what picks up the change), so the
            // auto-prefix would show the pre-rename name.
            Ok(_) => self.log_global(
                Severity::Ok,
                LogKind::User,
                format!(
                    "{new_display}: name {}, was {old_display}",
                    if cleared { "cleared" } else { "saved" }
                ),
            ),
            Err(e) => {
                self.rename_failed(format!("Names not saved: {e}"));
                return;
            }
        }
        self.close_rename();
        self.refresh_devices();
    }

    /// Toggle the help popover for `topic`, anchored under the clicked "?".
    fn toggle_help(&mut self, topic: &'static str, anchor: egui::Pos2) {
        self.help_anchor = anchor;
        self.help_open = if self.help_open == Some(topic) {
            None
        } else {
            Some(topic)
        };
    }
}

/// `ViewportId` of the popped-out activity-log window — shared by the code that
/// spawns it (`App::activity_log_window`) and the code that brings it to the
/// front (the top bar's "Activity log" link while detached).
fn activity_log_viewport_id() -> egui::ViewportId {
    egui::ViewportId::from_hash_of("activity-log")
}

/// Current unix time as a float (for the OATH "copied" flash window).
fn now_secs_f64() -> f64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs_f64())
        .unwrap_or(0.0)
}

/// A flat panel frame with a fill and symmetric inner padding.
fn panel_frame(fill: egui::Color32, mx: f32, my: f32) -> egui::Frame {
    egui::Frame::NONE
        .fill(fill)
        .inner_margin(egui::Margin::symmetric(mx as i8, my as i8))
}

/// A rounded square "glyph tile". `ch = Some(c)` paints a letter; `None` paints a
/// small clock (the Molto2 token mark).
fn glyph_tile(
    ui: &mut egui::Ui,
    size: f32,
    fill: egui::Color32,
    fg: egui::Color32,
    ch: Option<char>,
) {
    let (rect, _) = ui.allocate_exact_size(egui::vec2(size, size), egui::Sense::hover());
    ui.painter()
        .rect_filled(rect, egui::CornerRadius::same((size * 0.28) as u8), fill);
    match ch {
        Some(c) => {
            ui.painter().text(
                rect.center(),
                egui::Align2::CENTER_CENTER,
                c,
                theme::f_bold(size * 0.5),
                fg,
            );
        }
        None => {
            let c = rect.center();
            let r = size * 0.26;
            ui.painter().circle_stroke(c, r, egui::Stroke::new(1.6, fg));
            ui.painter().line_segment(
                [c, c + egui::vec2(0.0, -r * 0.72)],
                egui::Stroke::new(1.6, fg),
            );
            ui.painter().line_segment(
                [c, c + egui::vec2(r * 0.55, 0.0)],
                egui::Stroke::new(1.6, fg),
            );
        }
    }
}

/// Does the device match the sidebar filter text?
fn matches_filter(d: &Device, q: &str) -> bool {
    let q = q.trim().to_ascii_lowercase();
    if q.is_empty() {
        return true;
    }
    d.vendor.to_ascii_lowercase().contains(&q)
        || d.model.to_ascii_lowercase().contains(&q)
        || d.title().to_ascii_lowercase().contains(&q)
}

/// Advisory shown when two or more connected keys report the same serial.
/// Friendly names are keyed by serial, so same-serial keys can't be told apart
/// by name — surface that rather than letting the user assume a name is unique.
/// Returns the first duplicated serial (deterministic order) or `None` when
/// every serial is distinct.
fn duplicate_serial_note<'a>(serials: impl Iterator<Item = &'a str>) -> Option<String> {
    use std::collections::BTreeMap;
    let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
    for s in serials {
        *counts.entry(s).or_insert(0) += 1;
    }
    counts.into_iter().find(|&(_, n)| n > 1).map(|(serial, n)| {
        format!(
            "{n} connected keys report the same serial ({serial}); friendly names can't tell \
             them apart — pick each by its row in the list."
        )
    })
}

/// Short label for a capability tab.
fn cap_tab_label(t: CapTab) -> &'static str {
    match t {
        CapTab::Overview => "Overview",
        CapTab::Fido2 => "FIDO2",
        CapTab::Oath => "Authenticator",
        CapTab::Pgp => "OpenPGP",
        CapTab::Piv => "PIV",
        CapTab::Otp => "On-device OTP",
    }
}

/// A labelled password field row for the inline PIN form.
/// New==confirm guard for the PIV credential modal. Returns the inline error
/// message when the new secret and its confirmation differ, or `None` when they
/// match (or the flow has no confirm field, i.e. `UnblockPin`). Empty fields are
/// treated as "not yet a mismatch" so the error doesn't flash before the user
/// finishes typing.
fn piv_cred_mismatch(piv: &PivState, kind: PivCredKind) -> Option<&'static str> {
    let (new, confirm, msg) = match kind {
        PivCredKind::ChangePin => (
            &piv.pin_new,
            &piv.pin_confirm,
            "the two new PINs don't match",
        ),
        PivCredKind::ChangePuk => (
            &piv.puk_new,
            &piv.puk_confirm,
            "the two new PUKs don't match",
        ),
        // Unblock and the management-key-gated flows have no new==confirm pair;
        // their inputs are validated by the op's own client-side guards.
        PivCredKind::UnblockPin
        | PivCredKind::GenerateKey
        | PivCredKind::ImportCert
        | PivCredKind::SelfSign
        | PivCredKind::RequestCsr
        | PivCredKind::SetRetries
        | PivCredKind::ChangeMgmtKey
        | PivCredKind::DeleteCert
        | PivCredKind::DeleteKey
        | PivCredKind::MoveKey
        | PivCredKind::NewChuid
        | PivCredKind::SelfTest => return None,
    };
    if confirm.is_empty() || new == confirm {
        None
    } else {
        Some(msg)
    }
}

/// In-modal success confirmation text for each PIV credential flow. The
/// management-key-gated flows whose *detailed* result (e.g. the generated
/// public-key PEM) still surfaces in the pane only need a generic confirmation
/// here — the pane keeps showing the rich outcome.
fn piv_cred_success(kind: PivCredKind) -> &'static str {
    match kind {
        PivCredKind::ChangePin => "PIN changed",
        PivCredKind::ChangePuk => "PUK changed",
        PivCredKind::UnblockPin => "PIN unblocked and reset",
        PivCredKind::GenerateKey => "Key generated",
        PivCredKind::ImportCert => "Certificate imported",
        PivCredKind::SelfSign => "Certificate created",
        PivCredKind::RequestCsr => "Request signed and saved",
        PivCredKind::SetRetries => "Retry counts set",
        PivCredKind::ChangeMgmtKey => "Management key changed",
        PivCredKind::DeleteCert => "Certificate deleted",
        PivCredKind::DeleteKey => "Key deleted",
        PivCredKind::MoveKey => "Key moved",
        PivCredKind::NewChuid => "New CHUID written",
        PivCredKind::SelfTest => "Self-test complete",
    }
}

/// Run every [`keyroost_pivtest::SelfTest`] against the card on `reader`
/// (delegating the orchestration to [`keyroost_pivtest::run`]). Operations the
/// slot's key algorithm doesn't do come back `keyroost_pivtest::Outcome::Skipped`
/// (which carries the algorithm, so [`keyroost_pivtest::format_report`] can name
/// it) and are shown in the dialog like the others.
///
/// `Err` is a *setup* failure (couldn't open the card, no certificate in the
/// slot, unreadable key, PIN rejected) — nothing was tested.
///
/// The PIN is used only when `pin` is non-empty — never inferred from the
/// slot's PIN policy. That policy is left entirely to the caller to decide
/// whether to supply a PIN, so a test can deliberately be run without one to
/// see whether the card enforces its policy.
fn run_piv_self_test(
    reader: &str,
    slot: keyroost_piv::Slot,
    pin: &[u8],
    cached: keyroost_transport::PivSessionState,
) -> Result<
    (
        Vec<(keyroost_pivtest::SelfTest, keyroost_pivtest::Outcome)>,
        keyroost_transport::PivSessionState,
    ),
    String,
> {
    // The session itself can only report `TransportError` (from
    // `with_cached_transaction`'s own connect/SELECT machinery) — flattened
    // to `String` right at the end, via the outer `map_err`/`and_then`
    // below. Everything this closure does on its own (no certificate, an
    // unusable algorithm, a rejected PIN) keeps building its `String`
    // exactly as before, one level in, via `inner`.
    keyroost_transport::PivSession::with_cached_transaction(reader, cached, |s| {
        let inner = (|| -> Result<_, String> {
            // Verify against the slot CERTIFICATE's public key on purpose: the
            // cert is what other PIV software consumes, so a pass proves the
            // cert matches the slot's key material. A compressed cert is
            // inflated on read (#147/#148).
            let cert = s
                .read_certificate(slot)
                .map_err(|e| e.to_string())?
                .ok_or_else(|| format!("{} has no certificate to test against", slot.label()))?;
            let (alg, pubkey) = keyroost_piv::x509_parse::parse_certificate_public_key(&cert)
                .map_err(|e| format!("could not read the slot certificate's key: {e}"))?;

            if !keyroost_pivtest::SelfTest::all()
                .into_iter()
                .any(|op| keyroost_pivtest::supports(op, alg))
            {
                return Err(format!("no self-test applies to a {} key", alg.label()));
            }

            // Verify once up front so a wrong PIN fails the whole run (one
            // retry, not one per op). PIN-per-use slots (9C) drop the
            // verified state after each GENERAL AUTHENTICATE, so the per-op
            // closure re-verifies before every op after the first that
            // actually runs.
            let has_pin = !pin.is_empty();
            if has_pin {
                s.verify_pin(pin).map_err(|e| e.to_string())?;
            }
            let mut ran = 0usize;
            let results =
                keyroost_pivtest::run(alg, &pubkey, |op, input| -> Result<Vec<u8>, String> {
                    if has_pin && ran > 0 {
                        s.verify_pin(pin).map_err(|e| e.to_string())?;
                    }
                    ran += 1;
                    if op.is_key_agreement() {
                        s.key_agree(slot, alg, input)
                    } else if op == keyroost_pivtest::SelfTest::Decrypt {
                        s.decrypt(slot, alg, input)
                    } else {
                        s.sign(slot, alg, input)
                    }
                    .map_err(|e| e.to_string())
                });
            Ok((results, s.state()))
        })();
        Ok::<_, TransportError>(inner)
    })
    .map_err(|e| e.to_string())
    .and_then(|inner| inner)
}

/// Slots a key may be moved to: every standard + retired slot that is empty
/// and is not the source. `occupied(slot)` reports current key presence.
/// Whether `sel` currently holds a private key, read from the loaded occupancy
/// caches. Standard slots read `slot_keys` (a carried algorithm means a key is
/// present); a retired slot reads the lazily-populated `retired_occupancy`
/// cache (`None` cache, or a slot the cache doesn't list, is treated as empty).
/// Pure so the overwrite guard can be unit-tested without hardware or `self`.
fn piv_slot_occupied(
    sel: PivSlotSel,
    slot_keys: &[(
        keyroost_piv::Slot,
        Option<keyroost_piv::KeyAlg>,
        Option<String>,
    )],
    retired_occupancy: Option<&[(keyroost_piv::Slot, keyroost_transport::SlotKeyPresence)]>,
) -> bool {
    match sel {
        PivSlotSel::Retired(n) => retired_occupancy
            .and_then(|v| v.iter().find(|(s, _)| *s == keyroost_piv::Slot::Retired(n)))
            .is_some_and(|(_, key)| *key == keyroost_transport::SlotKeyPresence::Present),
        _ => {
            let sel_slot = sel.to_slot();
            slot_keys
                .iter()
                .find(|(s, _, _)| *s == sel_slot)
                .map(|(_, a, _)| a.is_some())
                .unwrap_or(false)
        }
    }
}

/// What the pane can say about whether a slot holds a private key, for the
/// Generate / Move "replace?" warning. Unlike [`piv_slot_occupied`] (which
/// gates actions that need a key, so only a known key counts), this fails
/// closed: anything keyroost can't vouch for as empty is [`Self::MaybeKey`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PivOccupancy {
    /// A key is known to be there.
    Key,
    /// keyroost can't tell, or hasn't read the slot yet.
    MaybeKey,
    /// The card said there is no key.
    Empty,
}

/// [`PivOccupancy`] for `slot`. Standard slots: a carried algorithm in
/// `slot_keys` is a key, otherwise `standard` (the status read's per-slot
/// [`keyroost_transport::SlotKeyPresence`]) decides. Retired slots read the
/// lazily-populated `retired_occupancy` cache. Only a confirmed "no key" is
/// [`PivOccupancy::Empty`]; an unlisted slot or a missing cache is
/// [`PivOccupancy::MaybeKey`]. Pure so it can be unit-tested.
fn piv_slot_occupancy(
    slot: keyroost_piv::Slot,
    slot_keys: &[(
        keyroost_piv::Slot,
        Option<keyroost_piv::KeyAlg>,
        Option<String>,
    )],
    standard: &[(keyroost_piv::Slot, keyroost_transport::SlotKeyPresence)],
    retired_occupancy: Option<&[(keyroost_piv::Slot, keyroost_transport::SlotKeyPresence)]>,
) -> PivOccupancy {
    use keyroost_transport::SlotKeyPresence as K;
    let presence = if matches!(slot, keyroost_piv::Slot::Retired(_)) {
        retired_occupancy.and_then(|v| v.iter().find(|(s, _)| *s == slot).map(|(_, k)| *k))
    } else {
        if slot_keys
            .iter()
            .any(|(s, alg, _)| *s == slot && alg.is_some())
        {
            return PivOccupancy::Key;
        }
        standard.iter().find(|(s, _)| *s == slot).map(|(_, k)| *k)
    };
    match presence {
        Some(K::Present) => PivOccupancy::Key,
        Some(K::NoKey) => PivOccupancy::Empty,
        _ => PivOccupancy::MaybeKey,
    }
}

/// The red "replace?" warning for generating a key into `slot`, or `None`
/// when the slot is known to be empty. (Move has its own notes: see
/// [`piv_move_dest_warning`] and [`piv_move_dest_note`].)
fn piv_replace_warning(occupancy: PivOccupancy, slot: &str) -> Option<String> {
    match occupancy {
        PivOccupancy::Key => Some(format!(
            "This OVERWRITES and destroys the existing key in {slot}. This cannot be undone."
        )),
        PivOccupancy::MaybeKey => Some(format!(
            "{slot} may already hold a key, which would be replaced. This cannot be undone."
        )),
        PivOccupancy::Empty => None,
    }
}

/// The red note for a Move destination the card reports holds a key:
/// keyroost refuses that move before anything is sent. (A destination
/// keyroost can't read gets [`piv_move_dest_note`] instead.)
fn piv_move_dest_warning(occupancy: PivOccupancy, slot: &str) -> Option<String> {
    match occupancy {
        PivOccupancy::Key => Some(format!(
            "{slot} already holds a key \u{2014} delete it first or pick an empty slot."
        )),
        PivOccupancy::MaybeKey | PivOccupancy::Empty => None,
    }
}

/// The neutral note for a Move destination keyroost can't read: the move is
/// sent, and the card decides.
fn piv_move_dest_note(occupancy: PivOccupancy, slot: &str) -> Option<String> {
    matches!(occupancy, PivOccupancy::MaybeKey)
        .then(|| format!("keyroost can't tell whether {slot} holds a key; the card decides."))
}

/// Whether a slot-emptiness-sensitive button should dim specifically because
/// the active slot is confirmed empty — the narrower criterion
/// `keyroost_piv::compat::PivExtension::GetSlotKeyStatus` unlocks. Shared by
/// "Delete key" (distinct from "Delete certificate"'s `selected_has_cert`
/// check — a different object, gated by a different extension) and "Import
/// certificate" (which has no separate firmware gate of its own to check
/// first, unlike "Delete key" — see that button's call site for why this is
/// only meaningful there once `delete_key_gate` itself isn't
/// `FeatureGate::Unsupported`).
///
/// `true` only when `get_slot_key_status_gate` resolves
/// [`FeatureGate::Supported`](keyroost_piv::compat::FeatureGate::Supported)
/// *and* `selected_has_key` is `false` — this device has a confirmed,
/// device-reported way to know slot occupancy (GET METADATA, or HID
/// Crescendo's own GET PIV PROPERTIES), and it says this slot has no key.
/// Every other combination — the gate isn't `Supported`, or it is and the
/// slot does hold a key — leaves the button enabled: without a reliable
/// device signal, a `None` algorithm reading could just as easily mean
/// "this device can't tell us" as "genuinely empty" (see
/// [`keyroost_piv::compat::PivExtension::GetSlotKeyStatus`]'s doc), and
/// hiding a real capability on a guess is worse than occasionally offering a
/// delete that fails deep with "slot has no key", or an import that a
/// key loaded out-of-band this session can't see would in fact have matched.
#[must_use]
fn slot_confirmed_empty(
    get_slot_key_status_gate: keyroost_piv::compat::FeatureGate,
    selected_has_key: bool,
) -> bool {
    use keyroost_piv::compat::FeatureGate;
    get_slot_key_status_gate == FeatureGate::Supported && !selected_has_key
}

fn move_key_eligible_destinations(
    src: keyroost_piv::Slot,
    occupied: &dyn Fn(keyroost_piv::Slot) -> bool,
) -> Vec<keyroost_piv::Slot> {
    keyroost_piv::Slot::all()
        .into_iter()
        .chain(keyroost_piv::Slot::retired_all())
        .filter(|&s| s != src && !occupied(s))
        .collect()
}

fn pin_field(ui: &mut egui::Ui, p: &Palette, label: &str, buf: &mut String) {
    ui.horizontal(|ui| {
        ui.add_sized(
            [96.0, 22.0],
            egui::Label::new(
                egui::RichText::new(label)
                    .font(theme::f_reg(13.0))
                    .color(p.txt2),
            ),
        );
        let resp = ui.add(
            egui::TextEdit::singleline(buf)
                .password(true)
                .desired_width(200.0),
        );
        guard_secret_field(ui.ctx(), &resp);
    });
    ui.add_space(4.0);
}

/// Like [`pin_field`] but with a hint and custom width — for secrets that are
/// longer than a PIN (the PIV management key). Masked: a management key is a
/// card-write credential and shouldn't sit readable on screen.
fn secret_field(
    ui: &mut egui::Ui,
    p: &Palette,
    label: &str,
    buf: &mut String,
    hint: &str,
    label_w: f32,
    w: f32,
) {
    ui.horizontal(|ui| {
        ui.add_sized(
            [label_w, 22.0],
            egui::Label::new(
                egui::RichText::new(label)
                    .font(theme::f_reg(13.0))
                    .color(p.txt2),
            ),
        );
        let resp = ui.add(
            egui::TextEdit::singleline(buf)
                .password(true)
                .hint_text(hint)
                .desired_width(w),
        );
        guard_secret_field(ui.ctx(), &resp);
    });
    ui.add_space(4.0);
}

/// Masked secret input with a reveal ("eye") toggle painted *inside* the
/// field itself, at its right edge, instead of beside it. A widened right
/// text margin keeps typed characters clear of the icon; the widget's outer
/// `desired_width` is untouched, so this drops into a spot already sized for
/// a plain masked `TextEdit` without changing that size — unlike
/// [`secret_edit`], which adds a separate icon column next to the field.
/// `revealed` is read for the initial mask state and flipped in place when
/// the eye is clicked. Used only by the PIV pane and the factory-reset
/// dialog (see [`piv_pin_field`]/[`piv_secret_field`]); every other secret
/// field in the app still uses [`secret_edit`] or a plain mask.
fn inline_secret_edit(
    ui: &mut egui::Ui,
    p: &Palette,
    buf: &mut String,
    revealed: &mut bool,
    hint: &str,
    width: f32,
) -> egui::Response {
    let mut edit = egui::TextEdit::singleline(buf)
        .desired_width(width)
        .margin(egui::Margin {
            left: 4,
            right: 30,
            top: 2,
            bottom: 2,
        });
    if !*revealed {
        edit = edit.password(true);
    }
    if !hint.is_empty() {
        edit = edit.hint_text(hint);
    }
    let resp = ui.add(edit);
    // Eye toggle painted over the field's own right edge. This claims no
    // extra layout space of its own — it only paints/interacts within the
    // rect the TextEdit above already occupies.
    let center = egui::pos2(resp.rect.right() - 13.0, resp.rect.center().y);
    let icon_rect = egui::Rect::from_center_size(center, egui::vec2(20.0, resp.rect.height()));
    let ir = ui.interact(icon_rect, resp.id.with("reveal"), egui::Sense::click());
    let col = if ir.hovered() { p.txt } else { p.txt2 };
    paint_eye_icon(ui, center, col);
    if !*revealed {
        // Slash across the eye to signal the hidden state.
        ui.painter().line_segment(
            [
                egui::pos2(center.x - 6.0, center.y + 4.0),
                egui::pos2(center.x + 6.0, center.y - 4.0),
            ],
            egui::Stroke::new(1.1, col),
        );
    }
    if ir.hovered() {
        ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
    }
    if ir.clicked() {
        *revealed = !*revealed;
    }
    let _ = ir.on_hover_text(if *revealed { "Hide" } else { "Show" });
    guard_secret_field(ui.ctx(), &resp);
    resp
}

/// Like [`pin_field`], but the value can be revealed via [`inline_secret_edit`]'s
/// in-field eye toggle, and the label column width is a caller-supplied
/// `label_w` rather than a hardcoded 96px — needed for the rows (`SelfSign`,
/// `SetRetries`) that share a column with a "Management key" row (see
/// [`label_text_width`]). PIV-pane/factory-reset-dialog only — see that
/// function's doc for why this isn't just a flag on `pin_field`.
fn piv_pin_field(
    ui: &mut egui::Ui,
    p: &Palette,
    label: &str,
    buf: &mut String,
    revealed: &mut bool,
    label_w: f32,
) {
    ui.horizontal(|ui| {
        ui.add_sized(
            [label_w, 22.0],
            egui::Label::new(
                egui::RichText::new(label)
                    .font(theme::f_reg(13.0))
                    .color(p.txt2),
            ),
        );
        inline_secret_edit(ui, p, buf, revealed, "", 200.0);
    });
    ui.add_space(4.0);
}

/// Like [`secret_field`], but with [`piv_pin_field`]'s inline reveal toggle.
/// Same scope note: PIV pane and factory-reset dialog only.
#[allow(clippy::too_many_arguments)]
fn piv_secret_field(
    ui: &mut egui::Ui,
    p: &Palette,
    label: &str,
    buf: &mut String,
    revealed: &mut bool,
    hint: &str,
    label_w: f32,
    w: f32,
) {
    ui.horizontal(|ui| {
        ui.add_sized(
            [label_w, 22.0],
            egui::Label::new(
                egui::RichText::new(label)
                    .font(theme::f_reg(13.0))
                    .color(p.txt2),
            ),
        );
        inline_secret_edit(ui, p, buf, revealed, hint, w);
    });
    ui.add_space(4.0);
}

/// Fine-print note inside a management card.
fn card_note(ui: &mut egui::Ui, p: &Palette, t: &str) {
    ui.label(
        egui::RichText::new(t)
            .font(theme::f_reg(12.0))
            .color(p.txt3),
    );
}

/// The "Valid for" fields shared by the certificate and CHUID cards: three
/// `DragValue`s — years, months, days, in that order — that sum, mirroring
/// `keyroostctl piv cert generate`/`chuid generate`'s combinable `--years`/`--months`/
/// `--days` exactly (see [`keyroost_piv::add_calendar_period`]). Renders
/// only the three fields, not the "Valid for" label itself — the two call
/// sites lay that out differently (a plain label vs. one column-aligned with
/// the field above it), so each renders its own. Each field's own range
/// tops out at what that unit alone could still represent from `now` —
/// generous rather than exact once more than one field is nonzero, since the
/// actual encoder clamps the summed result regardless.
fn piv_valid_for_fields(
    ui: &mut egui::Ui,
    now: u32,
    years: &mut u32,
    months: &mut u32,
    days: &mut u32,
) {
    ui.add(
        egui::DragValue::new(years)
            .range(0..=keyroost_piv::max_valid_years(u64::from(now)))
            .suffix(" y"),
    );
    ui.add(
        egui::DragValue::new(months)
            .range(0..=keyroost_piv::max_valid_months(u64::from(now)))
            .suffix(" mo"),
    );
    ui.add(
        egui::DragValue::new(days)
            .range(0..=keyroost_piv::max_valid_days(u64::from(now)))
            .suffix(" d"),
    );
}

/// Every X.509 `keyUsage` bit with its menu label and hover description, in
/// RFC 5280 order.
const KEY_USAGE_CHOICES: [(keyroost_piv::x509::KeyUsage, &str, &str); 9] = {
    use keyroost_piv::x509::KeyUsage as K;
    [
        (
            K::DIGITAL_SIGNATURE,
            "Digital signature",
            "Verify digital signatures that are not certificate or CRL signatures \
             and not non-repudiation signatures (e.g. authentication, TLS client auth).",
        ),
        (
            K::NON_REPUDIATION,
            "Non-repudiation",
            "Also called content commitment: verify signatures that bind the signer \
             to the signed content (document signing).",
        ),
        (
            K::KEY_ENCIPHERMENT,
            "Key encipherment",
            "Encrypt (wrap) other keys for transport, e.g. RSA key transport.",
        ),
        (
            K::DATA_ENCIPHERMENT,
            "Data encipherment",
            "Directly encrypt raw user data with the public key.",
        ),
        (
            K::KEY_AGREEMENT,
            "Key agreement",
            "Derive shared secrets with the key (ECDH).",
        ),
        (
            K::KEY_CERT_SIGN,
            "Certificate signing",
            "Sign other certificates (CA key).",
        ),
        (
            K::CRL_SIGN,
            "CRL signing",
            "Sign certificate revocation lists.",
        ),
        (
            K::ENCIPHER_ONLY,
            "Encipher only",
            "With key agreement: the derived key may only be used to encrypt. \
             Selecting it also selects key agreement; exclusive with decipher only.",
        ),
        (
            K::DECIPHER_ONLY,
            "Decipher only",
            "With key agreement: the derived key may only be used to decrypt. \
             Selecting it also selects key agreement; exclusive with encipher only.",
        ),
    ]
};

/// Switch one `keyUsage` bit on or off while keeping the set valid per
/// RFC 5280 (`encipherOnly`/`decipherOnly` need `keyAgreement` and exclude
/// each other).
fn toggle_key_usage(
    cur: keyroost_piv::x509::KeyUsage,
    bit: keyroost_piv::x509::KeyUsage,
    on: bool,
) -> keyroost_piv::x509::KeyUsage {
    use keyroost_piv::x509::KeyUsage as K;
    let mut ku = cur.with(bit, on);
    if on && bit == K::ENCIPHER_ONLY {
        ku = ku
            .with(K::KEY_AGREEMENT, true)
            .with(K::DECIPHER_ONLY, false);
    } else if on && bit == K::DECIPHER_ONLY {
        ku = ku
            .with(K::KEY_AGREEMENT, true)
            .with(K::ENCIPHER_ONLY, false);
    } else if !on && bit == K::KEY_AGREEMENT {
        ku = ku
            .with(K::ENCIPHER_ONLY, false)
            .with(K::DECIPHER_ONLY, false);
    }
    ku
}

/// Carry a remembered `keyUsage` extension over to a slot key of algorithm
/// `new`. A selection that was just the slot's PIV default follows the default
/// for the new algorithm. Otherwise the choice is kept, except that
/// `keyEncipherment` and `keyAgreement` swap when the new key supports only
/// the other one, and bits the new key can't back are dropped (taking
/// `critical` along if nothing is left).
fn reconcile_key_usage(
    slot: keyroost_piv::Slot,
    ext: keyroost_piv::x509::KeyUsageExt,
    old: Option<keyroost_piv::KeyAlg>,
    new: keyroost_piv::KeyAlg,
) -> keyroost_piv::x509::KeyUsageExt {
    use keyroost_piv::x509::{
        piv_default_key_usage, supported_key_usages, KeyUsage as K, KeyUsageExt,
    };
    let default_for = |a| piv_default_key_usage(slot, a).unwrap_or_default();
    if ext == default_for(old) {
        return default_for(Some(new));
    }
    let supported = supported_key_usages(new);
    let mut ku = ext.usages;
    for (bit, other) in [
        (K::KEY_ENCIPHERMENT, K::KEY_AGREEMENT),
        (K::KEY_AGREEMENT, K::KEY_ENCIPHERMENT),
    ] {
        if ku.contains(bit) && !supported.contains(bit) && supported.contains(other) {
            ku = ku.with(bit, false).with(other, true);
        }
    }
    let mut kept = K::EMPTY;
    for (bit, _, _) in KEY_USAGE_CHOICES {
        kept = kept.with(bit, ku.contains(bit) && supported.contains(bit));
    }
    if !kept.contains(K::KEY_AGREEMENT) {
        kept = kept
            .with(K::ENCIPHER_ONLY, false)
            .with(K::DECIPHER_ONLY, false);
    }
    KeyUsageExt {
        usages: kept,
        critical: ext.critical && !kept.is_empty(),
    }
}

/// Combo-box caption for a `keyUsage` selection.
/// A selection equal to the slot's PIV default is led by "Slot default".
/// `degraded`: the default is undefined only because the key can't back the
/// standard's usages; it is still captioned "Slot default (undefined)".
fn key_usage_summary(
    ext: keyroost_piv::x509::KeyUsageExt,
    default: keyroost_piv::x509::KeyUsageExt,
    degraded: bool,
) -> String {
    if ext.usages.is_empty() {
        return if degraded && ext == default {
            "Slot default (undefined)".to_owned()
        } else {
            "Undefined".to_owned()
        };
    }
    let mut parts: Vec<&str> = KEY_USAGE_CHOICES
        .iter()
        .filter(|(b, _, _)| ext.usages.contains(*b))
        .map(|(_, l, _)| *l)
        .collect();
    if ext.critical {
        parts.push("critical");
    }
    let list = parts.join(", ");
    if ext == default {
        format!("Slot default ({list})")
    } else {
        list
    }
}

/// A key/value detail row for the device-metadata card: a muted fixed-width
/// label on the left, the value on the right. Wraps long values.
fn mds_kv(ui: &mut egui::Ui, p: &Palette, key: &str, value: &str) {
    ui.horizontal(|ui| {
        ui.add_sized(
            [150.0, 16.0],
            egui::Label::new(
                egui::RichText::new(key)
                    .font(theme::f_reg(12.0))
                    .color(p.txt3),
            )
            .wrap_mode(egui::TextWrapMode::Extend),
        );
        ui.label(
            egui::RichText::new(value)
                .font(theme::f_reg(12.5))
                .color(p.txt2),
        );
    });
    ui.add_space(3.0);
}

/// One "label  value" cell in the metadata grid, occupying width `w`. The label
/// is muted and fixed-width; the value sits immediately to its right so the pair
/// reads as a unit rather than drifting apart.
fn mds_cell(ui: &mut egui::Ui, p: &Palette, key: &str, value: &str, w: f32) {
    let label_w = 138.0_f32.min(w * 0.5);
    ui.allocate_ui(egui::vec2(w, 18.0), |ui| {
        ui.horizontal(|ui| {
            ui.spacing_mut().item_spacing.x = 10.0;
            ui.add_sized(
                [label_w, 16.0],
                egui::Label::new(
                    egui::RichText::new(key)
                        .font(theme::f_reg(12.0))
                        .color(p.txt3),
                )
                .wrap_mode(egui::TextWrapMode::Extend)
                .halign(egui::Align::LEFT),
            );
            ui.add(
                egui::Label::new(
                    egui::RichText::new(value)
                        .font(theme::f_reg(12.5))
                        .color(p.txt2),
                )
                .wrap_mode(egui::TextWrapMode::Truncate),
            );
        });
    });
}

/// A themed single-line text input with a fixed-width label — the non-password
/// sibling of [`pin_field`], for cardholder name / URL / file path.
fn text_field(ui: &mut egui::Ui, p: &Palette, label: &str, buf: &mut String, hint: &str, w: f32) {
    ui.horizontal(|ui| {
        ui.add_sized(
            [96.0, 22.0],
            egui::Label::new(
                egui::RichText::new(label)
                    .font(theme::f_reg(13.0))
                    .color(p.txt2),
            ),
        );
        ui.add(
            egui::TextEdit::singleline(buf)
                .hint_text(hint)
                .desired_width(w),
        );
    });
    ui.add_space(4.0);
}

/// Width for the New CHUID dialog's GUID input (and, to keep the two fields
/// visually aligned, its management-key input): the actually-rendered width
/// of a representative 36-character canonical GUID in the dialog's body
/// font, plus a little slack for the text edit's own internal padding and
/// for whatever font it ends up drawing with. Measured instead of a fixed
/// guess so the field tracks real font metrics rather than drifting from
/// them (and the dialog stops reserving space nothing actually needs).
fn chuid_guid_field_width(ctx: &egui::Context) -> f32 {
    // All-zero digits and dashes: close to the widest a canonical GUID gets
    // in most fonts, without needing per-character metrics.
    let sample = "00000000-0000-0000-0000-000000000000";
    let w = ctx
        .fonts_mut(|f| {
            f.layout_no_wrap(sample.to_owned(), theme::f_reg(13.0), egui::Color32::WHITE)
        })
        .size()
        .x;
    w + 24.0
}

/// Font-measured width (+ padding) of a label text — the general form behind
/// [`chuid_label_width`]. A fixed-guess label column (the app's usual 96px)
/// is only ever wide enough for the labels someone happened to test with;
/// when a dialog shows two rows sharing a label column and one label is
/// longer than the guess, that row's label overflows into the field next to
/// it, which then starts at a different x than the other row's field.
/// Measuring the actual longest label at the current font/zoom — the same
/// reason [`chuid_guid_field_width`] measures rather than guesses — avoids
/// that regardless of font metrics.
fn label_text_width(ctx: &egui::Context, text: &str) -> f32 {
    let w = ctx
        .fonts_mut(|f| f.layout_no_wrap(text.to_owned(), theme::f_reg(13.0), egui::Color32::WHITE))
        .size()
        .x;
    w + 8.0
}

/// Label-column width for the New CHUID dialog's rows, and for any other
/// dialog with a row sharing a column with a "Management key"/PIN row (see
/// `App::piv_modal_mgmt_field`'s label_w for callers): the rendered width of
/// "Management key" (the longest of the New CHUID dialog's three row labels
/// there — "GUID" and "Valid for" both fit inside it) plus a little padding.
fn chuid_label_width(ctx: &egui::Context) -> f32 {
    label_text_width(ctx, "Management key")
}

/// `ui.selectable_value`'s own row, but sized the same whether or not the
/// pointer is hovering it. Plain `ui.selectable_value` builds on
/// `Button::selectable`, which only forces `frame_when_inactive(true)` for
/// the *currently selected* row; every other row paints no stroke at rest
/// and reserves no space for one either. This app's theme (`Palette::apply`)
/// gives the `inactive` widget state a real 1px stroke width too — for text
/// fields' own visible boundary — where egui's own default is 0, so an
/// *unselected* row ends up measurably shorter at rest than hovered: 1px is
/// exactly what egui's frame math sets aside for the stroke it isn't
/// painting. In a combo popup with a small, fixed option list sitting close
/// to the popup's height cap, that per-row wobble was enough to tip the
/// whole list into needing a scrollbar the instant the pointer landed on a
/// row — every PIV dropdown built from a `for` loop over a fixed option set
/// (algorithm, management-key algorithm, PIN/touch policy, move destination)
/// hits this the same way. Forcing the frame on unconditionally makes the
/// reserved space — and so the row's height — independent of hover.
fn stable_selectable_value<'a, T: PartialEq>(
    ui: &mut egui::Ui,
    current: &mut T,
    value: T,
    text: impl egui::IntoAtoms<'a>,
) -> egui::Response {
    let selected = *current == value;
    let resp = ui.add(egui::Button::selectable(selected, text).frame_when_inactive(true));
    if resp.clicked() && *current != value {
        *current = value;
    }
    resp
}

/// Opacity for a gated (disabled) row in the PIV algorithm/policy combos —
/// [`piv_keyalg_combo`] and [`piv_mgmtalg_combo`] gate entries today;
/// `piv_policy_combo` sets it too even though every `PivPolicyOption` quirk
/// currently filters `options` instead of disabling a value in place (see
/// its `show_ui` closure) — so this is ready the day one does. The
/// move-destination combo is the one PIV dropdown left out: it only ever
/// offers an already-filtered, all-enabled slot list. egui's own default
/// (`Visuals::disabled_alpha`, 0.5) reads as barely-lighter-than-enabled at
/// this popup's font size, so a gated row and a pickable one are too close
/// in weight to tell apart at a glance; this app sets it lower, scoped to
/// just these popups' own `Ui` (see each `show_ui` closure), so it doesn't
/// touch other disabled widgets in the app.
const PIV_COMBO_DISABLED_ALPHA: f32 = 0.32;

/// A PIV key-algorithm picker combo, listing every `keyroost_piv::KeyAlg`
/// variant. `gate_of` resolves each candidate's
/// `keyroost_piv::compat::PivExtension::SlotKeyAlgorithm` gate on the live
/// device: an entry gating `Unsupported` renders disabled (dimmed, not
/// removed — the combo's shape stays the same as gates change) the same way
/// the Move/Delete-key rows dim on this device; `Unverified` entries stay
/// enabled and are instead called out together in a note below the combo
/// (see `cap_piv`), since a per-row marker doesn't fit a closed dropdown the
/// way it does an always-visible row.
fn piv_keyalg_combo(
    ui: &mut egui::Ui,
    id: &str,
    sel: &mut keyroost_piv::KeyAlg,
    gate_of: impl Fn(keyroost_piv::KeyAlg) -> keyroost_piv::compat::FeatureGate,
) {
    egui::ComboBox::from_id_salt(id)
        .selected_text(sel.label())
        .show_ui(ui, |ui| {
            // `disabled_alpha`'s egui default (0.5) leaves a gated row only
            // faintly lighter than an enabled one at this popup's font size —
            // see PIV_COMBO_DISABLED_ALPHA. Set on this popup's own `Ui`
            // (built fresh from the ambient style per `Palette::apply`'s
            // `ScrollStyle` comment above), so it reaches every row below
            // without touching disabled widgets elsewhere in the app.
            ui.style_mut().visuals.disabled_alpha = PIV_COMBO_DISABLED_ALPHA;
            for opt in keyroost_piv::KeyAlg::ALL {
                let enabled = gate_of(opt) != keyroost_piv::compat::FeatureGate::Unsupported;
                ui.add_enabled_ui(enabled, |ui| {
                    stable_selectable_value(ui, sel, opt, opt.label());
                });
            }
        });
}

/// If `sel` gates `Unsupported` under `gate_of`, snap it to the first
/// candidate in `keyroost_piv::KeyAlg::ALL` that doesn't — the slot
/// key-algorithm counterpart of [`piv_mgmtalg_unsupported_fallback`], same
/// reasoning: `fallback` (the caller's usual "widely-supported default", e.g.
/// `KeyAlg::EccP256`) is itself just one candidate and could be the very
/// entry gating `Unsupported` on some fingerprint, so it isn't returned
/// unconditionally — only once every algorithm in `ALL` gates `Unsupported`
/// and there's nothing better left to pick. Factored out of `cap_piv` so this
/// fallback rule is unit-testable without an egui context.
#[must_use]
fn piv_keyalg_unsupported_fallback(
    sel: keyroost_piv::KeyAlg,
    fallback: keyroost_piv::KeyAlg,
    gate_of: impl Fn(keyroost_piv::KeyAlg) -> keyroost_piv::compat::FeatureGate,
) -> keyroost_piv::KeyAlg {
    if gate_of(sel) != keyroost_piv::compat::FeatureGate::Unsupported {
        return sel;
    }
    keyroost_piv::KeyAlg::ALL
        .into_iter()
        .find(|&alg| gate_of(alg) != keyroost_piv::compat::FeatureGate::Unsupported)
        .unwrap_or(fallback)
}

/// An OpenPGP key-algorithm picker combo, restricted to `choices` (the card's
/// own Algorithm Information menu, or every algorithm that fits the slot).
fn openpgp_keyalg_combo(
    ui: &mut egui::Ui,
    id: &str,
    sel: &mut OpenPgpKeyAlgSel,
    choices: &[OpenPgpKeyAlgSel],
) {
    egui::ComboBox::from_id_salt(id)
        .selected_text(sel.label())
        .show_ui(ui, |ui| {
            for &opt in choices {
                ui.selectable_value(sel, opt, opt.label());
            }
        });
}

/// A PIV PIN/touch policy value selectable in the Generate key modal's combo
/// boxes: its display label and the full set of choices, in menu order.
/// `Default` is always first — it's the initial selection, and the plain PIV
/// APDU every card accepts. Also used for the slot state line's "pin: …,
/// touch: …" display.
trait PivPolicyOption: Copy + PartialEq + 'static {
    const ALL: &'static [Self];
    fn label(self) -> &'static str;
}

impl PivPolicyOption for keyroost_piv::PinPolicy {
    const ALL: &'static [Self] = &[Self::Default, Self::Never, Self::Once, Self::Always];
    fn label(self) -> &'static str {
        match self {
            Self::Never => "never",
            Self::Once => "once",
            Self::Always => "always",
            Self::Default => "default",
        }
    }
}

impl PivPolicyOption for keyroost_piv::TouchPolicy {
    const ALL: &'static [Self] = &[Self::Default, Self::Never, Self::Cached, Self::Always];
    fn label(self) -> &'static str {
        match self {
            Self::Never => "never",
            Self::Cached => "cached",
            Self::Always => "always",
            Self::Default => "default",
        }
    }
}

/// Snap `*sel` to `options[0]` if it isn't already one of `options` — the
/// generic counterpart of [`piv_mgmtalg_clamp`], used when a per-fingerprint
/// [`keyroost_piv::compat::PivQuirk`] (e.g.
/// [`SlotTouchPolicyCachedNotSupported`](keyroost_piv::compat::PivQuirk::SlotTouchPolicyCachedNotSupported))
/// has dropped a value from `options` that was previously selected — e.g. a
/// device switch left `Cached` selected on a fingerprint that doesn't accept
/// it. `T::ALL[0]` is always `Default`, so `options` never actually excludes
/// it (only `Once`/`Cached` are ever quirk-gated) — this only ever snaps back
/// to `Default`, never to some other survivor.
fn piv_policy_clamp<T: PivPolicyOption>(sel: &mut T, options: &[T]) {
    if let Some(&first) = options.first() {
        if !options.contains(sel) {
            *sel = first;
        }
    }
}

/// PIN/Touch Policy picker combo (Generate key modal). Generic over
/// [`PivPolicyOption`] — the type of `sel` alone picks the right label
/// function. `options` is the offered set — [`PivPolicyOption::ALL`] on a
/// device with no relevant quirk, or that list with one value removed (see
/// [`piv_policy_clamp`]) — mirroring [`piv_mgmtalg_combo`]'s own
/// caller-filtered-options shape.
fn piv_policy_combo<T: PivPolicyOption>(ui: &mut egui::Ui, id: &str, sel: &mut T, options: &[T]) {
    piv_policy_clamp(sel, options);
    egui::ComboBox::from_id_salt(id)
        .selected_text(sel.label())
        .show_ui(ui, |ui| {
            // No option is ever gated disabled today — quirk-excluded values
            // are dropped from `options` outright rather than shown dimmed —
            // but set the same dimming as the two combos above in case a
            // future quirk gates a policy value in place instead of
            // filtering it out (see `PIV_COMBO_DISABLED_ALPHA`).
            ui.style_mut().visuals.disabled_alpha = PIV_COMBO_DISABLED_ALPHA;
            for &opt in options {
                stable_selectable_value(ui, sel, opt, opt.label());
            }
        });
}

/// Snap `*sel` to `options[0]` if it isn't already one of `options` — used
/// so [`piv_mgmtalg_combo`] never shows a selection it isn't actually
/// offering (e.g. `*sel` left on an algorithm the previously-selected device
/// offered but this one doesn't). Factored out of that function so the
/// clamp rule is unit-testable without an egui context. No-op on an empty
/// `options` — there's nothing to snap to.
fn piv_mgmtalg_clamp(sel: &mut PivMgmtAlgSel, options: &[PivMgmtAlgSel]) {
    if let Some(&first) = options.first() {
        if !options.contains(sel) {
            *sel = first;
        }
    }
}

/// If `sel` gates `Unsupported` under `gate_of`, snap it to the first offered
/// option that doesn't — used so the management-key algorithm combo never
/// preselects a disabled entry. Deliberately not "snap to `options[0]`"
/// outright, the way [`piv_mgmtalg_clamp`] does for an *unoffered* selection:
/// `options[0]` (`TripleDes` on [`PivMgmtAlgSel::ALL`] today, now that it's
/// alphabetized — this reasoning predates that and originally named `Aes192`,
/// which was both `options[0]` *and* the type's `#[default]` at the time) can
/// itself be the very entry gating `Unsupported` — a HID Crescendo device's
/// XAUTH key never accepts AES-192, for instance — so falling back to it
/// again would leave the combo showing a disabled selection instead of fixing
/// anything. Falls back to `options[0]` only when
/// every offered option gates `Unsupported`, and leaves `sel` alone
/// (including when it isn't `Unsupported` to begin with) if `options` is
/// empty — there's nothing to snap to either way. Factored out of `cap_piv`
/// so this fallback rule is unit-testable without an egui context, the same
/// reason [`piv_mgmtalg_clamp`] is its own function.
#[must_use]
fn piv_mgmtalg_unsupported_fallback(
    sel: PivMgmtAlgSel,
    options: &[PivMgmtAlgSel],
    gate_of: impl Fn(PivMgmtAlgSel) -> keyroost_piv::compat::FeatureGate,
) -> PivMgmtAlgSel {
    if gate_of(sel) != keyroost_piv::compat::FeatureGate::Unsupported {
        return sel;
    }
    options
        .iter()
        .copied()
        .find(|&opt| gate_of(opt) != keyroost_piv::compat::FeatureGate::Unsupported)
        .or_else(|| options.first().copied())
        .unwrap_or(sel)
}

/// The management-key algorithm combo's per-algorithm "unverified" warning
/// list — every offered algorithm gating [`keyroost_piv::compat::FeatureGate::Unverified`],
/// *unless* `extension_gate`
/// (`keyroost_piv::compat::PivExtension::SetManagementKey`'s own gate, not a
/// per-algorithm one) is already
/// [`keyroost_piv::compat::FeatureGate::Unsupported`] — in which case this is
/// always empty. When the whole extension is unsupported, the "Change
/// management key…" button and the algorithm combo are already disabled with
/// their own blocked-hint tooltip (see `cap_piv`'s "Management key" row); a
/// caller can't pick an algorithm for a change it can't make at all, so
/// calling out individually "unverified" algorithms on top of that would be
/// misleading noise rather than useful information. Factored out of `cap_piv`
/// so this suppression rule is unit-testable without an egui context, the
/// same reason [`piv_mgmtalg_unsupported_fallback`] is its own function.
#[must_use]
fn piv_mgmtalg_unverified_labels(
    extension_gate: keyroost_piv::compat::FeatureGate,
    options: &[PivMgmtAlgSel],
    gate_of: impl Fn(PivMgmtAlgSel) -> keyroost_piv::compat::FeatureGate,
) -> Vec<&'static str> {
    if extension_gate == keyroost_piv::compat::FeatureGate::Unsupported {
        return Vec::new();
    }
    options
        .iter()
        .copied()
        .filter(|&opt| gate_of(opt) == keyroost_piv::compat::FeatureGate::Unverified)
        .map(PivMgmtAlgSel::label)
        .collect()
}

/// A PIV management-key-algorithm picker combo. `options` is the offered set
/// — [`PivMgmtAlgSel::ALL`] at every call site today, the same five entries
/// on every device (see that type's doc); kept as a parameter rather than
/// hard-coded so the clamp/fallback logic below stays generically testable.
/// If `*sel` isn't among `options`, it snaps to `options[0]` before drawing —
/// see [`piv_mgmtalg_clamp`].
///
/// `gate_of` resolves each candidate's
/// `keyroost_piv::compat::PivExtension::ManagementKeyAlgorithm` gate on the
/// live device, same shape and same treatment as [`piv_keyalg_combo`]'s own
/// `gate_of`: an entry gating `Unsupported` renders disabled (dimmed, not
/// removed — the combo's shape stays the same as gates change); `Unverified`
/// entries stay enabled and are instead called out together in a note above
/// the combo (see `cap_piv`).
fn piv_mgmtalg_combo(
    ui: &mut egui::Ui,
    id: &str,
    sel: &mut PivMgmtAlgSel,
    options: &[PivMgmtAlgSel],
    gate_of: impl Fn(PivMgmtAlgSel) -> keyroost_piv::compat::FeatureGate,
) {
    piv_mgmtalg_clamp(sel, options);
    egui::ComboBox::from_id_salt(id)
        .selected_text(sel.label())
        .show_ui(ui, |ui| {
            // See `piv_keyalg_combo`'s matching line: bump the dimming for
            // gated rows in this popup only.
            ui.style_mut().visuals.disabled_alpha = PIV_COMBO_DISABLED_ALPHA;
            for &opt in options {
                let enabled = gate_of(opt) != keyroost_piv::compat::FeatureGate::Unsupported;
                ui.add_enabled_ui(enabled, |ui| {
                    stable_selectable_value(ui, sel, opt, opt.label());
                });
            }
        });
}

/// Accept a certificate file's bytes as PEM or DER, returning DER. `None` when
/// the bytes are neither.
fn cert_bytes_to_der(bytes: &[u8]) -> Option<Vec<u8>> {
    if let Ok(text) = std::str::from_utf8(bytes) {
        if let Some(start) = text.find("-----BEGIN CERTIFICATE-----") {
            let after = &text[start + "-----BEGIN CERTIFICATE-----".len()..];
            let end = after.find("-----END CERTIFICATE-----")?;
            let b64: String = after[..end].split_whitespace().collect();
            return keyroost_proto::codec::base64_decode(&b64).ok();
        }
    }
    // Not PEM — accept DER (must begin with a SEQUENCE tag).
    if bytes.first() == Some(&0x30) {
        Some(bytes.to_vec())
    } else {
        None
    }
}

/// Paint a rounded glyph tile at `rect` with the painter (no widget allocation,
/// so it never steals clicks from a surrounding row). `ch = None` draws a clock.
fn paint_glyph_tile(
    ui: &egui::Ui,
    rect: egui::Rect,
    fill: egui::Color32,
    fg: egui::Color32,
    ch: Option<char>,
) {
    ui.painter().rect_filled(
        rect,
        egui::CornerRadius::same((rect.width() * 0.28) as u8),
        fill,
    );
    match ch {
        Some(c) => {
            ui.painter().text(
                rect.center(),
                egui::Align2::CENTER_CENTER,
                c,
                theme::f_bold(rect.width() * 0.5),
                fg,
            );
        }
        None => {
            let c = rect.center();
            let r = rect.width() * 0.26;
            ui.painter().circle_stroke(c, r, egui::Stroke::new(1.6, fg));
            ui.painter().line_segment(
                [c, c + egui::vec2(0.0, -r * 0.72)],
                egui::Stroke::new(1.6, fg),
            );
            ui.painter().line_segment(
                [c, c + egui::vec2(r * 0.55, 0.0)],
                egui::Stroke::new(1.6, fg),
            );
        }
    }
}

/// Paint a small rounded pill at `left_top` with the painter; returns its width
/// so the caller can advance a cursor.
fn paint_pill(
    ui: &egui::Ui,
    left_top: egui::Pos2,
    text: &str,
    fg: egui::Color32,
    bg: egui::Color32,
) -> f32 {
    let galley = ui.fonts_mut(|f| f.layout_no_wrap(text.to_string(), theme::f_sb(11.0), fg));
    let pad_x = 8.0;
    let h = 18.0;
    let w = galley.size().x + pad_x * 2.0;
    let rect = egui::Rect::from_min_size(left_top, egui::vec2(w, h));
    ui.painter()
        .rect_filled(rect, egui::CornerRadius::same(255), bg);
    let pos = egui::pos2(left_top.x + pad_x, rect.center().y - galley.size().y / 2.0);
    ui.painter().galley(pos, galley, fg);
    w
}

// ---- small vector icons, painted so they render regardless of font coverage
// (IBM Plex Sans lacks ⓘ / ◐ / ↻ / ⧉ / ✓ / ✕, which otherwise show as tofu) ----

/// Half-filled circle — the light/dark theme toggle.
fn paint_theme_icon(ui: &egui::Ui, center: egui::Pos2, r: f32, color: egui::Color32) {
    use std::f32::consts::{FRAC_PI_2, PI};
    ui.painter()
        .circle_stroke(center, r, egui::Stroke::new(1.3, color));
    let n = 20;
    let pts: Vec<egui::Pos2> = (0..=n)
        .map(|i| {
            let a = FRAC_PI_2 + PI * (i as f32 / n as f32);
            center + r * egui::vec2(a.cos(), a.sin())
        })
        .collect();
    ui.painter()
        .add(egui::Shape::convex_polygon(pts, color, egui::Stroke::NONE));
}

/// An eye (two lids + a pupil) — the colorblind-mode toggle.
fn paint_eye_icon(ui: &egui::Ui, center: egui::Pos2, color: egui::Color32) {
    let stroke = egui::Stroke::new(1.3, color);
    let (w, h) = (8.0_f32, 4.6_f32);
    let n = 14;
    let lid = |sign: f32| -> Vec<egui::Pos2> {
        (0..=n)
            .map(|i| {
                let t = -1.0 + 2.0 * (i as f32 / n as f32);
                egui::pos2(center.x + t * w, center.y + sign * h * (1.0 - t * t))
            })
            .collect()
    };
    ui.painter().add(egui::Shape::line(lid(-1.0), stroke));
    ui.painter().add(egui::Shape::line(lid(1.0), stroke));
    ui.painter().circle_filled(center, 2.2, color);
}

/// Circular arrow — refresh / rescan. Clockwise, with a filled arrowhead at the
/// leading end (egui's y-down space makes increasing angle clockwise).
fn paint_refresh_icon(ui: &egui::Ui, center: egui::Pos2, r: f32, color: egui::Color32) {
    let stroke = egui::Stroke::new(1.4, color);
    let (a0, a1) = (0.5_f32, 5.6_f32);
    let n = 24;
    let pts: Vec<egui::Pos2> = (0..=n)
        .map(|i| {
            let a = a0 + (a1 - a0) * (i as f32 / n as f32);
            center + r * egui::vec2(a.cos(), a.sin())
        })
        .collect();
    ui.painter().add(egui::Shape::line(pts, stroke));
    // Filled arrowhead at the leading (clockwise) end, pointing along the motion.
    let end = center + r * egui::vec2(a1.cos(), a1.sin());
    let tangent = egui::vec2(-a1.sin(), a1.cos());
    let radial = egui::vec2(a1.cos(), a1.sin());
    let tip = end + tangent * 3.5;
    let b1 = end + radial * 2.6 - tangent * 0.8;
    let b2 = end - radial * 2.6 - tangent * 0.8;
    ui.painter().add(egui::Shape::convex_polygon(
        vec![tip, b1, b2],
        color,
        egui::Stroke::NONE,
    ));
}

/// Two stacked sheets — copy.
/// Format a Unix timestamp (seconds) as a human-readable UTC string
/// `YYYY-MM-DD HH:MM:SS UTC`. Self-contained civil-date conversion (Howard
/// Hinnant's algorithm) so no date crate is pulled in.
fn fmt_unix_utc(secs: u32) -> String {
    let days = (secs / 86_400) as i64;
    let rem = secs % 86_400;
    let (hh, mm, ss) = (rem / 3600, (rem % 3600) / 60, rem % 60);
    // days since 1970-01-01 -> civil date
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    format!("{y:04}-{m:02}-{d:02} {hh:02}:{mm:02}:{ss:02} UTC")
}

fn paint_copy_icon(ui: &egui::Ui, center: egui::Pos2, color: egui::Color32) {
    let s = egui::Stroke::new(1.3, color);
    let back = egui::Rect::from_min_size(center + egui::vec2(-1.0, -5.0), egui::vec2(7.0, 8.0));
    let front = egui::Rect::from_min_size(center + egui::vec2(-5.0, -1.0), egui::vec2(7.0, 8.0));
    ui.painter().rect_stroke(
        back,
        egui::CornerRadius::same(1),
        s,
        egui::StrokeKind::Inside,
    );
    ui.painter().rect_stroke(
        front,
        egui::CornerRadius::same(1),
        s,
        egui::StrokeKind::Inside,
    );
}

/// A small QR-glyph: three finder squares plus a couple of module dots.
#[cfg(feature = "qr")]
pub(crate) fn paint_qr_icon(ui: &egui::Ui, center: egui::Pos2, color: egui::Color32) {
    let s = egui::Stroke::new(1.2, color);
    // Three finder squares (top-left, top-right, bottom-left).
    let finder = |min: egui::Vec2| {
        let r = egui::Rect::from_min_size(center + min, egui::vec2(3.4, 3.4));
        ui.painter()
            .rect_stroke(r, egui::CornerRadius::same(1), s, egui::StrokeKind::Inside);
    };
    finder(egui::vec2(-5.0, -5.0));
    finder(egui::vec2(1.6, -5.0));
    finder(egui::vec2(-5.0, 1.6));
    // A few modules in the data quadrant so it reads as a QR, not four boxes.
    let dot = |off: egui::Vec2| {
        ui.painter().rect_filled(
            egui::Rect::from_min_size(center + off, egui::vec2(1.2, 1.2)),
            egui::CornerRadius::ZERO,
            color,
        );
    };
    dot(egui::vec2(2.0, 2.0));
    dot(egui::vec2(4.0, 4.0));
    dot(egui::vec2(2.0, 4.4));
}

/// Checkmark — copied / confirmed.
fn paint_check_icon(ui: &egui::Ui, center: egui::Pos2, color: egui::Color32) {
    let s = egui::Stroke::new(1.7, color);
    ui.painter().line_segment(
        [
            center + egui::vec2(-4.0, 0.0),
            center + egui::vec2(-1.0, 3.0),
        ],
        s,
    );
    ui.painter().line_segment(
        [
            center + egui::vec2(-1.0, 3.0),
            center + egui::vec2(4.0, -3.5),
        ],
        s,
    );
}

/// Cross — delete / dismiss.
fn paint_x_icon(ui: &egui::Ui, center: egui::Pos2, color: egui::Color32) {
    let s = egui::Stroke::new(1.4, color);
    ui.painter().line_segment(
        [
            center + egui::vec2(-3.5, -3.5),
            center + egui::vec2(3.5, 3.5),
        ],
        s,
    );
    ui.painter().line_segment(
        [
            center + egui::vec2(-3.5, 3.5),
            center + egui::vec2(3.5, -3.5),
        ],
        s,
    );
}

/// The window body shared by the detach / reattach pair: a square shifted to the
/// bottom-left with its top-right corner left open for the arrow. Drawn
/// identically by both so the glyphs read as one control in two states. Of the
/// 8pt top and right edges only 3pt is drawn — a deep `5.0` corner cut — so the
/// frame stays well clear of the arrow that crosses that corner.
fn paint_window_body(painter: &egui::Painter, center: egui::Pos2, s: egui::Stroke) {
    let b = egui::Rect::from_min_size(center + egui::vec2(-6.0, -2.0), egui::vec2(8.0, 8.0));
    painter.add(egui::Shape::line(
        vec![
            egui::pos2(b.right() - 5.0, b.top()),
            b.left_top(),
            b.left_bottom(),
            b.right_bottom(),
            egui::pos2(b.right(), b.top() + 5.0),
        ],
        s,
    ));
}

/// A window frame with an arrow leaving its top-right corner — "pop this pane
/// out into its own window". Mirrors the external-link affordance the top bar's
/// "Learn \u{2197}" uses.
fn paint_detach_icon(ui: &egui::Ui, center: egui::Pos2, color: egui::Color32) {
    let s = egui::Stroke::new(1.3, color);
    let painter = ui.painter();
    paint_window_body(painter, center, s);
    // Diagonal arrow crossing that corner, pointing out to the top-right.
    let tip = center + egui::vec2(6.0, -6.0);
    painter.line_segment([center + egui::vec2(-1.0, 1.0), tip], s);
    painter.add(egui::Shape::line(
        vec![tip + egui::vec2(-4.5, 0.0), tip, tip + egui::vec2(0.0, 4.5)],
        s,
    ));
}

/// The mirror of [`paint_detach_icon`]: same window frame, but the arrow flies
/// *in* through the open corner — "dock this back into the main window". Its tip
/// rests at the glyph centre, inside the body, pointing down-left; the head
/// keeps the same clearance from the frame that the detach arrow does.
fn paint_reattach_icon(ui: &egui::Ui, center: egui::Pos2, color: egui::Color32) {
    let s = egui::Stroke::new(1.3, color);
    let painter = ui.painter();
    paint_window_body(painter, center, s);
    let tip = center;
    painter.line_segment([center + egui::vec2(6.0, -6.0), tip], s);
    painter.add(egui::Shape::line(
        vec![tip + egui::vec2(4.5, 0.0), tip, tip + egui::vec2(0.0, -4.5)],
        s,
    ));
}

/// Paint one selectable device row. The whole row is a single painter-drawn
/// click target (no nested widgets), so clicking anywhere in it selects the
/// device — fixing the "only the gaps are clickable" inconsistency.
fn device_row(ui: &mut egui::Ui, p: &Palette, dev: &Device, selected: bool) -> bool {
    let w = ui.available_width();
    let h = 68.0;
    let (rect, resp) = ui.allocate_exact_size(egui::vec2(w, h), egui::Sense::click());
    let bg = if selected {
        p.raised
    } else if resp.hovered() {
        p.line_soft
    } else {
        egui::Color32::TRANSPARENT
    };
    ui.painter().rect(
        rect,
        egui::CornerRadius::same(11),
        bg,
        egui::Stroke::new(
            1.0,
            if selected {
                p.line
            } else {
                egui::Color32::TRANSPARENT
            },
        ),
        egui::StrokeKind::Inside,
    );
    if selected {
        ui.painter().rect_filled(
            egui::Rect::from_min_size(
                rect.left_top() + egui::vec2(0.0, 13.0),
                egui::vec2(3.0, h - 26.0),
            ),
            egui::CornerRadius::same(3),
            p.accent,
        );
    }

    let token = dev.kind == DeviceKind::Token || dev.kind == DeviceKind::ProgToken;
    let tile = egui::Rect::from_min_size(
        rect.left_top() + egui::vec2(14.0, (h - 38.0) / 2.0),
        egui::vec2(38.0, 38.0),
    );
    if token {
        paint_glyph_tile(ui, tile, p.brand_soft(), p.brand, None);
    } else {
        paint_glyph_tile(
            ui,
            tile,
            p.raised2,
            p.txt2,
            Some(
                dev.vendor
                    .chars()
                    .next()
                    .unwrap_or('?')
                    .to_ascii_uppercase(),
            ),
        );
    }

    let tx = tile.right() + 11.0;
    let right_pad = 16.0;
    // status dot, top-right
    ui.painter().circle_filled(
        egui::pos2(rect.right() - right_pad, rect.top() + 18.0),
        3.5,
        p.ok,
    );
    // vendor eyebrow
    ui.painter().text(
        egui::pos2(tx, rect.top() + 13.0),
        egui::Align2::LEFT_TOP,
        &dev.vendor,
        theme::f_sb(11.0),
        p.txt3,
    );
    // model, truncated to the available width
    let avail = (rect.right() - right_pad - 8.0) - tx;
    let galley = ui.fonts_mut(|f| {
        let mut job = egui::text::LayoutJob::single_section(
            dev.title().to_string(),
            egui::TextFormat {
                font_id: theme::f_sb(13.5),
                color: p.txt,
                ..Default::default()
            },
        );
        job.wrap = egui::text::TextWrapping {
            max_width: avail.max(0.0),
            max_rows: 1,
            break_anywhere: true,
            overflow_character: Some('\u{2026}'),
        };
        f.layout_job(job)
    });
    ui.painter()
        .galley(egui::pos2(tx, rect.top() + 26.0), galley, p.txt);
    // capability pills — labels come from the shared cap_badges() vocabulary so
    // the GUI and the CLI overview never disagree. Tokens keep the amber accent.
    let py = rect.top() + 46.0;
    let (fg, bg) = if token {
        (p.brand, p.brand_soft())
    } else {
        (p.txt2, p.raised2)
    };
    let mut px = tx;
    for (label, state) in dev.cap_badge_states() {
        // An unverified capability (offered on a hint, never checked against
        // the device) renders as a dimmer "OTP?" pill — same vocabulary as the
        // CLI's badge line, so the two never disagree about what was proven.
        if state == CapState::Unverified {
            let text = format!("{label}?");
            px += paint_pill(ui, egui::pos2(px, py), &text, p.txt3, bg) + 5.0;
        } else {
            px += paint_pill(ui, egui::pos2(px, py), label, fg, bg) + 5.0;
        }
    }
    if resp.hovered() {
        ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
    }
    resp.clicked()
}

impl eframe::App for App {
    // Note: `eframe::App::save` is intentionally not implemented. This crate
    // builds eframe without its `persistence` feature (to avoid pulling in
    // three extra crates), so `save()` would never be called. UI preferences
    // are persisted by `App::persist_settings` into `settings.json` instead —
    // see the `settings` module.

    fn ui(&mut self, root_ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
        // eframe 0.35 drives the app through `App::ui` with a root `Ui` rather
        // than the old `update(ctx)`. Our layout is panel-based: the four panels
        // below are shown into `root_ui`, while the dialogs/popovers (which still
        // take `&Context`) use this cheap `Context` handle cloned from it.
        let ctx_owned = root_ui.ctx().clone();
        let ctx = &ctx_owned;
        // Clipboard hygiene: ~45s after an OTP code was copied, clear the
        // clipboard so the code doesn't live on in clipboard-manager history —
        // but only if the clipboard still holds that exact code. Content the
        // user copied elsewhere in the meantime is never clobbered. arboard is
        // already in the tree via eframe's clipboard integration; if the
        // clipboard can't be read (e.g. some Wayland setups), fail open and
        // clear nothing rather than risk destroying foreign content.
        if let Some((ref code, t)) = self.clipboard_clear_at {
            let now = now_secs_f64();
            if now >= t {
                if let Ok(mut cb) = arboard::Clipboard::new() {
                    if cb.get_text().is_ok_and(|current| current == *code) {
                        let _ = cb.clear();
                    }
                }
                self.clipboard_clear_at = None;
            } else {
                ctx.request_repaint_after(std::time::Duration::from_secs_f64((t - now).max(0.1)));
            }
        }
        // Every file dropped on the window joins the import queue; each is
        // read and identified in turn before anything opens.
        self.import_take_drops(ctx);

        // Apply any results from background device jobs and the import
        // thread before drawing.
        self.drain_worker();
        // While a device job is in flight (e.g. fingerprint enrollment writing
        // live progress to a shared cell), keep the frame loop ticking so the UI
        // reflects per-sample updates instead of freezing until the job ends.
        if self.busy() {
            ctx.request_repaint_after(std::time::Duration::from_millis(100));
        }
        self.drain_import();
        // Land any path picked by a native file-chooser into its target field.
        self.drain_file_dialogs();
        // The next waiting file starts once nothing else is showing or running.
        self.import_start_next();
        let p = self.palette();
        // Rebuilding + re-applying egui Visuals every frame is wasted work;
        // only do it when a theme knob actually changed.
        let theme_key = (self.mode, self.accent_idx, self.colorblind);
        if self.applied_theme != Some(theme_key) {
            p.apply(ctx, self.mode);
            self.applied_theme = Some(theme_key);
        }

        // UI scale ("Text size", issue #42). Let Ctrl +/-/scroll zoom the whole
        // UI immediately (egui then scales fonts AND painted symbols uniformly).
        ctx.options_mut(|o| o.zoom_with_keyboard = true);
        match self.applied_zoom {
            // First frame: push *our* persisted factor into the context. This
            // is also the persistence-conflict fix: eframe restores egui's own
            // memory (which includes egui's separately-persisted zoom factor)
            // before this runs, so two sources of truth exist. We resolve it by
            // making our "zoom" storage key authoritative — re-applying it here
            // every launch deterministically overrides whatever egui restored,
            // so the two can never drift (last writer is always us). We do NOT
            // read `ctx.zoom_factor()` back on this frame: doing so previously
            // clobbered the loaded value with a stale 1.0, which `save()` then
            // persisted, so the chosen size reset on every reopen.
            None => {
                self.zoom = theme::clamp_zoom(self.zoom);
                ctx.set_zoom_factor(self.zoom);
                self.applied_zoom = Some(self.zoom);
            }
            // Steady state: the context owns the live factor (Ctrl +/-/scroll
            // and the slider's on-release commit both write it via
            // `set_zoom_factor`). Mirror it back into `self.zoom` so the readout
            // and the persisted value stay in sync — but never while the slider
            // is mid-drag, since the drag stashes its preview in `zoom_pending`
            // and has not committed to the context yet.
            Some(_) => {
                if self.zoom_pending.is_none() {
                    // Ctrl +/- and Ctrl-scroll use egui's built-in keyboard zoom,
                    // which ignores our 80–200% slider bounds. If it ran past the
                    // limit, pull the context back to the clamp so the keyboard
                    // path obeys the same range as the slider (issue #42).
                    let live = ctx.zoom_factor();
                    let clamped = theme::clamp_zoom(live);
                    if (live - clamped).abs() > f32::EPSILON {
                        ctx.set_zoom_factor(clamped);
                    }
                    self.zoom = clamped;
                    self.applied_zoom = Some(self.zoom);
                    // The zoom only lands here once it's committed to the
                    // context (slider release, Ctrl +/-/scroll, or Reset), never
                    // mid-drag (guarded by `zoom_pending`). Persist on the
                    // committed value; `persist_settings` no-ops when the factor
                    // is unchanged, so this is cheap on every quiescent frame.
                    self.persist_settings();
                }
            }
        }

        // First frame: scan for devices automatically so the user isn't staring
        // at an empty pane wondering whether the app is broken.
        if !self.scanned {
            self.scanned = true;
            self.schedule_scan_burst();
        }

        // Armed FIDO reset: poll the live key list so we can fire the reset the
        // instant the user re-inserts the key. Runs before the hotplug refresh
        // and holds the worker slot, so a replug-triggered rescan can't beat the
        // reset to it.
        if self.reset_arm.is_some() {
            self.poll_reset_arm();
            ctx.request_repaint_after(std::time::Duration::from_millis(200));
        }

        // Reader hotplug: the watcher set this flag (and woke us). Start a
        // rescan burst (suppressed while a reset is armed, so its job can't
        // steal the worker slot).
        if self.reset_arm.is_none()
            && self
                .devices_dirty
                .swap(false, std::sync::atomic::Ordering::Relaxed)
        {
            self.schedule_scan_burst();
        }

        // Drive the rescan burst: run a scan when one is due and the worker is
        // free, then schedule the next. Spacing gives a slow reader (Molto2)
        // time to register with pcscd between attempts.
        //
        // Held off while an inline rename field is open: a scan replaces the
        // device list and can move the selection out from under the open field
        // (acute with the Molto2's flapping CCID reader). The pending count is
        // kept, and `close_rename` requests a repaint, so the burst resumes
        // the moment the field closes — without keeping a 2 Hz wakeup loop
        // armed for the whole edit.
        if self.reset_arm.is_none() && self.pending_scans > 0 {
            let now = std::time::Instant::now();
            let due = self.next_scan_at.is_none_or(|t| now >= t);
            let renaming = self.rename_target.is_some();
            if due && !self.busy() && !renaming {
                self.refresh_devices();
                self.pending_scans -= 1;
                self.next_scan_at = Some(now + std::time::Duration::from_millis(1500));
            }
            if self.pending_scans > 0 && !renaming {
                ctx.request_repaint_after(std::time::Duration::from_millis(500));
            }
        }

        self.top_bar(root_ui, &p);
        self.device_sidebar(root_ui, &p);
        if self.log_open && !self.log_detached {
            self.activity_log(root_ui, &p);
        }
        self.central(root_ui, &p);

        // Popped-out activity log: its own OS window, rendered every frame while
        // detached. "Reattach" docks it back into the bottom drawer; the
        // window's close button collapses the log entirely.
        if self.log_open && self.log_detached {
            self.activity_log_window(ctx, &p);
        }

        // Modal dialogs (reused from the per-applet logic) + Molto2 import dialogs.
        self.render_reset_dialog(ctx);
        self.render_advanced_confirm(ctx, &p);
        self.render_enroll_dialog(ctx, &p);
        if let Some(id) = self.render_fp_delete_confirm(ctx, &p) {
            self.delete_fingerprint(id);
        }
        self.render_oath_delete_confirm(ctx);
        self.render_oath_reset_confirm(ctx);
        self.render_factory_reset_confirm(ctx, &p);
        self.render_oath_add_modal(ctx, &p);
        self.render_openpgp_cred_modal(ctx, &p);
        self.render_piv_confirms(ctx);
        self.render_piv_cred_modal(ctx, &p);
        self.molto_dialogs(ctx);
        self.render_import(ctx, &p);

        // Help popover, painted last so it sits above everything.
        if let Some(topic) = self.help_open {
            if ui::help_popover(ctx, &p, topic, self.help_anchor) {
                self.help_open = None;
            }
        }

        // Keep OATH rings / Molto2 time ticking while a device is selected.
        // Only keep ticking when something actually animates (OATH countdown
        // rings, the Molto2 view, or the "copied" flash) — not on every static
        // pane, which would burn frames and feel sluggish.
        // Auto-refresh on-device TOTP codes when their time window rolls over.
        // The device returns codes only at read time, so once the window flips
        // the shown codes are stale; reload them (like clicking Refresh). Keyed
        // on the shortest period among the visible TOTP rows so a 30s entry
        // refreshes on its boundary even if a 60s entry is also present.
        if matches!(self.cap_tab, CapTab::Otp) && self.otp.loaded {
            let min_period = self
                .otp
                .rows
                .iter()
                .filter(|r| r.type_str.eq_ignore_ascii_case("TOTP") && r.code.is_some())
                .map(|r| if r.period == 0 { 30 } else { r.period as u64 })
                .min();
            if let Some(period) = min_period {
                let now = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_secs())
                    .unwrap_or(0);
                let window = now / period;
                match self.otp_last_window {
                    Some(prev) if prev != window => {
                        self.otp_last_window = Some(window);
                        self.load_otp_entries();
                    }
                    None => self.otp_last_window = Some(window),
                    _ => {}
                }
            }
        } else {
            // Reset when leaving the tab so re-entry doesn't trigger a spurious
            // reload on a window that "changed" while we weren't watching.
            self.otp_last_window = None;
        }

        let animating = self.copied.is_some()
            || matches!(self.cap_tab, CapTab::Oath)
            || (matches!(self.cap_tab, CapTab::Overview)
                && self.oath.loaded
                && !self.oath.creds.is_empty())
            || (matches!(self.cap_tab, CapTab::Otp)
                && self
                    .otp
                    .rows
                    .iter()
                    .any(|r| r.type_str.eq_ignore_ascii_case("TOTP") && r.code.is_some()))
            || self
                .selected_device()
                .is_some_and(|d| d.kind == DeviceKind::Token);
        if animating {
            ctx.request_repaint_after(std::time::Duration::from_millis(500));
        }
    }
}

// --- Device-centric rendering ------------------------------------------------
impl App {
    /// Toggle the help popover for `topic`, anchored under the clicked "?" button.
    fn help_dot(&mut self, ui: &mut egui::Ui, p: &Palette, topic: &'static str) {
        let r = ui::help_button(ui, p, self.help_open == Some(topic));
        if r.hovered() {
            ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
        }
        if r.clicked() {
            self.toggle_help(topic, r.rect.left_bottom());
        }
    }

    /// Top bar: brand · "keyroost" · connected count | accents · theme · Learn ·
    /// Activity log · Refresh.
    fn top_bar(&mut self, root_ui: &mut egui::Ui, p: &Palette) {
        let ctx = root_ui.ctx().clone();
        // The bar height must track the zoom factor: at a larger text size the
        // glyph tile, labels and icons are all scaled up, and a fixed 52px panel
        // would clip them and let the left content overrun the right-hand
        // controls. Scale the base height by the live zoom so the bar grows with
        // its contents (clamped so it never collapses below the base).
        let zoom = theme::clamp_zoom(ctx.zoom_factor());
        let bar_h = (52.0 * zoom).max(52.0);
        egui::Panel::top("bar")
            .exact_size(bar_h)
            .frame(panel_frame(p.bar, 16.0, 0.0))
            .show(root_ui, |ui| {
                ui.horizontal_centered(|ui| {
                    glyph_tile(ui, 26.0, p.brand, p.accent_ink, Some('k'));
                    ui.add_space(8.0);
                    ui.label(
                        egui::RichText::new("keyroost")
                            .font(theme::f_bold(14.0))
                            .color(p.txt),
                    );
                    ui.add_space(6.0);
                    // Quiet version chip: the only place the app says which
                    // version it is (#98), so keep it visible but muted.
                    ui.label(
                        egui::RichText::new(VERSION_LABEL)
                            .font(theme::f_reg(11.0))
                            .color(p.txt3),
                    );
                    ui.add_space(12.0);
                    theme::status_dot(ui, p.ok, 7.0);
                    ui.add_space(5.0);
                    ui.label(
                        egui::RichText::new(format!("{} connected", self.devices.len()))
                            .font(theme::f_reg(12.0))
                            .color(p.txt2),
                    );
                    if self.busy() {
                        ui.add_space(12.0);
                        ui.spinner();
                        if let Some(label) = &self.busy_label {
                            // Truncate so a long status never pushes the left
                            // content into the right-hand controls (overlap on
                            // small / zoomed layouts).
                            ui.add(
                                egui::Label::new(
                                    egui::RichText::new(label.as_str())
                                        .font(theme::f_reg(12.0))
                                        .color(p.txt3),
                                )
                                .truncate(),
                            );
                        }
                    }

                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if theme::button(ui, p, BtnKind::Ghost, "Refresh").clicked() {
                            self.schedule_scan_burst();
                        }
                        ui.add_space(4.0);
                        let log_color = if self.log_open { p.accent } else { p.txt2 };
                        if ui
                            .add(
                                egui::Label::new(
                                    egui::RichText::new("Activity log")
                                        .font(theme::f_sb(12.5))
                                        .color(log_color),
                                )
                                .sense(egui::Sense::click()),
                            )
                            .on_hover_cursor(egui::CursorIcon::PointingHand)
                            .clicked()
                        {
                            if self.log_detached {
                                // The log is popped out into its own window;
                                // the link brings that window forward rather
                                // than toggling (and closing) the drawer that
                                // isn't showing.
                                ctx.send_viewport_cmd_to(
                                    activity_log_viewport_id(),
                                    egui::ViewportCommand::Focus,
                                );
                            } else {
                                self.log_open = !self.log_open;
                            }
                        }
                        ui.add_space(10.0);
                        ui.hyperlink_to(
                            egui::RichText::new("Learn \u{2197}")
                                .font(theme::f_sb(12.5))
                                .color(p.txt2),
                            ui::help::LEARN_BASE,
                        );
                        ui.add_space(10.0);
                        let (trect, tresp) =
                            ui.allocate_exact_size(egui::vec2(18.0, 18.0), egui::Sense::click());
                        paint_theme_icon(ui, trect.center(), 7.0, p.txt2);
                        if tresp
                            .on_hover_text("Toggle light / dark")
                            .on_hover_cursor(egui::CursorIcon::PointingHand)
                            .clicked()
                        {
                            self.mode = match self.mode {
                                Mode::Dark => Mode::Light,
                                Mode::Light => Mode::Dark,
                            };
                            self.persist_settings();
                        }
                        ui.add_space(10.0);
                        let (erect, eresp) =
                            ui.allocate_exact_size(egui::vec2(18.0, 18.0), egui::Sense::click());
                        paint_eye_icon(
                            ui,
                            erect.center(),
                            if self.colorblind { p.accent } else { p.txt2 },
                        );
                        if eresp
                            .on_hover_text("Colorblind-safe colors")
                            .on_hover_cursor(egui::CursorIcon::PointingHand)
                            .clicked()
                        {
                            self.colorblind = !self.colorblind;
                            self.persist_settings();
                        }
                        ui.add_space(10.0);
                        // "Text size" (issue #42): a compact UI-scale control.
                        // The slider drives egui's global zoom factor, which
                        // scales fonts AND painted symbols uniformly. A live "%"
                        // readout sits to the right (rightmost in this RTL row),
                        // with a "Reset" that appears only when off 100%.
                        self.text_size_control(ui, p);
                        ui.add_space(10.0);
                        for (i, c) in Palette::ACCENTS.iter().enumerate().rev() {
                            let (rect, resp) = ui
                                .allocate_exact_size(egui::vec2(16.0, 16.0), egui::Sense::click());
                            let on = i == self.accent_idx;
                            ui.painter().circle_filled(
                                rect.center(),
                                if on { 6.0 } else { 5.0 },
                                *c,
                            );
                            if on {
                                ui.painter().circle_stroke(
                                    rect.center(),
                                    7.5,
                                    egui::Stroke::new(1.5, p.txt),
                                );
                            }
                            if resp.hovered() {
                                ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
                            }
                            if resp.clicked() {
                                self.accent_idx = i;
                                self.persist_settings();
                            }
                        }
                    });
                });
            });
    }

    /// "Text size" control for the top bar (issue #42): a compact slider over
    /// egui's global zoom factor (80%–200%), with a live "%" readout and a
    /// "Reset" that surfaces only when the scale is off 100%. Writing the slider
    /// calls `set_zoom_factor`, so the whole UI — fonts and painted symbols —
    /// rescales uniformly. Lives inside the top bar's right-to-left layout, so
    /// widgets are added right-to-left: readout, slider, label, then Reset.
    fn text_size_control(&mut self, ui: &mut egui::Ui, p: &Palette) {
        // The slider lives inside the very UI it scales, so applying the zoom
        // *live* during a drag grows/shifts the slider track under the cursor
        // and runs the value away to the maximum. Fix: apply-on-release. While
        // dragging we edit a preview (`zoom_pending`) and leave the context
        // factor alone, so the UI stays stable; we commit `set_zoom_factor`
        // only when the drag ends. Keyboard/scroll zoom is unaffected (it has
        // no feedback loop) and keeps writing the context directly.
        //
        // The slider edits `factor`: the pending preview if a drag is in
        // flight, otherwise the committed live factor. The readout tracks the
        // same value so it follows the handle during the drag.
        let mut factor = self
            .zoom_pending
            .unwrap_or_else(|| theme::clamp_zoom(ui.ctx().zoom_factor()));

        // Live percentage readout (rightmost). FIXED width: as the value crosses
        // 99%→100% the glyph count goes 3→4; in the bar's right-to-left layout a
        // wider readout would shove the slider track left under the cursor and
        // make the value lurch (issue #42). `allocate_exact_size` reserves the
        // widest readout's box unconditionally (unlike `allocate_ui_with_layout`,
        // which advances by content width and so would still let the track move);
        // we then paint the value right-aligned inside it, so the slider geometry
        // is identical for "99%" and "100%".
        let pct = (factor * 100.0).round() as i32;
        let cell = ui.fonts_mut(|f| {
            f.layout_no_wrap("888%".to_owned(), theme::f_sb(12.0), p.txt2)
                .size()
        });
        let (rrect, _) = ui.allocate_exact_size(
            egui::vec2(cell.x.ceil(), cell.y.ceil()),
            egui::Sense::hover(),
        );
        ui.painter().text(
            rrect.right_center(),
            egui::Align2::RIGHT_CENTER,
            format!("{pct}%"),
            theme::f_sb(12.0),
            p.txt2,
        );
        ui.add_space(6.0);

        // The slider itself. Style its track/handle to the palette so it reads
        // as part of the bar rather than egui's default blue. egui draws both the
        // rail and the handle from `inactive.bg_fill`; on the LIGHT theme `raised2`
        // sits almost on top of the bar, so the rail, handle and steppers were
        // near-invisible (#59). Use a clearly darker control gray on light (the
        // dark bar keeps `raised2`, which already contrasts fine).
        let (track, track_hot) = match self.mode {
            Mode::Light => (theme::darken(p.bar, 0.16), theme::darken(p.bar, 0.26)),
            Mode::Dark => (p.raised2, theme::lighten(p.raised2, 0.08)),
        };
        let style = ui.style_mut();
        style.visuals.widgets.inactive.bg_fill = track;
        style.visuals.widgets.hovered.bg_fill = track_hot;
        style.visuals.widgets.active.bg_fill = p.accent;
        style.visuals.widgets.inactive.fg_stroke = egui::Stroke::new(1.0, p.txt2);
        style.visuals.widgets.hovered.fg_stroke = egui::Stroke::new(1.0, p.txt);
        style.spacing.slider_width = 92.0;

        // [+] / [−] steppers flanking the slider, each nudging the size by 1%
        // (0.01). The bar is laid out right-to-left, so to read "[−] slider [+]"
        // left-to-right we emit the [+] first, then the slider, then the [−].
        // A small closure paints one square stepper button and reports clicks.
        let step = |ui: &mut egui::Ui, glyph: &str| -> egui::Response {
            let (rect, resp) = ui.allocate_exact_size(egui::vec2(16.0, 16.0), egui::Sense::click());
            let hot = resp.hovered();
            ui.painter()
                .rect_filled(rect, 3.0, if hot { track_hot } else { track });
            ui.painter().text(
                rect.center(),
                egui::Align2::CENTER_CENTER,
                glyph,
                theme::f_sb(13.0),
                if hot { p.txt } else { p.txt2 },
            );
            resp.on_hover_cursor(egui::CursorIcon::PointingHand)
        };

        // [+] (rightmost of the trio in this RTL row). Preview only (stash in
        // `zoom_pending` + arm the commit timer); the rescale is deferred so the
        // button stays under the cursor for repeated clicks — see the commit
        // block after the [−] stepper.
        let plus = step(ui, "+");
        if plus.clicked() {
            factor = theme::clamp_zoom(factor + 0.01);
            self.zoom_pending = Some(factor);
            self.zoom_commit_at =
                Some(std::time::Instant::now() + std::time::Duration::from_millis(350));
        }
        ui.add_space(4.0);

        let resp = ui.add(
            egui::Slider::new(&mut factor, theme::ZOOM_MIN..=theme::ZOOM_MAX)
                .show_value(false)
                .trailing_fill(true),
        );
        if resp.dragged() {
            // Mid-drag: preview only, don't touch the context (avoids runaway).
            // A drag supersedes any pending stepper preview.
            self.zoom_pending = Some(theme::clamp_zoom(factor));
            self.zoom_commit_at = None;
        } else if resp.drag_stopped() {
            // Drag released: commit the chosen size to the context once.
            ui.ctx().set_zoom_factor(theme::clamp_zoom(factor));
            self.zoom_pending = None;
            self.zoom_commit_at = None;
        } else if resp.changed() {
            // Click/keyboard committed a value without a drag (e.g. arrow keys
            // or clicking the track): apply immediately, nothing to preview.
            ui.ctx().set_zoom_factor(theme::clamp_zoom(factor));
            self.zoom_pending = None;
            self.zoom_commit_at = None;
        }
        let resp = resp
            .on_hover_text("Text size — scales the whole interface (Ctrl + / Ctrl − also work)");

        ui.add_space(4.0);
        // [−] (leftmost of the trio). Preview-only like [+].
        let minus = step(ui, "\u{2212}");
        if minus.clicked() {
            factor = theme::clamp_zoom(factor - 0.01);
            self.zoom_pending = Some(factor);
            self.zoom_commit_at =
                Some(std::time::Instant::now() + std::time::Duration::from_millis(350));
        }

        // Commit a stepper preview once the user settles: pointer off both
        // buttons, or 350ms since the last click. The slider commits its own
        // preview on release, so a pending value reaching here is always from a
        // stepper. Deferring keeps the bar (and the buttons) from rescaling out
        // from under the cursor during a run of clicks; we repaint at the
        // deadline so it still applies if the pointer never moves.
        if let Some(at) = self.zoom_commit_at {
            let settled = (!plus.hovered() && !minus.hovered()) || std::time::Instant::now() >= at;
            if settled && !resp.dragged() {
                if let Some(f) = self.zoom_pending.take() {
                    ui.ctx().set_zoom_factor(f);
                }
                self.zoom_commit_at = None;
            } else {
                ui.ctx()
                    .request_repaint_after(at.saturating_duration_since(std::time::Instant::now()));
            }
        }

        ui.add_space(7.0);

        // Label.
        ui.label(
            egui::RichText::new("Text size")
                .font(theme::f_reg(12.0))
                .color(p.txt2),
        );

        // "Reset" appears only when we're off the default, so the chrome stays
        // quiet for users who never change it.
        if (factor - theme::ZOOM_DEFAULT).abs() > f32::EPSILON {
            ui.add_space(8.0);
            if ui
                .add(
                    egui::Label::new(
                        egui::RichText::new("Reset")
                            .font(theme::f_sb(12.0))
                            .color(p.accent),
                    )
                    .sense(egui::Sense::click()),
                )
                .on_hover_cursor(egui::CursorIcon::PointingHand)
                .clicked()
            {
                ui.ctx().set_zoom_factor(theme::ZOOM_DEFAULT);
                self.zoom_pending = None;
                self.zoom_commit_at = None;
            }
        }
    }

    /// Left device bar: header · filter · rows · footer tip.
    fn device_sidebar(&mut self, root_ui: &mut egui::Ui, p: &Palette) {
        egui::Panel::left("devices")
            .exact_size(286.0)
            .resizable(false)
            .frame(panel_frame(p.side, 14.0, 12.0))
            .show(root_ui, |ui| {
                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new("DEVICES")
                            .font(theme::f_bold(11.0))
                            .color(p.txt3),
                    );
                    ui.add_space(6.0);
                    theme::pill(ui, &self.devices.len().to_string(), p.txt2, p.raised2);
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        let (rrect, rresp) =
                            ui.allocate_exact_size(egui::vec2(18.0, 18.0), egui::Sense::click());
                        paint_refresh_icon(ui, rrect.center(), 6.5, p.txt2);
                        if rresp
                            .on_hover_text("Rescan")
                            .on_hover_cursor(egui::CursorIcon::PointingHand)
                            .clicked()
                        {
                            self.schedule_scan_burst();
                        }
                    });
                });
                ui.add_space(8.0);
                ui.add(
                    egui::TextEdit::singleline(&mut self.filter)
                        .hint_text("Filter keys\u{2026}")
                        .desired_width(f32::INFINITY),
                );
                ui.add_space(8.0);

                if let Some(err) = &self.devices_error {
                    ui.colored_label(p.err, err);
                    ui.add_space(6.0);
                }

                let mut clicked: Option<DeviceId> = None;
                egui::ScrollArea::vertical()
                    .auto_shrink([false, false])
                    .show(ui, |ui| {
                        if self.devices.is_empty() {
                            ui.add_space(12.0);
                            ui.vertical_centered(|ui| {
                                ui.label(
                                    egui::RichText::new("No keys detected yet.")
                                        .font(theme::f_reg(13.0))
                                        .color(p.txt3),
                                );
                            });
                        }
                        for dev in self
                            .devices
                            .iter()
                            .filter(|d| matches_filter(d, &self.filter))
                        {
                            let selected = self.selected_device.as_deref() == Some(dev.id.as_str());
                            if device_row(ui, p, dev, selected) {
                                clicked = Some(dev.id.clone());
                            }
                            ui.add_space(2.0);
                        }
                    });
                if let Some(id) = clicked {
                    self.select_device(id);
                }

                // Footer tip (only worth showing once a key is present).
                if !self.devices.is_empty() {
                    ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| {
                        ui.add_space(4.0);
                        ui.horizontal_wrapped(|ui| {
                            ui.spacing_mut().item_spacing.x = 4.0;
                            ui.label(
                                egui::RichText::new("Several keys plugged in?")
                                    .font(theme::f_reg(12.0))
                                    .color(p.txt3),
                            );
                            ui.hyperlink_to(
                                egui::RichText::new("Give them names")
                                    .font(theme::f_sb(12.0))
                                    .color(p.accent),
                                ui::help::learn_url("/naming"),
                            );
                        });
                    });
                }
            });
    }

    /// Global activity-log drawer (bottom), replacing the Molto2-only log.
    fn activity_log(&mut self, root_ui: &mut egui::Ui, p: &Palette) {
        egui::Panel::bottom("log")
            .resizable(true)
            .default_size(180.0)
            // Enough to still show the header when dragged down; capped so
            // it can't swallow the whole window and crowd out the device
            // pane above it.
            .size_range(96.0..=560.0)
            .frame(panel_frame(p.bar, 16.0, 10.0))
            .show(root_ui, |ui| {
                self.activity_log_body(ui, p, false);
            });
    }

    /// Popped-out activity log: the same body rendered in its own OS window.
    /// Shown every frame while `log_detached`. Closing the window collapses the
    /// log entirely (same end state as the docked "Collapse" button); the
    /// header's "Reattach" button docks it back into the drawer instead.
    fn activity_log_window(&mut self, ctx: &egui::Context, p: &Palette) {
        let mut close_requested = false;
        ctx.show_viewport_immediate(
            activity_log_viewport_id(),
            egui::ViewportBuilder::default()
                .with_title("keyroost \u{2014} Activity log")
                .with_inner_size([620.0, 340.0])
                .with_min_inner_size([340.0, 140.0]),
            |ctx, _class| {
                egui::CentralPanel::default()
                    .frame(panel_frame(p.bar, 16.0, 10.0))
                    .show(ctx, |ui| {
                        self.activity_log_body(ui, p, true);
                    });
                if ctx.input(|i| i.viewport().close_requested()) {
                    close_requested = true;
                }
            },
        );
        if close_requested {
            // The window's close button collapses the log outright, rather
            // than dropping it back into the docked drawer.
            self.log_open = false;
            self.log_detached = false;
        }
    }

    /// The activity log's contents — header row plus the scrolling entry list —
    /// shared by the docked drawer and the popped-out window. `detached` picks
    /// the outer-right window control: the detach icon (plus "Collapse") when
    /// docked, its mirror image — the reattach icon — when popped out.
    fn activity_log_body(&mut self, ui: &mut egui::Ui, p: &Palette, detached: bool) {
        ui.horizontal(|ui| {
            ui.label(
                egui::RichText::new("ACTIVITY LOG")
                    .font(theme::f_bold(11.0))
                    .color(p.txt3),
            );
            ui.add_space(6.0);
            theme::pill(ui, "live", p.ok, p.ok_soft());
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                // Window control at the outer right in both states: an icon-only
                // affordance (detach glyph / its mirror) rather than a verb in
                // the row of text actions. The hit box is a full button-height
                // 32px tall so `Align::Center` lines the 18px glyph up with the
                // adjacent buttons and the "APDU trace" checkbox — a bare 18px
                // rect, allocated first in this row, centres against the row
                // before the buttons have grown it and ends up sitting high.
                let (wrect, wresp) =
                    ui.allocate_exact_size(egui::vec2(18.0, 32.0), egui::Sense::click());
                if detached {
                    paint_reattach_icon(ui, wrect.center(), p.txt2);
                    if wresp
                        .on_hover_text("Dock back into the main window")
                        .on_hover_cursor(egui::CursorIcon::PointingHand)
                        .clicked()
                    {
                        self.log_detached = false;
                    }
                } else {
                    paint_detach_icon(ui, wrect.center(), p.txt2);
                    if wresp
                        .on_hover_text("Open in a separate window")
                        .on_hover_cursor(egui::CursorIcon::PointingHand)
                        .clicked()
                    {
                        self.log_detached = true;
                    }
                    ui.add_space(6.0);
                    if theme::button(ui, p, BtnKind::Ghost, "Collapse").clicked() {
                        self.log_open = false;
                    }
                }
                ui.add_space(4.0);
                if theme::button(ui, p, BtnKind::Ghost, "Clear").clicked() {
                    // Drop every entry (and its APDU trace); the next device
                    // operation starts the log fresh.
                    self.log.clear();
                }
                ui.add_space(4.0);
                if theme::button(ui, p, BtnKind::Ghost, "Copy").clicked() {
                    // Traces ride along, indented under the entry they
                    // belong to — the point of the APDU trace is
                    // having the exact wire exchange to paste, not
                    // just the summary.
                    let all = self
                        .log
                        .iter()
                        .map(|l| match &l.trace {
                            Some(t) if !t.is_empty() => format!(
                                "{}\n{}",
                                l.text,
                                t.iter()
                                    .map(|apdu| format!("    {apdu}"))
                                    .collect::<Vec<_>>()
                                    .join("\n")
                            ),
                            _ => l.text.clone(),
                        })
                        .collect::<Vec<_>>()
                        .join("\n");
                    ui.ctx().copy_text(all);
                    // The user copied non-secret log text over the
                    // code; a pending auto-clear would clobber it.
                    self.clipboard_clear_at = None;
                }
                ui.add_space(10.0);
                // Runtime toggle for the worker thread's APDU capture
                // (see `Worker::spawn`) — no CLI flag, no restart:
                // flip it, and the very next device operation's trace
                // shows up under its log entry.
                let mut trace_on = self.apdu_trace.load(std::sync::atomic::Ordering::Relaxed);
                if ui.checkbox(&mut trace_on, "APDU trace").changed() {
                    self.apdu_trace
                        .store(trace_on, std::sync::atomic::Ordering::Relaxed);
                }
            });
        });
        ui.add_space(6.0);
        egui::ScrollArea::vertical()
            .stick_to_bottom(true)
            .auto_shrink([false, false])
            .show(ui, |ui| {
                for line in self.log.iter_mut() {
                    let base = match line.severity {
                        Severity::Ok => p.ok,
                        Severity::Warn => p.warn,
                        Severity::Err => p.err,
                        Severity::Info => p.txt2,
                    };
                    // User actions render exactly as every explicit
                    // Molto2 action always has: full-strength severity
                    // color, no prefix. Background entries — a device
                    // scan, a tab's initial status sweep, a re-read
                    // that follows a write — are alpha-muted toward
                    // the panel and get a leading "·", so the
                    // distinction survives colorblind palettes too and
                    // never reads as though the user just did
                    // something.
                    let (color, prefix, size) = match line.kind {
                        LogKind::User => (base, "", 12.0),
                        LogKind::Background => (theme::tint(base, 130), "\u{b7} ", 11.5),
                    };
                    ui.label(
                        egui::RichText::new(format!("{prefix}{}", line.text))
                            .font(theme::f_mono(size))
                            .color(color),
                    );
                    // APDU trace ("APDU trace" checkbox above):
                    // printed exactly like the CLI's own `--debug`
                    // output — the same formatted lines, captured
                    // verbatim (see `keyroost_transport::trace`) —
                    // indented under the entry they belong to.
                    if let Some(trace) = line.trace.as_ref() {
                        for apdu in trace {
                            ui.label(
                                egui::RichText::new(format!("    {apdu}"))
                                    .font(theme::f_mono(10.5))
                                    .color(p.txt3),
                            );
                        }
                    }
                }
            });
    }

    /// The central pane: empty state, the Molto2 token view, or the selected
    /// key's hero + capability tabs + active capability panel.
    fn central(&mut self, root_ui: &mut egui::Ui, p: &Palette) {
        egui::CentralPanel::default()
            .frame(panel_frame(p.surface, 0.0, 0.0))
            .show(root_ui, |ui| {
                match self.selected_device().cloned() {
                    None => self.empty_state(ui, p),
                    Some(dev) if dev.kind == DeviceKind::Token => self.molto_view(ui, p, &dev),
                    Some(dev) if dev.kind == DeviceKind::ProgToken => self.prog_view(ui, p, &dev),
                    Some(dev) => {
                        // Cap the content column to a readable width and center it.
                        // At wide window sizes a full-width card flings its label to
                        // the far left and its action to the far right, opening a dead
                        // gap in the middle that makes a row hard to read as one unit.
                        // A symmetric margin that grows past the base 26px once the
                        // pane exceeds ~920px keeps every pane (hero, tabs, cards) in
                        // one centered, legible column instead of stretching edge to
                        // edge — and removes the lopsided empty space on one side.
                        let hmargin = (((ui.available_width() - 920.0) * 0.5).max(26.0)).round();
                        egui::Frame::NONE
                            .inner_margin(egui::Margin::symmetric(hmargin as i8, 16))
                            .show(ui, |ui| {
                                self.device_hero(ui, p, &dev);
                                self.cap_tabs(ui, p, &dev);
                                ui.add_space(16.0);
                                // Hero + tabs stay pinned; the active pane scrolls.
                                // This is the one place every capability pane gets
                                // its overflow handling — a card-heavy OpenPGP pane
                                // or a key holding dozens of passkeys/TOTP codes
                                // scrolls instead of clipping at the window edge.
                                // Salted per tab so each pane keeps its own
                                // scroll position.
                                //
                                // Solid (space-reserving) scroll bars are the
                                // app-wide default set in `theme::Palette::apply`
                                // — no local override needed here. That default
                                // is what keeps this bar from floating over the
                                // cards' right edge (it used to sit on top of
                                // card borders and the panes' top-right action
                                // buttons).
                                egui::ScrollArea::vertical()
                                    .id_salt(("cap-pane", self.cap_tab as u8))
                                    .auto_shrink([false, false])
                                    .show(ui, |ui| {
                                        match self.cap_tab {
                                            CapTab::Overview => self.overview(ui, p, &dev),
                                            CapTab::Fido2 => self.cap_fido2(ui, p),
                                            CapTab::Oath => self.cap_oath(ui, p),
                                            CapTab::Pgp => self.cap_pgp(ui, p),
                                            CapTab::Piv => self.cap_piv(ui, p),
                                            CapTab::Otp => self.cap_otp(ui, p),
                                        }
                                        // Breathing room below the last card.
                                        ui.add_space(18.0);
                                    });
                            });
                    }
                }
            });
    }

    /// Welcoming first-run state shown when nothing is plugged in.
    fn empty_state(&mut self, ui: &mut egui::Ui, p: &Palette) {
        // Manually center a fixed-width column. `vertical_centered` doesn't
        // reliably center nested rows (a `horizontal` fills full width and
        // left-aligns), which is what jammed the buttons against the divider.
        let col_w = 440.0_f32;
        let pad = ((ui.available_width() - col_w) * 0.5).max(12.0);
        ui.add_space(90.0);
        ui.horizontal(|ui| {
            ui.add_space(pad);
            ui.allocate_ui_with_layout(
                egui::vec2(col_w, ui.available_height()),
                egui::Layout::top_down(egui::Align::Center),
                |ui| {
                    let (rect, _) = ui.allocate_exact_size(egui::vec2(64.0, 64.0), egui::Sense::hover());
                    ui.painter().rect_stroke(
                        rect,
                        egui::CornerRadius::same(16),
                        egui::Stroke::new(1.5, p.line),
                        egui::StrokeKind::Inside,
                    );
                    ui.painter().text(
                        rect.center(),
                        egui::Align2::CENTER_CENTER,
                        "\u{1F511}",
                        theme::f_reg(26.0),
                        p.txt3,
                    );
                    ui.add_space(18.0);
                    ui.label(egui::RichText::new("Plug in a security key to begin").font(theme::f_bold(19.0)).color(p.txt));
                    ui.add_space(8.0);
                    ui.label(
                        egui::RichText::new(
                            "keyroost manages YubiKeys, Nitrokeys, SoloKeys and Token2 tokens. Connect one over USB and it shows up in the list on the left.",
                        )
                        .font(theme::f_reg(13.0))
                        .color(p.txt2),
                    );
                    ui.add_space(22.0);
                    // Numbered steps: left-aligned within the centered column.
                    ui.allocate_ui_with_layout(egui::vec2(360.0, 0.0), egui::Layout::top_down(egui::Align::Min), |ui| {
                        for (n, step) in [
                            "Insert your key into a USB port",
                            "It appears in the Devices list automatically",
                            "Select it to view and manage everything it can do",
                        ]
                        .iter()
                        .enumerate()
                        {
                            ui.horizontal(|ui| {
                                let (badge, _) = ui.allocate_exact_size(egui::vec2(22.0, 22.0), egui::Sense::hover());
                                ui.painter().circle_filled(badge.center(), 11.0, p.accent_soft());
                                ui.painter().text(
                                    badge.center(),
                                    egui::Align2::CENTER_CENTER,
                                    format!("{}", n + 1),
                                    theme::f_sb(12.0),
                                    p.accent,
                                );
                                ui.add_space(10.0);
                                ui.label(egui::RichText::new(*step).font(theme::f_reg(13.0)).color(p.txt));
                            });
                            ui.add_space(10.0);
                        }
                    });
                    ui.add_space(14.0);
                    ui.horizontal(|ui| {
                        if theme::button(ui, p, BtnKind::Primary, "Scan for devices").clicked() {
                            self.schedule_scan_burst();
                        }
                        ui.add_space(8.0);
                        ui.hyperlink_to(
                            egui::RichText::new("Supported devices \u{2197}").font(theme::f_sb(12.5)).color(p.accent),
                            ui::help::learn_url("/devices"),
                        );
                    });
                    // Be honest on platforms without a HID backend yet: a plugged-in
                    // FIDO key simply won't appear, so say why rather than letting
                    // the user think it's broken.
                    if !keyroost_hid::hid_supported() {
                        ui.add_space(16.0);
                        ui.label(
                            egui::RichText::new(
                                "Note: FIDO / passkey security keys aren't supported on this platform yet. Smart-card features (OATH, OpenPGP, PIV, Token2 Molto2) work over PC/SC.",
                            )
                            .font(theme::f_reg(12.5))
                            .color(p.txt3),
                        );
                    }
                },
            );
        });
    }

    /// Act on the hero's offer to write the lost name `name` back onto `dev`.
    /// Writing opens the naming field on the key with the name filled in
    /// (and saves at once when the key's FIDO session is unlocked; otherwise
    /// the field asks for the PIN). Forgetting removes this computer's record
    /// of the name; "Not now" hides the offer for this session.
    fn apply_write_back(&mut self, dev: &Device, action: WriteBack, name: &str) {
        match action {
            WriteBack::Write => {
                self.open_rename(dev, Some(name));
                if !self.rename_needs_pin() {
                    self.save_device_name();
                }
            }
            WriteBack::Forget => {
                let saved = keyroost_keyring::Keyring::load_default().and_then(|mut k| {
                    k.remove(name);
                    k.save_default()
                });
                match saved {
                    Ok(_) => {
                        self.log(
                            Severity::Ok,
                            format!("forgot the name \"{name}\" on this computer"),
                        );
                        self.refresh_devices();
                    }
                    Err(e) => self.log(Severity::Err, format!("names not saved: {e}")),
                }
            }
            WriteBack::Dismiss => {
                self.write_back_dismissed.insert(dev.id.clone());
            }
        }
    }

    /// Whether the open naming field asks for a rename on this computer of
    /// a key that carries its name on the key (Save stays disabled).
    fn rename_blocked(&self) -> bool {
        self.rename_target.as_ref().is_some_and(|t| {
            device::plan_name_save(&t.naming, t.store, self.rename_input.trim())
                == Err(device::NAME_IS_ON_THE_KEY)
        })
    }

    /// Whether saving the open naming field writes to the key.
    fn rename_goes_on_key(&self) -> bool {
        self.rename_target.as_ref().is_some_and(|t| {
            matches!(
                device::plan_name_save(&t.naming, t.store, self.rename_input.trim()),
                Ok(device::NameSave::OnKey { .. })
            )
        })
    }

    /// The inline naming field's text box with Save and Cancel, shared by
    /// the security-key and Molto2 heroes. Returns (save, cancel).
    fn rename_field_row(&mut self, ui: &mut egui::Ui, p: &Palette) -> (bool, bool) {
        let held = self
            .rename_target
            .as_ref()
            .is_some_and(|t| t.saving || t.confirm.is_some());
        let resp = ui
            .add_enabled_ui(!held, |ui| {
                ui.add_sized(
                    [200.0, 32.0],
                    egui::TextEdit::singleline(&mut self.rename_input)
                        .vertical_align(egui::Align::Center)
                        .hint_text("friendly-name"),
                )
            })
            .inner;
        let enter = resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
        let save = if held || self.rename_blocked() {
            theme::button_disabled(ui, p, "Save");
            false
        } else {
            theme::button(ui, p, BtnKind::Primary, "Save").clicked() || enter
        };
        ui.add_space(4.0);
        let cancel = theme::button(ui, p, BtnKind::Ghost, "Cancel").clicked();
        (save, cancel)
    }

    /// What the naming field explains under the text box: where the name
    /// goes (and the choice, when the key can hold its own name), the PIN
    /// field for an on-key save, the last error, and the replace/remove
    /// question. `what` is "key" or "token". Returns (confirm, cancel the
    /// question, Enter pressed in the PIN field — a save like the name
    /// field's Enter).
    fn rename_details(&mut self, ui: &mut egui::Ui, p: &Palette, what: &str) -> (bool, bool, bool) {
        let note = |ui: &mut egui::Ui, text: &str| {
            ui.label(
                egui::RichText::new(text)
                    .font(theme::f_reg(11.5))
                    .color(p.txt3),
            );
        };
        let computer_note = format!(
            "Saves a fingerprint of this {what} (not its serial) with the name in keys.json \
             on this computer. Up to 64 characters."
        );
        let needs_pin = self.rename_needs_pin();
        let on_key = self.rename_goes_on_key();
        let blocked = self.rename_blocked();
        let Some(t) = self.rename_target.as_mut() else {
            return (false, false, false);
        };
        ui.add_space(3.0);
        if t.choices.contains(&device::NameStoreChoice::Key) {
            ui.add_enabled_ui(!t.saving && t.confirm.is_none(), |ui| {
                ui.radio_value(
                    &mut t.store,
                    device::NameStoreChoice::Computer,
                    egui::RichText::new("On this computer").font(theme::f_reg(12.5)),
                );
                note(ui, &computer_note);
                ui.add_space(2.0);
                ui.radio_value(
                    &mut t.store,
                    device::NameStoreChoice::Key,
                    egui::RichText::new("On this key").font(theme::f_reg(12.5)),
                );
                note(
                    ui,
                    "Visible to anyone who has the key. Saving asks for the key's PIN.",
                );
            });
        } else {
            if t.lacks_storage {
                note(
                    ui,
                    "This key can't store a name on itself; it is saved on this computer.",
                );
            }
            note(ui, &computer_note);
        }
        if blocked {
            ui.add_space(3.0);
            ui.colored_label(p.err, device::NAME_IS_ON_THE_KEY);
        }
        let mut submit = false;
        if on_key && needs_pin && !t.saving {
            ui.add_space(4.0);
            let pin = &mut self.rename_pin;
            let held = t.confirm.is_some();
            ui.horizontal(|ui| {
                ui.label(
                    egui::RichText::new("Key PIN")
                        .font(theme::f_reg(12.5))
                        .color(p.txt2),
                );
                let resp = ui.add(
                    egui::TextEdit::singleline(pin)
                        .password(true)
                        .desired_width(160.0),
                );
                guard_secret_field(ui.ctx(), &resp);
                submit =
                    !held && resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
            });
        }
        let Some(t) = self.rename_target.as_mut() else {
            return (false, false, false);
        };
        if let Some(e) = &t.error {
            ui.add_space(3.0);
            ui.colored_label(p.err, e);
        }
        let (mut confirm, mut cancel) = (false, false);
        if let Some((question, name)) = &t.confirm {
            ui.add_space(6.0);
            theme::card_frame(p)
                .stroke(egui::Stroke::new(1.0, theme::tint(p.err, 90)))
                .show(ui, |ui| {
                    ui.label(
                        egui::RichText::new(question)
                            .font(theme::f_reg(12.5))
                            .color(p.txt),
                    );
                    ui.add_space(6.0);
                    ui.horizontal(|ui| {
                        let (kind, label) = if name.is_some() {
                            (BtnKind::Primary, "Replace")
                        } else {
                            (BtnKind::Danger, "Remove")
                        };
                        confirm = theme::button(ui, p, kind, label).clicked();
                        cancel = theme::button(ui, p, BtnKind::Ghost, "Cancel").clicked();
                    });
                });
        }
        (confirm, cancel, submit)
    }

    /// Apply what [`Self::rename_details`] returned.
    fn apply_rename_question(&mut self, confirm: bool, cancel: bool) {
        if confirm {
            self.confirm_key_name_write();
        } else if cancel {
            if let Some(t) = self.rename_target.as_mut() {
                t.confirm = None;
            }
        }
    }

    /// Device hero strip at the top of a key's pane.
    fn device_hero(&mut self, ui: &mut egui::Ui, p: &Palette, dev: &Device) {
        let mut open_rename = false;
        let mut do_save = false;
        let mut do_cancel = false;
        let (mut do_confirm, mut do_unconfirm, mut pin_enter) = (false, false, false);
        let mut write_back: Option<WriteBack> = None;
        let offer = device::write_back_offer(dev, self.write_back_dismissed.contains(&dev.id))
            .filter(|_| self.rename_target.is_none())
            .map(str::to_owned);
        ui.horizontal(|ui| {
            glyph_tile(
                ui,
                46.0,
                p.raised2,
                p.txt2,
                Some(
                    dev.vendor
                        .chars()
                        .next()
                        .unwrap_or('?')
                        .to_ascii_uppercase(),
                ),
            );
            ui.add_space(12.0);
            ui.vertical(|ui| {
                ui.horizontal(|ui| {
                    if self.rename_target.is_some() {
                        (do_save, do_cancel) = self.rename_field_row(ui, p);
                    } else {
                        ui.label(
                            egui::RichText::new(dev.title())
                                .font(theme::f_bold(21.0))
                                .color(p.txt),
                        );
                        ui.add_space(5.0);
                        self.help_dot(ui, p, "device");
                        ui.add_space(8.0);
                        let label = if dev.name.is_some() {
                            "Rename"
                        } else {
                            "Name this key"
                        };
                        if ui
                            .add(
                                egui::Label::new(
                                    egui::RichText::new(label)
                                        .font(theme::f_sb(12.0))
                                        .color(p.accent),
                                )
                                .sense(egui::Sense::click()),
                            )
                            .clicked()
                        {
                            open_rename = true;
                        }
                    }
                });
                if self.rename_target.is_some() {
                    (do_confirm, do_unconfirm, pin_enter) = self.rename_details(ui, p, "key");
                }
                ui.add_space(2.0);
                let serial = if dev.serial.is_empty() {
                    "\u{2014}".to_string()
                } else {
                    dev.serial.clone()
                };
                let mut meta = format!(
                    "{} \u{00B7} #{} \u{00B7} {}",
                    dev.vendor, serial, dev.transport
                );
                if !dev.firmware.is_empty() {
                    meta.push_str(&format!(" \u{00B7} fw {}", dev.firmware));
                }
                if dev.naming.source == Some(keyroost_resolve::NameSource::Key) {
                    meta.push_str(" \u{00B7} name on key");
                }
                ui.label(
                    egui::RichText::new(meta)
                        .font(theme::f_reg(12.5))
                        .color(p.txt2),
                );
                if let Some(n) = &offer {
                    ui.add_space(6.0);
                    ui.horizontal(|ui| {
                        ui.label(
                            egui::RichText::new(format!(
                                "This key no longer carries its name \"{n}\"."
                            ))
                            .font(theme::f_reg(12.5))
                            .color(p.txt),
                        );
                        ui.add_space(6.0);
                        if theme::button(ui, p, BtnKind::Primary, "Write it back").clicked() {
                            write_back = Some(WriteBack::Write);
                        }
                        if theme::button(ui, p, BtnKind::Ghost, "Forget")
                            .on_hover_text("Remove this name from this computer.")
                            .clicked()
                        {
                            write_back = Some(WriteBack::Forget);
                        }
                        if theme::button(ui, p, BtnKind::Ghost, "Not now").clicked() {
                            write_back = Some(WriteBack::Dismiss);
                        }
                    });
                }
            });
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                ui.label(
                    egui::RichText::new("Connected")
                        .font(theme::f_sb(12.5))
                        .color(p.txt2),
                );
                ui.add_space(5.0);
                theme::status_dot(ui, p.ok, 8.0);
            });
        });
        self.apply_rename_question(do_confirm, do_unconfirm);
        let save = (do_save || pin_enter) && !self.rename_blocked();
        self.apply_rename_actions(dev, open_rename, do_cancel, save);
        if let (Some(action), Some(n)) = (write_back, offer) {
            self.apply_write_back(dev, action, &n);
        }
        ui.add_space(14.0);
        let y = ui.cursor().top();
        ui.painter()
            .hline(ui.max_rect().x_range(), y, egui::Stroke::new(1.0, p.line));
    }

    /// Capability tab bar under the hero. The active tab gets `txt` + an accent
    /// underline; the rest are muted.
    fn cap_tabs(&mut self, ui: &mut egui::Ui, p: &Palette, dev: &Device) {
        // A per-device remembered pick (or a device swap under an unchanged
        // selection) can be stale for this device — see `snap_cap_tab`'s doc.
        self.cap_tab = snap_cap_tab(self.cap_tab, &dev.tabs());
        ui.add_space(12.0);
        let mut next = None;
        ui.horizontal(|ui| {
            ui.spacing_mut().item_spacing.x = 20.0;
            for t in dev.tabs() {
                let active = self.cap_tab == t;
                let color = if active { p.txt } else { p.txt3 };
                // A capability keyroost could not check against the device
                // gets a quiet "?" — the tab works exactly the same, the
                // marker only keeps an offer from reading as verified fact.
                let unverified = dev.tab_unverified(t);
                let label = if unverified {
                    format!("{} ?", cap_tab_label(t))
                } else {
                    cap_tab_label(t).to_string()
                };
                let mut resp = ui
                    .add(
                        egui::Label::new(
                            egui::RichText::new(label)
                                .font(theme::f_sb(13.5))
                                .color(color),
                        )
                        .sense(egui::Sense::click()),
                    )
                    .on_hover_cursor(egui::CursorIcon::PointingHand);
                if unverified {
                    resp = resp.on_hover_text(
                        "Not verified: no smart-card reader was available to \
                         confirm this feature on the key (reader missing or the \
                         smart-card service is not running). It is offered \
                         anyway — using it gives a definite answer.",
                    );
                }
                if active {
                    let y = resp.rect.bottom() + 6.0;
                    ui.painter().line_segment(
                        [
                            egui::pos2(resp.rect.left(), y),
                            egui::pos2(resp.rect.right(), y),
                        ],
                        egui::Stroke::new(2.0, p.accent),
                    );
                }
                if resp.clicked() {
                    next = Some(t);
                }
            }
        });
        if let Some(t) = next {
            self.cap_tab = t;
        }
    }

    /// A card header row: title · "?" help · right-aligned "Manage →". Returns
    /// true when Manage is clicked (caller switches `cap_tab`).
    fn card_head(
        &mut self,
        ui: &mut egui::Ui,
        p: &Palette,
        title: &str,
        topic: &'static str,
    ) -> bool {
        let mut go = false;
        ui.horizontal(|ui| {
            ui.label(
                egui::RichText::new(title)
                    .font(theme::f_sb(14.5))
                    .color(p.txt),
            );
            ui.add_space(6.0);
            self.help_dot(ui, p, topic);
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                if ui
                    .add(
                        egui::Label::new(
                            egui::RichText::new("Manage \u{2192}")
                                .font(theme::f_sb(12.5))
                                .color(p.accent),
                        )
                        .sense(egui::Sense::click()),
                    )
                    .on_hover_cursor(egui::CursorIcon::PointingHand)
                    .clicked()
                {
                    go = true;
                }
            });
        });
        go
    }

    /// Device-metadata card (FIDO Metadata Service): vendor icon, description,
    /// and certification status for the selected key's AAGUID. Shown only when
    /// the AAGUID is known to the MDS dataset. Renders nothing otherwise so it
    /// doesn't clutter the overview for unknown keys.
    fn mds_card(&mut self, ui: &mut egui::Ui, p: &Palette, _dev: &Device) {
        let Some(aaguid) = self.security_keys.info.as_ref().map(|i| i.aaguid) else {
            return;
        };
        // Look up first; clone the few fields we render so we don't hold an
        // immutable borrow of `self.mds` across the icon-texture mutation.
        let Some(entry) = self.mds.get(&aaguid).cloned() else {
            return;
        };
        let key = ui::aaguid::format_aaguid_pub(&aaguid);
        // Live versions reported by the device's authenticatorGetInfo, preferred
        // over the MDS statement's copy since they describe the actual unit.
        let device_versions: Vec<String> = self
            .security_keys
            .info
            .as_ref()
            .map(|i| i.versions.clone())
            .unwrap_or_default();

        // Decode + upload the icon once per AAGUID, cached in `self.mds_icon`.
        if let Some(icon_uri) = entry.icon.as_deref() {
            let need = self
                .mds_icon
                .as_ref()
                .map(|(k, _)| k != &key)
                .unwrap_or(true);
            if need {
                if let Some(img) = ui::mds::decode_icon(icon_uri) {
                    let tex = ui.ctx().load_texture(
                        format!("mds-icon-{key}"),
                        img,
                        egui::TextureOptions::LINEAR,
                    );
                    self.mds_icon = Some((key.clone(), tex));
                } else {
                    self.mds_icon = None;
                }
            }
        } else {
            self.mds_icon = None;
        }

        theme::card_frame(p).show(ui, |ui| {
            // Claim the full row width so this card matches the capability cards
            // below it (which stretch via their right-aligned "Manage" header).
            ui.set_min_width(ui.available_width());
            self.card_head_plain(ui, p, "Device metadata (FIDO MDS)", "mds");
            ui.add_space(8.0);
            ui.horizontal(|ui| {
                if let Some((k, tex)) = &self.mds_icon {
                    if k == &key {
                        let side = 44.0;
                        ui.add(
                            egui::Image::from_texture(tex)
                                .fit_to_exact_size(egui::vec2(side, side)),
                        );
                        ui.add_space(12.0);
                    }
                }
                ui.vertical(|ui| {
                    if !entry.description.is_empty() {
                        ui.label(
                            egui::RichText::new(&entry.description)
                                .font(theme::f_sb(14.0))
                                .color(p.txt),
                        );
                        ui.add_space(3.0);
                    }
                    // Certification badge (level highlighted) + advisory flag.
                    if let Some(label) = entry.certification_label() {
                        let (fg, bg) = if entry.is_advisory() {
                            (p.err, p.warn_soft())
                        } else {
                            (p.ok, p.ok_soft())
                        };
                        theme::pill(ui, &label, fg, bg);
                    }
                });
            });

            ui.add_space(12.0);

            // Short fields go into a two-column grid (label/value pairs, two
            // pairs per row) so the card fills its width and columns align.
            // Long fields (Versions, AAGUID) get their own full-width rows below.
            let mut pairs: Vec<(&str, String)> = Vec::new();
            if let Some(lvl) = entry.certification_level() {
                pairs.push(("Certification level", lvl.to_string()));
            }
            if let Some(date) = &entry.effective_date {
                let d = date.split(['T', ' ']).next().unwrap_or(date);
                pairs.push(("Certified since", d.to_string()));
            }
            if let Some(fam) = &entry.protocol_family {
                pairs.push(("Protocol family", fam.clone()));
            }

            // Lay the short fields out as tight "label  value" cells distributed
            // across the card width. Pick 1-3 columns based on available width so
            // each value sits right next to its label and the row stays filled.
            let avail = ui.available_width();
            let cols = if avail >= 760.0 {
                3
            } else if avail >= 470.0 {
                2
            } else {
                1
            };
            let cell_w = (avail - 18.0 * (cols as f32 - 1.0)) / cols as f32;
            egui::Grid::new("mds-meta-grid")
                .num_columns(cols)
                .spacing(egui::vec2(18.0, 10.0))
                .min_col_width(0.0)
                .show(ui, |ui| {
                    for (i, (k, v)) in pairs.iter().enumerate() {
                        mds_cell(ui, p, k, v, cell_w);
                        if (i + 1) % cols == 0 {
                            ui.end_row();
                        }
                    }
                    if !pairs.len().is_multiple_of(cols) {
                        ui.end_row();
                    }
                });

            // Long, full-width fields.
            let versions = if !device_versions.is_empty() {
                device_versions
            } else {
                entry.mds_versions.clone()
            };
            ui.add_space(8.0);
            if !versions.is_empty() {
                mds_kv(ui, p, "Versions", &versions.join(", "));
            }
            mds_kv(ui, p, "AAGUID", &key);
        });
        ui.add_space(14.0);
    }

    /// Card header with no "Manage →" affordance (for read-only info cards).
    fn card_head_plain(
        &mut self,
        ui: &mut egui::Ui,
        p: &Palette,
        title: &str,
        topic: &'static str,
    ) {
        ui.horizontal(|ui| {
            ui.label(
                egui::RichText::new(title)
                    .font(theme::f_sb(14.5))
                    .color(p.txt),
            );
            ui.add_space(6.0);
            self.help_dot(ui, p, topic);
        });
    }

    /// Overview tab: one summary card per capability, each with a `Manage →` jump.
    /// Scrolling comes from the shared capability-pane scroller in `central`.
    fn overview(&mut self, ui: &mut egui::Ui, p: &Palette, dev: &Device) {
        ui.vertical(|ui| {
            self.mds_card(ui, p, dev);
            if dev.caps.has(Caps::FIDO2) {
                theme::card_frame(p).show(ui, |ui| {
                    if self.card_head(ui, p, "Passkeys & sign-in (FIDO2)", "fido2") {
                        self.cap_tab = CapTab::Fido2;
                    }
                    ui.add_space(8.0);
                    // Windows non-admin: FIDO access is gated, so `info` never
                    // loads; show an admin-needed hint instead of a perpetual
                    // "Reading key…". The Manage → jump opens the full card.
                    #[cfg(windows)]
                    let non_admin = self.security_keys.info.is_none()
                        && keyroost_winwebauthn::fido_key_present();
                    #[cfg(not(windows))]
                    let non_admin = false;
                    if non_admin {
                        theme::pill(ui, "Administrator rights needed", p.warn, p.warn_soft());
                        ui.add_space(6.0);
                        ui.label(
                            egui::RichText::new(
                                "Open the FIDO2 tab to manage this key via Windows \
                                 settings or restart as administrator.",
                            )
                            .font(theme::f_reg(13.0))
                            .color(p.txt2),
                        );
                    } else {
                        match self
                            .security_keys
                            .info
                            .as_ref()
                            .and_then(|i| i.option("clientPin"))
                        {
                            Some(true) => {
                                ui.horizontal(|ui| {
                                    theme::pill(ui, "PIN set", p.ok, p.ok_soft());
                                    ui.add_space(8.0);
                                    ui.label(
                                        egui::RichText::new(
                                            "PIN configured \u{00B7} ready for passkeys",
                                        )
                                        .font(theme::f_reg(13.0))
                                        .color(p.txt2),
                                    );
                                });
                            }
                            Some(false) => {
                                theme::pill(ui, "No PIN configured", p.warn, p.warn_soft());
                            }
                            None => {
                                ui.label(
                                    egui::RichText::new("Reading key\u{2026}")
                                        .font(theme::f_reg(13.0))
                                        .color(p.txt3),
                                );
                            }
                        }
                    }
                });
                ui.add_space(14.0);
            }
            if dev.caps.has(Caps::OATH) {
                theme::card_frame(p).show(ui, |ui| {
                    if self.card_head(ui, p, "Authenticator codes (OATH)", "oath") {
                        self.cap_tab = CapTab::Oath;
                    }
                    ui.add_space(8.0);
                    if self.oath.loaded && !self.oath.creds.is_empty() {
                        let total = self.oath.creds.len();
                        let mut copy = None;
                        for row in self.oath.creds.iter().take(2) {
                            let is_copied =
                                self.copied.as_ref().is_some_and(|(n, _)| n == &row.name);
                            if let (Some(code), _, _) = oath_row(ui, p, row, is_copied, false) {
                                copy = Some((row.name.clone(), code));
                            }
                            ui.add_space(6.0);
                        }
                        if total > 2 {
                            ui.label(
                                egui::RichText::new(format!("+{} more codes", total - 2))
                                    .font(theme::f_reg(12.5))
                                    .color(p.txt3),
                            );
                        }
                        if let Some((name, code)) = copy {
                            ui.ctx().copy_text(code.clone());
                            self.copied = Some((name, now_secs_f64() + 1.2));
                            self.clipboard_clear_at = Some((code, now_secs_f64() + 45.0));
                        }
                    } else {
                        ui.label(
                            egui::RichText::new("Open Authenticator to view live codes.")
                                .font(theme::f_reg(13.0))
                                .color(p.txt3),
                        );
                    }
                });
                ui.add_space(14.0);
            }
            if dev.caps.has(Caps::PGP) {
                theme::card_frame(p).show(ui, |ui| {
                    if self.card_head(ui, p, "OpenPGP", "pgp") {
                        self.cap_tab = CapTab::Pgp;
                    }
                    ui.add_space(8.0);
                    if let Some(st) = &self.openpgp.status {
                        ui.horizontal_wrapped(|ui| {
                            ui.spacing_mut().item_spacing.x = 5.0;
                            theme::pill(
                                ui,
                                &format!(
                                    "Signature \u{00B7} {}",
                                    slot_summary(&st.sig_attrs, &st.fingerprint_sig)
                                ),
                                p.txt2,
                                p.raised2,
                            );
                            theme::pill(
                                ui,
                                &format!(
                                    "Encryption \u{00B7} {}",
                                    slot_summary(&st.dec_attrs, &st.fingerprint_dec)
                                ),
                                p.txt2,
                                p.raised2,
                            );
                            theme::pill(
                                ui,
                                &format!(
                                    "Auth \u{00B7} {}",
                                    slot_summary(&st.aut_attrs, &st.fingerprint_aut)
                                ),
                                p.txt2,
                                p.raised2,
                            );
                        });
                    } else {
                        ui.label(
                            egui::RichText::new("Open OpenPGP and Read status to view key slots.")
                                .font(theme::f_reg(13.0))
                                .color(p.txt3),
                        );
                    }
                });
                ui.add_space(14.0);
            }
            if dev.caps.has(Caps::PIV) {
                theme::card_frame(p).show(ui, |ui| {
                    if self.card_head(ui, p, "PIV smart card", "piv") {
                        self.cap_tab = CapTab::Piv;
                    }
                    ui.add_space(8.0);
                    if let Some(st) = &self.piv.status {
                        ui.horizontal_wrapped(|ui| {
                            ui.spacing_mut().item_spacing.x = 5.0;
                            for slot in &st.slots {
                                let lab = format!(
                                    "{:02X} \u{00B7} {}",
                                    slot.slot.key_ref(),
                                    if slot.cert_unreadable.is_some() {
                                        "unreadable cert"
                                    } else if slot.cert_present {
                                        "cert"
                                    } else {
                                        match slot.key {
                                            keyroost_transport::SlotKeyPresence::Present => "key",
                                            keyroost_transport::SlotKeyPresence::NoKey => "empty",
                                            // Can't rule a key out.
                                            _ => "no cert",
                                        }
                                    }
                                );
                                theme::pill(ui, &lab, p.txt2, p.raised2);
                            }
                        });
                    } else {
                        ui.label(
                            egui::RichText::new("Open PIV to read certificate slots.")
                                .font(theme::f_reg(13.0))
                                .color(p.txt3),
                        );
                    }
                });
            }
            if dev.caps.has(Caps::OTP) {
                ui.add_space(14.0);
                theme::card_frame(p).show(ui, |ui| {
                    if self.card_head(ui, p, "On-device OTP", "otp") {
                        self.cap_tab = CapTab::Otp;
                    }
                    ui.add_space(8.0);
                    if self.otp.loaded && !self.otp.rows.is_empty() {
                        let total = self.otp.rows.len();
                        for row in self.otp.rows.iter().take(2) {
                            let label = if row.account_name.is_empty() {
                                row.app_name.clone()
                            } else {
                                format!("{} \u{00B7} {}", row.app_name, row.account_name)
                            };
                            ui.horizontal(|ui| {
                                theme::pill(ui, row.type_str, p.txt2, p.raised2);
                                ui.label(
                                    egui::RichText::new(label)
                                        .font(theme::f_reg(13.0))
                                        .color(p.txt2),
                                );
                            });
                            ui.add_space(4.0);
                        }
                        if total > 2 {
                            ui.label(
                                egui::RichText::new(format!("+{} more entries", total - 2))
                                    .font(theme::f_reg(12.5))
                                    .color(p.txt3),
                            );
                        }
                    } else {
                        ui.label(
                            egui::RichText::new("Open On-device OTP to view stored entries.")
                                .font(theme::f_reg(13.0))
                                .color(p.txt3),
                        );
                    }
                });
            }
            // Whole-device factory reset — offered only for a Key (Molto2 keeps
            // its own reset in its pane; a bare ProgToken has no resettable
            // applet, so its plan is empty and no card renders).
            if dev.kind == DeviceKind::Key {
                let plan = keyroost_resolve::factory_reset_plan(dev.caps);
                if !plan.is_empty() {
                    ui.add_space(14.0);
                    let mut arm = false;
                    theme::card_frame(p)
                        .stroke(egui::Stroke::new(1.0, theme::tint(p.err, 90)))
                        .show(ui, |ui| {
                            ui.horizontal(|ui| {
                                ui.label(
                                    egui::RichText::new("Factory reset")
                                        .font(theme::f_sb(14.5))
                                        .color(p.err),
                                );
                                ui.with_layout(
                                    egui::Layout::right_to_left(egui::Align::Center),
                                    |ui| {
                                        if theme::button(
                                            ui,
                                            p,
                                            BtnKind::Danger,
                                            "Factory reset\u{2026}",
                                        )
                                        .clicked()
                                        {
                                            arm = true;
                                        }
                                    },
                                );
                            });
                            ui.label(
                                egui::RichText::new(format!(
                                    "Resets every applet on this key ({}) to factory state. \
                                     Each step reports on its own \u{2014} anything that \
                                     doesn't complete is listed below.",
                                    plan.iter()
                                        .map(|s| s.label())
                                        .collect::<Vec<_>>()
                                        .join(", ")
                                ))
                                .font(theme::f_reg(12.5))
                                .color(p.txt2),
                            );
                            // Live per-step report while a reset runs (or its
                            // outcome afterwards, until the selection changes).
                            if !self.factory_reset_report.is_empty() {
                                ui.add_space(8.0);
                                for row in &self.factory_reset_report {
                                    let (text, tone) = factory_reset_row_line(row);
                                    let color = match tone {
                                        RowTone::Done => p.ok,
                                        RowTone::Waiting | RowTone::Warn => p.warn,
                                        RowTone::Bad => p.err,
                                        RowTone::Muted => p.txt3,
                                    };
                                    ui.label(
                                        egui::RichText::new(text)
                                            .font(theme::f_reg(12.5))
                                            .color(color),
                                    );
                                }
                            }
                        });
                    if arm {
                        self.start_factory_reset_confirm();
                    }
                }
            }
        });
    }

    /// FIDO2 / Passkeys tab — reuses the existing PIN + credentials section.
    /// Windows non-admin FIDO2 card: explain the admin requirement and offer to
    /// open Windows' security-key settings (PIN / reset / biometrics work there
    /// without elevation) or restart keyroost as administrator for full
    /// management here. Only built on Windows; the helper is inert elsewhere.
    #[cfg(windows)]
    fn fido2_non_admin_card(&mut self, ui: &mut egui::Ui, p: &Palette) {
        theme::card_frame(p).show(ui, |ui| {
            ui.label(
                egui::RichText::new("Administrator rights needed")
                    .font(theme::f_sb(14.5))
                    .color(p.txt),
            );
            ui.add_space(8.0);
            ui.label(
                egui::RichText::new(
                    "A security key is connected, but managing its FIDO2 settings \
                     (PIN, passkeys, reset, fingerprints) in this app requires \
                     administrator rights on Windows.",
                )
                .font(theme::f_reg(13.0))
                .color(p.txt2),
            );
            ui.add_space(4.0);
            ui.label(
                egui::RichText::new(
                    "Change the PIN, manage biometrics or reset the key without \
                     admin rights using Windows' built-in security-key settings, \
                     or restart this app as administrator for full management here.",
                )
                .font(theme::f_reg(13.0))
                .color(p.txt2),
            );
            ui.add_space(12.0);
            ui.horizontal(|ui| {
                if theme::button(
                    ui,
                    p,
                    BtnKind::Primary,
                    "Open Windows security-key settings",
                )
                .clicked()
                {
                    if let Err(e) = keyroost_winwebauthn::open_windows_security_key_settings() {
                        self.security_keys.error =
                            Some(format!("Couldn't open Windows security-key settings: {e}"));
                    }
                }
                if theme::button(ui, p, BtnKind::Default, "Restart as administrator").clicked() {
                    match keyroost_winwebauthn::relaunch_as_admin() {
                        // Elevated instance requested: exit this non-elevated one
                        // so only the admin process remains.
                        Ok(()) => std::process::exit(0),
                        Err(e) => {
                            self.security_keys.error =
                                Some(format!("Couldn't restart as administrator: {e}"));
                        }
                    }
                }
            });
        });
    }

    fn cap_fido2(&mut self, ui: &mut egui::Ui, p: &Palette) {
        // Non-admin Windows: if a FIDO key is present but we have no working FIDO
        // access (the HID interface is gated), show the admin-needed card with a
        // link to Windows' settings and an elevate button, instead of the normal
        // — and here non-functional — management UI.
        #[cfg(windows)]
        {
            let no_access = self.security_keys.info.is_none();
            if no_access && keyroost_winwebauthn::fido_key_present() {
                self.fido2_non_admin_card(ui, p);
                return;
            }
        }

        let pin = pin_support(self.security_keys.info.as_ref());

        // --- PIN & sign-in card (inline Set / Change PIN; no floating modal) ---
        let mut go_set = false;
        let mut go_change = false;
        let mut cancel = false;
        theme::card_frame(p).show(ui, |ui| {
            ui.horizontal(|ui| {
                ui.label(
                    egui::RichText::new("PIN & sign-in")
                        .font(theme::f_sb(14.5))
                        .color(p.txt),
                );
                ui.add_space(6.0);
                self.help_dot(ui, p, "pin");
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    let (kind, label) = match pin {
                        PinSupport::Set => (BtnKind::Default, "Change PIN"),
                        PinSupport::NotSet => (BtnKind::Primary, "Set a PIN"),
                        // Unknown (still reading) or no PIN feature at all:
                        // nothing to offer.
                        PinSupport::Unknown | PinSupport::Unsupported => return,
                    };
                    if theme::button(ui, p, kind, label).clicked() {
                        let open = !self.security_keys.change_pin.open;
                        // Replacing the dialog drops the old one, whose Drop
                        // zeroizes any typed PINs; then restore the toggle state.
                        self.security_keys.change_pin = ChangePinDialog::default();
                        self.security_keys.change_pin.open = open;
                        self.security_keys.error = None;
                    }
                    // Lock the whole session here, where the lock/unlock state
                    // lives — locking ends access to passkeys, fingerprints and
                    // settings alike, so it doesn't belong inside one panel.
                    if self.security_keys.session.is_some() {
                        ui.add_space(6.0);
                        if theme::button(ui, p, BtnKind::Ghost, "Lock").clicked() {
                            self.lock_session();
                        }
                    }
                });
            });
            ui.add_space(8.0);
            match pin {
                PinSupport::Set => {
                    ui.horizontal(|ui| {
                        theme::pill(ui, "PIN set", p.ok, p.ok_soft());
                        ui.add_space(8.0);
                        // Reflect whether the key is already unlocked: once a
                        // session is open, the "unlock below" prompt is stale.
                        let hint = if self.security_keys.session.is_some() {
                            "This key has a PIN."
                        } else {
                            "This key has a PIN. Unlock below to manage it."
                        };
                        ui.label(
                            egui::RichText::new(hint)
                                .font(theme::f_reg(13.0))
                                .color(p.txt2),
                        );
                    });
                }
                PinSupport::NotSet => {
                    ui.horizontal(|ui| {
                        theme::pill(ui, "No PIN yet", p.warn, p.warn_soft());
                        ui.add_space(8.0);
                        ui.label(
                            egui::RichText::new(
                                "Set a PIN to protect this key and turn on passkeys.",
                            )
                            .font(theme::f_reg(13.0))
                            .color(p.txt2),
                        );
                    });
                }
                PinSupport::Unsupported => {
                    // getInfo answered and clientPin isn't in the options map:
                    // the key has no PIN feature. Say so — this state used to
                    // fall into the None arm below and read "Reading key…"
                    // forever.
                    ui.horizontal(|ui| {
                        theme::pill(ui, "No PIN support", p.txt2, p.raised2);
                        ui.add_space(8.0);
                        ui.label(
                            egui::RichText::new("This key does not support a PIN.")
                                .font(theme::f_reg(13.0))
                                .color(p.txt2),
                        );
                    });
                }
                PinSupport::Unknown => {
                    let msg = if self.security_keys.error.is_some() {
                        "Couldn't read this key."
                    } else {
                        // The initial read can be dropped if the worker was
                        // busy at selection time; retry rather than showing
                        // "Reading key…" forever.
                        if self.security_keys.info.is_none() && !self.busy() {
                            self.fetch_selected_info();
                        }
                        "Reading key\u{2026}"
                    };
                    ui.label(
                        egui::RichText::new(msg)
                            .font(theme::f_reg(13.0))
                            .color(p.txt3),
                    );
                }
            }

            if self.security_keys.change_pin.open {
                let setting = pin == PinSupport::NotSet;
                ui.add_space(10.0);
                egui::Frame::NONE
                    .fill(p.raised)
                    .inner_margin(egui::Margin::same(12))
                    .corner_radius(egui::CornerRadius::same(8))
                    .show(ui, |ui| {
                        ui.label(
                            egui::RichText::new(if setting {
                                "Create a PIN"
                            } else {
                                "Change PIN"
                            })
                            .font(theme::f_sb(13.0))
                            .color(p.txt),
                        );
                        ui.add_space(8.0);
                        if setting {
                            pin_field(ui, p, "New PIN", &mut self.security_keys.change_pin.new);
                            pin_field(ui, p, "Confirm", &mut self.security_keys.change_pin.confirm);
                        } else {
                            pin_field(ui, p, "Current PIN", &mut self.security_keys.change_pin.old);
                            pin_field(ui, p, "New PIN", &mut self.security_keys.change_pin.new);
                            pin_field(
                                ui,
                                p,
                                "Confirm new PIN",
                                &mut self.security_keys.change_pin.confirm,
                            );
                        }
                        ui.add_space(8.0);
                        ui.horizontal(|ui| {
                            if theme::button(
                                ui,
                                p,
                                BtnKind::Primary,
                                if setting { "Set PIN" } else { "Change PIN" },
                            )
                            .clicked()
                            {
                                if setting {
                                    go_set = true;
                                } else {
                                    go_change = true;
                                }
                            }
                            ui.add_space(6.0);
                            if theme::button(ui, p, BtnKind::Ghost, "Cancel").clicked() {
                                cancel = true;
                            }
                        });
                        ui.add_space(4.0);
                        ui.label(
                            egui::RichText::new("4\u{2013}63 characters.")
                                .font(theme::f_reg(11.5))
                                .color(p.txt3),
                        );
                    });
            }

            if let Some(err) = &self.security_keys.error {
                ui.add_space(6.0);
                ui.colored_label(p.err, err);
            }
        });
        if cancel {
            self.security_keys.change_pin = ChangePinDialog::default();
        }
        if go_set {
            self.submit_set_pin();
        }
        if go_change {
            self.submit_change_pin();
        }

        let unlocked = self.security_keys.session.is_some();
        let has_bio = self.bio_cmd_code().is_some();
        let supports_cfg = self
            .security_keys
            .info
            .as_ref()
            .and_then(|i| i.option("authnrCfg"))
            == Some(true);
        // The Settings tab itself is broader than the advanced controls: any
        // CTAP2 key can be reset (#81), so the tab shows whenever the key is
        // CTAP2 and only the authenticatorConfig section inside is cfg-gated.
        let settings_available = fido_settings_available(self.security_keys.info.as_ref());
        // Same option pair CredMgmt::new consults: the standard command, or
        // the pre-2.1 preview many CTAP 2.0 keys ship.
        let has_cred_mgmt = self.security_keys.info.as_ref().is_some_and(|i| {
            i.option("credMgmt") == Some(true) || i.option("credentialMgmtPreview") == Some(true)
        });
        let has_large_blobs = self
            .security_keys
            .info
            .as_ref()
            .and_then(|i| i.option("largeBlobs"))
            == Some(true);

        // When the key has a PIN but isn't unlocked yet, show a standalone
        // unlock card. Unlocking gates passkeys, fingerprints, and settings
        // alike, so it lives above the tabs rather than inside the Passkeys tab.
        if pin == PinSupport::Set && !unlocked {
            ui.add_space(14.0);
            let mut unlock = false;
            theme::card_frame(p).show(ui, |ui| {
                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new("Unlock this key")
                            .font(theme::f_sb(14.5))
                            .color(p.txt),
                    );
                    ui.add_space(6.0);
                    self.help_dot(ui, p, "unlock");
                });
                ui.add_space(8.0);
                ui.horizontal(|ui| {
                    let resp = ui.add_sized(
                        [220.0, 32.0],
                        egui::TextEdit::singleline(&mut self.security_keys.pin_input)
                            .vertical_align(egui::Align::Center)
                            .password(true)
                            .hint_text("Enter PIN to unlock this key"),
                    );
                    guard_secret_field(ui.ctx(), &resp);
                    let submit = theme::button(ui, p, BtnKind::Primary, "Unlock").clicked();
                    if submit
                        || (resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)))
                    {
                        unlock = true;
                    }
                });
                let extras = match (has_bio, settings_available) {
                    (true, true) => "passkeys, fingerprints, and settings",
                    (true, false) => "passkeys and fingerprints",
                    (false, true) => "passkeys and settings",
                    (false, false) => "passkeys",
                };
                ui.add_space(4.0);
                ui.label(
                    egui::RichText::new(format!("Unlock to manage {extras}."))
                        .font(theme::f_reg(11.5))
                        .color(p.txt3),
                );
            });
            if unlock {
                self.try_unlock();
            }

            // Read-only "Security policy" summary. getInfo is unauthenticated,
            // so the policy STATE is known without a PIN. Shown only on keys
            // that support authenticatorConfig (the same gate as the Settings
            // tab); the controls themselves still live in that tab post-unlock.
            if supports_cfg {
                let info = self.security_keys.info.as_ref();
                let always_uv = info.and_then(|i| i.option("alwaysUv"));
                let min_pin = info.and_then(|i| i.min_pin_length);
                let force_change = info.and_then(|i| i.force_pin_change);
                let ep = info.and_then(|i| i.option("ep"));

                ui.add_space(14.0);
                theme::card_frame(p).show(ui, |ui| {
                    ui.label(
                        egui::RichText::new("Security policy")
                            .font(theme::f_sb(14.5))
                            .color(p.txt),
                    );
                    ui.add_space(8.0);

                    let row = |ui: &mut egui::Ui, label: &str, value: String| {
                        ui.horizontal(|ui| {
                            ui.label(
                                egui::RichText::new(label)
                                    .font(theme::f_reg(12.0))
                                    .color(p.txt3),
                            );
                            ui.with_layout(
                                egui::Layout::right_to_left(egui::Align::Center),
                                |ui| {
                                    ui.label(
                                        egui::RichText::new(value)
                                            .font(theme::f_sb(12.0))
                                            .color(p.txt),
                                    );
                                },
                            );
                        });
                    };

                    row(
                        ui,
                        "Always require user verification",
                        match always_uv {
                            Some(true) => "On".to_string(),
                            Some(false) => "Off".to_string(),
                            None => "\u{2014}".to_string(),
                        },
                    );
                    ui.add_space(4.0);
                    row(
                        ui,
                        "Minimum PIN length",
                        match min_pin {
                            Some(n) => n.to_string(),
                            None => "\u{2014}".to_string(),
                        },
                    );
                    if force_change == Some(true) {
                        ui.add_space(4.0);
                        row(ui, "Force PIN change", "Required on next use".to_string());
                    }
                    if let Some(ep) = ep {
                        ui.add_space(4.0);
                        row(
                            ui,
                            "Enterprise attestation",
                            if ep { "Enabled" } else { "Supported" }.to_string(),
                        );
                    }

                    ui.add_space(8.0);
                    ui.label(
                        egui::RichText::new("Unlock to change these.")
                            .font(theme::f_reg(11.5))
                            .color(p.txt3),
                    );
                });
            }
        }

        // Reset must stay reachable without the PIN: when the key is CTAP2
        // but can't be unlocked (PIN forgotten/blocked, not set, or clientPin
        // unsupported), render the Reset card standalone here — once
        // unlocked, the Settings tab below owns it instead.
        if show_standalone_reset(unlocked, self.security_keys.info.as_ref()) {
            ui.add_space(14.0);
            self.render_fido_reset_card(ui, p);
        }

        // Once unlocked, the sub-view tabs sit at the top of the content, each
        // owning its own panel below. Styled like the main capability tabs:
        // bold label with an accent underline on the active one.
        if unlocked {
            let mut tabs: Vec<(FidoSubview, &str)> = Vec::new();
            // Passkey management is its own capability (credMgmt, or the
            // pre-2.1 preview) — a CTAP2 key without it gets no Passkeys tab
            // rather than a tab whose only content errors at runtime.
            if has_cred_mgmt {
                tabs.push((FidoSubview::Passkeys, "Passkeys"));
            }
            if has_bio {
                tabs.push((FidoSubview::Fingerprints, "Fingerprints"));
            }
            if settings_available {
                tabs.push((FidoSubview::Settings, "Settings"));
            }
            if has_large_blobs {
                tabs.push((FidoSubview::LargeBlobs, "Storage"));
            }
            // The persisted pick can be stale (it outlives selection changes,
            // and the newly selected key may not offer the old tab): snap it
            // to a tab this key actually has before painting the strip.
            self.security_keys.subview = snap_subview(self.security_keys.subview, &tabs);
            ui.add_space(14.0);
            let mut next: Option<FidoSubview> = None;
            // Paint an opaque surface strip here first (full content width,
            // fixed height covering the label row + its underline) so the row has
            // a clean backing - drawn before the labels, so it sits under them.
            {
                let top = ui.cursor().top();
                let strip = egui::Rect::from_min_max(
                    egui::pos2(ui.max_rect().left(), top - 4.0),
                    egui::pos2(ui.max_rect().right(), top + 30.0),
                );
                ui.painter().rect_filled(strip, 0.0, p.surface);
            }
            ui.horizontal(|ui| {
                ui.spacing_mut().item_spacing.x = 20.0;
                for (view, label) in &tabs {
                    let active = self.security_keys.subview == *view;
                    let color = if active { p.txt } else { p.txt3 };
                    let resp = ui
                        .add(
                            egui::Label::new(
                                egui::RichText::new(*label)
                                    .font(theme::f_sb(13.5))
                                    .color(color),
                            )
                            .sense(egui::Sense::click()),
                        )
                        .on_hover_cursor(egui::CursorIcon::PointingHand);
                    if active {
                        let y = resp.rect.bottom() + 6.0;
                        ui.painter().line_segment(
                            [
                                egui::pos2(resp.rect.left(), y),
                                egui::pos2(resp.rect.right(), y),
                            ],
                            egui::Stroke::new(2.0, p.accent),
                        );
                    }
                    if resp.clicked() {
                        next = Some(*view);
                    }
                }
            });
            if let Some(v) = next {
                self.security_keys.subview = v;
            }
        } else {
            self.security_keys.subview = FidoSubview::Passkeys;
        }
        let subview = self.security_keys.subview;

        // --- Passkeys panel: only when unlocked and the Passkeys tab is active. ---
        if unlocked && subview == FidoSubview::Passkeys {
            ui.add_space(14.0);
            let mut reload = false;
            let mut delete: Option<Vec<u8>> = None;
            // Collected in the credential loop (below), applied after the card so
            // the extract job isn't dispatched while `self` is borrowed by the
            // cloned rps list: (rp id, credential's largeBlob key).
            // The largeBlob key is key material: carry it zeroizing from the
            // moment it leaves the credential listing.
            let mut save_cert: Option<(String, zeroize::Zeroizing<[u8; 32]>)> = None;
            theme::card_frame(p).show(ui, |ui| {
                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new("Resident passkeys")
                            .font(theme::f_sb(14.5))
                            .color(p.txt),
                    );
                    ui.add_space(6.0);
                    self.help_dot(ui, p, "passkeys");
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if theme::button(ui, p, BtnKind::Default, "Reload").clicked() {
                            reload = true;
                        }
                    });
                });
                ui.add_space(8.0);
                let session_info = self.security_keys.session.as_ref().map(|s| {
                    (
                        s.metadata.existing_count,
                        s.metadata.max_remaining,
                        s.rps.clone(),
                    )
                });
                if let Some((existing, max_remaining, rps)) = session_info {
                    ui.label(
                        egui::RichText::new(format!(
                            "{existing} stored \u{00B7} room for {max_remaining} more"
                        ))
                        .font(theme::f_reg(12.5))
                        .color(p.txt2),
                    );
                    ui.add_space(6.0);
                    if rps.is_empty() {
                        ui.label(
                            egui::RichText::new("No passkeys stored on this key yet.")
                                .font(theme::f_reg(13.0))
                                .color(p.txt3),
                        );
                    }
                    // No inner scroller: the shared capability-pane scroller in
                    // `central` handles overflow, so a long passkey list flows
                    // down the page instead of trapping the wheel in a box.
                    ui.vertical(|ui| {
                        for (rp, creds) in rps.iter() {
                            let header =
                                if let Some(name) = rp.name.as_ref().filter(|s| !s.is_empty()) {
                                    format!("{}  ({})", rp.id, name)
                                } else {
                                    rp.id.clone()
                                };
                            ui.collapsing(header, |ui| {
                                if creds.is_empty() {
                                    ui.label("(no credentials)");
                                }
                                for c in creds {
                                    // Right-to-left so the Remove button claims its
                                    // space first; the identity column then fills the
                                    // remaining width and wraps within it (long hex
                                    // IDs no longer run under the button).
                                    ui.with_layout(
                                        egui::Layout::right_to_left(egui::Align::Min),
                                        |ui| {
                                            if theme::button(ui, p, BtnKind::Ghost, "Remove")
                                                .clicked()
                                            {
                                                delete = Some(c.credential_id.clone());
                                            }
                                            // SSH credentials that carry a largeBlob
                                            // key can hold an OpenSSH certificate;
                                            // offer to extract + save it. Extraction
                                            // is device I/O + decrypt, so it runs as a
                                            // background job (see `save_ssh_cert`).
                                            if ssh_cred_offers_cert(
                                                &rp.id,
                                                c.large_blob_key.as_ref(),
                                            ) {
                                                ui.add_space(6.0);
                                                if theme::button(
                                                    ui,
                                                    p,
                                                    BtnKind::Ghost,
                                                    "Save certificate\u{2026}",
                                                )
                                                .clicked()
                                                {
                                                    if let Some(key) = c.large_blob_key {
                                                        save_cert = Some((
                                                            rp.id.clone(),
                                                            zeroize::Zeroizing::new(key),
                                                        ));
                                                    }
                                                }
                                            }
                                            ui.add_space(8.0);
                                            ui.vertical(|ui| {
                                                // Distinct identity fields, like the
                                                // authenticator's credential details:
                                                // User Name (UPN), Display Name, User
                                                // ID, Credential ID.
                                                let row = |ui: &mut egui::Ui,
                                                           label: &str,
                                                           val: String,
                                                           mono: bool| {
                                                    if val.is_empty() {
                                                        return;
                                                    }
                                                    ui.horizontal_wrapped(|ui| {
                                                        ui.spacing_mut().item_spacing.x = 6.0;
                                                        ui.label(
                                                            egui::RichText::new(label)
                                                                .font(theme::f_sb(11.5))
                                                                .color(p.txt3),
                                                        );
                                                        let font = if mono {
                                                            theme::f_mono(11.5)
                                                        } else {
                                                            theme::f_reg(12.0)
                                                        };
                                                        ui.label(
                                                            egui::RichText::new(val)
                                                                .font(font)
                                                                .color(p.txt2),
                                                        );
                                                    });
                                                };
                                                row(
                                                    ui,
                                                    "User Name",
                                                    c.user.name.clone().unwrap_or_default(),
                                                    false,
                                                );
                                                row(
                                                    ui,
                                                    "Display Name",
                                                    c.user.display_name.clone().unwrap_or_default(),
                                                    false,
                                                );
                                                // User ID: text if printable ASCII,
                                                // else hex (often a random blob).
                                                let uid = if c.user.id.is_empty() {
                                                    String::new()
                                                } else if c
                                                    .user
                                                    .id
                                                    .iter()
                                                    .all(|b| b.is_ascii_graphic() || *b == b' ')
                                                {
                                                    String::from_utf8_lossy(&c.user.id).into_owned()
                                                } else {
                                                    hex_full(&c.user.id)
                                                };
                                                row(ui, "User ID", uid, true);
                                                row(
                                                    ui,
                                                    "Credential ID",
                                                    hex_full(&c.credential_id),
                                                    true,
                                                );
                                            });
                                        },
                                    );
                                    ui.separator();
                                }
                            });
                        }
                    });
                }
            });
            if reload {
                self.refresh_credentials();
            }
            if let Some(id) = delete {
                self.delete_credential(id);
            }
            if let Some((rp_id, key)) = save_cert {
                self.save_ssh_cert(rp_id, key);
            }
            // Result of the last "Save certificate…" (extraction error, or the
            // saved path plus the parsed cert summary).
            if let Some(status) = self.security_keys.ssh_cert_status.clone() {
                ui.add_space(8.0);
                theme::card_frame(p).show(ui, |ui| {
                    for line in status.lines() {
                        ui.label(
                            egui::RichText::new(line)
                                .font(theme::f_reg(12.5))
                                .color(p.txt2),
                        );
                    }
                });
            }
        }

        // --- Fingerprint management (only when unlocked and the key supports it) ---
        if subview == FidoSubview::Fingerprints
            && self.security_keys.session.is_some()
            && self.bio_cmd_code().is_some()
        {
            ui.add_space(14.0);
            let mut do_enroll = false;
            let mut do_refresh_fp = false;
            let mut fp_rename_commit: Option<(Vec<u8>, String)> = None;
            theme::card_frame(p).show(ui, |ui| {
                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new("Fingerprints")
                            .font(theme::f_sb(14.5))
                            .color(p.txt),
                    );
                    ui.add_space(6.0);
                    self.help_dot(ui, p, "fingerprint");
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if theme::button(ui, p, BtnKind::Default, "Reload").clicked() {
                            do_refresh_fp = true;
                        }
                    });
                });
                ui.add_space(8.0);

                // Enroll wizard now renders as a centered modal overlay
                // (render_enroll_dialog, called from the top-level render). Keep
                // the flag so the list below is hidden while a capture runs.
                let enrolling = self.security_keys.fp_progress.is_some();

                // The list (None until first read). Hidden while the wizard runs.
                if !enrolling {
                    match &self.security_keys.fingerprints {
                        None => {
                            ui.label(
                                egui::RichText::new("Click Reload to read enrolled fingerprints.")
                                    .font(theme::f_reg(13.0))
                                    .color(p.txt3),
                            );
                        }
                        Some(list) if list.is_empty() => {
                            ui.label(
                                egui::RichText::new("No fingerprints enrolled yet.")
                                    .font(theme::f_reg(13.0))
                                    .color(p.txt3),
                            );
                        }
                        Some(list) => {
                            for e in list.iter() {
                                let id = e.template_id.clone();
                                ui.horizontal(|ui| {
                                    ui.monospace(hex_short(&id));
                                    // Inline rename editor for this row, or the name + buttons.
                                    let renaming = self
                                        .security_keys
                                        .fp_rename
                                        .as_ref()
                                        .is_some_and(|(rid, _)| rid == &id);
                                    if renaming {
                                        if let Some((_, buf)) =
                                            self.security_keys.fp_rename.as_mut()
                                        {
                                            ui.add_sized(
                                                [160.0, 32.0],
                                                egui::TextEdit::singleline(buf)
                                                    .vertical_align(egui::Align::Center),
                                            );
                                        }
                                        if theme::button(ui, p, BtnKind::Primary, "Save").clicked()
                                        {
                                            if let Some((rid, buf)) =
                                                self.security_keys.fp_rename.take()
                                            {
                                                fp_rename_commit = Some((rid, buf));
                                            }
                                        }
                                        if theme::button(ui, p, BtnKind::Ghost, "Cancel").clicked()
                                        {
                                            self.security_keys.fp_rename = None;
                                        }
                                    } else {
                                        let name =
                                            e.friendly_name.as_deref().unwrap_or("(unnamed)");
                                        ui.label(name);
                                        ui.with_layout(
                                            egui::Layout::right_to_left(egui::Align::Center),
                                            |ui| {
                                                if theme::button(ui, p, BtnKind::Ghost, "Delete")
                                                    .clicked()
                                                {
                                                    self.security_keys.fp_confirm_delete =
                                                        Some(id.clone());
                                                }
                                                if theme::button(ui, p, BtnKind::Ghost, "Rename")
                                                    .clicked()
                                                {
                                                    self.security_keys.fp_rename = Some((
                                                        id.clone(),
                                                        e.friendly_name.clone().unwrap_or_default(),
                                                    ));
                                                }
                                            },
                                        );
                                    }
                                });
                            }
                        }
                    }
                }

                ui.add_space(10.0);
                // Enroll a new fingerprint (hidden while a wizard is running).
                if !enrolling {
                    ui.horizontal(|ui| {
                        ui.add_sized(
                            [160.0, 32.0],
                            egui::TextEdit::singleline(&mut self.security_keys.fp_new_name)
                                .vertical_align(egui::Align::Center)
                                .hint_text("name (optional)"),
                        );
                        if theme::button(ui, p, BtnKind::Primary, "Enroll new\u{2026}").clicked() {
                            do_enroll = true;
                        }
                    });
                    ui.label(
                        egui::RichText::new(
                            "Enrolling asks you to touch the sensor several times. \
                             Keyboard-HID is not needed; this uses the FIDO interface.",
                        )
                        .font(theme::f_reg(11.0))
                        .color(p.txt3),
                    );
                }

                // --- Delete confirmation ("Are you sure?") ---
            });
            if do_refresh_fp {
                self.refresh_fingerprints();
            }
            if do_enroll {
                self.enroll_fingerprint();
            }
            if let Some((id, name)) = fp_rename_commit {
                self.rename_fingerprint(id, name);
            }
        }

        // --- Settings sub-view: advanced config + the danger reset card. ---
        if subview == FidoSubview::Settings {
            // Advanced (authenticatorConfig) security-policy controls — only
            // on keys that speak authenticatorConfig (CTAP 2.1). The Reset
            // card below renders unconditionally: authenticatorReset is
            // baseline CTAP2, and it must stay reachable on 2.0-only keys (#81).
            if supports_cfg {
                self.render_fido_advanced(ui, p);
            }

            ui.add_space(14.0);
            self.render_fido_reset_card(ui, p);
        }

        if subview == FidoSubview::LargeBlobs {
            self.render_large_blobs(ui, p);
        }
    }

    /// The destructive "Reset this key" card (red stroke; arms the
    /// typed-confirm ResetDialog, rendered app-level). Shown inside the
    /// Settings subview when unlocked, and standalone when the key can't be
    /// unlocked — authenticatorReset needs no PIN and is the recovery path
    /// for a forgotten/blocked one, so it must never hide behind unlock
    /// (see [`show_standalone_reset`]).
    fn render_fido_reset_card(&mut self, ui: &mut egui::Ui, p: &Palette) {
        let mut arm_reset = false;
        theme::card_frame(p)
            .stroke(egui::Stroke::new(1.0, theme::tint(p.err, 90)))
            .show(ui, |ui| {
                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new("Reset this key")
                            .font(theme::f_sb(14.5))
                            .color(p.err),
                    );
                    ui.add_space(6.0);
                    self.help_dot(ui, p, "reset");
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if theme::button(ui, p, BtnKind::Danger, "Reset key\u{2026}").clicked() {
                            arm_reset = true;
                        }
                    });
                });
                ui.label(
                    egui::RichText::new(
                        "Wipes every passkey and the PIN on this key. Cannot be undone.",
                    )
                    .font(theme::f_reg(12.5))
                    .color(p.txt2),
                );
            });
        if arm_reset {
            self.security_keys.reset = ResetDialog {
                open: true,
                ..Default::default()
            };
        }
    }

    /// Append a keyroost text note to the array and write it back. Needs the
    /// unlocked session's PIN (the write path requires a Large-Blob-Write token).
    fn add_large_blob_note(&mut self, text: String) {
        let Some(target) = self.selected_fido_target() else {
            self.security_keys.lb_status = Some("No FIDO key selected.".into());
            return;
        };
        let Some(session) = self.fido_session() else {
            self.security_keys.lb_status =
                Some("Unlock the key with your PIN first to add data.".into());
            return;
        };
        let pin = session.pin.clone();
        // Start from the currently-loaded array if we have one, else an empty
        // array (read fresh inside the worker to avoid clobbering RP entries we
        // never loaded).
        let loaded = self.security_keys.large_blobs.clone();

        let for_device = self.selected_device.clone();
        self.spawn_job("Saving to large blobs\u{2026}", move || {
            let result = (|| -> Result<
                (
                    keyroost_ctap::large_blobs::LargeBlobArray,
                    keyroost_ctap::large_blobs::BlobCapacity,
                ),
                String,
            > {
                let (mut dev, cbor, _init) = open_fido(&target)?;
                if !cbor {
                    return Err("device is U2F-only".into());
                }
                let info = keyroost_ctap::get_info(&mut dev).map_err(|e| e.to_string())?;

                // Always re-read immediately before writing so we append onto the
                // authenticator's current array (not a stale cached copy), which
                // protects any RP entries written since our last load.
                let current =
                    keyroost_ctap::large_blobs::read(&mut dev, &info).map_err(|e| e.to_string())?;
                let _ = loaded; // cached copy only informs the UI, not the write

                // Plan before unlocking, so a certain refusal costs no PIN try.
                let updated = current.with_text_note(&text);
                let serialized = updated
                    .serialize_with_checksum()
                    .map_err(|e| e.to_string())?;
                let token = large_blob_write_token(&mut dev, &info, &pin, &current)?;
                // Names read from keys before or during the write are stale.
                keyroost_resolve::with_key_names_forgotten(|| {
                    keyroost_ctap::large_blobs::write(&mut dev, &info, &token, &serialized)
                })
                    .map_err(|e| e.to_string())?;

                let array =
                    keyroost_ctap::large_blobs::read(&mut dev, &info).map_err(|e| e.to_string())?;
                let cap = array.capacity(&info);
                Ok((array, cap))
            })();

            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return; // selection changed mid-op; discard the stale completion
                }
                match result {
                    Ok((array, cap)) => {
                        let n = array.len();
                        app.security_keys.large_blobs = Some(array);
                        app.security_keys.lb_capacity = Some(cap);
                        app.security_keys.lb_new_text.clear();
                        app.security_keys.lb_show_add = false;
                        app.security_keys.lb_status = Some(format!(
                            "Saved. {n} entr{} total.",
                            if n == 1 { "y" } else { "ies" }
                        ));
                        app.security_keys.error = None;
                    }
                    Err(e) => {
                        app.security_keys.lb_status = Some(format!("Save failed: {e}"));
                    }
                }
            })
        });
    }

    /// Replace the keyroost note at `idx` with `text` and write the array back.
    /// Refuses if the entry is not a keyroost note. Needs the session PIN.
    fn edit_large_blob_note(&mut self, idx: usize, text: String) {
        let Some(target) = self.selected_fido_target() else {
            self.security_keys.lb_status = Some("No FIDO key selected.".into());
            return;
        };
        let Some(session) = self.fido_session() else {
            self.security_keys.lb_status =
                Some("Unlock the key with your PIN first to edit notes.".into());
            return;
        };
        let pin = session.pin.clone();

        let for_device = self.selected_device.clone();
        self.spawn_job("Saving edit to large blobs\u{2026}", move || {
            let result = (|| -> Result<
                (
                    keyroost_ctap::large_blobs::LargeBlobArray,
                    keyroost_ctap::large_blobs::BlobCapacity,
                ),
                String,
            > {
                let (mut dev, cbor, _init) = open_fido(&target)?;
                if !cbor {
                    return Err("device is U2F-only".into());
                }
                let info = keyroost_ctap::get_info(&mut dev).map_err(|e| e.to_string())?;

                // Re-read live so we edit the authenticator's current array and
                // never clobber RP entries written since our last load.
                let current =
                    keyroost_ctap::large_blobs::read(&mut dev, &info).map_err(|e| e.to_string())?;
                let updated = current.with_replaced_note(idx, &text).ok_or(
                    "that entry is not an editable keyroost note (it may have \
                            changed on the key — reload and try again)",
                )?;
                // Plan before unlocking, so a certain refusal costs no PIN try.
                let serialized = updated
                    .serialize_with_checksum()
                    .map_err(|e| e.to_string())?;
                let token = large_blob_write_token(&mut dev, &info, &pin, &current)?;
                // Names read from keys before or during the write are stale.
                keyroost_resolve::with_key_names_forgotten(|| {
                    keyroost_ctap::large_blobs::write(&mut dev, &info, &token, &serialized)
                })
                    .map_err(|e| e.to_string())?;

                let array =
                    keyroost_ctap::large_blobs::read(&mut dev, &info).map_err(|e| e.to_string())?;
                let cap = array.capacity(&info);
                Ok((array, cap))
            })();

            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return; // selection changed mid-op; discard the stale completion
                }
                match result {
                    Ok((array, cap)) => {
                        app.security_keys.large_blobs = Some(array);
                        app.security_keys.lb_capacity = Some(cap);
                        app.security_keys.lb_editing = None;
                        app.security_keys.lb_edit_text.clear();
                        app.security_keys.lb_status = Some("Note updated.".into());
                        app.security_keys.error = None;
                    }
                    Err(e) => {
                        app.security_keys.lb_status = Some(format!("Edit failed: {e}"));
                    }
                }
            })
        });
    }

    /// Read the large-blob array from the selected key (no PIN required) and
    /// cache it. Runs synchronously — a read is one or two small fragments.
    fn load_large_blobs(&mut self) {
        let Some(target) = self.selected_fido_target() else {
            self.security_keys.lb_status = Some("No FIDO key selected.".into());
            return;
        };
        let result = (|| -> Result<
            (
                keyroost_ctap::large_blobs::LargeBlobArray,
                keyroost_ctap::large_blobs::BlobCapacity,
            ),
            String,
        > {
            let (mut dev, cbor, _init) = open_fido(&target)?;
            if !cbor {
                return Err("device is U2F-only".into());
            }
            let info = keyroost_ctap::get_info(&mut dev).map_err(|e| e.to_string())?;
            let array =
                keyroost_ctap::large_blobs::read(&mut dev, &info).map_err(|e| e.to_string())?;
            let cap = array.capacity(&info);
            Ok((array, cap))
        })();
        match result {
            Ok((array, cap)) => {
                let n = array.len();
                self.security_keys.large_blobs = Some(array);
                self.security_keys.lb_capacity = Some(cap);
                self.security_keys.lb_selected = None;
                self.security_keys.lb_status = Some(format!(
                    "Loaded {n} entr{}.",
                    if n == 1 { "y" } else { "ies" }
                ));
            }
            Err(e) => {
                self.security_keys.lb_status = Some(format!("Load failed: {e}"));
            }
        }
    }

    /// Delete entry `idx`, re-serialize the remaining entries with a fresh
    /// checksum, and write the array back. Needs a Large-Blob-Write token, which
    /// we derive from the unlocked session's PIN. Runs on the worker thread.
    fn delete_large_blob_entry(&mut self, idx: usize) {
        let Some(target) = self.selected_fido_target() else {
            self.security_keys.lb_status = Some("No FIDO key selected.".into());
            return;
        };
        let Some(array) = self.security_keys.large_blobs.clone() else {
            return;
        };
        let Some(session) = self.fido_session() else {
            self.security_keys.lb_status =
                Some("Unlock the key with your PIN first to modify large blobs.".into());
            return;
        };
        let Some(target_entry) = array.entry(idx).cloned() else {
            return;
        };
        let pin = session.pin.clone();
        // Deleting the key's name entry: the hero then offers to write it
        // back, which needs a fresh scan.
        let removes_name = matches!(
            target_entry.classify(),
            keyroost_ctap::large_blobs::EntryKind::KeyName(_)
        );

        // Capture the *target entry* (not its cached index). The actual removal
        // happens against a fresh read of the live array inside the worker, so an
        // RP entry written to the key since our last load is preserved and a
        // position shift can't delete the wrong entry. Matches the re-read shape
        // of `add_large_blob_note` / `edit_large_blob_note` / the CLI delete.

        let for_device = self.selected_device.clone();
        self.spawn_job("Updating large blobs\u{2026}", move || {
            let result = (|| -> Result<
                (
                    keyroost_ctap::large_blobs::LargeBlobArray,
                    keyroost_ctap::large_blobs::BlobCapacity,
                ),
                String,
            > {
                let (mut dev, cbor, _init) = open_fido(&target)?;
                if !cbor {
                    return Err("device is U2F-only".into());
                }
                let info = keyroost_ctap::get_info(&mut dev).map_err(|e| e.to_string())?;

                // Re-read the live array and remove the matching entry from it
                // (by content, since `LargeBlobEntry` is `PartialEq`).
                let live =
                    keyroost_ctap::large_blobs::read(&mut dev, &info).map_err(|e| e.to_string())?;
                let found = live.entries().into_iter().position(|e| *e == target_entry);
                let Some(updated) = found.and_then(|pos| live.without_entry(pos)) else {
                    return Err(
                        "that entry is no longer on the key (its storage changed since it was \
                         loaded) \u{2014} nothing was deleted; reload and try again."
                            .into(),
                    );
                };
                // Plan before unlocking, so a certain refusal costs no PIN try.
                let serialized = updated
                    .serialize_with_checksum()
                    .map_err(|e| e.to_string())?;
                let token = large_blob_write_token(&mut dev, &info, &pin, &live)?;
                // Names read from keys before or during the write are stale.
                keyroost_resolve::with_key_names_forgotten(|| {
                    keyroost_ctap::large_blobs::write(&mut dev, &info, &token, &serialized)
                })
                    .map_err(|e| e.to_string())?;

                // Read back so the view reflects the authenticator's actual state.
                let array =
                    keyroost_ctap::large_blobs::read(&mut dev, &info).map_err(|e| e.to_string())?;
                let cap = array.capacity(&info);
                Ok((array, cap))
            })();

            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return; // selection changed mid-op; discard the stale completion
                }
                match result {
                    Ok((array, cap)) => {
                        let n = array.len();
                        app.security_keys.large_blobs = Some(array);
                        app.security_keys.lb_capacity = Some(cap);
                        app.security_keys.lb_selected = None;
                        app.security_keys.lb_status =
                            Some(format!("Entry deleted. {n} remaining."));
                        app.security_keys.error = None;
                        if removes_name {
                            app.refresh_devices();
                        }
                    }
                    Err(e) => {
                        app.security_keys.lb_status = Some(format!("Update failed: {e}"));
                    }
                }
            })
        });
    }

    /// Wipe the entire large-blob array: serialize an empty array with a fresh
    /// checksum and write it back. This is what a FIDO reset does NOT do, so it
    /// is the only way to erase plaintext notes that survive a reset. With
    /// `keep_name` and a name on the key, the key's name entry is written back
    /// exactly as read (`fido blob clear --keep-name`). Refuses, before the PIN
    /// is used, when the array on the key is no longer the one shown. Needs a
    /// Large-Blob-Write token derived from the unlocked session's PIN. Runs on
    /// the worker thread.
    fn clear_large_blob_storage(&mut self, keep_name: bool) {
        let Some(target) = self.selected_fido_target() else {
            self.security_keys.lb_status = Some("No FIDO key selected.".into());
            return;
        };
        let Some(shown) = self.security_keys.large_blobs.clone() else {
            return;
        };
        let Some(session) = self.fido_session() else {
            self.security_keys.lb_status =
                Some("Unlock the key with your PIN first to modify large blobs.".into());
            return;
        };
        let pin = session.pin.clone();
        // The name goes when it isn't kept: the hero then offers to write it
        // back, which needs a fresh scan.
        let removes_name = shown.label().is_some() && !keep_name;

        let for_device = self.selected_device.clone();
        self.spawn_job("Clearing large blobs\u{2026}", move || {
            let result = (|| -> Result<
                (
                    keyroost_ctap::large_blobs::LargeBlobArray,
                    keyroost_ctap::large_blobs::BlobCapacity,
                ),
                String,
            > {
                let (mut dev, cbor, _init) = open_fido(&target)?;
                if !cbor {
                    return Err("device is U2F-only".into());
                }
                let info = keyroost_ctap::get_info(&mut dev).map_err(|e| e.to_string())?;
                // Plan before unlocking, so a certain refusal costs no PIN try:
                // clear only the array the person was shown.
                let current =
                    keyroost_ctap::large_blobs::read(&mut dev, &info).map_err(|e| e.to_string())?;
                if current.raw_array() != shown.raw_array() {
                    return Err(
                        "the key's large-blob storage changed since it was loaded \
                         \u{2014} nothing was cleared; reload and try again."
                            .into(),
                    );
                }
                // Wipe every element, including any skipped (non-standard)
                // ones; keep the name entry exactly as read when asked.
                let serialized = match current.label().filter(|_| keep_name) {
                    Some(_) => current
                        .only_label()
                        .serialize_with_checksum()
                        .map_err(|e| e.to_string())?,
                    None => keyroost_ctap::large_blobs::empty_array_serialized(),
                };
                let token = large_blob_write_token(&mut dev, &info, &pin, &current)?;
                // Names read from keys before or during the write are stale.
                keyroost_resolve::with_key_names_forgotten(|| {
                    keyroost_ctap::large_blobs::write(&mut dev, &info, &token, &serialized)
                })
                .map_err(|e| e.to_string())?;

                // Read back so the view reflects the authenticator's actual state.
                let array =
                    keyroost_ctap::large_blobs::read(&mut dev, &info).map_err(|e| e.to_string())?;
                let cap = array.capacity(&info);
                Ok((array, cap))
            })();

            Box::new(move |app: &mut App| {
                if !completion_still_valid(for_device.as_ref(), app.selected_device.as_ref()) {
                    return; // selection changed mid-op; discard the stale completion
                }
                match result {
                    Ok((array, cap)) => {
                        let n = array.len();
                        app.security_keys.large_blobs = Some(array);
                        app.security_keys.lb_capacity = Some(cap);
                        app.security_keys.lb_selected = None;
                        app.security_keys.lb_status = Some(format!(
                            "Storage cleared. {n} entr{} remaining.",
                            if n == 1 { "y" } else { "ies" }
                        ));
                        app.security_keys.error = None;
                        if removes_name {
                            app.refresh_devices();
                        }
                    }
                    Err(e) => {
                        app.security_keys.lb_status = Some(format!("Clear failed: {e}"));
                    }
                }
            })
        });
    }

    /// Large-blob array viewer/editor (CTAP authenticatorLargeBlobs 0x0C).
    ///
    /// Reads the key-global serialized array (no PIN needed) and shows it both
    /// as a structured entry list and as a hex/ASCII dump. Deleting an entry
    /// re-serializes the remaining entries, recomputes the 16-byte checksum
    /// trailer, and writes the whole array back (which needs a PIN, because the
    /// write path requires a token with the Large Blob Write permission).
    fn render_large_blobs(&mut self, ui: &mut egui::Ui, p: &Palette) {
        ui.add_space(14.0);

        // Auto-load the array the first time this tab is shown, so entries
        // appear without a manual Load click. The flag stops a failed read from
        // retrying every frame; Reload remains available to refresh on demand.
        if !self.security_keys.lb_autoloaded && self.security_keys.large_blobs.is_none() {
            self.security_keys.lb_autoloaded = true;
            self.load_large_blobs();
        }

        // Header + Load/Reload control.
        let mut do_load = false;
        ui.horizontal(|ui| {
            ui.label(
                egui::RichText::new("Large blob storage")
                    .font(theme::f_sb(14.5))
                    .color(p.txt),
            );
            ui.add_space(6.0);
            self.help_dot(ui, p, "large_blobs");
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                let label = if self.security_keys.large_blobs.is_some() {
                    "Reload"
                } else {
                    "Load"
                };
                if theme::button(ui, p, BtnKind::Ghost, label).clicked() {
                    do_load = true;
                }
                ui.add_space(8.0);
                let add_label = if self.security_keys.lb_show_add {
                    "Close"
                } else {
                    "Add"
                };
                if theme::button(ui, p, BtnKind::Ghost, add_label).clicked() {
                    self.security_keys.lb_show_add = !self.security_keys.lb_show_add;
                }
                // "Clear all storage" wipes every entry — the only way to erase
                // plaintext notes a FIDO reset leaves behind. Show it only when
                // there is something to clear and the session is unlocked (the
                // write needs a PIN-derived token, like Delete). The first click
                // arms a confirm; the confirmed click fires below.
                let entry_count = self
                    .security_keys
                    .large_blobs
                    .as_ref()
                    .map(|a| a.len() + a.skipped_count())
                    .unwrap_or(0);
                let unlocked = self.security_keys.session.is_some();
                if entry_count > 0 && unlocked {
                    ui.add_space(8.0);
                    if theme::button(ui, p, BtnKind::Danger, "Clear all storage").clicked() {
                        self.security_keys.lb_confirm_clear = true;
                        self.security_keys.lb_keep_name = self
                            .security_keys
                            .large_blobs
                            .as_ref()
                            .is_some_and(device::keep_name_default);
                    }
                }
            });
        });
        ui.add_space(4.0);
        ui.label(
            egui::RichText::new(
                "This store is readable by anyone holding the key and is meant for \
                 RP-encrypted data \u{2014} not a place for plaintext secrets.",
            )
            .font(theme::f_reg(11.5))
            .color(p.txt3),
        );

        if let Some(cap) = self.security_keys.lb_capacity {
            ui.add_space(8.0);
            let frac = if cap.max_bytes == 0 {
                0.0
            } else {
                (cap.used_bytes as f32 / cap.max_bytes as f32).clamp(0.0, 1.0)
            };
            ui.horizontal(|ui| {
                ui.add(
                    egui::ProgressBar::new(frac)
                        .desired_width(160.0)
                        .desired_height(8.0),
                );
                ui.add_space(8.0);
                ui.label(
                    egui::RichText::new(format!(
                        "{} of {} bytes used \u{00b7} {} free \u{00b7} {} {}",
                        cap.used_bytes,
                        cap.max_bytes,
                        cap.free_bytes,
                        cap.entry_count,
                        if cap.entry_count == 1 {
                            "entry"
                        } else {
                            "entries"
                        },
                    ))
                    .font(theme::f_reg(11.5))
                    .color(p.txt2),
                );
            });
        }

        if let Some(status) = &self.security_keys.lb_status {
            ui.add_space(6.0);
            ui.label(
                egui::RichText::new(status)
                    .font(theme::f_reg(12.0))
                    .color(p.txt2),
            );
        }

        if do_load {
            self.load_large_blobs();
        }

        // Add-a-note composer — only when the user clicked Add. Requires an
        // unlocked session (the write needs a PIN-derived token); show a hint
        // instead when locked.
        if self.security_keys.lb_show_add {
            ui.add_space(12.0);
            theme::card_frame(p).show(ui, |ui| {
                ui.label(
                    egui::RichText::new("Add a text note")
                        .font(theme::f_sb(13.0))
                        .color(p.txt),
                );
                ui.add_space(4.0);
                ui.label(
                    egui::RichText::new(
                        "Stored as a keyroost entry you can read back here. It is NOT \
                         encrypted and is visible to anyone holding the key.",
                    )
                    .font(theme::f_reg(11.0))
                    .color(p.txt3),
                );
                ui.add_space(6.0);
                ui.add(
                    egui::TextEdit::multiline(&mut self.security_keys.lb_new_text)
                        .desired_rows(2)
                        .desired_width(f32::INFINITY)
                        .hint_text("Type a note to store on the key\u{2026}"),
                );
                ui.add_space(6.0);
                let unlocked = self.security_keys.session.is_some();
                let has_text = !self.security_keys.lb_new_text.trim().is_empty();
                ui.horizontal(|ui| {
                    let add = theme::button(ui, p, BtnKind::Primary, "Add note");
                    if add.clicked() && unlocked && has_text {
                        let text = self.security_keys.lb_new_text.clone();
                        self.add_large_blob_note(text);
                    }
                    if !unlocked {
                        ui.label(
                            egui::RichText::new("Unlock with your PIN to save.")
                                .font(theme::f_reg(11.0))
                                .color(p.txt3),
                        );
                    }
                });
            });
        }

        // Render the loaded array, if any.
        let Some(array) = self.security_keys.large_blobs.clone() else {
            return;
        };

        ui.add_space(10.0);
        let skipped = array.skipped_count();
        if array.is_empty() && skipped == 0 {
            ui.label(
                egui::RichText::new("The large-blob array is empty.")
                    .font(theme::f_reg(12.5))
                    .color(p.txt2),
            );
            return;
        }

        let mut delete_request: Option<usize> = None;
        let mut start_edit: Option<(usize, String)> = None;
        let mut save_edit: Option<(usize, String)> = None;
        let mut cancel_edit = false;
        let selected = self.security_keys.lb_selected;
        let editing = self.security_keys.lb_editing;
        for (idx, entry) in array.entries().into_iter().enumerate() {
            theme::card_frame(p).show(ui, |ui| {
                use keyroost_ctap::large_blobs::EntryKind;
                let classification = entry.classify();
                let note_text = match &classification {
                    EntryKind::Note(text) => Some(text.clone()),
                    _ => None,
                };
                ui.horizontal(|ui| {
                    let title = if note_text.is_some() {
                        format!("Note {}", idx + 1)
                    } else {
                        format!("Entry {}", idx + 1)
                    };
                    ui.label(
                        egui::RichText::new(title)
                            .font(theme::f_sb(13.0))
                            .color(p.txt),
                    );
                    ui.add_space(8.0);
                    let meta = match &classification {
                        EntryKind::Note(_) => "keyroost text note".to_string(),
                        EntryKind::KeyName(l) => device::key_name_row_text(&l.label),
                        EntryKind::SshCert { .. } => format!(
                            "ssh-cert \u{00b7} {} bytes \u{00b7} relying-party data",
                            entry.ciphertext.len(),
                        ),
                        EntryKind::Opaque => format!(
                            "{} bytes ciphertext \u{00b7} {}-byte nonce \u{00b7} origSize {} \u{00b7} relying-party data",
                            entry.ciphertext.len(),
                            entry.nonce.len(),
                            entry.orig_size,
                        ),
                    };
                    ui.label(
                        egui::RichText::new(meta)
                            .font(theme::f_reg(11.5))
                            .color(p.txt3),
                    );
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if theme::button(ui, p, BtnKind::Danger, "Delete").clicked() {
                            delete_request = Some(idx);
                        }
                        let is_open = selected == Some(idx);
                        let toggle = if is_open { "Hide bytes" } else { "View bytes" };
                        if theme::button(ui, p, BtnKind::Ghost, toggle).clicked() {
                            self.security_keys.lb_selected =
                                if is_open { None } else { Some(idx) };
                        }
                        // The key's name is changed with Rename, never here.
                        if matches!(classification, EntryKind::KeyName(_)) {
                            theme::button_disabled(ui, p, "Edit")
                                .on_hover_text("Change it with Rename");
                        }
                        // Edit only applies to keyroost's own notes.
                        if note_text.is_some()
                            && editing != Some(idx)
                            && theme::button(ui, p, BtnKind::Ghost, "Edit").clicked()
                        {
                            start_edit = Some((idx, note_text.clone().unwrap_or_default()));
                        }
                        // Export is read-only, so it's always available
                        // regardless of session lock state.
                        if theme::button(ui, p, BtnKind::Ghost, "Export\u{2026}").clicked() {
                            let is_cert =
                                matches!(classification, EntryKind::SshCert { .. });
                            let default_name = if is_cert {
                                format!("entry-{idx}-cert.pub")
                            } else {
                                format!("large-blob-entry-{idx}.bin")
                            };
                            self.spawn_file_dialog(
                                FileTarget::LbExport(idx),
                                true,
                                &[("All files", &["*"])],
                                Some(&default_name),
                            );
                        }
                    });
                });
                // keyroost notes: inline editor when editing this entry, else
                // the decoded text read-only. SSH certificates get a parsed
                // field-by-field view; anything else (opaque RP data) shows
                // nothing extra here — its bytes remain available via "View
                // bytes" below.
                if editing == Some(idx) {
                    ui.add_space(6.0);
                    ui.add(
                        egui::TextEdit::multiline(&mut self.security_keys.lb_edit_text)
                            .desired_rows(2)
                            .desired_width(f32::INFINITY),
                    );
                    ui.add_space(6.0);
                    let unlocked = self.security_keys.session.is_some();
                    let has_text =
                        !self.security_keys.lb_edit_text.trim().is_empty();
                    ui.horizontal(|ui| {
                        if theme::button(ui, p, BtnKind::Primary, "Save").clicked()
                            && unlocked
                            && has_text
                        {
                            save_edit = Some((idx, self.security_keys.lb_edit_text.clone()));
                        }
                        if theme::button(ui, p, BtnKind::Ghost, "Cancel").clicked() {
                            cancel_edit = true;
                        }
                        if !unlocked {
                            ui.label(
                                egui::RichText::new("Unlock with your PIN to save.")
                                    .font(theme::f_reg(11.0))
                                    .color(p.txt3),
                            );
                        }
                    });
                } else if let Some(text) = &note_text {
                    ui.add_space(6.0);
                    ui.label(
                        egui::RichText::new(text)
                            .font(theme::f_reg(12.5))
                            .color(p.txt),
                    );
                } else if let EntryKind::SshCert { info, .. } = &classification {
                    ui.add_space(6.0);
                    egui::Grid::new(format!("lb_cert_{idx}"))
                        .num_columns(2)
                        .spacing([12.0, 2.0])
                        .show(ui, |ui| {
                            let row = |ui: &mut egui::Ui, k: &str, v: String| {
                                ui.label(
                                    egui::RichText::new(k).font(theme::f_reg(11.5)).color(p.txt3),
                                );
                                ui.label(
                                    egui::RichText::new(v).font(theme::f_reg(11.5)).color(p.txt),
                                );
                                ui.end_row();
                            };
                            let kind = if info.cert_type
                                == keyroost_ctap::ssh_cert::CERT_TYPE_USER
                            {
                                "user"
                            } else {
                                "host"
                            };
                            row(ui, "Type", format!("{} ({kind})", info.key_type));
                            row(ui, "Key ID", info.key_id.clone());
                            row(ui, "Serial", info.serial.to_string());
                            row(
                                ui,
                                "Principals",
                                if info.principals.is_empty() {
                                    "(any)".to_string()
                                } else {
                                    info.principals.join(", ")
                                },
                            );
                            row(
                                ui,
                                "Valid",
                                keyroost_ctap::ssh_cert::format_validity(
                                    info.valid_after,
                                    info.valid_before,
                                ),
                            );
                            for (n, v) in &info.critical_options {
                                row(
                                    ui,
                                    "Critical",
                                    if v.is_empty() {
                                        n.clone()
                                    } else {
                                        format!("{n}={v}")
                                    },
                                );
                            }
                            for ext in &info.extensions {
                                row(ui, "Extension", ext.clone());
                            }
                        });
                }
                if selected == Some(idx) {
                    ui.add_space(8.0);
                    Self::hex_ascii_view(ui, p, &entry.ciphertext);
                }
            });
            ui.add_space(8.0);
        }
        if skipped > 0 {
            ui.label(
                egui::RichText::new(format!(
                    "{skipped} element(s) not in the standard format (kept unchanged)"
                ))
                .font(theme::f_reg(11.5))
                .color(p.txt3),
            );
        }

        // Apply edit-related actions collected during the loop (kept outside it
        // to avoid borrowing `self` while iterating the cloned array).
        if let Some((idx, text)) = start_edit {
            self.security_keys.lb_editing = Some(idx);
            self.security_keys.lb_edit_text = text;
        }
        if cancel_edit {
            self.security_keys.lb_editing = None;
            self.security_keys.lb_edit_text.clear();
        }
        if let Some((idx, text)) = save_edit {
            self.edit_large_blob_note(idx, text);
        }

        // A delete is a write; confirm before touching the key.
        if let Some(idx) = delete_request {
            self.security_keys.lb_confirm_delete = Some(idx);
        }
        if let Some(idx) = self.security_keys.lb_confirm_delete {
            let is_name = array.entry(idx).is_some_and(|e| {
                matches!(
                    e.classify(),
                    keyroost_ctap::large_blobs::EntryKind::KeyName(_)
                )
            });
            ui.add_space(6.0);
            theme::card_frame(p)
                .stroke(egui::Stroke::new(1.0, theme::tint(p.err, 90)))
                .show(ui, |ui| {
                    ui.label(
                        egui::RichText::new(format!(
                            "Delete entry {} and rewrite the array? Requires your PIN.{}",
                            idx + 1,
                            if is_name {
                                " This removes the key's name."
                            } else {
                                ""
                            }
                        ))
                        .font(theme::f_reg(12.5))
                        .color(p.txt),
                    );
                    ui.add_space(6.0);
                    ui.horizontal(|ui| {
                        if theme::button(ui, p, BtnKind::Danger, "Delete entry").clicked() {
                            self.security_keys.lb_confirm_delete = None;
                            self.delete_large_blob_entry(idx);
                        }
                        if theme::button(ui, p, BtnKind::Ghost, "Cancel").clicked() {
                            self.security_keys.lb_confirm_delete = None;
                        }
                    });
                });
        }

        // Clearing all storage is irreversible and wipes every note, so the
        // first click only arms this confirm; the user must confirm explicitly.
        if self.security_keys.lb_confirm_clear {
            let label = array.label().map(|(_, l)| l.label);
            let names = array
                .entries()
                .into_iter()
                .filter(|e| {
                    matches!(
                        e.classify(),
                        keyroost_ctap::large_blobs::EntryKind::KeyName(_)
                    )
                })
                .count();
            let keep = self.security_keys.lb_keep_name && label.is_some();
            let n = array.len() + skipped - if keep { names } else { 0 };
            let plural = if n == 1 { "y" } else { "ies" };
            ui.add_space(6.0);
            theme::card_frame(p)
                .stroke(egui::Stroke::new(1.0, theme::tint(p.err, 90)))
                .show(ui, |ui| {
                    let name_clause = match (&label, keep) {
                        (Some(_), true) => " The key's name stays.".to_string(),
                        (Some(l), false) if keyroost_keyring::validate_name(l).is_ok() => {
                            format!(" This also removes the key's name \"{l}\".")
                        }
                        (Some(_), false) => " This also removes the key's name.".to_string(),
                        (None, _) => String::new(),
                    };
                    let every = if keep {
                        "every other entry"
                    } else {
                        "every entry"
                    };
                    let what = if keep {
                        format!("Wipe {n} entr{plural} from this key?")
                    } else {
                        format!("Wipe all {n} entr{plural} from this key?")
                    };
                    ui.label(
                        egui::RichText::new(format!(
                            "{what} This erases {every} \u{2014} \
                             including any relying-party data (e.g. SSH certificates, sign-in \
                             records), not just keyroost notes. Cannot be undone; requires your \
                             PIN.{name_clause}",
                        ))
                        .font(theme::f_reg(12.5))
                        .color(p.txt),
                    );
                    if label.is_some() {
                        ui.add_space(4.0);
                        ui.checkbox(&mut self.security_keys.lb_keep_name, "Keep the key's name");
                    }
                    ui.add_space(6.0);
                    ui.horizontal(|ui| {
                        let confirm = if keep {
                            format!("Confirm \u{2014} wipe {n} entr{plural}")
                        } else {
                            format!("Confirm \u{2014} wipe all {n} entr{plural}")
                        };
                        if n == 0 {
                            theme::button_disabled(ui, p, &confirm);
                        } else if theme::button(ui, p, BtnKind::Danger, &confirm).clicked() {
                            self.security_keys.lb_confirm_clear = false;
                            self.clear_large_blob_storage(keep);
                        }
                        if theme::button(ui, p, BtnKind::Ghost, "Cancel").clicked() {
                            self.security_keys.lb_confirm_clear = false;
                        }
                    });
                });
        }
    }

    /// Render a byte slice as a side-by-side hex + ASCII dump, 16 bytes/row.
    fn hex_ascii_view(ui: &mut egui::Ui, p: &Palette, bytes: &[u8]) {
        let mut text = String::new();
        for (i, row) in bytes.chunks(16).enumerate() {
            let mut hex = String::new();
            let mut ascii = String::new();
            for (j, b) in row.iter().enumerate() {
                hex.push_str(&format!("{:02x} ", b));
                if j == 7 {
                    hex.push(' ');
                }
                ascii.push(if b.is_ascii_graphic() || *b == b' ' {
                    *b as char
                } else {
                    '.'
                });
            }
            // Pad short final rows so the ASCII column lines up.
            let width = 16 * 3 + 1;
            while hex.len() < width {
                hex.push(' ');
            }
            text.push_str(&format!("{:08x}  {} |{}|\n", i * 16, hex, ascii));
        }
        ui.add(
            egui::Label::new(
                egui::RichText::new(text.trim_end())
                    .font(theme::f_mono(11.5))
                    .color(p.txt2),
            )
            .wrap(),
        );
    }

    /// Advanced security-policy view (CTAP authenticatorConfig). Grouped here,
    /// behind the overflow menu, because several of these are irreversible and
    /// shouldn't sit alongside everyday controls. Each action takes the device
    /// PIN at apply time (config needs its own permissioned token) and the
    /// irreversible ones require an explicit typed confirmation.
    fn render_fido_advanced(&mut self, ui: &mut egui::Ui, p: &Palette) {
        let always_uv = self
            .security_keys
            .info
            .as_ref()
            .and_then(|i| i.option("alwaysUv"));
        // Enterprise attestation support: the `ep` option is present (true =
        // already enabled, false = supported but off) on keys that can do it,
        // and absent entirely on keys that can't. Hide the row when unsupported.
        let ep = self
            .security_keys
            .info
            .as_ref()
            .and_then(|i| i.option("ep"));
        let supports_ep = ep.is_some();
        let ep_enabled = ep == Some(true);
        let min_pin_length = self
            .security_keys
            .info
            .as_ref()
            .and_then(|i| i.min_pin_length);

        ui.add_space(14.0);
        theme::card_frame(p).show(ui, |ui| {
            ui.horizontal(|ui| {
                ui.label(
                    egui::RichText::new("Security policy")
                        .font(theme::f_sb(14.5))
                        .color(p.txt),
                );
                ui.add_space(6.0);
                self.help_dot(ui, p, "settings");
            });
            ui.add_space(4.0);
            ui.label(
                egui::RichText::new(
                    "These change the key's security policy. Some are irreversible \
                     without a full reset \u{2014} read each note before applying.",
                )
                .font(theme::f_reg(12.0))
                .color(p.txt3),
            );
            ui.add_space(10.0);

            // Each row: a description + a button that arms the confirm dialog.
            let mut arm: Option<AdvancedAction> = None;

            // Always-UV (reversible toggle).
            ui.horizontal(|ui| {
                ui.vertical(|ui| {
                    ui.label(
                        egui::RichText::new("Always require user verification")
                            .font(theme::f_sb(13.0))
                            .color(p.txt),
                    );
                    let state = match always_uv {
                        Some(true) => "Currently on \u{2014} every sign-in needs PIN or biometric.",
                        Some(false) => "Currently off.",
                        None => "State unknown.",
                    };
                    ui.label(
                        egui::RichText::new(state)
                            .font(theme::f_reg(11.5))
                            .color(p.txt3),
                    );
                });
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    if theme::button(ui, p, BtnKind::Default, "Toggle").clicked() {
                        arm = Some(AdvancedAction::ToggleAlwaysUv);
                    }
                });
            });
            ui.add_space(8.0);

            // Set minimum PIN length (one-way).
            ui.horizontal(|ui| {
                ui.vertical(|ui| {
                    ui.label(
                        egui::RichText::new("Set minimum PIN length")
                            .font(theme::f_sb(13.0))
                            .color(p.txt),
                    );
                    ui.label(
                        egui::RichText::new("Can only be raised, never lowered without a reset.")
                            .font(theme::f_reg(11.5))
                            .color(p.txt3),
                    );
                    let current = match min_pin_length {
                        Some(n) => format!("Current minimum: {} characters", n),
                        None => "Current minimum: \u{2014}".to_string(),
                    };
                    ui.label(
                        egui::RichText::new(current)
                            .font(theme::f_reg(11.5))
                            .color(p.txt3),
                    );
                });
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    if theme::button(ui, p, BtnKind::Default, "Set\u{2026}").clicked() {
                        arm = Some(AdvancedAction::SetMinPin);
                    }
                });
            });
            ui.add_space(8.0);

            // Force PIN change.
            ui.horizontal(|ui| {
                ui.vertical(|ui| {
                    ui.label(
                        egui::RichText::new("Force PIN change on next use")
                            .font(theme::f_sb(13.0))
                            .color(p.txt),
                    );
                    ui.label(
                        egui::RichText::new("Useful before handing the key to someone else.")
                            .font(theme::f_reg(11.5))
                            .color(p.txt3),
                    );
                });
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    if theme::button(ui, p, BtnKind::Default, "Force\u{2026}").clicked() {
                        arm = Some(AdvancedAction::ForcePinChange);
                    }
                });
            });
            // Enterprise attestation (one-way) — only shown on keys that
            // support it (the `ep` getInfo option is present).
            if supports_ep {
                ui.add_space(8.0);
                ui.horizontal(|ui| {
                    ui.vertical(|ui| {
                        ui.label(
                            egui::RichText::new("Enable enterprise attestation")
                                .font(theme::f_sb(13.0))
                                .color(p.txt),
                        );
                        let note = if ep_enabled {
                            "Currently on. Disabling it again requires a device reset."
                        } else {
                            "One-way: disabling it again requires a device reset."
                        };
                        ui.label(
                            egui::RichText::new(note)
                                .font(theme::f_reg(11.5))
                                .color(p.txt3),
                        );
                    });
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if ep_enabled {
                            // Already enabled: nothing actionable, show a pill.
                            theme::pill(ui, "Enabled", p.ok, p.ok_soft());
                        } else if theme::button(ui, p, BtnKind::Danger, "Enable\u{2026}").clicked()
                        {
                            arm = Some(AdvancedAction::EnterpriseAttestation);
                        }
                    });
                });
            }

            if let Some(action) = arm {
                // Fields listed explicitly: AdvancedDialog now has a Drop impl
                // (to wipe the PIN), so struct-update from `Default::default()`
                // is disallowed (can't move fields out of a Drop type).
                self.security_keys.advanced = Some(AdvancedDialog {
                    action,
                    pin_input: String::new(),
                    min_pin_input: String::new(),
                    force_change: false,
                    device: self.selected_device.clone(),
                });
                self.security_keys.error = None;
            }
        });
    }

    /// Inline confirm + PIN entry for an armed Advanced action.
    /// Confirm/apply overlay for an armed Advanced action. Rendered as a
    /// centered modal window (like the reset dialog) so it floats over the
    /// Settings panel instead of pushing the list down.
    /// Shared centered-modal chrome used by the Settings, fingerprint-delete,
    /// and enrollment dialogs so they all look identical: no native title bar,
    /// a custom frame (pop fill, line stroke, drop shadow, 20px padding), a
    /// title at button-font size with a painted X close, and Esc-to-dismiss.
    /// `body` draws the dialog contents. `width` is the dialog's max content
    /// width (300.0 is the shape every other caller uses; a caller with
    /// wider content — e.g. a GUID that needs to stay on one line — passes a
    /// larger value so the title row, and the close X pinned to its right
    /// edge, actually span the content instead of clipping/misaligning
    /// against it). Returns true if the X or Esc was used (the caller
    /// dismisses its own state).
    fn modal_window(
        ctx: &egui::Context,
        p: &Palette,
        id: &str,
        title: &str,
        width: f32,
        body: impl FnOnce(&mut egui::Ui),
    ) -> bool {
        let mut closed = ctx.input(|i| i.key_pressed(egui::Key::Escape));
        egui::Window::new(id)
            .collapsible(false)
            .resizable(false)
            .title_bar(false)
            .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
            .frame(egui::Frame {
                inner_margin: egui::Margin::same(20),
                corner_radius: egui::CornerRadius::same(13),
                fill: p.pop,
                stroke: egui::Stroke::new(1.0, p.line),
                shadow: egui::epaint::Shadow {
                    offset: [0, 12],
                    blur: 40,
                    spread: 0,
                    color: egui::Color32::from_black_alpha(115),
                },
                ..Default::default()
            })
            .show(ctx, |ui| {
                ui.set_max_width(width);
                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new(title)
                            .font(theme::f_sb(13.0))
                            .color(p.txt),
                    );
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        let (xr, xresp) =
                            ui.allocate_exact_size(egui::vec2(18.0, 18.0), egui::Sense::click());
                        let xcolor = if xresp.hovered() { p.txt } else { p.txt3 };
                        paint_x_icon(ui, xr.center(), xcolor);
                        if xresp.clicked() {
                            closed = true;
                        }
                    });
                });
                ui.add_space(12.0);
                body(ui);
            });
        closed
    }

    /// Centered-modal enrollment dialog (same chrome as the Settings dialogs):
    /// live per-sample progress, a Cancel during capture, and a Done once the
    /// flow finishes.
    fn render_enroll_dialog(&mut self, ctx: &egui::Context, p: &Palette) {
        let Some(prog) = self.security_keys.fp_progress.clone() else {
            return;
        };

        // Snapshot the shared state under one short lock so the body closure
        // (which only borrows `ui`) doesn't need the mutex.
        let (captured, total, last_message, done) = {
            let Ok(g) = prog.lock() else { return };
            (
                g.captured,
                g.total.max(1),
                g.last_message.clone(),
                g.done.clone(),
            )
        };
        let frac = (captured as f32 / total as f32).clamp(0.0, 1.0);
        let finished = done.is_some();

        let mut want_cancel = false;
        let mut want_done = false;
        let closed =
            Self::modal_window(
                ctx,
                p,
                "fp_enroll",
                "Enroll fingerprint",
                300.0,
                |ui| match &done {
                    None => {
                        ui.label(
                            egui::RichText::new(format!(
                                "Enrolling \u{2014} sample {} of {}",
                                captured.min(total),
                                total
                            ))
                            .font(theme::f_sb(13.0))
                            .color(p.accent),
                        );
                        ui.add_space(8.0);
                        ui.add(egui::ProgressBar::new(frac).desired_width(280.0));
                        ui.add_space(6.0);
                        ui.label(
                            egui::RichText::new(format!("\u{1F446} {last_message}"))
                                .font(theme::f_reg(12.0))
                                .color(p.txt2),
                        );
                        ui.add_space(16.0);
                        if theme::button(ui, p, BtnKind::Default, "Cancel").clicked() {
                            want_cancel = true;
                        }
                    }
                    Some(Ok(())) => {
                        ui.label(
                            egui::RichText::new("\u{2713} Fingerprint enrolled")
                                .font(theme::f_sb(13.0))
                                .color(p.ok),
                        );
                        ui.add_space(8.0);
                        ui.add(egui::ProgressBar::new(1.0).desired_width(280.0));
                        ui.add_space(16.0);
                        if theme::button(ui, p, BtnKind::Primary, "Done").clicked() {
                            want_done = true;
                        }
                    }
                    Some(Err(e)) => {
                        ui.colored_label(p.err, format!("Enrollment failed: {e}"));
                        ui.add_space(16.0);
                        if theme::button(ui, p, BtnKind::Default, "Close").clicked() {
                            want_done = true;
                        }
                    }
                },
            );

        if want_cancel {
            // Signal the worker to abort the capture between samples.
            if let Ok(mut g) = prog.lock() {
                g.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
                g.last_message = "Cancelling\u{2026}".into();
            }
        }
        // Done / Close / the X / Esc dismiss the dialog once the flow is
        // finished. While a capture is still running, the X/Esc act as Cancel
        // rather than leaving an orphaned worker.
        if want_done || (closed && finished) {
            self.security_keys.fp_progress = None;
        } else if closed && !finished {
            if let Ok(mut g) = prog.lock() {
                g.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
                g.last_message = "Cancelling\u{2026}".into();
            }
        }
    }

    /// Centered-modal confirmation for deleting a fingerprint (same chrome as
    /// the Settings dialogs). Returns the template id to delete, if confirmed.
    fn render_fp_delete_confirm(&mut self, ctx: &egui::Context, p: &Palette) -> Option<Vec<u8>> {
        let id = self.security_keys.fp_confirm_delete.clone()?;
        let label = self
            .security_keys
            .fingerprints
            .as_ref()
            .and_then(|l| l.iter().find(|e| e.template_id == id))
            .and_then(|e| e.friendly_name.clone())
            .unwrap_or_else(|| hex_short(&id));

        let mut confirm = false;
        let mut cancel = false;
        let closed = Self::modal_window(ctx, p, "fp_delete", "Delete fingerprint?", 300.0, |ui| {
            ui.label(
                egui::RichText::new(format!(
                    "Delete fingerprint \u{201c}{label}\u{201d}? This cannot be undone."
                ))
                .font(theme::f_reg(12.5))
                .color(p.txt),
            );
            ui.add_space(16.0);
            ui.horizontal(|ui| {
                if theme::button(ui, p, BtnKind::Danger, "Delete").clicked() {
                    confirm = true;
                }
                ui.add_space(8.0);
                if theme::button(ui, p, BtnKind::Default, "Cancel").clicked() {
                    cancel = true;
                }
            });
        });

        if cancel || closed {
            self.security_keys.fp_confirm_delete = None;
            return None;
        }
        if confirm {
            self.security_keys.fp_confirm_delete = None;
            return Some(id);
        }
        None
    }

    fn render_advanced_confirm(&mut self, ctx: &egui::Context, p: &Palette) {
        let Some(dlg) = self.security_keys.advanced.as_ref() else {
            return;
        };
        let action = dlg.action;
        if action == AdvancedAction::None {
            return;
        }
        if !completion_still_valid(dlg.device.as_ref(), self.selected_device.as_ref()) {
            self.security_keys.advanced = None;
            return;
        }

        let (title, irreversible) = match action {
            AdvancedAction::ToggleAlwaysUv => ("Toggle always-UV", false),
            AdvancedAction::SetMinPin => ("Set minimum PIN length", true),
            AdvancedAction::ForcePinChange => ("Force a PIN change", false),
            AdvancedAction::EnterpriseAttestation => ("Enable enterprise attestation", true),
            AdvancedAction::None => return,
        };

        let mut apply = false;
        let mut cancel = false;
        // No built-in title bar, so handle Esc-to-dismiss ourselves.
        if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
            cancel = true;
        }
        egui::Window::new(title)
            .collapsible(false)
            .resizable(false)
            .title_bar(false)
            .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
            .frame(egui::Frame {
                inner_margin: egui::Margin::same(20),
                corner_radius: egui::CornerRadius::same(13),
                fill: p.pop,
                stroke: egui::Stroke::new(1.0, p.line),
                shadow: egui::epaint::Shadow {
                    offset: [0, 12],
                    blur: 40,
                    spread: 0,
                    color: egui::Color32::from_black_alpha(115),
                },
                ..Default::default()
            })
            .show(ctx, |ui| {
                ui.set_max_width(300.0);
                // Custom title at the button font size (the default window title
                // bar is dropped via title_bar(false), so render our own).
                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new(title)
                            .font(theme::f_sb(13.0))
                            .color(p.txt),
                    );
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        let (xr, xresp) =
                            ui.allocate_exact_size(egui::vec2(18.0, 18.0), egui::Sense::click());
                        let xcolor = if xresp.hovered() { p.txt } else { p.txt3 };
                        paint_x_icon(ui, xr.center(), xcolor);
                        if xresp.clicked() {
                            cancel = true;
                        }
                    });
                });
                ui.add_space(12.0);
                if irreversible {
                    ui.label(
                        egui::RichText::new(
                            "This cannot be undone without a full reset of the key.",
                        )
                        .font(theme::f_reg(12.0))
                        .color(p.warn),
                    );
                    ui.add_space(12.0);
                }

                if action == AdvancedAction::SetMinPin {
                    ui.horizontal(|ui| {
                        ui.label("New minimum length");
                        if let Some(d) = self.security_keys.advanced.as_mut() {
                            ui.add(
                                egui::TextEdit::singleline(&mut d.min_pin_input)
                                    .desired_width(64.0)
                                    .hint_text("e.g. 6"),
                            );
                        }
                    });
                    ui.add_space(8.0);
                    if let Some(d) = self.security_keys.advanced.as_mut() {
                        ui.checkbox(&mut d.force_change, "Also force a PIN change now");
                    }
                    ui.add_space(12.0);
                }

                ui.horizontal(|ui| {
                    ui.label("Device PIN");
                    if let Some(d) = self.security_keys.advanced.as_mut() {
                        let resp = ui.add(
                            egui::TextEdit::singleline(&mut d.pin_input)
                                .password(true)
                                .desired_width(160.0),
                        );
                        guard_secret_field(ui.ctx(), &resp);
                    }
                });
                ui.add_space(16.0);

                ui.horizontal(|ui| {
                    let kind = if irreversible {
                        BtnKind::Danger
                    } else {
                        BtnKind::Primary
                    };
                    if theme::button(ui, p, kind, "Apply").clicked() {
                        apply = true;
                    }
                    ui.add_space(8.0);
                    if theme::button(ui, p, BtnKind::Default, "Cancel").clicked() {
                        cancel = true;
                    }
                });

                if let Some(err) = &self.security_keys.error {
                    ui.add_space(10.0);
                    ui.label(
                        egui::RichText::new(err)
                            .font(theme::f_reg(12.0))
                            .color(p.err),
                    );
                }
            });

        if apply {
            self.run_advanced_action();
        } else if cancel {
            // The Cancel button, the ✕, or pressing Esc all dismiss.
            self.security_keys.advanced = None;
            self.security_keys.error = None;
        }
    }

    /// Render the *current* management-key collector inside the modal, but only
    /// for the flows that need it (`PivCredKind::needs_mgmt_key`). Shows a "Use
    /// default management key" toggle (the common case — most users never rotate
    /// the well-known factory default) and, when it's off, the hex entry field.
    /// When the toggle is on the field is hidden and the op reads the default via
    /// `piv_current_mgmt_auth`. The toggle itself is disabled — greyed out,
    /// unclickable — whenever `Self::piv_current_default_mgmt_key` resolves
    /// `None`: this fingerprint/version carries no
    /// `keyroost_piv::compat::PivQuirk::Default9bManagementKey`, so keyroost has
    /// no default to offer rather than one that might just be wrong. When it
    /// does resolve `Some`, hovering the (enabled) checkbox shows the
    /// applicable default key as hex in a tooltip, so the user can see what
    /// they're about to authorize with before committing to it.
    ///
    /// When this device's fingerprint resolves
    /// `keyroost_piv::compat::PivExtension::PinManagementAuth` to `Supported`
    /// *or* `Unverified`, a second "Use PIN" toggle appears alongside it —
    /// with a warning-triangle marker next to it for `Unverified`, same as
    /// every other gated control in this pane, so the user can still try it
    /// but knows it hasn't been confirmed on this specific device.
    /// `Unsupported` hides the toggle entirely, same as before. Both toggles
    /// are pure views onto — and setters of — the single
    /// `PivState::mgmt_auth_mode` (see that type's doc for why): checking
    /// either sets the mode to that variant; unchecking either always
    /// returns to `PivMgmtAuthMode::Manual`, never leaves the other toggle's
    /// variant standing. With "Use PIN" on, the hex field either turns into
    /// a PIN entry (label "PIN", hint "PIN") — or, for a flow with a
    /// dedicated PIN field of its own (`PivCredKind::shares_pin_field`),
    /// disappears entirely, since that field's PIN is reused for management
    /// auth too (there is only one PIV application PIN).
    fn piv_modal_mgmt_field(&mut self, ui: &mut egui::Ui, p: &Palette, kind: PivCredKind) {
        if !kind.needs_mgmt_key() {
            return;
        }
        let pin_auth_gate = {
            let (fp, ver, fw) = self.piv.status.as_ref().map_or(
                (
                    keyroost_piv::fingerprint::AppletFingerprint::Generic,
                    None,
                    None,
                ),
                |s| {
                    (
                        s.applet_fingerprint,
                        s.version.as_deref(),
                        s.version_firmware.as_deref(),
                    )
                },
            );
            self.piv_gate(
                keyroost_piv::compat::PivExtension::PinManagementAuth,
                fp,
                ver,
                fw,
            )
        };
        let pin_auth_available = !matches!(
            pin_auth_gate,
            keyroost_piv::compat::FeatureGate::Unsupported
        );
        if !pin_auth_available && self.piv.mgmt_auth_mode == PivMgmtAuthMode::Pin {
            // Keeps state sane if a device switch mid-modal drops support out
            // from under an already-checked toggle.
            self.piv.mgmt_auth_mode = PivMgmtAuthMode::Manual;
        }
        let default_key = self.piv_current_default_mgmt_key();
        if default_key.is_none() && self.piv.mgmt_auth_mode == PivMgmtAuthMode::Default {
            // Same rationale as the "Use PIN" reset above: don't leave the
            // toggle checked for a default a device switch just took away.
            self.piv.mgmt_auth_mode = PivMgmtAuthMode::Manual;
        }
        ui.horizontal(|ui| {
            let mut is_default = self.piv.mgmt_auth_mode == PivMgmtAuthMode::Default;
            let mut resp = ui.add_enabled(
                default_key.is_some(),
                egui::Checkbox::new(&mut is_default, "Use default management key"),
            );
            if let Some(key) = default_key {
                // Only on the enabled checkbox — a disabled one has no
                // applicable default to show.
                resp = resp.on_hover_text(format!("Default management key: {}", hex_lower(key)));
            }
            if resp.changed() {
                self.piv.mgmt_auth_mode =
                    piv_mgmt_mode_after_toggle(is_default, PivMgmtAuthMode::Default);
            }
            if pin_auth_available {
                let mut is_pin = self.piv.mgmt_auth_mode == PivMgmtAuthMode::Pin;
                if ui.checkbox(&mut is_pin, "Use PIN").changed() {
                    self.piv.mgmt_auth_mode =
                        piv_mgmt_mode_after_toggle(is_pin, PivMgmtAuthMode::Pin);
                }
                if matches!(pin_auth_gate, keyroost_piv::compat::FeatureGate::Unverified) {
                    ui.add_space(4.0);
                    theme::warn_marker(ui, p).on_hover_text(format!(
                        "{} {}",
                        keyroost_piv::compat::PivExtension::PinManagementAuth.requirement(),
                        keyroost_piv::compat::FeatureGate::UNVERIFIED_SUFFIX
                    ));
                }
            }
        });
        if self.piv.mgmt_auth_mode == PivMgmtAuthMode::Default {
            return;
        }
        let use_pin = self.piv.mgmt_auth_mode == PivMgmtAuthMode::Pin;
        if use_pin && kind.shares_pin_field() {
            return;
        }
        // Match whichever row shares a label column with this one, so the
        // fields line up: the New CHUID dialog's GUID row (and, for
        // `ChangeMgmtKey`, that same modal's own "New key" row below this
        // one), or — for `SelfSign`/`SetRetries` — the dedicated PIN row
        // below this one. "GUID"/"New key"/"PIN" are all short enough to fit
        // the shared 96px label box, but "Management key" isn't, so every
        // row sharing a column with it needs the wider, measured width or
        // their inputs start at different x. Field width stays each row's
        // own — only the label column needs to match. Every other flow
        // (nothing else visible to misalign against) keeps the narrower
        // default.
        let label_w = if matches!(
            kind,
            PivCredKind::NewChuid
                | PivCredKind::ChangeMgmtKey
                | PivCredKind::SelfSign
                | PivCredKind::SetRetries
        ) {
            chuid_label_width(ui.ctx())
        } else {
            96.0
        };
        let width = if kind == PivCredKind::NewChuid {
            chuid_guid_field_width(ui.ctx())
        } else {
            300.0
        };
        let (label, hint) = if use_pin {
            ("PIN", "PIN")
        } else {
            ("Management key", "hex (48/32/64 chars)")
        };
        let mut mgmt_key_rev = self
            .secret_reveal
            .get("piv-mgmt-key-input")
            .copied()
            .unwrap_or(false);
        piv_secret_field(
            ui,
            p,
            label,
            &mut self.piv.mgmt_key_input,
            &mut mgmt_key_rev,
            hint,
            label_w,
            width,
        );
        self.secret_reveal
            .insert("piv-mgmt-key-input", mgmt_key_rev);
    }

    /// The Compression row of the Import certificate and Self-signed
    /// certificate dialogs (the CLI's `--compress` / `--no-compress`), with
    /// the same help the CLI gives. `label_w` is the dialog's label column, so
    /// the row lines up with the management-key and PIN rows above it.
    fn piv_modal_compression_field(&mut self, ui: &mut egui::Ui, p: &Palette, label_w: f32) {
        ui.add_space(4.0);
        ui.horizontal(|ui| {
            ui.add_sized(
                [label_w, 22.0],
                egui::Label::new(
                    egui::RichText::new("Compression")
                        .font(theme::f_reg(13.0))
                        .color(p.txt2),
                ),
            );
            piv_cert_compression_combo(ui, "piv-cert-compression", &mut self.piv.cert_compression);
        });
        card_note(
            ui,
            p,
            "Compressed is the PIV standard's gzip form; some software may not read \
             compressed certificates. Automatic compresses only if the card refuses the \
             certificate as too large.",
        );
    }

    /// PIV credential-entry modal: drives the PIN/PUK flows (Change PIN / Change
    /// PUK / Unblock PIN) *and* the management-key-gated operations (generate
    /// key, import / self-sign / CSR, set retries, change management key) inside
    /// the shared `modal_window` chrome, so the secret fields *and* the op's
    /// result stay centered on-screen rather than scrolling off (issue #31).
    ///
    /// The secret fields live in `PivState` (rendered here, not inline in the
    /// pane); the inline pane keeps the *non-secret* parameters (slot, algorithm,
    /// file path, subject, validity, retry counts). The modal state
    /// (`PivState::cred_modal`) tracks the flow, an in-flight flag, and the op
    /// result. On Submit it validates (new==confirm for PIN/PUK; the ops' own
    /// client-side guards for the rest), then runs the existing op, which writes
    /// the outcome back into the modal via `apply_piv_cred_result`. Rich,
    /// non-secret results (e.g. the generated public-key PEM) still surface in
    /// the pane — the modal only shows a generic success line. Cancel / ✕ / Esc —
    /// and a successful Done — wipe the secret fields.
    fn render_piv_cred_modal(&mut self, ctx: &egui::Context, p: &Palette) {
        let Some(kind) = self.piv.cred_modal.as_ref().map(|m| m.kind) else {
            return;
        };
        let busy = self.piv.cred_modal.as_ref().is_some_and(|m| m.busy);
        let result = self.piv.cred_modal.as_ref().and_then(|m| m.result.clone());
        let detail = self.piv.cred_modal.as_ref().and_then(|m| m.detail.clone());
        // The self-test spinner asks for a touch when the selected slot's
        // touch policy needs one (mirrors the Generate-key spinner wording).
        let busy_text = if kind == PivCredKind::SelfTest
            && matches!(
                self.piv_selected_slot_policy().map(|(_, t)| t),
                Some(keyroost_piv::TouchPolicy::Always | keyroost_piv::TouchPolicy::Cached)
            ) {
            format!("{} \u{2014} touch the key", kind.busy_label())
        } else {
            kind.busy_label().to_owned()
        };

        let mut want_submit = false;
        let mut want_close = false;
        // Inline new==confirm guard, mirroring the op-level backstop. Shown as
        // the modal's error line; blocks Submit when set.
        let mismatch = piv_cred_mismatch(&self.piv, kind);
        // Whether the target slot already holds a key — drives the Generate-key
        // overwrite warning + relabel and the Import-cert replace note.
        // Precomputed before the closure borrows `self` mutably.
        let selected_occupied = self.piv_selected_occupied();
        // The Generate warning fails closed (a slot keyroost can't vouch for
        // as empty may hold a key); the "Overwrite key" relabel stays for a
        // known key only.
        let selected_occupancy = self.piv_occupancy(self.piv.selected_slot.to_slot());

        // Move-key flow: precompute the source slot and the eligible destination
        // slots (empty, non-source) before the modal borrows `self` mutably. A
        // standard slot is occupied when its `slot_keys` entry carries a key
        // algorithm; a retired slot's occupancy comes from the lazily-read cache
        // (unknown → treated as empty; the transport re-checks and refuses an
        // occupied destination, so a stale cache can't cause a bad move).
        let move_src = self.piv.selected_slot.to_slot();
        let move_dests: Vec<keyroost_piv::Slot> = if kind == PivCredKind::MoveKey {
            let piv = &self.piv;
            let occupied = |s: keyroost_piv::Slot| -> bool {
                if matches!(s, keyroost_piv::Slot::Retired(_)) {
                    piv.retired_occupancy
                        .as_ref()
                        .and_then(|v| v.iter().find(|(rs, _)| *rs == s))
                        .is_some_and(|(_, key)| {
                            *key == keyroost_transport::SlotKeyPresence::Present
                        })
                } else {
                    piv.slot_keys
                        .iter()
                        .find(|(sl, _, _)| *sl == s)
                        .map(|(_, alg, _)| alg.is_some())
                        .unwrap_or(false)
                }
            };
            move_key_eligible_destinations(move_src, &occupied)
        } else {
            Vec::new()
        };
        // New CHUID's GUID field needs to stay on one line at its full
        // canonical `8-4-4-4-12` width (36 characters); every other flow
        // fits the default. Sized from the same measured field width the
        // GUID/management-key inputs use, not a separate fixed guess, so
        // the dialog doesn't reserve space nothing in it actually needs:
        // label column + spacing + field + spacing + refresh icon + a
        // little breathing room before the edge.
        let width = if kind == PivCredKind::NewChuid {
            chuid_label_width(ctx) + 8.0 + chuid_guid_field_width(ctx) + 6.0 + 22.0 + 12.0
        } else {
            300.0
        };
        let closed = Self::modal_window(ctx, p, "piv_cred", kind.title(), width, |ui| {
            match &result {
                Some(Ok(())) => {
                    // Success: confirmation + a single Done that dismisses.
                    ui.label(
                        egui::RichText::new(format!("\u{2713} {}", piv_cred_success(kind)))
                            .font(theme::f_sb(13.0))
                            .color(p.ok),
                    );
                    // Per-operation breakdown (self-test): one line each.
                    if let Some(d) = &detail {
                        ui.add_space(6.0);
                        for line in d.lines() {
                            card_note(ui, p, line);
                        }
                    }
                    ui.add_space(16.0);
                    if theme::button(ui, p, BtnKind::Primary, "Done").clicked() {
                        want_close = true;
                    }
                }
                _ => {
                    // Entry form (also the path while busy / after an error so the
                    // user can retry without losing the dialog).
                    match kind {
                        PivCredKind::ChangePin => {
                            let mut old_rev = self
                                .secret_reveal
                                .get("piv-pin-old")
                                .copied()
                                .unwrap_or(false);
                            let mut new_rev = self
                                .secret_reveal
                                .get("piv-pin-new")
                                .copied()
                                .unwrap_or(false);
                            let mut confirm_rev = self
                                .secret_reveal
                                .get("piv-pin-confirm")
                                .copied()
                                .unwrap_or(false);
                            // Sized to "Confirm new PIN", the widest of this
                            // dialog's three labels, so all three fields'
                            // left edges line up (see `label_text_width`).
                            let label_w = label_text_width(ui.ctx(), "Confirm new PIN");
                            piv_pin_field(
                                ui,
                                p,
                                "Current PIN",
                                &mut self.piv.pin_old,
                                &mut old_rev,
                                label_w,
                            );
                            piv_pin_field(
                                ui,
                                p,
                                "New PIN",
                                &mut self.piv.pin_new,
                                &mut new_rev,
                                label_w,
                            );
                            piv_pin_field(
                                ui,
                                p,
                                "Confirm new PIN",
                                &mut self.piv.pin_confirm,
                                &mut confirm_rev,
                                label_w,
                            );
                            self.secret_reveal.insert("piv-pin-old", old_rev);
                            self.secret_reveal.insert("piv-pin-new", new_rev);
                            self.secret_reveal.insert("piv-pin-confirm", confirm_rev);
                            card_note(ui, p, "6\u{2013}8 characters.");
                        }
                        PivCredKind::ChangePuk => {
                            let mut old_rev = self
                                .secret_reveal
                                .get("piv-puk-old")
                                .copied()
                                .unwrap_or(false);
                            let mut new_rev = self
                                .secret_reveal
                                .get("piv-puk-new")
                                .copied()
                                .unwrap_or(false);
                            let mut confirm_rev = self
                                .secret_reveal
                                .get("piv-puk-confirm")
                                .copied()
                                .unwrap_or(false);
                            // Sized to "Confirm new PUK" — same rationale as
                            // `ChangePin` above.
                            let label_w = label_text_width(ui.ctx(), "Confirm new PUK");
                            piv_pin_field(
                                ui,
                                p,
                                "Current PUK",
                                &mut self.piv.puk_old,
                                &mut old_rev,
                                label_w,
                            );
                            piv_pin_field(
                                ui,
                                p,
                                "New PUK",
                                &mut self.piv.puk_new,
                                &mut new_rev,
                                label_w,
                            );
                            piv_pin_field(
                                ui,
                                p,
                                "Confirm new PUK",
                                &mut self.piv.puk_confirm,
                                &mut confirm_rev,
                                label_w,
                            );
                            self.secret_reveal.insert("piv-puk-old", old_rev);
                            self.secret_reveal.insert("piv-puk-new", new_rev);
                            self.secret_reveal.insert("piv-puk-confirm", confirm_rev);
                            card_note(ui, p, "8 characters.");
                        }
                        PivCredKind::UnblockPin => {
                            let mut puk_rev = self
                                .secret_reveal
                                .get("piv-unblock-puk")
                                .copied()
                                .unwrap_or(false);
                            let mut new_pin_rev = self
                                .secret_reveal
                                .get("piv-unblock-new-pin")
                                .copied()
                                .unwrap_or(false);
                            piv_pin_field(
                                ui,
                                p,
                                "PUK",
                                &mut self.piv.unblock_puk,
                                &mut puk_rev,
                                96.0,
                            );
                            piv_pin_field(
                                ui,
                                p,
                                "New PIN",
                                &mut self.piv.unblock_new_pin,
                                &mut new_pin_rev,
                                96.0,
                            );
                            self.secret_reveal.insert("piv-unblock-puk", puk_rev);
                            self.secret_reveal
                                .insert("piv-unblock-new-pin", new_pin_rev);
                            card_note(ui, p, "Recovers a blocked PIN without wiping any keys.");
                        }
                        // Management-key-gated flows: only the *secrets* live here;
                        // their non-secret parameters stay inline in the pane.
                        PivCredKind::GenerateKey => {
                            // Generating into an occupied slot silently destroys
                            // the existing private key (irreversible). Warn in
                            // red before the auth field, mirroring the delete
                            // cards; the submit button is relabelled below.
                            if let Some(warning) = piv_replace_warning(
                                selected_occupancy,
                                &self.piv.selected_slot.to_slot().label(),
                            ) {
                                ui.colored_label(
                                    p.err,
                                    egui::RichText::new(warning).font(theme::f_sb(12.5)),
                                );
                                ui.add_space(6.0);
                            }
                            self.piv_modal_mgmt_field(ui, p, kind);
                            card_note(ui, p, "Authorizes overwriting the slot with a fresh key.");
                            ui.add_space(8.0);

                            // PIN/touch policy (tags 0xAA/0xAB on GENERATE
                            // ASYMMETRIC KEYPAIR) are Yubico extensions, not SP
                            // 800-73-4 — gated the same three-way way
                            // (`keyroost_piv::compat`) Move/Delete key are
                            // elsewhere in this pane, just resolved locally
                            // here since this modal doesn't share those rows'
                            // gate locals. `default` needs neither extension
                            // and is unaffected either way.
                            use keyroost_piv::compat::{FeatureGate, PivExtension};
                            let (piv_fp, piv_ver, piv_fw_ver) = self.piv.status.as_ref().map_or(
                                (
                                    keyroost_piv::fingerprint::AppletFingerprint::Generic,
                                    None,
                                    None,
                                ),
                                |s| {
                                    (
                                        s.applet_fingerprint,
                                        s.version.as_deref(),
                                        s.version_firmware.as_deref(),
                                    )
                                },
                            );
                            let pin_policy_gate = self.piv_gate(
                                PivExtension::SlotPinPolicy,
                                piv_fp,
                                piv_ver,
                                piv_fw_ver,
                            );
                            let touch_policy_gate = self.piv_gate(
                                PivExtension::SlotTouchPolicy,
                                piv_fp,
                                piv_ver,
                                piv_fw_ver,
                            );
                            // Narrower than the two gates above: a device can
                            // support the extension in general yet reject one
                            // specific value (e.g. YubiKey firmware 4.0-4.2
                            // supports touch policy but not `cached`).
                            let policy_quirks =
                                keyroost_piv::compat::resolve_quirks(piv_fp, piv_ver, piv_fw_ver);
                            let pin_once_blocked = policy_quirks.contains(
                                &keyroost_piv::compat::PivQuirk::SlotPinPolicyOnceNotSupported,
                            );
                            let touch_cached_blocked = policy_quirks.contains(
                                &keyroost_piv::compat::PivQuirk::SlotTouchPolicyCachedNotSupported,
                            );
                            let pin_policy_unverified_hint = format!(
                                "{} {}",
                                PivExtension::SlotPinPolicy.requirement(),
                                FeatureGate::UNVERIFIED_SUFFIX
                            );
                            let pin_policy_blocked_hint = format!(
                                "{} {}",
                                PivExtension::SlotPinPolicy.requirement(),
                                FeatureGate::INCOMPATIBLE_SUFFIX
                            );
                            let touch_policy_unverified_hint = format!(
                                "{} {}",
                                PivExtension::SlotTouchPolicy.requirement(),
                                FeatureGate::UNVERIFIED_SUFFIX
                            );
                            let touch_policy_blocked_hint = format!(
                                "{} {}",
                                PivExtension::SlotTouchPolicy.requirement(),
                                FeatureGate::INCOMPATIBLE_SUFFIX
                            );
                            // `Unsupported` blocks the whole combo (matching
                            // Move/Delete key's own treatment) rather than
                            // just the one value the quirks above narrow —
                            // there's nothing to offer once the extension
                            // itself is known absent, so force the selection
                            // back to `default` rather than leave a stale
                            // non-default value the combo can no longer show
                            // as selectable.
                            if matches!(pin_policy_gate, FeatureGate::Unsupported) {
                                self.piv.gen_pin_policy = keyroost_piv::PinPolicy::Default;
                            }
                            if matches!(touch_policy_gate, FeatureGate::Unsupported) {
                                self.piv.gen_touch_policy = keyroost_piv::TouchPolicy::Default;
                            }
                            let pin_policy_options: Vec<keyroost_piv::PinPolicy> =
                                keyroost_piv::PinPolicy::ALL
                                    .iter()
                                    .copied()
                                    .filter(|&opt| {
                                        !(pin_once_blocked && opt == keyroost_piv::PinPolicy::Once)
                                    })
                                    .collect();
                            let touch_policy_options: Vec<keyroost_piv::TouchPolicy> =
                                keyroost_piv::TouchPolicy::ALL
                                    .iter()
                                    .copied()
                                    .filter(|&opt| {
                                        !(touch_cached_blocked
                                            && opt == keyroost_piv::TouchPolicy::Cached)
                                    })
                                    .collect();

                            ui.horizontal(|ui| {
                                ui.label(
                                    egui::RichText::new("Pin Policy")
                                        .font(theme::f_reg(13.0))
                                        .color(p.txt2),
                                );
                                if matches!(pin_policy_gate, FeatureGate::Unverified) {
                                    ui.add_space(4.0);
                                    theme::warn_marker(ui, p)
                                        .on_hover_text(pin_policy_unverified_hint.as_str());
                                }
                                ui.add_space(8.0);
                                ui.add_enabled_ui(
                                    !matches!(pin_policy_gate, FeatureGate::Unsupported),
                                    |ui| {
                                        piv_policy_combo(
                                            ui,
                                            "piv-gen-pin-policy",
                                            &mut self.piv.gen_pin_policy,
                                            &pin_policy_options,
                                        );
                                    },
                                )
                                .response
                                .on_disabled_hover_text(pin_policy_blocked_hint.as_str());
                            });
                            ui.add_space(4.0);
                            ui.horizontal(|ui| {
                                ui.label(
                                    egui::RichText::new("Touch Policy")
                                        .font(theme::f_reg(13.0))
                                        .color(p.txt2),
                                );
                                if matches!(touch_policy_gate, FeatureGate::Unverified) {
                                    ui.add_space(4.0);
                                    theme::warn_marker(ui, p)
                                        .on_hover_text(touch_policy_unverified_hint.as_str());
                                }
                                ui.add_space(8.0);
                                ui.add_enabled_ui(
                                    !matches!(touch_policy_gate, FeatureGate::Unsupported),
                                    |ui| {
                                        piv_policy_combo(
                                            ui,
                                            "piv-gen-touch-policy",
                                            &mut self.piv.gen_touch_policy,
                                            &touch_policy_options,
                                        );
                                    },
                                )
                                .response
                                .on_disabled_hover_text(touch_policy_blocked_hint.as_str());
                            });
                            if piv_policy_caveat_hint_needed(pin_policy_gate, touch_policy_gate) {
                                card_note(
                                    ui,
                                    p,
                                    "Policy other than `default` requires YubiKey or compatible \
                                     token.",
                                );
                            }
                        }
                        PivCredKind::ImportCert => {
                            card_note(ui, p, &format!("Reading {}", self.piv.cert_path));
                            self.piv_modal_mgmt_field(ui, p, kind);
                            // Same label column as the management-key row
                            // (ImportCert uses the default 96px box).
                            self.piv_modal_compression_field(ui, p, 96.0);
                            // Importing only replaces the public certificate
                            // object (no key loss) — a lighter note, not a red
                            // warning.
                            if selected_occupied {
                                let slot = self.piv.selected_slot.to_slot().label();
                                card_note(
                                    ui,
                                    p,
                                    &format!("This replaces the certificate currently in {slot}."),
                                );
                            }
                            card_note(ui, p, "Authorizes writing the certificate to the slot.");
                        }
                        PivCredKind::SelfSign => {
                            self.piv_modal_mgmt_field(ui, p, kind);
                            let mut sign_pin_rev = self
                                .secret_reveal
                                .get("piv-sign-pin")
                                .copied()
                                .unwrap_or(false);
                            // Matches `piv_modal_mgmt_field`'s own label
                            // column above, so the two fields' left edges
                            // line up.
                            piv_pin_field(
                                ui,
                                p,
                                "PIN",
                                &mut self.piv.sign_pin,
                                &mut sign_pin_rev,
                                chuid_label_width(ui.ctx()),
                            );
                            self.secret_reveal.insert("piv-sign-pin", sign_pin_rev);
                            self.piv_modal_compression_field(ui, p, chuid_label_width(ui.ctx()));
                            card_note(
                                ui,
                                p,
                                if self.piv.mgmt_auth_mode == PivMgmtAuthMode::Pin {
                                    "The PIN unlocks management and authorizes the \
                                     on-card signature."
                                } else {
                                    "Management key authorizes the import; the PIN authorizes \
                                     the on-card signature."
                                },
                            );
                        }
                        PivCredKind::RequestCsr => {
                            card_note(ui, p, &format!("Saving to {}", self.piv.csr_path));
                            let mut sign_pin_rev = self
                                .secret_reveal
                                .get("piv-sign-pin")
                                .copied()
                                .unwrap_or(false);
                            piv_pin_field(
                                ui,
                                p,
                                "PIN",
                                &mut self.piv.sign_pin,
                                &mut sign_pin_rev,
                                96.0,
                            );
                            self.secret_reveal.insert("piv-sign-pin", sign_pin_rev);
                            card_note(ui, p, "The PIN authorizes the on-card signature.");
                        }
                        PivCredKind::SelfTest => {
                            let mut sign_pin_rev = self
                                .secret_reveal
                                .get("piv-sign-pin")
                                .copied()
                                .unwrap_or(false);
                            piv_pin_field(
                                ui,
                                p,
                                "PIN (optional)",
                                &mut self.piv.sign_pin,
                                &mut sign_pin_rev,
                                96.0,
                            );
                            self.secret_reveal.insert("piv-sign-pin", sign_pin_rev);
                            card_note(
                                ui,
                                p,
                                "PIN optional; device state and policy may still require it.",
                            );
                            card_note(
                                ui,
                                p,
                                "Runs every self-test the slot's key supports (decrypt / \
                                 key-agree / sign) and verifies each result against the \
                                 certificate's public key. Nothing on the card changes.",
                            );
                        }
                        PivCredKind::SetRetries => {
                            self.piv_modal_mgmt_field(ui, p, kind);
                            let mut retries_pin_rev = self
                                .secret_reveal
                                .get("piv-retries-pin")
                                .copied()
                                .unwrap_or(false);
                            // Matches `piv_modal_mgmt_field`'s own label
                            // column above, so the two fields' left edges
                            // line up.
                            piv_pin_field(
                                ui,
                                p,
                                "Current PIN",
                                &mut self.piv.retries_pin_auth,
                                &mut retries_pin_rev,
                                chuid_label_width(ui.ctx()),
                            );
                            self.secret_reveal
                                .insert("piv-retries-pin", retries_pin_rev);
                            card_note(
                                ui,
                                p,
                                if self.piv.mgmt_auth_mode == PivMgmtAuthMode::Pin {
                                    "Resets PIN and PUK to factory defaults; the PIN both \
                                     unlocks management and authorizes the reset."
                                } else {
                                    "Resets PIN and PUK to factory defaults; needs the \
                                     management key and the current PIN."
                                },
                            );
                        }
                        PivCredKind::ChangeMgmtKey => {
                            self.piv_modal_mgmt_field(ui, p, kind);
                            // Shared with `piv_modal_mgmt_field`'s own
                            // "Management key"/"PIN" row above (see its
                            // comment) so this row's field starts at the same
                            // x. The "Generate random key & Copy" link and "Allow
                            // PIN unlock" checkbox below it are centered
                            // instead, not lined up under this column — see
                            // their own comments.
                            let label_w = chuid_label_width(ui.ctx());
                            match self.piv.new_mgmt_alg.to_alg() {
                                Some(alg) => {
                                    let new_key_hint = format!("hex ({} chars)", alg.key_len() * 2);
                                    let mut new_key_rev = self
                                        .secret_reveal
                                        .get("piv-new-mgmt-key")
                                        .copied()
                                        .unwrap_or(false);
                                    piv_secret_field(
                                        ui,
                                        p,
                                        "New key",
                                        &mut self.piv.new_mgmt_key_input,
                                        &mut new_key_rev,
                                        &new_key_hint,
                                        label_w,
                                        300.0,
                                    );
                                    self.secret_reveal.insert("piv-new-mgmt-key", new_key_rev);
                                    ui.add_space(2.0);
                                    // Centered rather than lined up under the
                                    // label column like the rows above/below
                                    // it — this link and the "Allow PIN
                                    // unlock" checkbox beneath it read as a
                                    // pair of standalone actions, not a
                                    // labeled field, so they share the
                                    // modal's horizontal center instead.
                                    ui.vertical_centered(|ui| {
                                        // Plain accent-colored `Label` +
                                        // `Sense::click()`, not `ui.link()` —
                                        // same pattern as the zoom "Reset"
                                        // link above: a pointing-hand cursor
                                        // on hover, but no underline.
                                        if ui
                                            .add(
                                                egui::Label::new(
                                                    egui::RichText::new(
                                                        "Generate random key & Copy",
                                                    )
                                                    .font(theme::f_sb(13.0))
                                                    .color(p.accent),
                                                )
                                                .sense(egui::Sense::click()),
                                            )
                                            .on_hover_cursor(egui::CursorIcon::PointingHand)
                                            .on_hover_text(
                                                "Fill in a fresh random key of the selected \
                                                 length and copy it to the clipboard.",
                                            )
                                            .clicked()
                                        {
                                            self.piv_generate_random_mgmt_key(ui.ctx(), alg);
                                        }
                                    });
                                    // "Allow PIN unlock": whether the new key
                                    // is also stored PIN-protected (Yubico's
                                    // `PivExtension::PinManagementAuth`) —
                                    // gated the same three-way way the
                                    // GenerateKey modal's own PIN/touch
                                    // policy rows are, resolved locally here
                                    // since this modal doesn't share the
                                    // status card's gate locals. HID
                                    // Crescendo unlocks management off the
                                    // PIN already, with no key material to
                                    // store — forced on and disabled there
                                    // instead of gated, same "nothing to
                                    // toggle" treatment
                                    // `set_management_key_pin_protected`
                                    // itself gives that fingerprint (it skips
                                    // the maintenance step outright).
                                    use keyroost_piv::compat::{FeatureGate, PivExtension};
                                    let is_hid_crescendo = self.piv.status.as_ref().is_some_and(|s| {
                                        matches!(
                                            s.applet_fingerprint,
                                            keyroost_piv::fingerprint::AppletFingerprint::HidCrescendo(_)
                                        )
                                    });
                                    ui.add_space(4.0);
                                    // Centered under the link above, not under
                                    // the field label column — see that row's
                                    // comment.
                                    if is_hid_crescendo {
                                        self.piv.new_mgmt_allow_pin_unlock = true;
                                        ui.vertical_centered(|ui| {
                                            ui.add_enabled_ui(false, |ui| {
                                                ui.checkbox(
                                                    &mut self.piv.new_mgmt_allow_pin_unlock,
                                                    "Allow PIN unlock",
                                                );
                                            });
                                        });
                                    } else {
                                        let (piv_fp, piv_ver, piv_fw_ver) =
                                            self.piv.status.as_ref().map_or(
                                                (
                                                    keyroost_piv::fingerprint::AppletFingerprint::Generic,
                                                    None,
                                                    None,
                                                ),
                                                |s| {
                                                    (
                                                        s.applet_fingerprint,
                                                        s.version.as_deref(),
                                                        s.version_firmware.as_deref(),
                                                    )
                                                },
                                            );
                                        let pin_unlock_gate = self.piv_gate(
                                            PivExtension::PinManagementAuth,
                                            piv_fp,
                                            piv_ver,
                                            piv_fw_ver,
                                        );
                                        let pin_unlock_blocked_hint = format!(
                                            "{} {}",
                                            PivExtension::PinManagementAuth.requirement(),
                                            FeatureGate::INCOMPATIBLE_SUFFIX
                                        );
                                        // `ui.vertical_centered` only centers
                                        // a row correctly when the row is a
                                        // single widget claiming its own
                                        // natural size — `ui.horizontal`
                                        // always pre-claims the *full*
                                        // available width up front (so
                                        // multi-widget centering has nothing
                                        // left to center), which is exactly
                                        // why the checkbox-alone branches
                                        // above and below this one center
                                        // fine while this one (checkbox +
                                        // conditional warning icon, two
                                        // widgets on one line) didn't. Measure
                                        // the row's actual rendered width and
                                        // pad it into the middle by hand
                                        // instead; the padding is one frame
                                        // stale right after the icon
                                        // appears/disappears, which is
                                        // imperceptible for a row that only
                                        // changes on a device switch.
                                        let row_w_id =
                                            egui::Id::new("piv-allow-pin-unlock-row-width");
                                        let last_row_w =
                                            ui.data(|d| d.get_temp::<f32>(row_w_id)).unwrap_or(0.0);
                                        ui.horizontal(|ui| {
                                            ui.add_space(
                                                ((ui.available_width() - last_row_w) / 2.0)
                                                    .max(0.0),
                                            );
                                            let row = ui.horizontal(|ui| {
                                                ui.add_enabled_ui(
                                                    !matches!(
                                                        pin_unlock_gate,
                                                        FeatureGate::Unsupported
                                                    ),
                                                    |ui| {
                                                        ui.checkbox(
                                                            &mut self.piv.new_mgmt_allow_pin_unlock,
                                                            "Allow PIN unlock",
                                                        );
                                                    },
                                                )
                                                .response
                                                .on_disabled_hover_text(
                                                    pin_unlock_blocked_hint.as_str(),
                                                );
                                                if matches!(
                                                    pin_unlock_gate,
                                                    FeatureGate::Unverified
                                                ) {
                                                    ui.add_space(4.0);
                                                    theme::warn_marker(ui, p).on_hover_text(
                                                        format!(
                                                            "{} {}",
                                                            PivExtension::PinManagementAuth
                                                                .requirement(),
                                                            FeatureGate::UNVERIFIED_SUFFIX
                                                        )
                                                        .as_str(),
                                                    );
                                                }
                                            });
                                            ui.data_mut(|d| {
                                                d.insert_temp(row_w_id, row.response.rect.width())
                                            });
                                        });
                                    }
                                    card_note(
                                        ui,
                                        p,
                                        if self.piv.mgmt_auth_mode == PivMgmtAuthMode::Pin {
                                            "Enter the PIN, then the new key. Select \"Allow \
                                             PIN Unlock\" to also unlock management with the \
                                             PIN, in addition to the management key."
                                        } else {
                                            "Enter the current key, then the new key. Select \
                                             \"Allow PIN unlock\" to also unlock management \
                                             with the PIN, in addition to the management key."
                                        },
                                    );
                                }
                                // "Delete" (HID Crescendo only, see
                                // `PivMgmtAlgSel`): no new-key field at all —
                                // an empty key is sent, deleting XAUTH key 1
                                // instead of replacing it.
                                None => {
                                    card_note(
                                        ui,
                                        p,
                                        if self.piv.mgmt_auth_mode == PivMgmtAuthMode::Pin {
                                            "Enter the PIN to unlock. This deletes the \
                                             management key rather than replacing it, \
                                             leaving the PIN as the only remaining \
                                             authentication mechanism."
                                        } else {
                                            "Enter the current key to unlock. This deletes \
                                             the management key rather than replacing it, \
                                             leaving the PIN as the only remaining \
                                             authentication mechanism."
                                        },
                                    );
                                }
                            }
                        }
                        PivCredKind::DeleteCert => {
                            let slot = self.piv.selected_slot.label();
                            ui.colored_label(
                                p.err,
                                egui::RichText::new(format!(
                                    "Removes the certificate in {slot}. The private key in \
                                     the slot remains. This cannot be undone."
                                ))
                                .font(theme::f_sb(12.5)),
                            );
                            ui.add_space(6.0);
                            self.piv_modal_mgmt_field(ui, p, kind);
                            card_note(ui, p, "The management key authorizes the deletion.");
                        }
                        PivCredKind::DeleteKey => {
                            let slot = self.piv.selected_slot.label();
                            ui.colored_label(
                                p.err,
                                egui::RichText::new(format!(
                                    "Permanently erases the private key in {slot}. This \
                                     cannot be undone."
                                ))
                                .font(theme::f_sb(12.5)),
                            );
                            ui.add_space(6.0);
                            self.piv_modal_mgmt_field(ui, p, kind);
                            card_note(
                                ui,
                                p,
                                "The management key authorizes the deletion. Needs \
                                 YubiKey 5.7+ or compatible third party device.",
                            );
                        }
                        PivCredKind::MoveKey => {
                            ui.label(
                                egui::RichText::new(format!(
                                    "Move the key in {} to another slot.",
                                    move_src.label()
                                ))
                                .font(theme::f_reg(12.5))
                                .color(p.txt2),
                            );
                            ui.add_space(6.0);
                            ui.horizontal(|ui| {
                                ui.label(
                                    egui::RichText::new("Destination")
                                        .font(theme::f_reg(13.0))
                                        .color(p.txt2),
                                );
                                ui.add_space(8.0);
                                let sel_text = self
                                    .piv
                                    .move_dest
                                    .map(|d| d.label())
                                    .unwrap_or_else(|| "Choose a slot\u{2026}".to_string());
                                egui::ComboBox::from_id_salt("piv-move-dest")
                                    .selected_text(sel_text)
                                    .show_ui(ui, |ui| {
                                        for dest in &move_dests {
                                            stable_selectable_value(
                                                ui,
                                                &mut self.piv.move_dest,
                                                Some(*dest),
                                                dest.label(),
                                            );
                                        }
                                    });
                            });
                            ui.add_space(6.0);
                            if let Some(dest) = self.piv.move_dest {
                                let occupancy = self.piv_occupancy(dest);
                                if let Some(warning) =
                                    piv_move_dest_warning(occupancy, &dest.label())
                                {
                                    ui.colored_label(
                                        p.err,
                                        egui::RichText::new(warning).font(theme::f_sb(12.5)),
                                    );
                                    ui.add_space(6.0);
                                }
                                if let Some(note) = piv_move_dest_note(occupancy, &dest.label()) {
                                    card_note(ui, p, &note);
                                    ui.add_space(6.0);
                                }
                            }
                            self.piv_modal_mgmt_field(ui, p, kind);
                            card_note(
                                ui,
                                p,
                                "Moves only the key; the certificate stays in the \
                                 source slot. Needs YubiKey 5.7+ or compatible third \
                                 party device.",
                            );
                        }
                        PivCredKind::NewChuid => {
                            self.piv_modal_mgmt_field(ui, p, kind);
                            ui.horizontal(|ui| {
                                ui.add_sized(
                                    [chuid_label_width(ui.ctx()), 22.0],
                                    egui::Label::new(
                                        egui::RichText::new("GUID")
                                            .font(theme::f_reg(13.0))
                                            .color(p.txt2),
                                    ),
                                );
                                ui.add(
                                    egui::TextEdit::singleline(&mut self.piv.chuid_guid)
                                        .hint_text("hex, dashes optional")
                                        .desired_width(chuid_guid_field_width(ui.ctx())),
                                );
                                ui.add_space(6.0);
                                let (rrect, rresp) = ui.allocate_exact_size(
                                    egui::vec2(22.0, 22.0),
                                    egui::Sense::click(),
                                );
                                paint_refresh_icon(ui, rrect.center(), 7.0, p.txt2);
                                if rresp
                                    .on_hover_text("Generate a new random GUID")
                                    .on_hover_cursor(egui::CursorIcon::PointingHand)
                                    .clicked()
                                {
                                    self.piv_refresh_chuid_guid();
                                }
                            });
                            ui.add_space(4.0);
                            ui.horizontal(|ui| {
                                // Same fixed label column the "GUID" row above
                                // uses, so the years field's left edge lines up
                                // with the GUID input's.
                                ui.add_sized(
                                    [chuid_label_width(ui.ctx()), 22.0],
                                    egui::Label::new(
                                        egui::RichText::new("Valid for")
                                            .font(theme::f_reg(13.0))
                                            .color(p.txt2),
                                    ),
                                );
                                piv_valid_for_fields(
                                    ui,
                                    unix_now(),
                                    &mut self.piv.chuid_valid_years,
                                    &mut self.piv.chuid_valid_months,
                                    &mut self.piv.chuid_valid_days,
                                );
                            });
                            card_note(
                                ui,
                                p,
                                "Writes a fresh card ID. Windows' generic smartcard \
                                 minidriver caches PIV data by the CHUID's GUID, so this \
                                 is what makes it notice a key or certificate actually \
                                 changed. The expiration date is informational only — it \
                                 has no technical implications.",
                            );
                        }
                    }

                    // Inline error/result line: the new==confirm mismatch, then
                    // the op's error (kept open for a retry).
                    if let Some(msg) = mismatch {
                        ui.add_space(6.0);
                        ui.colored_label(p.err, msg);
                    } else if let Some(Err(e)) = &result {
                        ui.add_space(6.0);
                        ui.colored_label(p.err, e);
                    }

                    ui.add_space(16.0);
                    ui.horizontal(|ui| {
                        if busy {
                            ui.add(egui::Spinner::new());
                            ui.label(
                                egui::RichText::new(busy_text.as_str())
                                    .font(theme::f_reg(12.5))
                                    .color(p.txt2),
                            );
                        } else {
                            // Relabel Generate as a conscious "Overwrite key"
                            // when the target slot is occupied; the op itself is
                            // unchanged.
                            let submit = if kind == PivCredKind::GenerateKey && selected_occupied {
                                "Overwrite key"
                            } else {
                                kind.submit_label()
                            };
                            if theme::button(ui, p, BtnKind::Primary, submit).clicked()
                                && mismatch.is_none()
                            {
                                want_submit = true;
                            }
                            ui.add_space(8.0);
                            if theme::button(ui, p, BtnKind::Default, "Cancel").clicked() {
                                want_close = true;
                            }
                        }
                    });
                }
            }
        });

        // ✕ / Esc dismiss too, but never yank the dialog out from under a
        // running op (mirrors the enroll dialog's busy handling).
        if (closed || want_close) && !busy {
            self.piv_cred_modal_close();
            return;
        }
        if want_submit && !busy {
            // Mark busy first so the modal shows the spinner this frame; the op
            // writes the result back via `apply_piv_cred_result`. If the worker
            // is busy (spawn_job returns false implicitly), the op simply no-ops
            // and the next click retries.
            if let Some(m) = self.piv.cred_modal.as_mut() {
                m.busy = true;
                m.result = None;
            }
            // Clear any stale pane error so a client-side guard tripping during
            // this dispatch is distinguishable from a previous failure.
            self.piv.error = None;
            match kind {
                PivCredKind::ChangePin => self.piv_change_pin(),
                PivCredKind::ChangePuk => self.piv_change_puk(),
                PivCredKind::UnblockPin => self.piv_unblock_pin(),
                PivCredKind::GenerateKey => self.piv_generate_key(),
                PivCredKind::ImportCert => self.piv_import_cert(),
                PivCredKind::SelfSign => self.piv_self_sign(),
                PivCredKind::RequestCsr => self.piv_request_csr(),
                PivCredKind::SetRetries => self.piv_set_retries(),
                PivCredKind::ChangeMgmtKey => self.piv_change_management_key(),
                PivCredKind::DeleteCert => self.piv_delete_cert(),
                PivCredKind::DeleteKey => self.piv_delete_key(),
                PivCredKind::MoveKey => self.piv_move_key(),
                PivCredKind::NewChuid => self.piv_new_chuid(),
                PivCredKind::SelfTest => self.piv_self_test(),
            }
            // If the op didn't actually queue, unstick the modal. This happens
            // either because the worker was busy (no error set — just retry on
            // the next click) or because a client-side guard rejected the input
            // (bad hex, wrong new-key length, empty subject/path) and stored the
            // reason in `piv.error` — surface that reason in the modal result so
            // it shows in the dialog rather than scrolling off in the pane.
            if !self.busy() {
                let guard_err = self.piv.error.clone();
                if let Some(m) = self.piv.cred_modal.as_mut() {
                    m.busy = false;
                    if let Some(e) = guard_err {
                        m.result = Some(Err(e));
                    }
                }
            }
        }
    }

    /// Close the PIV credential modal, wiping every PIN/PUK field it could have
    /// touched (cheap to over-wipe; all are secrets).
    fn piv_cred_modal_close(&mut self) {
        wipe(&mut self.piv.pin_old);
        wipe(&mut self.piv.pin_new);
        wipe(&mut self.piv.pin_confirm);
        wipe(&mut self.piv.puk_old);
        wipe(&mut self.piv.puk_new);
        wipe(&mut self.piv.puk_confirm);
        wipe(&mut self.piv.unblock_puk);
        wipe(&mut self.piv.unblock_new_pin);
        // Management-key-gated flows also route their secrets through this modal.
        wipe(&mut self.piv.mgmt_key_input);
        wipe(&mut self.piv.new_mgmt_key_input);
        wipe(&mut self.piv.sign_pin);
        wipe(&mut self.piv.retries_pin_auth);
        self.piv.mgmt_auth_mode = PivMgmtAuthMode::default();
        self.piv.new_mgmt_allow_pin_unlock = false;
        self.piv.move_dest = None;
        self.piv.gen_pin_policy = keyroost_piv::PinPolicy::Default;
        self.piv.gen_touch_policy = keyroost_piv::TouchPolicy::Default;
        self.piv.cert_compression = PivCertCompressionSel::Auto;
        self.piv.cred_modal = None;
    }

    /// Render the admin-PIN (PW3) collector inside the OpenPGP modal, but only
    /// for the flows that need it (`OpenPgpCredKind::needs_admin_pin`). Shows a
    /// "Use default admin PIN (PW3)" toggle (the factory default `12345678`,
    /// common during bring-up) and, when it's off, the masked PIN field. When the
    /// toggle is on the field is hidden and the op reads the default via
    /// `openpgp_admin_pin_value`.
    fn openpgp_modal_admin_field(&mut self, ui: &mut egui::Ui, p: &Palette, kind: OpenPgpCredKind) {
        if !kind.needs_admin_pin() {
            return;
        }
        ui.checkbox(
            &mut self.openpgp.use_default_admin,
            "Use default admin PIN (PW3)",
        );
        if !self.openpgp.use_default_admin {
            pin_field(ui, p, "Admin PIN", &mut self.openpgp.admin_pin);
        }
    }

    /// OpenPGP credential-entry modal: drives the PIN flows (Change user PIN /
    /// Change admin PIN / Unblock user PIN) *and* the admin-PIN (PW3)-gated writes
    /// (set cardholder name / URL, generate / import key) plus the factory reset,
    /// inside the shared `modal_window` chrome, so the secret fields *and* the
    /// op's result stay centered on-screen rather than scrolling off (issue #31).
    ///
    /// The secret fields live in `OpenPgpState` (rendered here, not inline in the
    /// pane); the inline pane keeps the *non-secret* parameters (name, URL, slot,
    /// file path). The modal state (`OpenPgpState::cred_modal`) tracks the flow,
    /// an in-flight flag, and the op result. On Submit it runs the existing op,
    /// which writes the outcome back into the modal via `apply_openpgp_cred_result`.
    /// Rich, non-secret results (e.g. the new key fingerprint) still surface in
    /// the pane — the modal only shows a generic success line. Cancel / ✕ / Esc —
    /// and a successful Done — wipe the secret fields.
    fn render_openpgp_cred_modal(&mut self, ctx: &egui::Context, p: &Palette) {
        let Some(kind) = self.openpgp.cred_modal.as_ref().map(|m| m.kind) else {
            return;
        };
        let busy = self.openpgp.cred_modal.as_ref().is_some_and(|m| m.busy);
        let result = self
            .openpgp
            .cred_modal
            .as_ref()
            .and_then(|m| m.result.clone());

        let mut want_submit = false;
        let mut want_close = false;
        // Inline new==confirm guard, mirroring the op-level backstop (currently
        // never fires — the OpenPGP PIN forms have no confirm field — but kept
        // for shape parity with the PIV modal).
        let mismatch = openpgp_cred_mismatch(&self.openpgp, kind);

        let closed = Self::modal_window(ctx, p, "openpgp_cred", kind.title(), 300.0, |ui| {
            match &result {
                Some(Ok(())) => {
                    // Success: confirmation + a single Done that dismisses.
                    ui.label(
                        egui::RichText::new(format!("\u{2713} {}", kind.success()))
                            .font(theme::f_sb(13.0))
                            .color(p.ok),
                    );
                    ui.add_space(16.0);
                    if theme::button(ui, p, BtnKind::Primary, "Done").clicked() {
                        want_close = true;
                    }
                }
                _ => {
                    // Entry form (also the path while busy / after an error so the
                    // user can retry without losing the dialog).
                    match kind {
                        OpenPgpCredKind::ChangeUserPin => {
                            pin_field(ui, p, "Current PIN", &mut self.openpgp.user_pin_old);
                            pin_field(ui, p, "New PIN", &mut self.openpgp.user_pin_new);
                            card_note(ui, p, "User PIN (PW1): 6\u{2013}127 characters.");
                        }
                        OpenPgpCredKind::ChangeAdminPin => {
                            pin_field(ui, p, "Current PIN", &mut self.openpgp.admin_pin_old);
                            pin_field(ui, p, "New PIN", &mut self.openpgp.admin_pin_new);
                            card_note(ui, p, "Admin PIN (PW3): 8\u{2013}127 characters.");
                        }
                        OpenPgpCredKind::UnblockUserPin => {
                            self.openpgp_modal_admin_field(ui, p, kind);
                            pin_field(ui, p, "New user PIN", &mut self.openpgp.unblock_new);
                            card_note(
                                ui,
                                p,
                                "Resets a blocked user PIN using the admin PIN (PW3).",
                            );
                        }
                        OpenPgpCredKind::SetName => {
                            self.openpgp_modal_admin_field(ui, p, kind);
                            card_note(ui, p, "Authorizes writing the cardholder name.");
                        }
                        OpenPgpCredKind::SetUrl => {
                            self.openpgp_modal_admin_field(ui, p, kind);
                            card_note(ui, p, "Authorizes writing the public-key URL.");
                        }
                        OpenPgpCredKind::GenerateKey => {
                            let crt = self.openpgp.selected_key.to_crt();
                            let choices =
                                OpenPgpKeyAlgSel::choices(self.openpgp.supported.as_ref(), crt);
                            ui.horizontal(|ui| {
                                ui.add_sized(
                                    [96.0, 22.0],
                                    egui::Label::new(
                                        egui::RichText::new("Algorithm")
                                            .font(theme::f_reg(13.0))
                                            .color(p.txt2),
                                    ),
                                );
                                openpgp_keyalg_combo(
                                    ui,
                                    "openpgp-gen-alg",
                                    &mut self.openpgp.gen_alg,
                                    &choices,
                                );
                            });
                            ui.add_space(4.0);
                            if self.openpgp.supported.is_none() {
                                card_note(
                                    ui,
                                    p,
                                    "This card does not list its algorithms; the card \
                                     rejects any it cannot do.",
                                );
                            }
                            self.openpgp_modal_admin_field(ui, p, kind);
                            card_note(
                                ui,
                                p,
                                "OVERWRITES the slot with a fresh on-card key (clearable \
                                 only by a full reset). May need a touch.",
                            );
                        }
                        OpenPgpCredKind::GenerateImportKey | OpenPgpCredKind::ImportKeyFile => {
                            self.openpgp_modal_admin_field(ui, p, kind);
                            card_note(
                                ui,
                                p,
                                "OVERWRITES the slot with the imported key (clearable only \
                                 by a full reset). May need a touch.",
                            );
                        }
                        OpenPgpCredKind::Reset => {
                            card_note(
                                ui,
                                p,
                                "Wipes ALL OpenPGP keys and restores default PINs. Works \
                                 even if the PINs are forgotten. No PIN needed.",
                            );
                        }
                    }

                    // Inline error/result line: the (currently inert) mismatch,
                    // then the op's error (kept open for a retry).
                    if let Some(msg) = mismatch {
                        ui.add_space(6.0);
                        ui.colored_label(p.err, msg);
                    } else if let Some(Err(e)) = &result {
                        ui.add_space(6.0);
                        ui.colored_label(p.err, e);
                    }

                    ui.add_space(16.0);
                    ui.horizontal(|ui| {
                        if busy {
                            ui.add(egui::Spinner::new());
                            ui.label(
                                egui::RichText::new(kind.busy_label())
                                    .font(theme::f_reg(12.5))
                                    .color(p.txt2),
                            );
                        } else {
                            let btn = if kind == OpenPgpCredKind::Reset {
                                BtnKind::Danger
                            } else {
                                BtnKind::Primary
                            };
                            if theme::button(ui, p, btn, kind.submit_label()).clicked()
                                && mismatch.is_none()
                            {
                                want_submit = true;
                            }
                            ui.add_space(8.0);
                            if theme::button(ui, p, BtnKind::Default, "Cancel").clicked() {
                                want_close = true;
                            }
                        }
                    });
                }
            }
        });

        // ✕ / Esc dismiss too, but never yank the dialog out from under a
        // running op (mirrors the PIV modal's busy handling).
        if (closed || want_close) && !busy {
            self.openpgp_cred_modal_close();
            return;
        }
        if want_submit && !busy {
            // The modal is bound to the device it opened for (KEY-013); a
            // stale one must close, not dispatch against the new selection.
            if !completion_still_valid(
                self.openpgp
                    .cred_modal
                    .as_ref()
                    .and_then(|m| m.device.as_ref()),
                self.selected_device.as_ref(),
            ) {
                self.openpgp_cred_modal_close();
                return;
            }
            // Mark busy first so the modal shows the spinner this frame; the op
            // writes the result back via `apply_openpgp_cred_result`.
            if let Some(m) = self.openpgp.cred_modal.as_mut() {
                m.busy = true;
                m.result = None;
            }
            self.openpgp.error = None;
            match kind {
                OpenPgpCredKind::ChangeUserPin => self.change_openpgp_user_pin(),
                OpenPgpCredKind::ChangeAdminPin => self.change_openpgp_admin_pin(),
                OpenPgpCredKind::UnblockUserPin => self.unblock_openpgp_user_pin(),
                OpenPgpCredKind::SetName => self.set_openpgp_name(),
                OpenPgpCredKind::SetUrl => self.set_openpgp_url(),
                OpenPgpCredKind::GenerateKey => {
                    self.generate_openpgp_key();
                }
                OpenPgpCredKind::GenerateImportKey => {
                    self.import_openpgp_key(ImportSource::Generate);
                }
                OpenPgpCredKind::ImportKeyFile => {
                    self.import_openpgp_key(ImportSource::FromFile);
                }
                OpenPgpCredKind::Reset => {
                    self.reset_openpgp();
                }
            }
            // If the op didn't actually queue, unstick the modal. Either the
            // worker was busy (no error set — retry on the next click) or a
            // client-side guard rejected the input and stored the reason in
            // `openpgp.error`; surface that in the modal so it shows in the
            // dialog rather than scrolling off in the pane.
            if !self.busy() {
                let guard_err = self.openpgp.error.clone();
                if let Some(m) = self.openpgp.cred_modal.as_mut() {
                    m.busy = false;
                    if let Some(e) = guard_err {
                        m.result = Some(Err(e));
                    }
                }
            }
        }
    }

    /// Close the OpenPGP credential modal, wiping every PIN field it could have
    /// touched (cheap to over-wipe; all are secrets) and clearing the
    /// use-default toggle.
    fn openpgp_cred_modal_close(&mut self) {
        self.openpgp.wipe_secrets();
        self.openpgp.cred_modal = None;
    }

    /// Authenticator / OATH tab — live codes with countdown rings + copy.
    fn cap_oath(&mut self, ui: &mut egui::Ui, p: &Palette) {
        // Auto-attempt a read once per selection (a hard error won't retry).
        if !self.oath_tried && !self.busy() && self.oath.error.is_none() && !self.oath.locked {
            self.oath_tried = true;
            self.load_oath_creds();
        }
        ui.horizontal(|ui| {
            ui.label(
                egui::RichText::new("Authenticator codes")
                    .font(theme::f_sb(14.5))
                    .color(p.txt),
            );
            ui.add_space(6.0);
            self.help_dot(ui, p, "oath");
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                if theme::button(ui, p, BtnKind::Primary, "+ Add credential").clicked() {
                    // Opens the centered "New credential" modal (rendered in the
                    // update loop alongside the other credential modals).
                    self.oath.add = OathAddDialog::opened();
                }
                ui.add_space(6.0);
                if theme::button(ui, p, BtnKind::Default, "Import file\u{2026}").clicked() {
                    if let Some(id) = self.selected_device.clone() {
                        self.import_pick_file(import_flow::Origin::View(import_flow::DestKey {
                            device: id,
                            store: import_flow::StoreKind::Oath,
                        }));
                    }
                }
                ui.add_space(6.0);
                if theme::button(ui, p, BtnKind::Default, "Refresh").clicked() {
                    self.load_oath_creds();
                }
            });
        });
        ui.add_space(12.0);
        if let Some(err) = &self.oath.error {
            ui.colored_label(p.err, err);
            ui.add_space(6.0);
        }
        if self.oath.locked {
            theme::card_frame(p).show(ui, |ui| {
                ui.label(
                    egui::RichText::new("This key's OATH applet is password-protected.")
                        .font(theme::f_reg(13.0))
                        .color(p.txt),
                );
                ui.add_space(8.0);
                ui.horizontal(|ui| {
                    let resp = ui.add_sized(
                        [220.0, 32.0],
                        egui::TextEdit::singleline(&mut self.oath.password_input)
                            .vertical_align(egui::Align::Center)
                            .password(true),
                    );
                    guard_secret_field(ui.ctx(), &resp);
                    let submit = theme::button(ui, p, BtnKind::Primary, "Unlock").clicked();
                    // Enter in the field submits too, matching the FIDO2 unlock card
                    // and the other inline credential fields in this redesign.
                    if submit
                        || (resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)))
                    {
                        self.load_oath_creds();
                    }
                });
            });
            // Forgotten the password? Reset is the documented recovery and
            // needs no password — it must stay reachable from the locked
            // view, not hide behind the unlock it exists to replace.
            ui.add_space(14.0);
            self.render_oath_reset_card(ui, p);
            return;
        }
        if !self.oath.loaded {
            ui.label(
                egui::RichText::new("Reading codes\u{2026}")
                    .font(theme::f_reg(13.0))
                    .color(p.txt3),
            );
            return;
        }
        if self.oath.skipped > 0 {
            // Partial listing: the card holds entries we couldn't decode. Shown
            // before (and instead of) "No authenticator codes" — a key whose
            // only credentials are undecodable is NOT empty.
            ui.label(
                egui::RichText::new(format!(
                    "\u{26A0} {} entr{} on this key could not be decoded and {} not shown.",
                    self.oath.skipped,
                    if self.oath.skipped == 1 { "y" } else { "ies" },
                    if self.oath.skipped == 1 { "is" } else { "are" },
                ))
                .font(theme::f_reg(13.0))
                .color(p.warn),
            );
            ui.add_space(4.0);
        }
        if self.oath.creds.is_empty() {
            if self.oath.skipped == 0 {
                ui.label(
                    egui::RichText::new("No authenticator codes on this key.")
                        .font(theme::f_reg(13.0))
                        .color(p.txt3),
                );
            }
            // An empty applet can still carry a password; keep the reset
            // reachable so it can be cleared.
            ui.add_space(14.0);
            self.render_oath_reset_card(ui, p);
            return;
        }

        let mut copy: Option<(String, String)> = None;
        let mut delete: Option<String> = None;
        let mut read: Option<String> = None;
        theme::card_frame(p).show(ui, |ui| {
            let n = self.oath.creds.len();
            for (i, row) in self.oath.creds.iter().enumerate() {
                let is_copied = self.copied.as_ref().is_some_and(|(nm, _)| nm == &row.name);
                let (c, d, r) = oath_row(ui, p, row, is_copied, true);
                if let Some(code) = c {
                    copy = Some((row.name.clone(), code));
                }
                if d {
                    delete = Some(row.name.clone());
                }
                if r {
                    read = Some(row.name.clone());
                }
                if i + 1 < n {
                    ui.add_space(5.0);
                    let y = ui.cursor().top();
                    ui.painter().hline(
                        ui.max_rect().x_range(),
                        y,
                        egui::Stroke::new(1.0, p.line_soft),
                    );
                    ui.add_space(5.0);
                }
            }
        });
        if let Some((name, code)) = copy {
            ui.ctx().copy_text(code.clone());
            self.copied = Some((name, now_secs_f64() + 1.2));
            self.clipboard_clear_at = Some((code, now_secs_f64() + 45.0));
        }
        if let Some(name) = delete {
            if let Some(dev) = self.selected_device.clone() {
                self.oath.confirm_delete = Some((dev, name));
            }
        }
        if let Some(name) = read {
            self.read_hotp_code(&name);
        }

        // Danger card at the bottom of the pane, mirroring the FIDO2 /
        // OpenPGP / PIV reset cards.
        ui.add_space(14.0);
        self.render_oath_reset_card(ui, p);
    }

    /// The destructive "Reset applet" card for the OATH pane (red stroke;
    /// arms the device-bound confirmation modal). Rendered at the bottom of
    /// the unlocked pane AND under the locked view's password prompt — the
    /// applet's RESET needs no password and is the documented recovery for a
    /// forgotten one, so it must never hide behind the unlock (the same
    /// principle as the standalone FIDO reset card, 0.7.6).
    fn render_oath_reset_card(&mut self, ui: &mut egui::Ui, p: &Palette) {
        let mut arm = false;
        theme::card_frame(p)
            .stroke(egui::Stroke::new(1.0, theme::tint(p.err, 90)))
            .show(ui, |ui| {
                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new("Reset applet")
                            .font(theme::f_sb(14.5))
                            .color(p.err),
                    );
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if theme::button(ui, p, BtnKind::Danger, "Reset applet\u{2026}").clicked() {
                            arm = true;
                        }
                    });
                });
                ui.label(
                    egui::RichText::new(
                        "Wipes every authenticator credential and clears the password. \
                         Works without the password — this is the recovery for a \
                         forgotten one. Cannot be undone.",
                    )
                    .font(theme::f_reg(12.5))
                    .color(p.txt2),
                );
            });
        if arm {
            self.oath.confirm_reset = self.selected_device.clone();
        }
    }

    /// OpenPGP tab — read-only status + the existing management section.
    fn cap_pgp(&mut self, ui: &mut egui::Ui, p: &Palette) {
        // Intents collected inside the UI closures and applied afterwards, so a
        // submit method's `&mut self` never overlaps a card's borrow. (Mirrors
        // the PIV pane.) `open_modal` carries the chosen credential flow.
        let mut do_refresh = false;
        let mut open_modal: Option<OpenPgpCredKind> = None;
        let mut browse_import_key = false;
        // The key the user clicked in the sub-tab strip this frame (applied
        // after the card borrows end). `selected` is a copy of the active key so
        // the immutable card closures can compare without borrowing self.
        let mut clicked_key: Option<OpenPgpSlotSel> = None;
        let selected = self.openpgp.selected_key;

        let note = |ui: &mut egui::Ui, t: &str| card_note(ui, p, t);

        // --- OpenPGP card status card (full-width, FIDO2 shape): title + help
        // left, Read status right, applet-wide status body, then the applet-wide
        // admin (Card details, PINs) folded in as setting-rows.
        theme::card_frame(p).show(ui, |ui| {
            ui.set_min_width(ui.available_width());
            ui.horizontal(|ui| {
                ui.label(
                    egui::RichText::new("OpenPGP card")
                        .font(theme::f_sb(14.5))
                        .color(p.txt),
                );
                ui.add_space(6.0);
                self.help_dot(ui, p, "pgp");
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    if theme::button(ui, p, BtnKind::Default, "Read status").clicked() {
                        do_refresh = true;
                    }
                });
            });
            ui.add_space(8.0);
            if let Some(err) = &self.openpgp.error {
                ui.colored_label(p.err, err);
                ui.add_space(6.0);
            }
            if let Some(notice) = &self.openpgp.notice {
                ui.colored_label(p.ok, notice);
                ui.add_space(6.0);
            }
            // Applet-wide status: AID / serial / PIN retries / signatures made.
            // The three per-key algorithm+fingerprint rows live under the sub-tab
            // strip now, not here.
            if let Some(status) = &self.openpgp.status {
                let serial = status
                    .serial_text()
                    .unwrap_or_else(|| "\u{2014}".to_string());
                let sigs = status
                    .signature_count
                    .map_or("\u{2014}".to_string(), |n| n.to_string());
                ui.label(
                    egui::RichText::new(format!(
                        "AID {} \u{00B7} Serial {serial}",
                        hex_lower(&status.aid)
                    ))
                    .font(theme::f_reg(12.5))
                    .color(p.txt2),
                );
                ui.add_space(2.0);
                ui.label(
                    egui::RichText::new(format!(
                        "PIN retries PW1={} RC={} PW3={} \u{00B7} Signatures made {sigs}",
                        status.tries_pw1, status.tries_rc, status.tries_pw3
                    ))
                    .font(theme::f_reg(12.5))
                    .color(p.txt2),
                );
            } else if self.openpgp.error.is_none() {
                ui.label(
                    egui::RichText::new("Click Read status to read this card (no PIN or touch).")
                        .font(theme::f_reg(13.0))
                        .color(p.txt3),
                );
            }

            // Applet-wide administration folded in as FIDO2 setting-rows: the
            // cardholder details and the PIN operations apply to the whole card,
            // not to one key, so they sit with the applet status here.
            ui.add_space(12.0);

            // Card details: cardholder name + public-key URL. The values are
            // typed in the per-row text fields; both writes prompt for the admin
            // PIN (PW3) in a dialog.
            ui.horizontal(|ui| {
                ui.label(
                    egui::RichText::new("Card details")
                        .font(theme::f_sb(13.5))
                        .color(p.txt),
                );
                ui.add_space(6.0);
                self.help_dot(ui, p, "pgp-card-details");
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    if theme::button(ui, p, BtnKind::Default, "Set URL\u{2026}").clicked() {
                        open_modal = Some(OpenPgpCredKind::SetUrl);
                    }
                    ui.add_space(6.0);
                    if theme::button(ui, p, BtnKind::Default, "Set name\u{2026}").clicked() {
                        open_modal = Some(OpenPgpCredKind::SetName);
                    }
                });
            });
            ui.add_space(6.0);
            text_field(
                ui,
                p,
                "Name",
                &mut self.openpgp.name_input,
                "Surname<<Given",
                200.0,
            );
            ui.add_space(4.0);
            text_field(
                ui,
                p,
                "URL",
                &mut self.openpgp.url_input,
                "https://\u{2026}",
                240.0,
            );

            // PINs: change user / admin, unblock user. Each opens a dialog where
            // the PIN entry happens; nothing secret is typed inline.
            ui.add_space(10.0);
            ui.horizontal(|ui| {
                ui.label(
                    egui::RichText::new("PINs")
                        .font(theme::f_sb(13.5))
                        .color(p.txt),
                );
                ui.add_space(6.0);
                self.help_dot(ui, p, "pin");
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    if theme::button(ui, p, BtnKind::Default, "Unblock user PIN\u{2026}").clicked()
                    {
                        open_modal = Some(OpenPgpCredKind::UnblockUserPin);
                    }
                    ui.add_space(6.0);
                    if theme::button(ui, p, BtnKind::Default, "Change admin PIN\u{2026}").clicked()
                    {
                        open_modal = Some(OpenPgpCredKind::ChangeAdminPin);
                    }
                    ui.add_space(6.0);
                    if theme::button(ui, p, BtnKind::Default, "Change user PIN\u{2026}").clicked() {
                        open_modal = Some(OpenPgpCredKind::ChangeUserPin);
                    }
                });
            });
        });

        // --- Selected-key display data (shown under the key tab strip) -------
        // The active key's algorithm + fingerprint, read straight off the loaded
        // status. Precomputed here so the immutable card closures don't borrow
        // self.
        let sel_state: String = match &self.openpgp.status {
            Some(st) => {
                let (attrs, fpr) = selected.status_fields(st);
                if fpr.iter().all(|&b| b == 0) {
                    "no key".to_string()
                } else {
                    format!(
                        "{} \u{00B7} fpr {}",
                        keyroost_transport::describe_algorithm_attributes(attrs),
                        hex_lower(fpr)
                    )
                }
            }
            None => "read status to view this key".to_string(),
        };

        // --- Key sub-tab strip ----------------------------------------------
        // Signature / Decryption / Authentication, each a tab exactly like the
        // FIDO2 sub-tab strip: an opaque surface strip behind a row of bold
        // labels, the active one underlined with a 2px accent. Clicking a tab
        // selects that key; the Generate / Import cards below target it.
        ui.add_space(14.0);
        {
            let top = ui.cursor().top();
            let strip = egui::Rect::from_min_max(
                egui::pos2(ui.max_rect().left(), top - 4.0),
                egui::pos2(ui.max_rect().right(), top + 30.0),
            );
            ui.painter().rect_filled(strip, 0.0, p.surface);
        }
        ui.horizontal(|ui| {
            ui.spacing_mut().item_spacing.x = 20.0;
            for key in [
                OpenPgpSlotSel::Sign,
                OpenPgpSlotSel::Decrypt,
                OpenPgpSlotSel::Auth,
            ] {
                let active = selected == key;
                let color = if active { p.txt } else { p.txt3 };
                let resp = ui
                    .add(
                        egui::Label::new(
                            egui::RichText::new(key.tab_label())
                                .font(theme::f_sb(13.5))
                                .color(color),
                        )
                        .sense(egui::Sense::click()),
                    )
                    .on_hover_cursor(egui::CursorIcon::PointingHand);
                if active {
                    let y = resp.rect.bottom() + 6.0;
                    ui.painter().line_segment(
                        [
                            egui::pos2(resp.rect.left(), y),
                            egui::pos2(resp.rect.right(), y),
                        ],
                        egui::Stroke::new(2.0, p.accent),
                    );
                }
                if resp.clicked() {
                    clicked_key = Some(key);
                }
            }
        });

        // --- Selected key content (single column under the strip) -----------
        ui.add_space(14.0);
        ui.label(
            egui::RichText::new(format!("State: {sel_state}"))
                .font(theme::f_reg(12.5))
                .color(p.txt2),
        );
        ui.add_space(10.0);
        theme::card_frame(p).show(ui, |ui| {
            ui.set_min_width(ui.available_width());

            // Generate on-card: label + help left, Generate pinned right.
            ui.horizontal(|ui| {
                ui.label(
                    egui::RichText::new("Generate on-card")
                        .font(theme::f_sb(13.5))
                        .color(p.txt),
                );
                ui.add_space(6.0);
                self.help_dot(ui, p, "pgp-keys");
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    if theme::button(ui, p, BtnKind::Default, "Generate\u{2026}").clicked() {
                        open_modal = Some(OpenPgpCredKind::GenerateKey);
                    }
                });
            });
            note(
                ui,
                "Generating OVERWRITES this key (clearable only by a full reset). \
                 Prompts for the admin PIN; touch the key if it blinks.",
            );

            ui.add_space(12.0);
            // Import RSA-2048: file path + Browse left, the two import actions
            // pinned right.
            ui.horizontal(|ui| {
                ui.label(
                    egui::RichText::new("Import RSA-2048")
                        .font(theme::f_sb(13.5))
                        .color(p.txt),
                );
                ui.add_space(6.0);
                self.help_dot(ui, p, "pgp-keys");
            });
            ui.add_space(6.0);
            ui.horizontal(|ui| {
                text_field(
                    ui,
                    p,
                    "From file",
                    &mut self.openpgp.import_path,
                    "/path/to/key.pem (PKCS#1/8, PEM or DER)",
                    240.0,
                );
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    browse_import_key =
                        theme::button(ui, p, BtnKind::Default, "Browse\u{2026}").clicked();
                });
            });
            let have_path = !self.openpgp.import_path.trim().is_empty();
            ui.add_space(6.0);
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                if theme::button(ui, p, BtnKind::Default, "Import file\u{2026}").clicked()
                    && have_path
                {
                    open_modal = Some(OpenPgpCredKind::ImportKeyFile);
                }
                ui.add_space(6.0);
                if theme::button(ui, p, BtnKind::Default, "Generate & import\u{2026}").clicked() {
                    open_modal = Some(OpenPgpCredKind::GenerateImportKey);
                }
            });
        });
        ui.add_space(12.0);

        // Reset applet — its own destructive card with a red stroke at the
        // bottom of the pane (mirrors the FIDO2 / PIV "Reset" card), full width,
        // description left + red button right.
        theme::card_frame(p)
            .stroke(egui::Stroke::new(1.0, theme::tint(p.err, 90)))
            .show(ui, |ui| {
                ui.set_min_width(ui.available_width());
                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new("Reset applet")
                            .font(theme::f_sb(14.5))
                            .color(p.err),
                    );
                    ui.add_space(6.0);
                    self.help_dot(ui, p, "reset");
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if theme::button(ui, p, BtnKind::Danger, "Reset applet\u{2026}").clicked() {
                            open_modal = Some(OpenPgpCredKind::Reset);
                        }
                    });
                });
                ui.label(
                    egui::RichText::new(
                        "Wipes ALL OpenPGP keys and restores default PINs. Works even if \
                         the PINs are forgotten.",
                    )
                    .font(theme::f_reg(12.5))
                    .color(p.txt2),
                );
            });

        // Apply collected intents now that the card borrows have ended.
        if let Some(key) = clicked_key {
            self.openpgp.selected_key = key;
            self.openpgp.gen_alg = OpenPgpKeyAlgSel::CardDefault;
        }
        if do_refresh {
            self.load_openpgp_status();
        }
        if browse_import_key {
            self.spawn_file_dialog(
                FileTarget::OpenpgpImport,
                false,
                &[("Keys", &["pem", "der", "key"]), ("All files", &["*"])],
                None,
            );
        }
        // Open the chosen flow's credential modal, wiping any stale secret first
        // so a PIN typed for a previous flow can't ride along.
        if let Some(kind) = open_modal {
            self.openpgp.wipe_secrets();
            self.openpgp.error = None;
            self.openpgp.cred_modal =
                Some(OpenPgpCredModal::new(kind, self.selected_device.clone()));
        }
    }

    /// PIV tab — read-only status snapshot (auto-read on first view).
    fn cap_piv(&mut self, ui: &mut egui::Ui, p: &Palette) {
        use keyroost_piv::compat::{FeatureGate, PivExtension};
        if !self.piv_tried && !self.busy() {
            self.piv_tried = true;
            self.load_piv_status(LogKind::Background);
        }
        // Intents collected inside the UI closures and applied afterwards, so a
        // submit method's `&mut self` never overlaps a card's borrow.
        let mut do_refresh = false;
        let mut open_change_pin = false;
        let mut open_change_puk = false;
        let mut open_unblock = false;
        let mut open_generate = false;
        let mut open_import = false;
        let mut go_export = false;
        let mut open_self_sign = false;
        let mut open_csr = false;
        let mut open_set_retries = false;
        let mut open_change_mgmt = false;
        let mut open_delete_cert = false;
        let mut open_delete_key = false;
        let mut open_move_key = false;
        let mut open_self_test = false;
        let mut open_new_chuid = false;
        let mut toggle_compat_table = false;
        let mut click_retired_tab = false;
        let mut arm_reset = false;
        let mut go_to_overview = false;
        let mut copy_pem: Option<String> = None;
        // Slot the user clicked in the status card this frame (applied after the
        // card borrows end). `selected` is a copy of the active selection so the
        // immutable card closures can compare against it without borrowing self.
        let mut clicked_slot: Option<PivSlotSel> = None;
        let selected = self.piv.selected_slot;

        let note = |ui: &mut egui::Ui, t: &str| card_note(ui, p, t);

        // Yubico SET PIN RETRIES (`INS 0xFA`) sets the PIN's and PUK's retry
        // counters together in one APDU — there is no way to change one
        // without the other — so it's gated by a single extension rather
        // than a pair the way Move/Delete key are. Computed up front,
        // before the "Retry counts" row below (the per-slot gates further
        // down compute this same fingerprint/version triple again, for
        // their own slot-scoped purposes).
        let (retries_piv_fp, retries_piv_ver, retries_piv_fw_ver) =
            self.piv.status.as_ref().map_or(
                (
                    keyroost_piv::fingerprint::AppletFingerprint::Generic,
                    None,
                    None,
                ),
                |s| {
                    (
                        s.applet_fingerprint,
                        s.version.as_deref(),
                        s.version_firmware.as_deref(),
                    )
                },
            );
        let set_retries_gate = self.piv_gate(
            PivExtension::SetPinPukRetries,
            retries_piv_fp,
            retries_piv_ver,
            retries_piv_fw_ver,
        );
        let set_retries_unverified_hint = format!(
            "{} {}",
            PivExtension::SetPinPukRetries.requirement(),
            FeatureGate::UNVERIFIED_SUFFIX
        );
        let set_retries_blocked_hint = format!(
            "{} {}",
            PivExtension::SetPinPukRetries.requirement(),
            FeatureGate::INCOMPATIBLE_SUFFIX
        );
        // Change management key (Yubico SET MANAGEMENT KEY) is gated the
        // same way, from the same fingerprint/version triple as the retry
        // counts above — see the "Management key" row below.
        let change_mgmt_key_gate = self.piv_gate(
            PivExtension::SetManagementKey,
            retries_piv_fp,
            retries_piv_ver,
            retries_piv_fw_ver,
        );
        let change_mgmt_key_unverified_hint = format!(
            "{} {}",
            PivExtension::SetManagementKey.requirement(),
            FeatureGate::UNVERIFIED_SUFFIX
        );
        let change_mgmt_key_blocked_hint = format!(
            "{} {}",
            PivExtension::SetManagementKey.requirement(),
            FeatureGate::INCOMPATIBLE_SUFFIX
        );
        // Per-algorithm gates for the "Management key" row's algorithm
        // combo, below — same shape as `keyalg_gates` (the slot
        // key-algorithm combo's own gate table, built further down in this
        // function): resolved eagerly here (an owned array, not a closure
        // over `retries_piv_fp`/`retries_piv_ver`/`retries_piv_fw_ver`) for
        // the same borrow-lifetime reason `keyalg_gates`'s own doc gives. Not
        // every algorithm is universally implemented, standardized or not,
        // and `Delete` is a real HID-Crescendo-only capability rather than
        // always-unsupported filler — see
        // `PivExtension::ManagementKeyAlgorithm`'s own doc.
        let mgmtalg_gates: [(PivMgmtAlgSel, FeatureGate); PivMgmtAlgSel::ALL.len()] =
            PivMgmtAlgSel::ALL.map(|alg| {
                (
                    alg,
                    self.piv_gate(
                        PivExtension::ManagementKeyAlgorithm(alg.to_choice()),
                        retries_piv_fp,
                        retries_piv_ver,
                        retries_piv_fw_ver,
                    ),
                )
            });
        let mgmtalg_gate = move |alg: PivMgmtAlgSel| {
            mgmtalg_gates
                .iter()
                .find_map(|&(a, gate)| (a == alg).then_some(gate))
                .unwrap_or(FeatureGate::Unverified)
        };
        // Unsupported doesn't just dim the DragValues below -- with no way
        // to submit them, a count the user dragged in before this device
        // turned out incompatible (or left over from a previous, compatible
        // device, since this pane's state doesn't reset on every status
        // refresh) would otherwise sit there stale and misleading. Reset
        // both back to the same factory-default count `PivState::default()`
        // seeds them with, every frame this gate resolves `Unsupported` --
        // cheap and idempotent, and the fields are non-interactive anyway
        // while it holds.
        if matches!(set_retries_gate, FeatureGate::Unsupported) {
            self.piv.retries_pin = 3;
            self.piv.retries_puk = 3;
        }

        // --- PIV smart card status card (full-width, FIDO2 "PIN & sign-in"
        // shape): title + help left, Refresh right, applet/serial/retries body.
        //
        // Wrapped in `add_enabled_ui` rather than gating each button/field
        // below: egui propagates `enabled` down the whole child tree, so
        // this one call dims Refresh, the PIN/PUK/retries/management-key/
        // CHUID actions, and every input among them together, with nothing
        // to keep in sync as rows are added or reordered. `self.piv.inflight`
        // covers every PIV job, not just this card's own Refresh, so any
        // in-flight generate/import/delete/... elsewhere dims this card too.
        ui.add_enabled_ui(!self.piv.inflight, |ui| {
            theme::card_frame(p).show(ui, |ui| {
                ui.set_min_width(ui.available_width());
                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new("PIV smart card")
                            .font(theme::f_sb(14.5))
                            .color(p.txt),
                    );
                    ui.add_space(6.0);
                    self.help_dot(ui, p, "piv");
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if theme::button(ui, p, BtnKind::Default, "Refresh").clicked() {
                            do_refresh = true;
                        }
                    });
                });
                ui.add_space(8.0);
                if let Some(err) = &self.piv.error {
                    ui.colored_label(p.err, err);
                    ui.add_space(6.0);
                }
                if let Some(n) = &self.piv.notice {
                    ui.colored_label(p.ok, n);
                    ui.add_space(6.0);
                }
                // Status body: version / serial / PIN retries collapsed onto one
                // dotted line.
                if let Some(st) = &self.piv.status {
                    // Tolerant of any non-empty GET VERSION reply, not just real
                    // Yubico firmware's 3 bytes — some third-party PIV applets
                    // that answer this vendor extension at all use a different
                    // byte count (observed: a Swissbit iShield Key 2 Pro replies
                    // with 4).
                    //
                    // `version_firmware` is the token's own firmware version
                    // (read through a fingerprint-specific probe only some
                    // tokens answer — currently a Nitrokey only), a separate
                    // axis from the PIV applet's own version above — see
                    // `PivStatus::version_firmware`'s doc for why the two
                    // aren't interchangeable. Shown only when it adds
                    // information: suppressed when it's absent, and folded
                    // into the "Applet" segment (rather than repeated as its
                    // own dotted field) when it equals the applet version, so
                    // the common case where a token doesn't distinguish the
                    // two axes doesn't show the same number twice.
                    let applet_ver = st.version.as_deref().map(keyroost_piv::format_version_bytes);
                    let fw_ver = st
                        .version_firmware
                        .as_deref()
                        .filter(|fw| Some(*fw) != st.version.as_deref())
                        .map(keyroost_piv::format_version_bytes);
                    let applet_field = match (applet_ver, fw_ver) {
                        (Some(av), Some(fw)) => format!("Applet {av} (FW v{fw})"),
                        (Some(av), None) => format!("Applet {av}"),
                        (None, Some(fw)) => format!("Applet FW v{fw}"),
                        (None, None) => "Applet \u{2014}".to_string(),
                    };
                    let serial = st
                        .serial
                        .map_or("\u{2014}".to_string(), keyroost_piv::format_serial_short);
                    let retries = st
                        .pin_retries
                        .map_or("\u{2014}".to_string(), |n| n.to_string());
                    // The token's own reported name when it has one (e.g. a
                    // Nitrokey's admin application); otherwise the generic name
                    // for its fingerprinted applet family — same fallback as
                    // `keyroostctl piv info`'s plain-text output.
                    let applet_name = if st.applet_name.is_empty() {
                        st.applet_fingerprint.applet_name().to_string()
                    } else {
                        st.applet_name.clone()
                    };
                    ui.label(
                        egui::RichText::new(format!(
                            "{applet_name} \u{00B7} {applet_field} \u{00B7} Serial {serial} \u{00B7} PIN retries {retries}"
                        ))
                        .font(theme::f_reg(12.5))
                        .color(p.txt2),
                    );
                    // CHUID — GUID and expiration only. FASC-N carries no
                    // information worth showing here (it's a fixed filler, not
                    // real card data — see keyroost_piv::encode_chuid) and stays
                    // out of the UI; `keyroostctl piv info` still prints it.
                    // The signature and LRC fields are omitted everywhere.
                    if let Some(chuid) = &st.chuid {
                        ui.label(
                            egui::RichText::new(format!(
                                "CHUID: GUID {} \u{00B7} Expires {}",
                                chuid.guid_display(),
                                chuid.expiration_display()
                            ))
                            .font(theme::f_reg(12.5))
                            .color(p.txt2),
                        );
                    }
                } else if self.piv.error.is_none() {
                    ui.label(
                        egui::RichText::new("Reading PIV status\u{2026}")
                            .font(theme::f_reg(13.0))
                            .color(p.txt3),
                    );
                }

                // Applet-wide administration: PIN & PUK, retry counts, and the
                // management key all apply to the whole applet rather than to one
                // slot, so they sit with the applet status here.
                ui.add_space(12.0);

                // PIN & PUK: bold label + help left, the three actions right.
                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new("PIN & PUK")
                            .font(theme::f_sb(13.5))
                            .color(p.txt),
                    );
                    ui.add_space(6.0);
                    self.help_dot(ui, p, "pin");
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if theme::button(ui, p, BtnKind::Default, "Unblock PIN\u{2026}").clicked() {
                            open_unblock = true;
                        }
                        ui.add_space(6.0);
                        if theme::button(ui, p, BtnKind::Default, "Change PUK\u{2026}").clicked() {
                            open_change_puk = true;
                        }
                        ui.add_space(6.0);
                        if theme::button(ui, p, BtnKind::Default, "Change PIN\u{2026}").clicked() {
                            open_change_pin = true;
                        }
                    });
                });

                // Retry counts: label + help left, the tries DragValues and the
                // apply button right-aligned. SET PIN RETRIES (Yubico `INS
                // 0xFA`) sets both counters in one APDU, so it's gated by the
                // single `set_retries_gate` above rather than a pair, unlike
                // Move/Delete key: `Unsupported` dims both DragValues and the
                // button together (there's nothing partial to offer) and resets
                // both counts to their factory default above, rather than
                // leaving a stale drag-in value behind a disabled field; and
                // `Unverified` only adds the same warning marker Move key uses,
                // leaving everything else live.
                ui.add_space(10.0);
                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new("Retry counts")
                            .font(theme::f_sb(13.5))
                            .color(p.txt),
                    );
                    ui.add_space(6.0);
                    self.help_dot(ui, p, "piv-admin");
                    if matches!(set_retries_gate, FeatureGate::Unverified) {
                        ui.add_space(4.0);
                        theme::warn_marker(ui, p).on_hover_text(set_retries_unverified_hint.as_str());
                    }
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if matches!(set_retries_gate, FeatureGate::Unsupported) {
                            theme::button_disabled(ui, p, "Set retry counts\u{2026}")
                                .on_hover_text(set_retries_blocked_hint.as_str());
                        } else if theme::button(ui, p, BtnKind::Default, "Set retry counts\u{2026}")
                            .clicked()
                        {
                            open_set_retries = true;
                        }
                        ui.add_space(8.0);
                        let retries_unsupported = matches!(set_retries_gate, FeatureGate::Unsupported);
                        // A disabled `DragValue` still renders whatever number
                        // `self.piv.retries_{pin,puk}` currently holds — the
                        // factory-default `3` these two reset to just above, on
                        // a device that plain doesn't support setting retries at
                        // all. Left alone, that reads as a real reported count
                        // rather than the meaningless placeholder it is. Blank
                        // it via a custom formatter rather than the field's
                        // value: the value itself still has to stay a real `u8`
                        // (`DragValue` requires `Numeric`, and the same field
                        // backs the live, editable count on any device that
                        // *does* support this), so emptiness lives at the
                        // display layer, not the data.
                        let blank_when_unsupported = move |n: f64, _: std::ops::RangeInclusive<usize>| {
                            if retries_unsupported {
                                String::new()
                            } else {
                                format!("{}", n as u8)
                            }
                        };
                        ui.add_enabled(
                            !retries_unsupported,
                            egui::DragValue::new(&mut self.piv.retries_puk)
                                .range(1..=15u8)
                                .custom_formatter(blank_when_unsupported),
                        );
                        ui.label(
                            egui::RichText::new("PUK tries")
                                .font(theme::f_reg(13.0))
                                .color(p.txt2),
                        );
                        ui.add_space(8.0);
                        ui.add_enabled(
                            !retries_unsupported,
                            egui::DragValue::new(&mut self.piv.retries_pin)
                                .range(1..=15u8)
                                .custom_formatter(blank_when_unsupported),
                        );
                        ui.label(
                            egui::RichText::new("PIN tries")
                                .font(theme::f_reg(13.0))
                                .color(p.txt2),
                        );
                    });
                });

                // Management key: label + help left, algorithm combo and change
                // button right-aligned.
                ui.add_space(10.0);
                // Every candidate is offered on every device — including
                // `PivMgmtAlgSel::Delete`, HID Crescendo's "remove the
                // management key outright" choice, which renders disabled
                // rather than omitted on a device that can't do that — see
                // `PivMgmtAlgSel::ALL`'s own doc. Each option is gated
                // individually by `mgmtalg_gate` below, the same "list every
                // candidate, gate each one live" shape the Generate key
                // card's algorithm combo already uses.
                let mgmt_alg_options = &PivMgmtAlgSel::ALL[..];
                // Same "don't leave a selection the combo can no longer
                // offer" treatment as the Generate key card's algorithm
                // combo: a prior selection that's since become
                // known-unsupported (e.g. after switching devices) falls back
                // to the first offered option that's actually selectable —
                // see `piv_mgmtalg_unsupported_fallback`'s own doc for why
                // that isn't simply `mgmt_alg_options[0]`.
                self.piv.new_mgmt_alg = piv_mgmtalg_unsupported_fallback(
                    self.piv.new_mgmt_alg,
                    mgmt_alg_options,
                    mgmtalg_gate,
                );
                // Same `Unsupported`-only gate the "Change management key…"
                // button and the combo below both use, so button, combo, and
                // this per-algorithm warning all dim/suppress together — see
                // `piv_mgmtalg_unverified_labels`'s own doc for why the
                // warning specifically goes empty rather than merely
                // disabled.
                let mgmt_key_unsupported = matches!(change_mgmt_key_gate, FeatureGate::Unsupported);
                let mgmt_alg_unverified =
                    piv_mgmtalg_unverified_labels(change_mgmt_key_gate, mgmt_alg_options, mgmtalg_gate);
                let mgmt_alg_unverified_hint = format!(
                    "No entry for this key in keyroost's list: {}.",
                    mgmt_alg_unverified.join(", ")
                );
                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new("Management key")
                            .font(theme::f_sb(13.5))
                            .color(p.txt),
                    );
                    ui.add_space(6.0);
                    self.help_dot(ui, p, "piv-admin");
                    let extension_unverified = matches!(change_mgmt_key_gate, FeatureGate::Unverified);
                    if extension_unverified || !mgmt_alg_unverified.is_empty() {
                        ui.add_space(4.0);
                        // Both hints can apply at once (whether the
                        // management key can be changed at all, and which
                        // algorithms an actual change could use) — combined
                        // into one tooltip rather than two markers, same as
                        // this row's other pairs of caveats.
                        let combined_hint = match (extension_unverified, mgmt_alg_unverified.is_empty()) {
                            (true, false) => {
                                format!("{change_mgmt_key_unverified_hint} {mgmt_alg_unverified_hint}")
                            }
                            (true, true) => change_mgmt_key_unverified_hint.clone(),
                            (false, false) => mgmt_alg_unverified_hint.clone(),
                            (false, true) => unreachable!("guarded by the `if` above"),
                        };
                        theme::warn_marker(ui, p).on_hover_text(combined_hint.as_str());
                    }
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if matches!(change_mgmt_key_gate, FeatureGate::Unsupported) {
                            theme::button_disabled(ui, p, "Change management key\u{2026}")
                                .on_hover_text(change_mgmt_key_blocked_hint.as_str());
                        } else if theme::button(ui, p, BtnKind::Default, "Change management key\u{2026}")
                            .clicked()
                        {
                            open_change_mgmt = true;
                        }
                        ui.add_space(8.0);
                        // `mgmt_key_unsupported` (computed above, alongside
                        // `mgmt_alg_unverified`) is the same `Unsupported`-only
                        // gate the "Change management key…" button above
                        // already uses, so button, combo, and the
                        // per-algorithm warning all dim/suppress together.
                        ui.add_enabled_ui(!mgmt_key_unsupported, |ui| {
                            piv_mgmtalg_combo(
                                ui,
                                "piv-new-mgmt-alg",
                                &mut self.piv.new_mgmt_alg,
                                mgmt_alg_options,
                                mgmtalg_gate,
                            );
                        })
                        .response
                        .on_disabled_hover_text(change_mgmt_key_blocked_hint.as_str());
                    });
                });

                // CHUID: label + help left, the write action right-aligned.
                ui.add_space(10.0);
                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new("CHUID")
                            .font(theme::f_sb(13.5))
                            .color(p.txt),
                    );
                    ui.add_space(6.0);
                    self.help_dot(ui, p, "piv-admin");
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if theme::button(ui, p, BtnKind::Default, "New CHUID\u{2026}").clicked() {
                            open_new_chuid = true;
                        }
                    });
                });
            });
        });

        // --- Selected-slot display data (shown under the slot tab strip) ---
        let sel_state: String = if let PivSlotSel::Retired(n) = selected {
            // Retired slots aren't tracked by `status.slots` / `slot_keys`
            // (those only cover the four standard slots), so an occupied
            // retired slot would otherwise fall through to "empty" below.
            // Consult the lazily-populated retired-occupancy cache instead —
            // the same one `selected_has_key` reads — so the label stays
            // honest before a user hits Generate/Import on an archived key.
            let key = self
                .piv
                .retired_occupancy
                .as_ref()
                .and_then(|v| v.iter().find(|(s, _)| *s == keyroost_piv::Slot::Retired(n)))
                .map(|(_, key)| *key);
            piv_retired_slot_state_text(key)
        } else {
            let sel_slot = selected.to_slot();
            let sel_status = self
                .piv
                .status
                .as_ref()
                .and_then(|s| s.slots.iter().find(|sl| sl.slot == sel_slot));
            let cert_present = sel_status.is_some_and(|sl| sl.cert_present);
            let cert_unreadable = sel_status.and_then(|sl| sl.cert_unreadable);
            let cert_compressed = sel_status.is_some_and(|sl| sl.cert_compressed);
            let key = sel_status.map(|sl| sl.key).unwrap_or_default();
            let entry = self.piv.slot_keys.iter().find(|(s, _, _)| *s == sel_slot);
            let alg = entry.and_then(|(_, a, _)| *a);
            let dn = entry.and_then(|(_, _, d)| d.as_deref());
            let mut s =
                piv_slot_state_text(cert_unreadable, cert_present, cert_compressed, alg, key);
            // PIN/touch policy, only alongside an actual key — an empty slot
            // has no policy to report, and showing "not available" there
            // would read as a hardware problem rather than just "no key yet".
            if cert_present || alg.is_some() {
                let policy = self
                    .piv
                    .slot_policies
                    .iter()
                    .find(|(s, _)| *s == sel_slot)
                    .and_then(|(_, p)| *p);
                s.push_str(" \u{00B7} ");
                match policy {
                    Some((pin, touch)) => {
                        s.push_str("pin: ");
                        s.push_str(pin.label());
                        s.push_str(", touch: ");
                        s.push_str(touch.label());
                    }
                    None => s.push_str("pin/touch policy not available"),
                }
            }
            if let Some(dn) = dn {
                s.push_str(" \u{00B7} ");
                if dn.chars().count() > 64 {
                    s.extend(dn.chars().take(63));
                    s.push('\u{2026}');
                } else {
                    s.push_str(dn);
                }
            }
            s
        };
        // Whether the active slot holds a private key — gates the Move button
        // (and Move source). Standard slots read from `slot_keys`; a retired slot
        // reads from the lazily-populated occupancy cache.
        let selected_has_key = piv_slot_occupied(
            selected,
            &self.piv.slot_keys,
            self.piv.retired_occupancy.as_deref(),
        );
        // Whether the active slot holds an X.509 certificate — gates Export.
        // Standard slots read `status.slots`; retired slots carry no cert
        // signal in the loaded state, and neither does the pane before its
        // first status read, so both resolve optimistically (the button stays
        // live and the low-level "slot holds no certificate" error still
        // guards). Only a standard slot the card has read and found certless
        // dims the button.
        let selected_has_cert = match selected {
            PivSlotSel::Retired(_) => true,
            _ => {
                !self.piv.loaded
                    || self.piv.status.as_ref().is_some_and(|s| {
                        s.slots
                            .iter()
                            .any(|sl| sl.slot == selected.to_slot() && sl.cert_present)
                    })
            }
        };
        // Move key / Delete key are Yubico extensions (MOVE/DELETE KEY), not
        // SP 800-73-4. `keyroost_piv::compat` resolves a per-fingerprint
        // known-support table against the applet's reported version into a
        // three-way gate: enable, enable-but-flag (support unverified on this
        // device), or dim. An unsupported card refuses the APDU on its own —
        // there is no transport-side version gate any more. Clearing a
        // certificate is standard PIV and works everywhere.
        let (piv_fp, piv_ver, piv_fw_ver) = self.piv.status.as_ref().map_or(
            (
                keyroost_piv::fingerprint::AppletFingerprint::Generic,
                None,
                None,
            ),
            |s| {
                (
                    s.applet_fingerprint,
                    s.version.as_deref(),
                    s.version_firmware.as_deref(),
                )
            },
        );
        let move_key_gate = self.piv_gate(PivExtension::MoveKey, piv_fp, piv_ver, piv_fw_ver);
        let delete_key_gate = self.piv_gate(PivExtension::DeleteKey, piv_fp, piv_ver, piv_fw_ver);
        // Whether this device has a confirmed, device-reported way to know a
        // slot's key occupancy (GET METADATA, or HID Crescendo's own GET PIV
        // PROPERTIES — see `keyroost_piv::compat::PivExtension::GetSlotKeyStatus`'s
        // doc). Consulted below (`slot_confirmed_empty`) to decide whether
        // "Delete key" can safely dim on an empty slot the same way "Delete
        // certificate" dims on a certless one, and whether "Import
        // certificate" can safely dim on one too (nothing there for a freshly
        // imported certificate's key to possibly match) — only when this
        // resolves `Supported` is `selected_has_key` trustworthy enough to
        // block on; everywhere else `None` could just as easily mean "this
        // device can't tell us" as "genuinely empty".
        let get_slot_key_status_gate =
            self.piv_gate(PivExtension::GetSlotKeyStatus, piv_fp, piv_ver, piv_fw_ver);
        // Reset (Yubico RESET, `INS 0xFB`) is gated the same way, from the
        // same fingerprint/version triple — see the "Reset applet" card
        // below.
        let reset_gate = self.piv_gate(PivExtension::Reset, piv_fp, piv_ver, piv_fw_ver);
        // A device-wide reset directive that takes PIV down with it alongside
        // at least one other applet — a distinct extension from `Reset`
        // above, resolved independently (see
        // `keyroost_piv::compat::PivExtension::ResetGlobal`'s doc). Checked
        // here only to decide whether the "Reset applet" card below should
        // point at the whole-device factory reset (Overview tab) as a known
        // alternative when the PIV-only path can't be trusted — never to
        // change what that card's own button does.
        let reset_global_gate =
            self.piv_gate(PivExtension::ResetGlobal, piv_fp, piv_ver, piv_fw_ver);
        let show_reset_global_alternative =
            piv_reset_global_alternative_available(reset_gate, reset_global_gate);
        // Whether this device is known to take unusually long to finish
        // RESET (`PivQuirk::ResetLongRunning`, e.g. observed over a minute
        // on ArekinathPivApplet::SwissbitIShield1) — surfaced below as a
        // standing note on the "Reset applet" card, not just a hover, so it
        // isn't missed the moment the device looks like it's hung.
        let reset_long_running = keyroost_piv::compat::resolve_quirks(piv_fp, piv_ver, piv_fw_ver)
            .contains(&keyroost_piv::compat::PivQuirk::ResetLongRunning);
        // Per-algorithm gates for the "Generate key" card's algorithm combo,
        // below — resolved eagerly here (an owned array, not a closure over
        // `piv_ver`/`piv_fw_ver`) because those two borrow `self.piv.status`
        // and the combo is drawn from deep inside closures that also need
        // `&mut self`; holding the borrow that long would conflict. Not every
        // algorithm is universally implemented, standardized or not — see
        // `PivExtension::SlotKeyAlgorithm`'s own doc.
        let keyalg_gates: [(keyroost_piv::KeyAlg, FeatureGate); keyroost_piv::KeyAlg::ALL.len()] =
            keyroost_piv::KeyAlg::ALL.map(|alg| {
                (
                    alg,
                    self.piv_gate(
                        PivExtension::SlotKeyAlgorithm(alg),
                        piv_fp,
                        piv_ver,
                        piv_fw_ver,
                    ),
                )
            });
        let keyalg_gate = move |alg: keyroost_piv::KeyAlg| {
            keyalg_gates
                .iter()
                .find_map(|&(a, gate)| (a == alg).then_some(gate))
                .unwrap_or(FeatureGate::Unverified)
        };
        // Explanations for the non-standard slot operations when the
        // fingerprint known-support table can't clear them — built from the shared
        // vocabulary in `keyroost_piv::compat` so this pane and the CLI say the
        // same thing: the extension's `requirement()` sentence, then a state
        // suffix. Each string is a hover: on the \u{26a0} marker by the row's
        // help dot for Unverified, on the dimmed button for Unsupported.
        // "Key deletion" / "Moving keys" keep each distinct from the Delete
        // row's other button, "Delete certificate\u{2026}" — and the Delete-key
        // \u{26a0} hover additionally appends that "Delete certificate" is
        // standard PIV and unaffected (see the hover call site).
        let move_key_unverified_hint = format!(
            "{} {}",
            PivExtension::MoveKey.requirement(),
            FeatureGate::UNVERIFIED_SUFFIX
        );
        let move_key_blocked_hint = format!(
            "{} {}",
            PivExtension::MoveKey.requirement(),
            FeatureGate::INCOMPATIBLE_SUFFIX
        );
        let delete_key_unverified_hint = format!(
            "{} {}",
            PivExtension::DeleteKey.requirement(),
            FeatureGate::UNVERIFIED_SUFFIX
        );
        let delete_key_blocked_hint = format!(
            "{} {}",
            PivExtension::DeleteKey.requirement(),
            FeatureGate::INCOMPATIBLE_SUFFIX
        );
        let reset_unverified_hint = format!(
            "{} {}",
            PivExtension::Reset.requirement(),
            FeatureGate::UNVERIFIED_SUFFIX
        );
        let reset_blocked_hint = format!(
            "{} {}",
            PivExtension::Reset.requirement(),
            FeatureGate::INCOMPATIBLE_SUFFIX
        );
        // Both certificate actions below (self-sign into the slot, and sign a
        // CSR) are signed *by this slot's key*. With no key there is nothing to
        // sign with and the on-card step fails deep in the flow ("slot has no
        // key…"), so the buttons are dimmed until a key is present and say why
        // on hover — same treatment as the Move/Delete-key rows.
        let no_slot_key_hint = "This slot has no key. Generate a key in this slot first \u{2014} \
             a self-signed certificate and a CSR are both signed by it.";
        // Both certificate actions need the slot's key to actually sign —
        // X25519 (and any future key-agreement-only algorithm) can only do
        // ECDH on this card, so `keyroost_piv::x509::signature_hash` rejects
        // it. Building a certificate for such a key needs a different
        // enrollment mechanism (CRMF/CMP-style, proving possession via key
        // agreement instead of a signature) that keyroost doesn't implement,
        // so the buttons dim rather than fail deep in the signing flow.
        // `None` (algorithm not yet known — e.g. a retired slot, which
        // `slot_keys` never covers) doesn't block: same "don't guess"
        // treatment the Test row gives an unknown algorithm.
        let sel_key_can_sign = self
            .piv_selected_test_target()
            .0
            .is_none_or(|a| keyroost_piv::x509::signature_hash(a).is_ok());
        let cant_sign_hint = "This slot's key only supports key agreement, not signing \u{2014} \
             it can't produce a self-signed certificate or a CSR. keyroost has no CRMF/CMP-style \
             enrollment for that kind of key.";
        let no_slot_cert_hint =
            "This slot holds no certificate to export. Import one, or create a self-signed \
             certificate above.";
        let no_move_key_hint =
            "This slot has no key to move \u{2014} generate one in this slot first.";
        let no_del_cert_hint = "This slot holds no certificate to delete.";
        let no_del_key_hint = "This slot holds no key to delete.";
        // "Import certificate" dims only when this device *confirms* the
        // slot is empty (same `slot_confirmed_empty` gate as "Delete key" —
        // see its doc): a certificate can't possibly match a key this slot
        // doesn't hold. When occupancy can't be confirmed, the button stays
        // enabled — a matching key may have been loaded out of band and this
        // session just can't see it; `PivSession::import_certificate` itself
        // still compares against whatever key it *can* find before writing.
        let no_import_cert_hint = "This slot has no key for a certificate to match \u{2014} \
             generate or move one into this slot first.";
        // --- Slot sub-tab strip ---------------------------------------------
        // Each PIV slot is a tab, exactly like the FIDO2 sub-tab strip
        // (Passkeys / Settings / Storage): an opaque surface strip behind a row
        // of bold labels, the active one underlined with a 2px accent. Clicking
        // a tab selects that slot; every action card below targets it.
        ui.add_space(14.0);
        // Opaque surface behind the tab labels. The strip wraps to more than one
        // line when the window is too narrow to hold every tab on one row — the
        // slot cards below would otherwise be pinned to the unwrapped width of
        // this row and spill past the pane's right edge. Because the wrapped
        // height isn't known until the row is laid out, reserve a paint slot
        // here and fill it from the row's real rect afterwards.
        let strip_bg = ui.painter().add(egui::Shape::Noop);
        let strip_resp = ui.horizontal_wrapped(|ui| {
            ui.spacing_mut().item_spacing.x = 20.0;
            // Rows are far enough apart that a wrapped second row clears the
            // accent underline (drawn 6px below the row above) with margin.
            ui.spacing_mut().item_spacing.y = 22.0;
            let tab = |ui: &mut egui::Ui, label: String, active: bool| -> bool {
                let color = if active { p.txt } else { p.txt3 };
                let resp = ui
                    .add(
                        egui::Label::new(
                            egui::RichText::new(label)
                                .font(theme::f_sb(13.5))
                                .color(color),
                        )
                        // Each tab is one atom: it moves to the next row whole
                        // rather than letting its own text break across two.
                        .wrap_mode(egui::TextWrapMode::Extend)
                        .sense(egui::Sense::click()),
                    )
                    .on_hover_cursor(egui::CursorIcon::PointingHand);
                if active {
                    let y = resp.rect.bottom() + 6.0;
                    ui.painter().line_segment(
                        [
                            egui::pos2(resp.rect.left(), y),
                            egui::pos2(resp.rect.right(), y),
                        ],
                        egui::Stroke::new(2.0, p.accent),
                    );
                }
                resp.clicked()
            };
            for slot in [
                PivSlotSel::Auth,
                PivSlotSel::Sign,
                PivSlotSel::KeyMgmt,
                PivSlotSel::CardAuth,
            ] {
                if tab(ui, slot.label(), selected == slot) {
                    clicked_slot = Some(slot);
                }
            }
            // The twenty retired slots are a peer of the four standard ones, so
            // they get a tab of their own rather than a section wedged between
            // this strip and the cards it heads. Their own pane then has room to
            // list all twenty — a wrapped row of chips here would have swamped
            // the strip the moment more than a couple held keys.
            let retired_active = matches!(selected, PivSlotSel::Retired(_));
            if tab(
                ui,
                "retired keys (82\u{2013}95)".to_string(),
                retired_active,
            ) {
                click_retired_tab = true;
            }
            // Anchored to the tab rather than a line of prose above the list:
            // the list's own dots already say what is occupied, so a sentence
            // there was only restating them. Shown while the tab is active so
            // the strip stays clean the rest of the time.
            if retired_active {
                ui.add_space(2.0);
                self.help_dot(ui, p, "piv-retired");
            }
        });
        {
            let row = strip_resp.response.rect;
            let strip = egui::Rect::from_min_max(
                egui::pos2(ui.max_rect().left(), row.top() - 4.0),
                egui::pos2(ui.max_rect().right(), row.bottom() + 6.0),
            );
            ui.painter()
                .set(strip_bg, egui::Shape::rect_filled(strip, 0.0, p.surface));
        }
        // --- Retired-slot rail (only on the retired tab) --------------------
        // All twenty slots, listed the way the Molto2 view lists its profiles:
        // one row each, a filled dot on the right for the ones holding a key,
        // the selected row filled with the soft accent. Occupancy is read
        // lazily the first time this tab is opened — checking it means asking
        // the card about each of the twenty in turn, which is not worth doing
        // on every status refresh.
        if matches!(selected, PivSlotSel::Retired(_)) {
            ui.add_space(14.0);
            match self.piv.retired_occupancy.clone() {
                Some(occ) => {
                    // Show as many rows as the pane can spare before the action
                    // cards below, then scroll. Twenty rows fit outright on a
                    // reasonably tall window.
                    let rail_h = (ui.available_height() - 300.0).clamp(150.0, 20.0 * 30.0);
                    egui::ScrollArea::vertical()
                        .id_salt("piv-retired-rail")
                        .auto_shrink([false, false])
                        .max_height(rail_h)
                        .show(ui, |ui| {
                            ui.set_width(300.0);
                            for (slot, key) in occ {
                                let keyroost_piv::Slot::Retired(n) = slot else {
                                    continue;
                                };
                                let has_key = key == keyroost_transport::SlotKeyPresence::Present;
                                let sel_variant = PivSlotSel::Retired(n);
                                let active = selected == sel_variant;
                                let (rect, resp) = ui.allocate_exact_size(
                                    egui::vec2(ui.available_width(), 30.0),
                                    egui::Sense::click(),
                                );
                                let bg = if active {
                                    p.accent_soft()
                                } else if resp.hovered() {
                                    p.line_soft
                                } else {
                                    egui::Color32::TRANSPARENT
                                };
                                ui.painter().rect(
                                    rect,
                                    egui::CornerRadius::same(8),
                                    bg,
                                    egui::Stroke::NONE,
                                    egui::StrokeKind::Inside,
                                );
                                ui.painter().text(
                                    rect.left_center() + egui::vec2(12.0, 0.0),
                                    egui::Align2::LEFT_CENTER,
                                    format!("Slot {:02X} \u{00B7} retired key {n}", 0x81 + n),
                                    theme::f_mono(12.5),
                                    if active {
                                        p.accent
                                    } else if has_key {
                                        p.txt
                                    } else {
                                        p.txt3
                                    },
                                );
                                // Same affordance as the Molto2 rail's seed dot:
                                // presence is a mark on the row, not a word.
                                if has_key {
                                    ui.painter().circle_filled(
                                        egui::pos2(rect.right() - 12.0, rect.center().y),
                                        3.0,
                                        if active { p.accent } else { p.ok },
                                    );
                                }
                                let resp =
                                    resp.on_hover_text(piv_retired_slot_hover(&slot.label(), key));
                                if resp
                                    .on_hover_cursor(egui::CursorIcon::PointingHand)
                                    .clicked()
                                {
                                    clicked_slot = Some(sel_variant);
                                }
                            }
                        });
                }
                None => note(ui, "Reading retired slots\u{2026}"),
            }
        }
        // --- Selected slot content (single column under the strip) ----------
        // State line for the active slot, then the styled full-width action
        // cards (unchanged from the old detail column) in single-column flow.
        ui.add_space(14.0);
        ui.label(
            egui::RichText::new(format!("State: {sel_state}"))
                .font(theme::f_reg(12.5))
                .color(p.txt2),
        );
        ui.add_space(10.0);
        // Same `add_enabled_ui` inheritance trick as the status card above —
        // one wrap covers the per-slot action card and the "Reset applet"
        // card below it, dimming Generate/Certificate/Delete/Move/Test and
        // Reset together for any in-flight PIV job (`self.piv.inflight`).
        // The slot tab strip and retired-slot rail above this point stay
        // outside any wrap, so selecting a different slot (or a different
        // retired key) still works while a job is in flight.
        ui.add_enabled_ui(!self.piv.inflight, |ui| {
            theme::card_frame(p).show(ui, |ui| {
                ui.set_min_width(ui.available_width());

                // --- Generate key: bold label + help left, algorithm combo
                // and primary button pinned right (FIDO2 setting-row shape).
                // Each algorithm is gated independently
                // (`PivExtension::SlotKeyAlgorithm`, resolved eagerly into
                // `keyalg_gate` above) the same way Move/Delete key are gated
                // elsewhere in this pane — not every device implements every
                // algorithm, standardized or not (see that extension's own
                // doc).
                //
                // Same "don't leave a selection the combo can no longer
                // offer" treatment as the PIN/touch policy combos in the
                // Generate Key modal: a prior selection that's since become
                // known-unsupported (e.g. after switching readers) falls back
                // to the first selectable algorithm rather than staying
                // selected-but-disabled — see
                // `piv_keyalg_unsupported_fallback`'s own doc for why
                // `EccP256` is only a fallback-of-last-resort here, not
                // returned unconditionally.
                self.piv.gen_alg = piv_keyalg_unsupported_fallback(
                    self.piv.gen_alg,
                    keyroost_piv::KeyAlg::EccP256,
                    keyalg_gate,
                );
                let unverified_algs: Vec<&str> = keyroost_piv::KeyAlg::ALL
                    .into_iter()
                    .filter(|&alg| keyalg_gate(alg) == FeatureGate::Unverified)
                    .map(keyroost_piv::KeyAlg::label)
                    .collect();
                let gen_alg_unverified_hint = format!(
                    "No entry for this key in keyroost's list: {}.",
                    unverified_algs.join(", ")
                );
                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new("Generate key")
                            .font(theme::f_sb(13.5))
                            .color(p.txt),
                    );
                    ui.add_space(6.0);
                    self.help_dot(ui, p, "piv-generate");
                    // Same warn-triangle convention as Move/Delete/Reset key below:
                    // sits right after the help dot rather than a printed line, so
                    // "support unverified" reads the same way everywhere in this
                    // pane instead of being the one section that just prints it.
                    if !unverified_algs.is_empty() {
                        ui.add_space(4.0);
                        theme::warn_marker(ui, p).on_hover_text(gen_alg_unverified_hint.as_str());
                    }
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if theme::button(ui, p, BtnKind::Default, "Generate\u{2026}").clicked() {
                            open_generate = true;
                        }
                        ui.add_space(8.0);
                        piv_keyalg_combo(ui, "piv-gen-alg", &mut self.piv.gen_alg, keyalg_gate);
                    });
                });
                // Derived from the per-device session cache rather than a
                // dedicated field: that cache now survives switching to
                // another device's tab and back (see `App::piv_session_state`'s
                // doc), so this naturally does too, and it always reflects
                // whichever slot is currently selected rather than "whatever
                // was last generated, regardless of slot".
                let gen_pubkey_pem = self
                    .selected_device
                    .as_ref()
                    .and_then(|id| self.piv_session_state.get(id))
                    .and_then(|state| state.cached_pubkey(self.piv.selected_slot.to_slot()))
                    .and_then(|(alg, key)| {
                        keyroost_piv::spki::subject_public_key_info(key, alg).ok()
                    })
                    .map(|der| keyroost_piv::spki::to_pem(&der));
                if let Some(pem) = &gen_pubkey_pem {
                    ui.add_space(6.0);
                    ui.add(
                        egui::TextEdit::multiline(&mut pem.as_str())
                            .desired_rows(4)
                            .desired_width(f32::INFINITY)
                            .font(egui::TextStyle::Monospace),
                    );
                    ui.add_space(4.0);
                    // `with_layout` must be nested inside a `ui.horizontal` (as
                    // every other right-aligned action row in this pane does),
                    // not called directly on the card's top-down `ui`: called
                    // bare, its child `Ui` inherits the *entire remaining
                    // vertical space* of the card as its max_rect, and
                    // `Align::Center` then centers the button within all of
                    // that leftover height — which the row then allocates back
                    // into the parent as its own height. On a window taller
                    // than default that reads as a big dead gap here with the
                    // button floating in the middle of it.
                    ui.horizontal(|ui| {
                        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                            if theme::button(ui, p, BtnKind::Ghost, "Copy public key").clicked() {
                                copy_pem = Some(pem.clone());
                            }
                        });
                    });
                }

                ui.add_space(12.0);
                // --- Certificate: title row carries both issue actions
                // right-aligned — "Sign & save CSR" then "Self-signed -> slot" —
                // same layout "Import/Export cert" below uses, rather than
                // sharing a row with the subject/validity inputs (three "Valid
                // for" fields plus two buttons would collapse/wrap at narrow
                // window widths). Each is signed by the slot's key, so both dim
                // with the same reason when the slot has none. "Sign & save
                // CSR" opens a save dialog first (see `drain_file_dialogs`);
                // "Self-signed -> slot" opens the PIN / management-key modal.
                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new("Certificate")
                            .font(theme::f_sb(13.5))
                            .color(p.txt),
                    );
                    ui.add_space(6.0);
                    self.help_dot(ui, p, "piv-certificate");
                    // right_to_left: add "Self-signed" first so it sits at the
                    // far right, then "Sign & save CSR" to its left.
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if selected_has_key && sel_key_can_sign {
                            if theme::button(ui, p, BtnKind::Default, "Self-signed \u{2192} slot")
                                .clicked()
                            {
                                open_self_sign = true;
                            }
                        } else {
                            theme::button_disabled(ui, p, "Self-signed \u{2192} slot")
                                .on_hover_text(if selected_has_key {
                                    cant_sign_hint
                                } else {
                                    no_slot_key_hint
                                });
                        }
                        ui.add_space(8.0);
                        if selected_has_key && sel_key_can_sign {
                            if theme::button(ui, p, BtnKind::Default, "Sign & save CSR\u{2026}")
                                .clicked()
                            {
                                open_csr = true;
                            }
                        } else {
                            theme::button_disabled(ui, p, "Sign & save CSR\u{2026}").on_hover_text(
                                if selected_has_key {
                                    cant_sign_hint
                                } else {
                                    no_slot_key_hint
                                },
                            );
                        }
                    });
                });
                ui.add_space(6.0);
                text_field(
                    ui,
                    p,
                    "Name",
                    &mut self.piv.cert_subject,
                    "e.g. Alice — or full CN=Alice,O=Example,C=US",
                    300.0,
                );
                ui.horizontal(|ui| {
                    // Same 96px label column `text_field` uses for the "Name" row
                    // above, so this label lines up with it and the fields below
                    // start at the same x.
                    ui.add_sized(
                        [96.0, 22.0],
                        egui::Label::new(
                            egui::RichText::new("Valid for")
                                .font(theme::f_reg(13.0))
                                .color(p.txt2),
                        ),
                    );
                    piv_valid_for_fields(
                        ui,
                        unix_now(),
                        &mut self.piv.cert_valid_years,
                        &mut self.piv.cert_valid_months,
                        &mut self.piv.cert_valid_days,
                    );
                });
                // Key usage: remembered per device:slot, initialised from the PIV
                // standard's value for the slot.
                let (mut ext, usage_alg, usage_default) = self.piv_sync_key_usage();
                let usage_slot_key = (self.selected_device.clone(), self.piv.selected_slot);
                let usage_degraded = keyroost_piv::x509::piv_default_degrades_to_undefined(
                    self.piv.selected_slot.to_slot(),
                    usage_alg,
                );
                // Degraded default: Undefined is a separate pick from "Slot default".
                let mut explicit_undefined = usage_degraded
                    && ext.usages.is_empty()
                    && self
                        .piv
                        .cert_key_usage_explicit_undefined
                        .contains(&usage_slot_key);
                let default_selected = if usage_degraded {
                    ext == usage_default && !explicit_undefined
                } else {
                    ext == usage_default
                };
                ui.add_space(4.0);
                ui.horizontal(|ui| {
                    // Same 96px label column as the rows above, so the combo's
                    // left edge lines up with the years field.
                    ui.add_sized(
                        [96.0, 22.0],
                        egui::Label::new(
                            egui::RichText::new("Key usage")
                                .font(theme::f_reg(13.0))
                                .color(p.txt2),
                        ),
                    );
                    // The caption wraps at the pane edge (leaving room for the warning
                    // marker) instead of running off a narrow window.
                    let combo = ui
                        .scope(|ui| {
                            ui.set_max_width((ui.available_width() - 28.0).max(120.0));
                    egui::ComboBox::from_id_salt("piv-cert-key-usage")
                        .wrap()
                        .selected_text(key_usage_summary(ext, usage_default, usage_degraded && !explicit_undefined))
                        .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
                        .show_ui(ui, |ui| {
                            let (default_label, default_hint) = if usage_degraded {
                                (
                                    egui::RichText::new("\u{26A0} Slot default (undefined)")
                                        .color(p.warn),
                                    format!(
                                        "\u{26A0} The PIV standard's key usage for this slot \
                                         (key agreement) can't be backed by {} keys, so the \
                                         slot default degrades to Undefined: no keyUsage \
                                         extension is written. Select usages explicitly to \
                                         add one.",
                                        usage_alg.map_or("this slot's", |a| a.label())
                                    ),
                                )
                            } else {
                                (
                                    egui::RichText::new("Slot default"),
                                    "Select the key usage extension the PIV standard defines \
                                     for this slot: its usages, marked critical (for none, \
                                     same as Undefined). Selected automatically whenever \
                                     exactly that is selected; it only affects this menu, \
                                     not the certificate."
                                        .to_owned(),
                                )
                            };
                            if ui
                                .selectable_label(default_selected, default_label)
                                .on_hover_text(default_hint)
                                .clicked()
                            {
                                ext = usage_default;
                                explicit_undefined = false;
                            }
                            if ui
                                .selectable_label(
                                    ext.usages.is_empty()
                                        && !(usage_degraded && default_selected),
                                    "Undefined",
                                )
                                .on_hover_text(
                                    "Write no keyUsage extension to the certificate. \
                                     Cannot be combined with other usages or Critical.",
                                )
                                .clicked()
                            {
                                ext = keyroost_piv::x509::KeyUsageExt::default();
                                explicit_undefined = usage_degraded;
                            }
                            // Critical flag: only meaningful with at least one usage.
                            if ui
                                .add_enabled(
                                    !ext.usages.is_empty(),
                                    egui::Button::selectable(ext.critical, "Critical"),
                                )
                                .on_hover_text(
                                    "Mark the keyUsage extension critical: software that \
                                     doesn't understand or can't honour it must reject the \
                                     certificate. Required by the PIV standard.",
                                )
                                .on_disabled_hover_text(
                                    "Select at least one usage first. Undefined writes no \
                                     extension, so there is nothing to mark critical.",
                                )
                                .clicked()
                            {
                                ext.critical = !ext.critical;
                            }
                            for (bit, label, hint) in KEY_USAGE_CHOICES {
                                let on = ext.usages.contains(bit);
                                let usable = usage_alg.is_none_or(|a| {
                                    keyroost_piv::x509::supported_key_usages(a).contains(bit)
                                });
                                // Unsupported usages stay selectable but are flagged
                                // in the pane's warning colour.
                                let r = if usable {
                                    ui.add(egui::Button::selectable(on, label))
                                        .on_hover_text(hint)
                                } else {
                                    ui.add(egui::Button::selectable(
                                        on,
                                        egui::RichText::new(format!("\u{26A0} {label}"))
                                            .color(p.warn),
                                    ))
                                    .on_hover_text(format!(
                                        "{hint}\n\n\u{26A0} Incompatible with this slot's key type; a \
                                         certificate asserting it may be rejected."
                                    ))
                                };
                                if r.clicked() {
                                    ext.usages = toggle_key_usage(ext.usages, bit, !on);
                                    ext.critical &= !ext.usages.is_empty();
                                }
                            }
                        })
                        })
                        .inner;
                    combo.response.on_hover_text(
                        "Key usage is optional: left at Undefined, no key usage extension \
                         is written. It starts out set to the PIV standard's value for the \
                         slot (Undefined where the standard defines none), and you can \
                         select multiple usages. Critical marks the extension critical.",
                    );
                    // Selected usages this slot's key can't back: flag them next
                    // to the box, and list them on hover.
                    let incompatible: Vec<&str> = usage_alg
                        .map(|alg| {
                            let ok = keyroost_piv::x509::supported_key_usages(alg);
                            KEY_USAGE_CHOICES
                                .iter()
                                .filter(|(b, _, _)| ext.usages.contains(*b) && !ok.contains(*b))
                                .map(|(_, l, _)| *l)
                                .collect()
                        })
                        .unwrap_or_default();
                    if !incompatible.is_empty() {
                        ui.label(
                            egui::RichText::new("\u{26A0}")
                                .font(theme::f_reg(14.0))
                                .color(p.warn),
                        )
                        .on_hover_text(format!(
                            "Incompatible with this slot's key type ({}): {}.\n\nkeyroost still \
                             creates the certificate, but a certificate authority (or \
                             whatever later checks the certificate) may reject it or \
                             change the requested usages.",
                            usage_alg.map_or("", |a| a.label()),
                            incompatible.join(", ")
                        ));
                    }
                    // Slot default selected but degraded to undefined: same marker.
                    if usage_degraded && ext == usage_default && !explicit_undefined {
                        ui.label(
                            egui::RichText::new("\u{26A0}")
                                .font(theme::f_reg(14.0))
                                .color(p.warn),
                        )
                        .on_hover_text(format!(
                            "The slot default is undefined here: the PIV standard's key \
                             usage for this slot (key agreement) can't be backed by {} keys, \
                             so no keyUsage extension is written. Select usages explicitly \
                             to add one.",
                            usage_alg.map_or("this slot's", |a| a.label())
                        ));
                    }
                    if explicit_undefined && ext.usages.is_empty() {
                        self.piv
                            .cert_key_usage_explicit_undefined
                            .insert(usage_slot_key.clone());
                    } else {
                        self.piv
                            .cert_key_usage_explicit_undefined
                            .remove(&usage_slot_key);
                    }
                    self.piv.cert_key_usage.insert(
                        (self.selected_device.clone(), self.piv.selected_slot),
                        (ext, usage_alg),
                    );
                });

                ui.add_space(12.0);
                // --- Import / Export cert: both buttons on one right-aligned row,
                // "Import certificate" then "Export certificate". Import opens a
                // file picker then the management-key modal; Export opens a save
                // dialog and writes straight to the chosen path — no secret (see
                // `drain_file_dialogs`). Export dims when the slot holds no cert.
                // Import dims only when the slot is *confirmed* empty
                // (`slot_confirmed_empty`, same gate "Delete key" uses) — an
                // unconfirmed reading leaves it enabled, since a matching key may
                // have been loaded out of band this session can't see.
                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new("Import/Export cert")
                            .font(theme::f_sb(13.5))
                            .color(p.txt),
                    );
                    ui.add_space(6.0);
                    self.help_dot(ui, p, "piv-import-export");
                    // right_to_left: add "Export" first so it sits at the far
                    // right, then "Import" to its left.
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if selected_has_cert {
                            if theme::button(ui, p, BtnKind::Default, "Export certificate\u{2026}")
                                .clicked()
                            {
                                go_export = true;
                            }
                        } else {
                            theme::button_disabled(ui, p, "Export certificate\u{2026}")
                                .on_hover_text(no_slot_cert_hint);
                        }
                        ui.add_space(8.0);
                        if slot_confirmed_empty(get_slot_key_status_gate, selected_has_key) {
                            theme::button_disabled(ui, p, "Import certificate\u{2026}")
                                .on_hover_text(no_import_cert_hint);
                        } else if theme::button(
                            ui,
                            p,
                            BtnKind::Default,
                            "Import certificate\u{2026}",
                        )
                        .clicked()
                        {
                            open_import = true;
                        }
                    });
                });

                ui.add_space(12.0);
                // --- Move key: its own row, above Delete. It used to be a button
                // inside the Delete row, which put a deliberately non-destructive
                // action under a destructive heading and left it sharing the delete
                // help text — the one place a user checking "is this safe?" would
                // look. The row is always shown so the capability stays
                // discoverable; the button is dimmed with a hover reason when the
                // slot has no key to move, or on pre-5.7 firmware.
                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new("Move key")
                            .font(theme::f_sb(13.5))
                            .color(p.txt),
                    );
                    ui.add_space(6.0);
                    self.help_dot(ui, p, "piv-move");
                    // Support-unverified warning sits right after the help dot, by
                    // the operation's own explanation — not out by the button. It
                    // reflects the device's MOVE KEY support, so it shows whether or
                    // not this slot currently has a key for the button to act on
                    // (the button may be dimmed for "no key" underneath it).
                    if matches!(move_key_gate, FeatureGate::Unverified) {
                        ui.add_space(4.0);
                        theme::warn_marker(ui, p).on_hover_text(move_key_unverified_hint.as_str());
                    }
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        match move_key_gate {
                            // Known-unsupported on this device wins over "no key": the
                            // firmware reason is the one the user has to resolve
                            // first, and it holds whether or not the slot is empty.
                            FeatureGate::Unsupported => {
                                theme::button_disabled(ui, p, "Move key\u{2026}")
                                    .on_hover_text(move_key_blocked_hint.as_str());
                            }
                            // Unverified still runs — the card refuses if it truly
                            // can't — so the button stays live where there is a key;
                            // only the warning above marks the doubt.
                            FeatureGate::Supported | FeatureGate::Unverified => {
                                if !selected_has_key {
                                    theme::button_disabled(ui, p, "Move key\u{2026}")
                                        .on_hover_text(no_move_key_hint);
                                } else if theme::button(ui, p, BtnKind::Default, "Move key\u{2026}")
                                    .clicked()
                                {
                                    open_move_key = true;
                                }
                            }
                        }
                    });
                });
                ui.add_space(12.0);
                // --- Delete: bold label + help left, the two delete
                // actions right-aligned (Delete key is Danger, gated 5.7+).
                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new("Delete")
                            .font(theme::f_sb(13.5))
                            .color(p.txt),
                    );
                    ui.add_space(6.0);
                    self.help_dot(ui, p, "piv-delete");
                    // Support-unverified warning for "Delete key" sits here, beside
                    // the row's help dot — not out by the button — so its hover
                    // text names "Delete key" explicitly and spells out that
                    // "Delete certificate" (the other button on this row) is
                    // standard PIV and unaffected.
                    if matches!(delete_key_gate, FeatureGate::Unverified) {
                        ui.add_space(4.0);
                        theme::warn_marker(ui, p).on_hover_text(format!(
                            "{delete_key_unverified_hint} \u{201c}Delete certificate\u{201d} is \
                         standard PIV and unaffected."
                        ));
                    }
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        match delete_key_gate {
                            // Unsupported blocks outright, regardless of slot
                            // content — an operation the device can't run at all
                            // is the reason to lead with, not slot occupancy.
                            FeatureGate::Unsupported => {
                                // Kept visible but dimmed on pre-5.7 firmware so the
                                // action is discoverable; the hover text says why it
                                // can't run yet.
                                theme::button_disabled(ui, p, "Delete key\u{2026}")
                                    .on_hover_text(delete_key_blocked_hint.as_str());
                            }
                            // Unverified still runs — the card refuses if it truly
                            // can't — so the button stays live unless the slot's
                            // emptiness is independently confirmed below; only the
                            // warning by the help dot marks the firmware doubt.
                            FeatureGate::Supported | FeatureGate::Unverified => {
                                if slot_confirmed_empty(get_slot_key_status_gate, selected_has_key)
                                {
                                    theme::button_disabled(ui, p, "Delete key\u{2026}")
                                        .on_hover_text(no_del_key_hint);
                                } else if theme::button(
                                    ui,
                                    p,
                                    BtnKind::Danger,
                                    "Delete key\u{2026}",
                                )
                                .clicked()
                                {
                                    open_delete_key = true;
                                }
                            }
                        }
                        ui.add_space(6.0);
                        // "Delete certificate" is standard PIV, so no firmware gate
                        // — but like Export it needs a certificate to act on. Same
                        // cert-presence signal, same optimistic fallback for retired
                        // slots / pre-first-read. "Delete key" only gets the
                        // equivalent empty-slot treatment when this device actually
                        // confirms slot occupancy
                        // (`PivExtension::GetSlotKeyStatus`, checked inside the
                        // match above via `slot_confirmed_empty`) — everywhere
                        // else it stays enabled whenever DELETE KEY itself is:
                        // without a confirmed signal, key presence is simply
                        // unknown, and a stale key is still worth an attempt to
                        // erase.
                        if selected_has_cert {
                            if theme::button(ui, p, BtnKind::Default, "Delete certificate\u{2026}")
                                .clicked()
                            {
                                open_delete_cert = true;
                            }
                        } else {
                            theme::button_disabled(ui, p, "Delete certificate\u{2026}")
                                .on_hover_text(no_del_cert_hint);
                        }
                    });
                });

                // --- Test: one button that runs every self-test the selected
                // slot's key supports (decrypt / key-agree / sign, in that order)
                // and reports each result. Read-only — the card operates but
                // nothing is written. Live only when the slot holds a certificate
                // with a key type keyroost can test. Placed last in the card,
                // below the other slot actions, since it's a diagnostic rather
                // than a slot-management action.
                ui.add_space(12.0);
                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new("Test")
                            .font(theme::f_sb(13.5))
                            .color(p.txt),
                    );
                    ui.add_space(6.0);
                    self.help_dot(ui, p, "piv-test");
                    let (test_alg, test_has_cert) = self.piv_selected_test_target();
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if test_has_cert && test_alg.is_some() {
                            if theme::button(ui, p, BtnKind::Default, "Test\u{2026}").clicked() {
                                open_self_test = true;
                            }
                        } else {
                            let why = if !test_has_cert {
                                "Needs a certificate in this slot."
                            } else {
                                "The slot's key type is unknown."
                            };
                            ui.add_enabled_ui(false, |ui| {
                                theme::button(ui, p, BtnKind::Default, "Test\u{2026}")
                            })
                            .inner
                            .on_disabled_hover_text(why);
                        }
                    });
                });
            });
            ui.add_space(12.0);

            // Reset applet — its own destructive card with a red stroke at the
            // bottom of the pane (mirrors the FIDO2 "Reset this key" card exactly),
            // full width, description left + red button right.
            theme::card_frame(p)
                .stroke(egui::Stroke::new(1.0, theme::tint(p.err, 90)))
                .show(ui, |ui| {
                    ui.set_min_width(ui.available_width());
                    ui.horizontal(|ui| {
                        ui.label(
                            egui::RichText::new("Reset applet")
                                .font(theme::f_sb(14.5))
                                .color(p.err),
                        );
                        ui.add_space(6.0);
                        self.help_dot(ui, p, "reset");
                        // Same three-way gate as Move key / Delete key, from the
                        // same `keyroost_piv::compat` known-support table — see
                        // `reset_gate`'s definition above.
                        if matches!(reset_gate, FeatureGate::Unverified) {
                            ui.add_space(4.0);
                            theme::warn_marker(ui, p).on_hover_text(reset_unverified_hint.as_str());
                        }
                        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                            match reset_gate {
                                // Unverified still runs — the card refuses if it
                                // truly can't — so the button stays live; only
                                // the warning above marks the doubt.
                                FeatureGate::Supported | FeatureGate::Unverified => {
                                    if theme::button(ui, p, BtnKind::Danger, "Reset applet\u{2026}")
                                        .clicked()
                                    {
                                        arm_reset = true;
                                    }
                                }
                                FeatureGate::Unsupported => {
                                    // Kept visible but dimmed so the capability
                                    // stays discoverable; the hover text says why
                                    // it can't run yet.
                                    theme::button_disabled(ui, p, "Reset applet\u{2026}")
                                        .on_hover_text(reset_blocked_hint.as_str());
                                }
                            }
                        });
                    });
                    ui.label(
                        egui::RichText::new(if matches!(reset_gate, FeatureGate::Supported) {
                            // Known-supported: `force_reset_if_known_supported`
                            // burns the PIN/PUK retry counters itself when
                            // needed, so the precondition below no longer
                            // applies to what this button actually does.
                            "Wipes ALL PIV keys, certificates, and PINs."
                        } else {
                            "Wipes ALL PIV keys, certificates, and PINs. Typically requires both \
                         the PIN and PUK to already be blocked."
                        })
                        .font(theme::f_reg(12.5))
                        .color(p.txt2),
                    );
                    if reset_long_running {
                        ui.add_space(4.0);
                        ui.label(
                            egui::RichText::new(
                                keyroost_piv::compat::PivQuirk::RESET_LONG_RUNNING_HINT,
                            )
                            .font(theme::f_reg(12.5))
                            .color(p.warn),
                        );
                    }
                    if show_reset_global_alternative {
                        ui.add_space(6.0);
                        // Same click-sense-label style as the Overview cards' own
                        // "Manage →" jump (`App::card_head`) — an accent-colored
                        // text link, not a button, since this isn't itself an
                        // action, just a pointer to where the action lives; same
                        // browser-style pointing-hand cursor on hover, too.
                        if ui
                            .add(
                                egui::Label::new(
                                    egui::RichText::new("Factory reset supported \u{2192}")
                                        .font(theme::f_sb(12.5))
                                        .color(p.accent),
                                )
                                .sense(egui::Sense::click()),
                            )
                            .on_hover_cursor(egui::CursorIcon::PointingHand)
                            .clicked()
                        {
                            go_to_overview = true;
                        }
                    }
                });
            // Compatibility table: the last thing on the pane, shown only when
            // it matters — something is greyed out because the table says so,
            // or the user already chose to unlock it for this key.
            let ignored = self.piv_compat_ignored_selected();
            let unsupported = self.piv.status.as_ref().map_or(0, |st| {
                piv_compat_unsupported_count(
                    st.applet_fingerprint,
                    st.version.as_deref(),
                    st.version_firmware.as_deref(),
                )
            });
            if ignored || unsupported > 0 {
                ui.add_space(12.0);
                ui.horizontal(|ui| {
                    let (text, link, tip) = if ignored {
                        (
                            "Unsupported PIV features are enabled for this key.".to_string(),
                            "Undo",
                            "Grey them out again.",
                        )
                    } else {
                        (
                            if unsupported == 1 {
                                "1 PIV feature is marked unsupported for this key.".to_string()
                            } else {
                                format!(
                                    "{unsupported} PIV features are marked unsupported for this key."
                                )
                            },
                            "Enable Anyway",
                            "If this key can't do one of them, it will just refuse.",
                        )
                    };
                    ui.label(
                        egui::RichText::new(text)
                            .font(theme::f_reg(12.5))
                            .color(if ignored { p.warn } else { p.txt2 }),
                    );
                    if ui
                        .add(
                            egui::Label::new(
                                egui::RichText::new(link)
                                    .font(theme::f_sb(12.5))
                                    .color(p.accent),
                            )
                            .sense(egui::Sense::click()),
                        )
                        .on_hover_cursor(egui::CursorIcon::PointingHand)
                        .on_hover_text(tip)
                        .clicked()
                    {
                        toggle_compat_table = true;
                    }
                });
            }
        });

        // Apply collected intents now that the card borrows have ended.
        if let Some(slot) = clicked_slot {
            self.piv.selected_slot = slot;
        }
        if do_refresh {
            self.load_piv_status_with_cache(LogKind::User, PivCache::Bypass);
        }
        // The three buttons open the centered credential modal; the modal itself
        // (rendered once per frame) runs the actual op. Opening wipes any stale
        // fields first so a fresh dialog starts blank.
        if open_change_pin {
            self.piv_cred_modal_close();
            self.piv.cred_modal = Some(PivCredModal::new(PivCredKind::ChangePin));
        }
        if open_change_puk {
            self.piv_cred_modal_close();
            self.piv.cred_modal = Some(PivCredModal::new(PivCredKind::ChangePuk));
        }
        if open_unblock {
            self.piv_cred_modal_close();
            self.piv.cred_modal = Some(PivCredModal::new(PivCredKind::UnblockPin));
        }
        // The management-key-gated operations open the centered credential modal
        // (which collects their secrets and runs the op on Submit) rather than
        // running directly. Opening wipes any stale secret fields first so a
        // fresh dialog starts blank.
        if open_generate {
            self.piv_cred_modal_close();
            self.piv.cred_modal = Some(PivCredModal::new(PivCredKind::GenerateKey));
        }
        // Import / Export / CSR ask for the file first; the picked path is
        // routed by `drain_file_dialogs`, which then opens the secret modal
        // (import, CSR) or runs the write straight away (export).
        if open_import {
            self.spawn_file_dialog(
                FileTarget::PivCert,
                false,
                &[
                    ("Certificates", &["pem", "der", "crt", "cer"]),
                    ("All files", &["*"]),
                ],
                None,
            );
        }
        if go_export {
            self.spawn_file_dialog(
                FileTarget::PivExport,
                true,
                &[
                    ("Certificate (DER)", &["der", "cer"]),
                    ("Certificate (PEM)", &["pem", "crt"]),
                    ("All files", &["*"]),
                ],
                Some("cert.der"),
            );
        }
        if open_self_sign {
            self.piv_cred_modal_close();
            self.piv.cred_modal = Some(PivCredModal::new(PivCredKind::SelfSign));
        }
        if open_csr {
            self.spawn_file_dialog(
                FileTarget::PivCsr,
                true,
                &[("CSR", &["csr", "pem"]), ("All files", &["*"])],
                Some("request.csr"),
            );
        }
        if open_set_retries {
            self.piv_cred_modal_close();
            self.piv.cred_modal = Some(PivCredModal::new(PivCredKind::SetRetries));
        }
        if open_change_mgmt {
            self.piv_cred_modal_close();
            self.piv.cred_modal = Some(PivCredModal::new(PivCredKind::ChangeMgmtKey));
        }
        if open_delete_cert {
            self.piv_cred_modal_close();
            self.piv.cred_modal = Some(PivCredModal::new(PivCredKind::DeleteCert));
        }
        if open_delete_key {
            self.piv_cred_modal_close();
            self.piv.cred_modal = Some(PivCredModal::new(PivCredKind::DeleteKey));
        }
        if open_self_test {
            self.piv_cred_modal_close();
            self.piv.cred_modal = Some(PivCredModal::new(PivCredKind::SelfTest));
        }
        if open_move_key {
            self.piv_cred_modal_close();
            self.piv.cred_modal = Some(PivCredModal::new(PivCredKind::MoveKey));
            // Populate retired occupancy so the destination combo can exclude
            // occupied retired slots (the transport re-checks regardless). If
            // the worker is busy the read just doesn't queue; occupancy stays
            // `None` and the modal falls back to treating retired slots as
            // available, with the transport's own occupied-destination check
            // as the backstop.
            if self.piv.retired_occupancy.is_none() {
                let _ = self.load_piv_retired_occupancy();
            }
        }
        if toggle_compat_table {
            if let Some(id) = self.selected_device.clone() {
                if !self.piv_compat_ignored.remove(&id) {
                    self.piv_compat_ignored.insert(id);
                }
            }
            // Re-read so the internal reads the table was skipping (GET
            // METADATA, ATTEST) run — or stop running — straight away.
            self.load_piv_status_with_cache(LogKind::Background, PivCache::Bypass);
        }
        if open_new_chuid {
            self.piv_cred_modal_close();
            self.piv.cred_modal = Some(PivCredModal::new(PivCredKind::NewChuid));
            self.piv_refresh_chuid_guid();
        }
        if click_retired_tab {
            // Opening the tab has to land on a concrete slot, because every
            // action card below targets one. Prefer the first slot that holds a
            // key — the reason to come here is usually an existing archived key
            // — and fall back to retired key 1 when none does or occupancy has
            // not been read yet.
            let first_used = self
                .piv
                .retired_occupancy
                .as_ref()
                .and_then(|occ| {
                    occ.iter()
                        .find(|(_, key)| *key == keyroost_transport::SlotKeyPresence::Present)
                        .and_then(|(slot, _)| match slot {
                            keyroost_piv::Slot::Retired(n) => Some(*n),
                            _ => None,
                        })
                })
                .unwrap_or(1);
            self.piv.selected_slot = PivSlotSel::Retired(first_used);
            if self.piv.retired_occupancy.is_none() {
                // Nothing to undo if this doesn't queue: the pane shows
                // "Reading retired slots…" and the next click retries.
                let _ = self.load_piv_retired_occupancy();
            }
        }
        if arm_reset {
            self.piv.confirm_reset = Some(String::new());
        }
        if go_to_overview {
            self.cap_tab = CapTab::Overview;
        }
        if let Some(pem) = copy_pem {
            ui.ctx().copy_text(pem);
            self.clipboard_clear_at = None; // public key, not a secret to auto-clear
        }
    }

    /// The Molto2 token's dedicated amber view: hero band · customer-key strip ·
    /// 100-slot rail + editor.
    fn molto_view(&mut self, ui: &mut egui::Ui, p: &Palette, dev: &Device) {
        // Make brand-orange the accent throughout the Molto2 view, so its help
        // dots, links, selection highlights and primary action are all one
        // orange rather than mixing the app's blue accent into the token's
        // identity. Green stays for status, red for danger.
        let mp = Palette {
            accent: p.brand,
            ..*p
        };
        let p = &mp;
        let mut open_rename = false;
        let mut do_save = false;
        let mut do_cancel = false;
        // Hero (no amber band — the orange comes from the clock glyph + accents,
        // matching the security-key hero layout and avoiding a muddy brown tint).
        egui::Frame::NONE
            .inner_margin(egui::Margin::symmetric(26, 16))
            .show(ui, |ui| {
                ui.horizontal(|ui| {
                    glyph_tile(ui, 46.0, p.brand, p.accent_ink, None);
                    ui.add_space(12.0);
                    ui.vertical(|ui| {
                        ui.horizontal(|ui| {
                            if self.rename_target.is_some() {
                                (do_save, do_cancel) = self.rename_field_row(ui, p);
                            } else {
                                ui.label(
                                    egui::RichText::new(dev.title())
                                        .font(theme::f_bold(21.0))
                                        .color(p.txt),
                                );
                                ui.add_space(6.0);
                                theme::pill(ui, "Programmable TOTP token", p.brand, p.brand_soft());
                                ui.add_space(4.0);
                                self.help_dot(ui, p, "molto");
                                ui.add_space(6.0);
                                let label = if dev.name.is_some() {
                                    "Rename"
                                } else {
                                    "Name this token"
                                };
                                if ui
                                    .add(
                                        egui::Label::new(
                                            egui::RichText::new(label)
                                                .font(theme::f_sb(12.0))
                                                .color(p.accent),
                                        )
                                        .sense(egui::Sense::click()),
                                    )
                                    .clicked()
                                {
                                    open_rename = true;
                                }
                            }
                        });
                        if self.rename_target.is_some() {
                            // A token can't hold its own name: this computer only.
                            self.rename_details(ui, p, "token");
                        }
                        ui.add_space(2.0);
                        let serial = if dev.serial.is_empty() {
                            "\u{2014}".to_string()
                        } else {
                            dev.serial.clone()
                        };
                        ui.label(
                            egui::RichText::new(format!(
                                "{} \u{00B7} #{} \u{00B7} {} slots",
                                dev.vendor, serial, PROFILES
                            ))
                            .font(theme::f_reg(12.5))
                            .color(p.txt2),
                        );
                    });
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        ui.label(
                            egui::RichText::new("Connected")
                                .font(theme::f_sb(12.5))
                                .color(p.txt2),
                        );
                        ui.add_space(5.0);
                        theme::status_dot(ui, p.ok, 8.0);
                    });
                });
            });
        self.apply_rename_actions(dev, open_rename, do_cancel, do_save);

        // --- Device-wide settings (apply to the whole token) ---
        egui::Frame::NONE
            .inner_margin(egui::Margin::symmetric(26, 14))
            .show(ui, |ui| {
                theme::card_frame(p).show(ui, |ui| {
                    ui.horizontal(|ui| {
                        ui.label(egui::RichText::new("Device").font(theme::f_sb(14.5)).color(p.txt));
                        ui.add_space(6.0);
                        self.help_dot(ui, p, "molto");
                    });
                    ui.add_space(10.0);
                    ui.horizontal(|ui| {
                        ui.add_sized(
                            [104.0, 22.0],
                            egui::Label::new(egui::RichText::new("Customer key").font(theme::f_reg(13.0)).color(p.txt2)),
                        );
                        self.help_dot(ui, p, "custkey");
                        ui.add_space(6.0);
                        let mut rev =
                            self.secret_reveal.get("customer-key").copied().unwrap_or(false);
                        secret_edit(
                            ui,
                            p,
                            &mut self.customer_key_input,
                            &mut rev,
                            "default if empty",
                            200.0,
                        );
                        self.secret_reveal.insert("customer-key", rev);
                        ui.checkbox(&mut self.customer_key_hex, "hex");
                        if theme::button(ui, p, BtnKind::Default, "Authenticate").clicked() {
                            self.authenticate();
                        }
                        if self.authenticated {
                            theme::pill(ui, "authed", p.ok, p.ok_soft());
                        }
                    });
                    ui.add_space(4.0);
                    ui.label(
                        egui::RichText::new("Programming any slot first needs the token's customer key (blank = factory default).")
                            .font(theme::f_reg(11.5))
                            .color(p.txt3),
                    );
                    ui.add_space(12.0);
                    ui.horizontal(|ui| {
                        // Re-read every slot's public block on demand — keyless,
                        // so it works without authenticating. Covers a factory
                        // reset (which clears the list) and a failed open-sweep.
                        if theme::button(ui, p, BtnKind::Default, "Refresh slots").clicked() {
                            self.resweep_slot_meta(LogKind::User);
                        }
                        ui.add_space(6.0);
                        if theme::button(ui, p, BtnKind::Default, "Sync time on all").clicked() {
                            self.sync_time_all();
                        }
                        ui.add_space(6.0);
                        if theme::button(ui, p, BtnKind::Default, "Import file\u{2026}").clicked() {
                            self.import_pick_file(import_flow::Origin::View(
                                import_flow::DestKey {
                                    device: dev.id.clone(),
                                    store: import_flow::StoreKind::Molto2,
                                },
                            ));
                        }
                        ui.add_space(6.0);
                        if theme::button(ui, p, BtnKind::Danger, "Factory reset\u{2026}").clicked() {
                            self.molto_reset_confirm = true;
                        }
                    });
                    if self.molto_reset_confirm {
                        ui.add_space(10.0);
                        egui::Frame::NONE
                            .fill(p.err_soft())
                            .inner_margin(egui::Margin::same(12))
                            .corner_radius(egui::CornerRadius::same(8))
                            .show(ui, |ui| {
                                ui.label(
                                    egui::RichText::new("Factory-reset the token? This wipes all slots, then asks you to confirm with the \u{25B2} button on the device itself.")
                                        .font(theme::f_reg(12.5))
                                        .color(p.txt),
                                );
                                ui.add_space(8.0);
                                ui.horizontal(|ui| {
                                    if theme::button(ui, p, BtnKind::Danger, "Yes, factory reset").clicked() {
                                        self.molto_reset_confirm = false;
                                        self.factory_reset();
                                    }
                                    ui.add_space(6.0);
                                    if theme::button(ui, p, BtnKind::Default, "Cancel").clicked() {
                                        self.molto_reset_confirm = false;
                                    }
                                });
                            });
                    }
                });
            });

        // --- Per-slot programming (applies only to the selected slot) ---
        egui::Frame::NONE
            .inner_margin(egui::Margin::symmetric(26, 4))
            .show(ui, |ui| {
                theme::card_frame(p).show(ui, |ui| {
                    ui.label(egui::RichText::new("Program a slot").font(theme::f_sb(14.5)).color(p.txt));
                    ui.add_space(4.0);
                    ui.label(
                        egui::RichText::new("Pick a slot and program it. Slot titles and occupancy are readable by anyone holding the token \u{2014} no key needed \u{2014} so don't put secrets in titles. Seeds and codes can't be read back; codes show on the device's own screen.")
                            .font(theme::f_reg(11.5))
                            .color(p.txt3),
                    );
                    ui.add_space(10.0);
                    ui.horizontal_top(|ui| {
                        ui.vertical(|ui| {
                            // Wide enough for "Slot NN · " plus a full 12-char
                            // title (the device's title limit) in the mono font,
                            // with the seed dot clear of the text.
                            ui.set_width(212.0);
                            // Fill the remaining height so the rail isn't a fixed
                            // block jammed at the window bottom; leave a margin.
                            let rail_h = (ui.available_height() - 48.0).max(160.0);
                            let mut pick = None;
                            egui::ScrollArea::vertical().auto_shrink([false, false]).max_height(rail_h).show(ui, |ui| {
                                for s in 0..PROFILES {
                                    let selected = s == self.slot;
                                    let (rect, resp) = ui.allocate_exact_size(egui::vec2(ui.available_width(), 30.0), egui::Sense::click());
                                    let bg = if selected {
                                        p.brand_soft()
                                    } else if resp.hovered() {
                                        p.line_soft
                                    } else {
                                        egui::Color32::TRANSPARENT
                                    };
                                    ui.painter().rect(
                                        rect,
                                        egui::CornerRadius::same(8),
                                        bg,
                                        egui::Stroke::NONE,
                                        egui::StrokeKind::Inside,
                                    );
                                    let meta = self
                                        .slot_meta
                                        .as_ref()
                                        .and_then(|m| m.get(s as usize));
                                    let label = match meta.and_then(|b| b.title.as_deref()) {
                                        Some(t) => format!("Slot {s:02} \u{00B7} {}", sanitize_title(t)),
                                        None => format!("Slot {s:02}"),
                                    };
                                    // Clip to the row (short of the seed dot) so a
                                    // maximal title can never paint over the form
                                    // column beside the rail.
                                    let text_clip = egui::Rect::from_min_max(
                                        rect.min,
                                        egui::pos2(rect.right() - 20.0, rect.max.y),
                                    );
                                    ui.painter().with_clip_rect(text_clip).text(
                                        rect.left_center() + egui::vec2(12.0, 0.0),
                                        egui::Align2::LEFT_CENTER,
                                        label,
                                        theme::f_mono(12.5),
                                        if selected { p.brand } else { p.txt2 },
                                    );
                                    if meta.is_some_and(|b| b.seed_present) {
                                        ui.painter().circle_filled(
                                            egui::pos2(rect.right() - 12.0, rect.center().y),
                                            3.0,
                                            p.brand,
                                        );
                                    }
                                    if resp.clicked() {
                                        pick = Some(s);
                                    }
                                }
                            });
                            if let Some(s) = pick {
                                self.slot = s;
                                self.molto_delete_confirm = false;
                            }
                        });
                        ui.add_space(24.0);
                        ui.vertical(|ui| {
                            ui.label(egui::RichText::new(format!("SLOT {:02}", self.slot)).font(theme::f_bold(11.0)).color(p.brand));
                            ui.add_space(10.0);
                            editor_row(ui, p, "Title", |ui| {
                                ui.add(egui::TextEdit::singleline(&mut self.draft.title).hint_text("\u{2264} 12 chars").desired_width(360.0));
                            });
                            editor_row(ui, p, "Secret", |ui| {
                                let mut rev = self
                                    .secret_reveal
                                    .get("molto-secret")
                                    .copied()
                                    .unwrap_or(false);
                                secret_edit(
                                    ui,
                                    p,
                                    &mut self.draft.secret_base32,
                                    &mut rev,
                                    "base32 secret",
                                    360.0,
                                );
                                self.secret_reveal.insert("molto-secret", rev);
                            });
                            // Two columns for the short choices, to use the width.
                            let field_label = |ui: &mut egui::Ui, w: f32, text: &str| {
                                ui.add_sized([w, 22.0], egui::Label::new(egui::RichText::new(text).font(theme::f_reg(13.0)).color(p.txt2)));
                            };
                            ui.horizontal(|ui| {
                                field_label(ui, 92.0, "Algorithm");
                                let cur = match self.draft.algorithm {
                                    AlgoChoice::Sha1 => "SHA1",
                                    AlgoChoice::Sha256 => "SHA256",
                                };
                                if let Some(v) = theme::segmented(ui, p, &["SHA1", "SHA256"], cur, p.brand) {
                                    self.draft.algorithm = if v == "SHA256" { AlgoChoice::Sha256 } else { AlgoChoice::Sha1 };
                                }
                                ui.add_space(30.0);
                                field_label(ui, 50.0, "Digits");
                                let cur = match self.draft.digits {
                                    DigitsChoice::Four => "4",
                                    DigitsChoice::Six => "6",
                                    DigitsChoice::Eight => "8",
                                    DigitsChoice::Ten => "10",
                                };
                                if let Some(v) = theme::segmented(ui, p, &["4", "6", "8", "10"], cur, p.brand) {
                                    self.draft.digits = match v.as_str() {
                                        "4" => DigitsChoice::Four,
                                        "8" => DigitsChoice::Eight,
                                        "10" => DigitsChoice::Ten,
                                        _ => DigitsChoice::Six,
                                    };
                                }
                            });
                            ui.add_space(8.0);
                            ui.horizontal(|ui| {
                                field_label(ui, 92.0, "Time step");
                                let cur = match self.draft.time_step {
                                    StepChoice::S30 => "30s",
                                    StepChoice::S60 => "60s",
                                };
                                if let Some(v) = theme::segmented(ui, p, &["30s", "60s"], cur, p.brand) {
                                    self.draft.time_step = if v == "60s" { StepChoice::S60 } else { StepChoice::S30 };
                                }
                                ui.add_space(30.0);
                                field_label(ui, 50.0, "Display");
                                let cur = match self.draft.display_timeout {
                                    TimeoutChoice::S15 => "15s",
                                    TimeoutChoice::S30 => "30s",
                                    TimeoutChoice::S60 => "60s",
                                    TimeoutChoice::S120 => "120s",
                                };
                                if let Some(v) = theme::segmented(ui, p, &["15s", "30s", "60s", "120s"], cur, p.brand) {
                                    self.draft.display_timeout = match v.as_str() {
                                        "15s" => TimeoutChoice::S15,
                                        "60s" => TimeoutChoice::S60,
                                        "120s" => TimeoutChoice::S120,
                                        _ => TimeoutChoice::S30,
                                    };
                                }
                            });
                            ui.add_space(8.0);
                            ui.horizontal(|ui| {
                                if theme::button(ui, p, BtnKind::Primary, "Write to slot").clicked() {
                                    self.apply_draft();
                                }
                                ui.add_space(6.0);
                                if theme::button(ui, p, BtnKind::Default, "Write title only").clicked() {
                                    self.apply_title_only();
                                }
                                ui.add_space(6.0);
                                if theme::button(ui, p, BtnKind::Danger, "Delete seed\u{2026}").clicked() {
                                    self.molto_delete_confirm = true;
                                }
                                ui.add_space(6.0);
                                if theme::button(ui, p, BtnKind::Default, "Import otpauth\u{2026}").clicked() {
                                    self.import_dialog.open = true;
                                }
                                ui.add_space(6.0);
                                #[cfg(feature = "qr")]
                                {
                                    if scan_qr_button(ui, p) {
                                        self.molto_scan_qr();
                                    }
                                }
                                #[cfg(feature = "qr")]
                                ui.add_space(6.0);
                                if theme::button(ui, p, BtnKind::Default, "Sync time").clicked() {
                                    self.sync_time_selected();
                                }
                            });
                            if self.molto_delete_confirm {
                                ui.add_space(10.0);
                                egui::Frame::NONE
                                    .fill(p.err_soft())
                                    .inner_margin(egui::Margin::same(12))
                                    .corner_radius(egui::CornerRadius::same(8))
                                    .show(ui, |ui| {
                                        ui.label(
                                            egui::RichText::new(format!(
                                                "Delete slot {:02}'s seed? Only the seed is wiped \u{2014} the title stays. No key is needed for this: anyone holding the token could do the same.",
                                                self.slot
                                            ))
                                            .font(theme::f_reg(12.5))
                                            .color(p.txt),
                                        );
                                        ui.add_space(8.0);
                                        ui.horizontal(|ui| {
                                            if theme::button(ui, p, BtnKind::Danger, "Yes, delete seed").clicked() {
                                                self.molto_delete_confirm = false;
                                                self.delete_seed_selected();
                                            }
                                            ui.add_space(6.0);
                                            if theme::button(ui, p, BtnKind::Default, "Cancel").clicked() {
                                                self.molto_delete_confirm = false;
                                            }
                                        });
                                    });
                            }
                        });
                    });
                });
            });
    }

    /// Pane for the single-profile programmable token: shows model/serial/clock
    /// and a form to program a seed + configuration. Uses the brand accent like
    /// the Molto2 view.
    fn prog_view(&mut self, ui: &mut egui::Ui, p: &Palette, dev: &Device) {
        let mp = Palette {
            accent: p.brand,
            ..*p
        };
        let p = &mp;

        // Hero: brand tile + model + serial + on-device clock.
        egui::Frame::NONE
            .inner_margin(egui::Margin::symmetric(26, 16))
            .show(ui, |ui| {
                ui.horizontal(|ui| {
                    glyph_tile(ui, 46.0, p.brand, p.accent_ink, None);
                    ui.add_space(12.0);
                    ui.vertical(|ui| {
                        ui.label(
                            egui::RichText::new(dev.title())
                                .font(theme::f_bold(18.0))
                                .color(p.txt),
                        );
                        let serial = self
                            .prog_info
                            .as_ref()
                            .map(|i| i.serial.clone())
                            .unwrap_or_else(|| dev.serial.clone());
                        ui.label(
                            egui::RichText::new(format!("Token2 · serial {serial}"))
                                .font(theme::f_reg(12.5))
                                .color(p.txt2),
                        );
                        if let Some(info) = &self.prog_info {
                            ui.label(
                                egui::RichText::new(format!(
                                    "device clock (UTC): {}",
                                    fmt_unix_utc(info.utc_time)
                                ))
                                .font(theme::f_reg(12.0))
                                .color(p.txt3),
                            );
                        }
                    });
                });
            });

        ui.separator();

        // Program form.
        egui::Frame::NONE
            .inner_margin(egui::Margin::symmetric(26, 12))
            .show(ui, |ui| {
                ui.label(
                    egui::RichText::new("Program seed & configuration")
                        .font(theme::f_sb(14.0))
                        .color(p.txt),
                );
                ui.add_space(8.0);

                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new("Seed:")
                            .font(theme::f_reg(12.5))
                            .color(p.txt2),
                    );
                    let hint = if self.prog_seed_hex { "hex" } else { "base32" };
                    let mut rev = self
                        .secret_reveal
                        .get("prog-seed")
                        .copied()
                        .unwrap_or(false);
                    secret_edit(ui, p, &mut self.prog_seed_input, &mut rev, hint, 320.0);
                    self.secret_reveal.insert("prog-seed", rev);
                    ui.checkbox(&mut self.prog_seed_hex, "hex");
                });
                ui.add_space(6.0);

                ui.horizontal(|ui| {
                    ui.label(
                        egui::RichText::new("Algorithm:")
                            .font(theme::f_reg(12.5))
                            .color(p.txt2),
                    );
                    egui::ComboBox::from_id_salt("prog-algo")
                        .selected_text(if self.prog_algo_sha256 {
                            "SHA256"
                        } else {
                            "SHA1"
                        })
                        .show_ui(ui, |ui| {
                            ui.selectable_value(&mut self.prog_algo_sha256, false, "SHA1");
                            ui.selectable_value(&mut self.prog_algo_sha256, true, "SHA256");
                        });
                    ui.add_space(12.0);
                    ui.label(
                        egui::RichText::new("Time step:")
                            .font(theme::f_reg(12.5))
                            .color(p.txt2),
                    );
                    egui::ComboBox::from_id_salt("prog-step")
                        .selected_text(if self.prog_step_60 { "60s" } else { "30s" })
                        .show_ui(ui, |ui| {
                            ui.selectable_value(&mut self.prog_step_60, false, "30s");
                            ui.selectable_value(&mut self.prog_step_60, true, "60s");
                        });
                    ui.add_space(12.0);
                    ui.label(
                        egui::RichText::new("Sleep:")
                            .font(theme::f_reg(12.5))
                            .color(p.txt2),
                    );
                    let timeouts = ["15s", "30s", "60s", "120s"];
                    egui::ComboBox::from_id_salt("prog-timeout")
                        .selected_text(timeouts[self.prog_timeout_idx.min(3)])
                        .show_ui(ui, |ui| {
                            for (i, t) in timeouts.iter().enumerate() {
                                ui.selectable_value(&mut self.prog_timeout_idx, i, *t);
                            }
                        });
                });
                ui.add_space(12.0);

                let busy = self.busy();
                let can_burn = !busy && !self.prog_seed_input.trim().is_empty();
                ui.horizontal(|ui| {
                    ui.add_enabled_ui(can_burn, |ui| {
                        if theme::button(ui, p, BtnKind::Primary, "Burn seed").clicked() {
                            self.prog_burn();
                        }
                    });
                    #[cfg(feature = "qr")]
                    {
                        ui.add_space(6.0);
                        if scan_qr_button(ui, p) {
                            self.prog_scan_qr();
                        }
                    }
                });
                ui.add_space(4.0);
                ui.label(
                    egui::RichText::new(
                        "Sets the configuration (clock + parameters) and writes the seed.",
                    )
                    .font(theme::f_reg(11.5))
                    .color(p.txt3),
                );

                if let Some((ok, msg)) = &self.prog_status {
                    ui.add_space(8.0);
                    ui.label(
                        egui::RichText::new(msg)
                            .font(theme::f_sb(12.5))
                            .color(if *ok { p.ok } else { p.err }),
                    );
                }
            });
    }

    /// Authenticate (fixed device key) and program config + seed in one job.
    fn prog_burn(&mut self) {
        self.prog_status = None;
        let Some(reader) = self.selected_device().and_then(|d| d.reader.clone()) else {
            return;
        };
        // Decode the seed up front so input errors surface before any I/O.
        let raw = self.prog_seed_input.trim().to_string();
        let seed = if self.prog_seed_hex {
            keyroost_proto::codec::hex_decode(&raw)
        } else {
            keyroost_proto::codec::base32_decode(&raw)
        };
        let seed = match seed {
            Ok(s) if !s.is_empty() && s.len() <= 63 => s,
            Ok(s) => {
                self.log(
                    Severity::Err,
                    format!("seed length {} out of range (1..=63)", s.len()),
                );
                return;
            }
            Err(e) => {
                self.log(Severity::Err, format!("invalid seed: {e}"));
                return;
            }
        };
        // Pad short seeds to the standard 20-byte TOTP length with trailing
        // zero bytes, matching the vendor tool. Without this a 10-byte base32
        // secret is stored as 10 bytes and the device's codes won't match an
        // authenticator app that uses the same secret padded to 20 bytes.
        let seed = zeroize::Zeroizing::new(keyroost_token2prog::pad_totp_seed(seed));
        let algo = if self.prog_algo_sha256 {
            keyroost_token2prog::HmacAlgo::Sha256
        } else {
            keyroost_token2prog::HmacAlgo::Sha1
        };
        let step = if self.prog_step_60 {
            keyroost_token2prog::TimeStep::Seconds60
        } else {
            keyroost_token2prog::TimeStep::Seconds30
        };
        let timeout = match self.prog_timeout_idx {
            0 => keyroost_token2prog::DisplayTimeout::Sec15,
            2 => keyroost_token2prog::DisplayTimeout::Sec60,
            3 => keyroost_token2prog::DisplayTimeout::Sec120,
            _ => keyroost_token2prog::DisplayTimeout::Sec30,
        };
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs() as u32)
            .unwrap_or(0);
        let for_device = self.selected_device.clone();

        self.spawn_job("Programming token\u{2026}", move || {
            let result = (|| -> Result<(), String> {
                let mut s = Token2ProgSession::open_named(&reader).map_err(|e| e.to_string())?;
                // Refuse to program a device whose serial doesn't match a known
                // Token2 programmable-token model (mirrors the CLI's
                // `prog_guard_model`) — guards against writing to the wrong card
                // on a shared reader.
                let info = s.read_info().map_err(|e| e.to_string())?;
                if info.model().is_none() {
                    return Err(format!(
                        "serial '{}' does not match any known Token2 programmable-token \
                         model; refusing to program this device.",
                        info.serial
                    ));
                }
                s.authenticate().map_err(|e| e.to_string())?;
                let cfg = keyroost_token2prog::Config {
                    display_timeout: timeout,
                    algorithm: algo,
                    time_step: step,
                    utc_time: now,
                };
                s.set_config(&cfg).map_err(|e| e.to_string())?;
                s.set_seed(&seed).map_err(|e| e.to_string())?;
                Ok(())
            })();
            Box::new(move |app: &mut App| {
                if app.selected_device != for_device {
                    return; // user switched tokens mid-program
                }
                match result {
                    Ok(()) => {
                        app.log(Severity::Ok, "programmed token (config + seed)".to_string());
                        app.prog_status = Some((
                            true,
                            "Seed and configuration programmed successfully.".to_string(),
                        ));
                        // Scrub the typed seed (wipe, not clear — clear leaves the
                        // bytes in the buffer) and re-mask it for the next entry.
                        wipe(&mut app.prog_seed_input);
                        app.secret_reveal.insert("prog-seed", false);
                    }
                    Err(e) => {
                        app.log(Severity::Err, format!("program token: {e}"));
                        app.prog_status = Some((false, format!("Programming failed: {e}")));
                    }
                }
            })
        });
    }

    /// Shared QR-from-screen scan: returns the base32 secret (as written in the
    /// URI) plus the parsed `OtpAuth`, so callers can fill issuer/algorithm/etc.
    #[cfg(feature = "qr")]
    fn scan_qr_parsed(&mut self) -> Result<(String, keyroost_import::OtpAuth), String> {
        let uri = qrscan::scan_screens_for_otpauth()?;
        let parsed = parse_otpauth(&uri).map_err(|e| format!("QR parse failed: {e}"))?;
        let secret = uri
            .find("secret=")
            .map(|i| {
                let rest = &uri[i + 7..];
                let end = rest.find('&').unwrap_or(rest.len());
                rest[..end].to_owned()
            })
            .unwrap_or_default();
        if secret.is_empty() {
            return Err("scanned QR has no secret".into());
        }
        Ok((secret, parsed))
    }

    /// Fill the OATH "New credential" fields from a scanned screen QR.
    #[cfg(feature = "qr")]
    fn oath_scan_qr(&mut self) {
        match self.scan_qr_parsed() {
            Ok((secret, parsed)) => {
                self.oath.add.secret = secret;
                // The OATH dialog's name is "issuer:account"; fill it from the URI.
                let name = parsed.suggested_title();
                if !name.is_empty() {
                    self.oath.add.name = name;
                }
                self.oath.add.totp = true; // otpauth://totp
            }
            Err(e) => self.log(Severity::Err, format!("scan QR: {e}")),
        }
    }

    /// Fill the on-device OTP add-dialog fields from a scanned screen QR.
    #[cfg(feature = "qr")]
    fn otp_scan_qr(&mut self) {
        match self.scan_qr_parsed() {
            Ok((secret, parsed)) => {
                self.otp.add.secret = secret;
                if let Some(issuer) = &parsed.issuer {
                    self.otp.add.app_name = issuer.clone();
                }
                if let Some(account) = &parsed.account {
                    self.otp.add.account_name = account.clone();
                }
                self.otp.add.sha256 = matches!(parsed.algorithm, HmacAlgo::Sha256);
                self.otp.add.digits = parsed.digits as u8;
                self.otp.add.period = match parsed.time_step {
                    TimeStep::Seconds30 => 30,
                    TimeStep::Seconds60 => 60,
                };
                self.otp.add.totp = true; // otpauth://totp
            }
            Err(e) => self.log(Severity::Err, format!("scan QR: {e}")),
        }
    }

    /// Scan a TOTP QR from the screen and fill the prog seed form from it.
    #[cfg(feature = "qr")]
    fn prog_scan_qr(&mut self) {
        self.prog_status = None;
        match self.scan_qr_parsed() {
            Ok((secret, parsed)) => {
                self.prog_seed_input = zeroize::Zeroizing::new(secret);
                self.prog_seed_hex = false;
                // A freshly-scanned secret must not be revealed by a stale toggle.
                self.secret_reveal.insert("prog-seed", false);
                self.prog_algo_sha256 = matches!(parsed.algorithm, HmacAlgo::Sha256);
                self.prog_step_60 = matches!(parsed.time_step, TimeStep::Seconds60);
                self.prog_status = Some((
                    true,
                    "Filled seed and parameters from the scanned QR.".into(),
                ));
            }
            Err(e) => self.prog_status = Some((false, e)),
        }
    }

    /// The Molto2 "Import to slot" dialog (one otpauth:// URI). Files go
    /// through the shared import dialog in `import_flow`.
    fn molto_dialogs(&mut self, ctx: &egui::Context) {
        if self.import_dialog.open {
            let mut open = self.import_dialog.open;
            let mut should_apply = false;
            let mut cancel_clicked = false;
            egui::Window::new(format!("Import to slot #{:02}", self.slot))
                .open(&mut open)
                .collapsible(false)
                .resizable(false)
                .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
                .show(ctx, |ui| {
                    ui.label("Paste an otpauth:// URI:");
                    ui.add(
                        egui::TextEdit::multiline(&mut self.import_dialog.uri)
                            .desired_rows(3)
                            .desired_width(420.0)
                            .font(egui::TextStyle::Monospace),
                    );
                    ui.add_space(4.0);
                    ui.horizontal(|ui| {
                        if ui.button("Parse & populate fields").clicked() {
                            should_apply = true;
                        }
                        if ui.button("Cancel").clicked() {
                            cancel_clicked = true;
                        }
                    });
                });
            // Apply Cancel and [X] only now, after the window is drawn; either
            // route wipes the pasted URI.
            self.import_dialog.settle_open(open, cancel_clicked);
            if should_apply {
                self.import_otpauth();
            }
        }
    }
}

/// A stored OATH name as the row shows it: the issuer (or the whole name
/// when there is none), the account, and the `period/` prefix apart, so
/// `60/GitHub:alice` reads "GitHub", "alice", 60 s rather than "60/GitHub".
fn oath_display_name(name: &str, hotp: bool) -> (String, String, Option<u32>) {
    let oath_type = if hotp {
        keyroost_oath::OathType::Hotp
    } else {
        keyroost_oath::OathType::Totp
    };
    let parts = keyroost_oath::parse_name(name, oath_type);
    match parts.issuer {
        Some(issuer) => (issuer.to_owned(), parts.account.to_owned(), parts.period),
        None => (parts.account.to_owned(), String::new(), parts.period),
    }
}

/// Paint one OATH credential row: issuer/account · code · countdown ring ·
/// seconds · copy (· delete). Returns `(Some(code) if copy clicked, delete?)`.
fn oath_row(
    ui: &mut egui::Ui,
    p: &Palette,
    row: &OathRow,
    is_copied: bool,
    with_delete: bool,
) -> (Option<String>, bool, bool) {
    let (name, code, hotp) = (row.name.as_str(), row.code.as_deref(), row.hotp);
    let (issuer, account, period) = oath_display_name(name, hotp);
    let (secs, pct) = theme::totp_window(u64::from(row.period.max(1)));
    let code_color = if hotp {
        // HOTP codes don't expire — no about-to-roll warning color.
        p.accent
    } else if secs <= 5 {
        p.warn
    } else {
        p.accent
    };
    let mut copy = None;
    let mut delete = false;
    let mut read = false;
    ui.horizontal(|ui| {
        ui.vertical(|ui| {
            ui.horizontal(|ui| {
                ui.label(
                    egui::RichText::new(issuer)
                        .font(theme::f_sb(13.5))
                        .color(p.txt),
                );
                if hotp {
                    theme::pill(ui, "HOTP", p.txt2, p.line_soft);
                }
                if let Some(period) = period {
                    theme::pill(ui, &format!("{period} s"), p.txt2, p.line_soft);
                }
            });
            if !account.is_empty() {
                ui.label(
                    egui::RichText::new(account)
                        .font(theme::f_reg(12.0))
                        .color(p.txt3),
                );
            }
        });
        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
            if with_delete {
                let (xr, xresp) =
                    ui.allocate_exact_size(egui::vec2(18.0, 18.0), egui::Sense::click());
                paint_x_icon(ui, xr.center(), p.txt3);
                if xresp.on_hover_text("Delete").clicked() {
                    delete = true;
                }
                ui.add_space(8.0);
            }
            if hotp && code.is_none() {
                // No code yet: reading one advances the card's counter, so it
                // happens only on request. (No copy icon either — there's
                // nothing to copy.) The compact overview card doesn't handle
                // the click, so it gets a passive label instead of a button.
                if with_delete {
                    if theme::button(ui, p, BtnKind::Ghost, "Read code").clicked() {
                        read = true;
                    }
                } else {
                    ui.label(
                        egui::RichText::new("on demand")
                            .font(theme::f_reg(13.0))
                            .color(p.txt3),
                    );
                }
                return;
            }
            let (cr, cresp) = ui.allocate_exact_size(egui::vec2(20.0, 18.0), egui::Sense::click());
            if is_copied {
                paint_check_icon(ui, cr.center(), p.ok);
            } else {
                paint_copy_icon(ui, cr.center(), p.txt3);
            }
            if cresp.on_hover_text("Copy code").clicked() {
                if let Some(c) = code {
                    copy = Some(c.to_string());
                }
            }
            ui.add_space(10.0);
            if !hotp {
                // The countdown is a TOTP concept; an HOTP code stays valid
                // until used.
                ui.label(
                    egui::RichText::new(format!("{secs}s"))
                        .font(theme::f_reg(11.0))
                        .color(p.txt3),
                );
                ui.add_space(5.0);
                theme::ring(ui, pct, 20.0, code_color, p.line);
            }
            ui.add_space(14.0);
            match code {
                Some(c) => {
                    ui.label(
                        egui::RichText::new(c)
                            .font(theme::f_mono(19.0))
                            .color(code_color),
                    );
                }
                None => {
                    ui.label(
                        egui::RichText::new("touch")
                            .font(theme::f_reg(13.0))
                            .color(p.txt3),
                    );
                }
            }
        });
    });
    (copy, delete, read)
}

/// Flatten control characters out of a device-provided title before display
/// (same policy as the CLI's sanitize_cert_field).
fn sanitize_title(s: &str) -> String {
    s.chars()
        .map(|c| if c.is_control() { ' ' } else { c })
        .collect()
}

/// One labelled editor row in the Molto2 form: fixed-width label + a field.
fn editor_row(ui: &mut egui::Ui, p: &Palette, label: &str, add: impl FnOnce(&mut egui::Ui)) {
    ui.horizontal(|ui| {
        ui.add_sized(
            [92.0, 22.0],
            egui::Label::new(
                egui::RichText::new(label)
                    .font(theme::f_reg(13.0))
                    .color(p.txt2),
            ),
        );
        add(ui);
    });
    ui.add_space(8.0);
}

/// Summarize an OpenPGP key slot: its algorithm label, or "empty" when no key.
fn slot_summary(attrs: &[u8], fpr: &[u8; 20]) -> String {
    if fpr.iter().all(|&b| b == 0) {
        "empty".to_string()
    } else {
        keyroost_transport::describe_algorithm_attributes(attrs)
    }
}

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

    /// The `test-isolation` dev-dependency feature is on: a test here can
    /// never resolve, read or write the person's config directory.
    #[test]
    fn tests_never_resolve_the_real_config_dir() {
        let tmp = std::env::temp_dir();
        let dir = keyroost_keyring::config_dir().expect("always set in tests");
        assert!(dir.starts_with(&tmp), "{dir:?} is outside {tmp:?}");
        assert!(keyroost_keyring::config_path().unwrap().starts_with(&tmp));
        assert!(settings::config_path().unwrap().starts_with(&tmp));
    }

    /// A `period/` prefix is shown as the period, not as part of the issuer.
    #[test]
    fn oath_display_name_splits_the_period_prefix() {
        assert_eq!(
            oath_display_name("60/GitHub:alice", false),
            ("GitHub".into(), "alice".into(), Some(60))
        );
        assert_eq!(
            oath_display_name("GitHub:alice", false),
            ("GitHub".into(), "alice".into(), None)
        );
        assert_eq!(
            oath_display_name("60/alice", false),
            ("alice".into(), String::new(), Some(60))
        );
        assert_eq!(
            oath_display_name("plain", false),
            ("plain".into(), String::new(), None)
        );
        // HOTP names carry no period prefix.
        assert_eq!(
            oath_display_name("60/GitHub:alice", true),
            ("60/GitHub".into(), "alice".into(), None)
        );
    }

    /// Issue #170, same bug: Cancel in the "Import to slot" dialog.
    #[test]
    fn import_dialog_cancel_and_x_close_and_wipe_uri() {
        for (window_open, cancel) in [(true, true), (false, false)] {
            let mut d = ImportDialog {
                open: true,
                uri: "otpauth://totp/x?secret=JBSWY3DPEHPK3PXP".to_owned(),
            };
            d.settle_open(window_open, cancel);
            assert!(!d.open);
            assert!(d.uri.is_empty());
        }
        let mut d = ImportDialog {
            open: true,
            uri: "otpauth://totp/x".to_owned(),
        };
        d.settle_open(true, false);
        assert!(d.open);
        assert!(!d.uri.is_empty());
    }

    /// A minimal `PivStatus` reporting just `fingerprint`/`version` — enough
    /// to drive `App::piv_current_default_mgmt_key`'s resolution in a test.
    /// `PivStatus` is `#[non_exhaustive]`, so this crate can't use struct-
    /// literal syntax on it directly; go through `Default` and field
    /// assignment instead, same as the existing `PivStatus::default()` tests
    /// already do.
    fn piv_status_with(
        fingerprint: keyroost_piv::fingerprint::AppletFingerprint,
        version: Option<Vec<u8>>,
    ) -> keyroost_transport::PivStatus {
        let mut status = keyroost_transport::PivStatus::default();
        status.applet_fingerprint = fingerprint;
        status.version = version;
        status
    }

    /// A row built with `stable_selectable_value` must occupy the same
    /// height whether or not the pointer is hovering it — the property every
    /// PIV dropdown built from it (algorithm, management-key algorithm,
    /// PIN/touch policy, move destination) relies on to keep a combo popup
    /// sized close to its scroll cap from needing a scrollbar the instant
    /// the pointer lands on a row. Plain `ui.selectable_value` doesn't have
    /// this property: `Button::selectable` only reserves its frame's stroke
    /// width for the *currently selected* row, and this app's theme gives
    /// the `inactive` widget state a non-zero stroke width too (a text-field
    /// boundary fix, where egui's own default is zero), so an *unselected*
    /// row is measurably shorter at rest than hovered — see
    /// `stable_selectable_value`'s own doc for the exact mechanism.
    /// Exercises an *unselected* value, since that's the one plain
    /// `ui.selectable_value` sized inconsistently.
    #[test]
    fn stable_selectable_value_row_height_is_hover_invariant() {
        let ctx = egui::Context::default();
        crate::ui::theme::install_fonts(&ctx);
        Palette::new(Mode::Dark, Palette::ACCENTS[0], false).apply(&ctx, Mode::Dark);
        let mut current = keyroost_piv::KeyAlg::Rsa2048;
        let unselected = keyroost_piv::KeyAlg::Rsa3072;
        assert_ne!(current, unselected);
        let mut heights = vec![];
        let mut row_rect: Option<egui::Rect> = None;
        // Frame 0: no pointer — establishes the unhovered row's rect.
        // Frame 1: pointer moved onto that rect (registers as input, doesn't
        // yet affect layout — egui reads *last* frame's response to decide
        // *this* frame's widget state).
        // Frame 2: rendered again under sustained hover.
        for frame in 0..3 {
            let mut input = egui::RawInput {
                screen_rect: Some(egui::Rect::from_min_size(
                    egui::Pos2::ZERO,
                    egui::vec2(1200.0, 1200.0),
                )),
                ..Default::default()
            };
            if let Some(r) = row_rect.filter(|_| frame >= 1) {
                input.events.push(egui::Event::PointerMoved(r.center()));
            }
            let _ = ctx.run_ui(input, |ctx| {
                egui::CentralPanel::default().show(ctx, |ui| {
                    ui.set_min_width(160.0);
                    ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend);
                    let resp =
                        stable_selectable_value(ui, &mut current, unselected, unselected.label());
                    heights.push(resp.rect.height());
                    row_rect = Some(resp.rect);
                });
            });
        }
        assert_eq!(
            heights[0], heights[2],
            "row height must not change once the pointer starts hovering it: {heights:?}"
        );
    }

    /// `Palette::apply` must set solid (space-reserving) scroll bars as the
    /// *ambient context style*, not a local `Ui`-scoped one — a `ComboBox`
    /// popup (`egui::containers::Popup`) always rebuilds its content `Ui`
    /// from `Context::style()`/`all_styles_mut`'s targets rather than
    /// inheriting whatever the calling `Ui` had locally overridden, so this
    /// is the only place a scroll style actually reaches a dropdown's own
    /// list. Without it, the default floating scroll bar grows its hit-rect
    /// on hover (`floating_width` -> `bar_width`) right over the row
    /// underneath, and the two fight for hover each frame the pointer sits on
    /// that boundary — the "generate key" algorithm dropdown's flickering
    /// scrollbar. Checked on both themes since `all_styles_mut` (unlike
    /// `set_visuals`) touches the style egui caches per `Theme`, not just
    /// whichever one is active when `apply` runs.
    #[test]
    fn palette_apply_sets_solid_scroll_bars_for_both_themes() {
        let ctx = egui::Context::default();
        for mode in [Mode::Dark, Mode::Light] {
            Palette::new(mode, Palette::ACCENTS[0], false).apply(&ctx, mode);
        }
        for theme in [egui::Theme::Dark, egui::Theme::Light] {
            ctx.style_mut_of(theme, |s| {
                assert!(
                    !s.spacing.scroll.floating,
                    "{theme:?} scroll style should be solid, not the default floating"
                );
            });
        }
    }

    #[test]
    fn openpgp_algorithm_choices_are_the_cards_list_or_everything() {
        use keyroost_transport::{KeyCrt, OpenPgpKeyAlg};
        // No FA: card default + every algorithm that fits the slot.
        let all = OpenPgpKeyAlgSel::choices(None, KeyCrt::Decrypt);
        assert_eq!(all[0], OpenPgpKeyAlgSel::CardDefault);
        assert!(all.contains(&OpenPgpKeyAlgSel::Alg(OpenPgpKeyAlg::X25519)));
        assert!(!all.contains(&OpenPgpKeyAlgSel::Alg(OpenPgpKeyAlg::Ed25519)));
        assert!(OpenPgpKeyAlgSel::choices(None, KeyCrt::Sign)
            .contains(&OpenPgpKeyAlgSel::Alg(OpenPgpKeyAlg::Ed25519)));
        // FA present: exactly what the card listed (modelled entries), in card order.
        let info = keyroost_transport::AlgorithmInformation {
            sig: vec![
                vec![0x16, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01],
                vec![0x01, 0x08, 0x00, 0x00, 0x20, 0x00],
            ],
            dec: vec![],
            aut: vec![],
        };
        assert_eq!(
            OpenPgpKeyAlgSel::choices(Some(&info), KeyCrt::Sign),
            vec![
                OpenPgpKeyAlgSel::CardDefault,
                OpenPgpKeyAlgSel::Alg(OpenPgpKeyAlg::Ed25519),
                OpenPgpKeyAlgSel::Alg(OpenPgpKeyAlg::Rsa2048)
            ]
        );
        // A slot the card lists nothing for still offers everything (unknown ≠ none).
        assert!(OpenPgpKeyAlgSel::choices(Some(&info), KeyCrt::Auth).len() > 1);
    }

    /// #98: the top bar's version chip is the only place the running app
    /// states its version — keep it a well-formed "vX.Y.Z" so it never
    /// regresses to an empty or unprefixed string.
    #[test]
    fn version_label_is_v_prefixed_semver() {
        let rest = VERSION_LABEL
            .strip_prefix('v')
            .expect("version label must start with 'v'");
        assert_eq!(rest, env!("CARGO_PKG_VERSION"));
        assert!(
            rest.split('.').count() >= 3
                && rest.split('.').take(3).all(|part| {
                    !part.is_empty() && part.chars().all(|c| c.is_ascii_digit() || c == '-')
                }),
            "version label {VERSION_LABEL:?} is not vMAJOR.MINOR.PATCH"
        );
    }

    #[test]
    fn factory_reset_summary_lists_applets_and_flags_piv_and_fido() {
        use keyroost_resolve::{factory_reset_plan, Caps};
        use keyroost_transport::{FactoryResetPlan, PivResetPreview};
        let mut caps = Caps::default();
        for c in [Caps::OATH, Caps::PIV, Caps::FIDO2] {
            caps.insert(c);
        }
        let msg = factory_reset_confirm_summary(
            "SN123",
            "Token2 PIN+",
            &factory_reset_plan(caps),
            FactoryResetPivPreview::Resolved(PivResetPreview::Piv(
                FactoryResetPlan::BurnPinPukThenReset,
            )),
            false,
            false,
        );
        assert!(msg.contains("SN123") && msg.contains("Token2 PIN+"));
        assert!(msg.contains("OATH") && msg.contains("PIV") && msg.contains("FIDO2"));
        // PIV disclosure and FIDO replug note are present.
        assert!(msg.contains("PIN and PUK"));
        assert!(msg.to_lowercase().contains("unplug"));
        // The summary must not promise an outcome the PIV path can't guarantee:
        // that path blocks the PIN and PUK before the wipe.
        assert!(!msg.contains("stays fully usable"));
    }

    /// The confirm dialog's PIV paragraph is fingerprinted ahead of time (see
    /// `App::start_factory_reset_confirm`), so it must actually say something
    /// different per `FactoryResetPivPreview` case — a user deciding whether
    /// to proceed needs to know which one they're looking at.
    #[test]
    fn factory_reset_summary_piv_note_matches_the_fingerprinted_plan() {
        use keyroost_resolve::{factory_reset_plan, Caps};
        use keyroost_transport::{FactoryResetPlan, PivResetPreview};
        let plan = factory_reset_plan(Caps::PIV);
        // `needs_management_auth` only matters to the credential sentence,
        // covered by dedicated tests below -- the PIV-only note text under
        // test here never depends on it, so `false` is a neutral stand-in
        // throughout.

        let needs_mgmt_auth = factory_reset_confirm_summary(
            "SN",
            "Model",
            &plan,
            FactoryResetPivPreview::Resolved(PivResetPreview::Piv(
                FactoryResetPlan::NeedsManagementAuth,
            )),
            false,
            false,
        );
        assert!(
            needs_mgmt_auth.contains("management-key"),
            "{needs_mgmt_auth}"
        );
        // Now genuinely attempted (authenticate, then RESET), not refused --
        // unlike every other atomic case here, this one does NOT say "will
        // NOT be wiped".
        assert!(
            !needs_mgmt_auth.contains("NOT be wiped"),
            "{needs_mgmt_auth}"
        );
        // Atomic: authenticate-then-RESET is a clean pass/fail, no partial
        // state for the step report to disambiguate, unlike the burn case.
        assert!(
            !needs_mgmt_auth.contains("the report below"),
            "{needs_mgmt_auth}"
        );

        let unverified = factory_reset_confirm_summary(
            "SN",
            "Model",
            &plan,
            FactoryResetPivPreview::Resolved(PivResetPreview::Piv(FactoryResetPlan::Unverified)),
            false,
            false,
        );
        assert!(unverified.contains("no RESET entry"), "{unverified}");
        assert!(unverified.contains("without blocking"), "{unverified}");
        // Also atomic (a bare RESET attempt, no PIN/PUK burn) -- same
        // reasoning as NeedsManagementAuth above.
        assert!(!unverified.contains("the report below"), "{unverified}");

        let burn_then_reset = factory_reset_confirm_summary(
            "SN",
            "Model",
            &plan,
            FactoryResetPivPreview::Resolved(PivResetPreview::Piv(
                FactoryResetPlan::BurnPinPukThenReset,
            )),
            false,
            false,
        );
        assert!(burn_then_reset.contains("PIN and PUK"), "{burn_then_reset}");
        // The one multi-step case (block PIN, block PUK, then RESET): a
        // failure partway through leaves PIV in a state this text alone
        // can't describe, so -- unlike every atomic case above -- it must
        // point at the step report.
        assert!(
            burn_then_reset.contains("the report below the button says what state it's in"),
            "{burn_then_reset}"
        );

        // The device-wide mechanism has nothing PIV-specific to caveat --
        // it's just another applet in the plan.
        let global = factory_reset_confirm_summary(
            "SN",
            "Model",
            &plan,
            FactoryResetPivPreview::Resolved(PivResetPreview::Global),
            false,
            false,
        );
        assert!(!global.contains("PIV:"), "{global}");

        let check_failed = factory_reset_confirm_summary(
            "SN",
            "Model",
            &plan,
            FactoryResetPivPreview::CheckFailed,
            false,
            false,
        );
        assert!(check_failed.contains("couldn't confirm"), "{check_failed}");

        // `NotOffered` inside a plan that DOES include PIV shouldn't happen in
        // practice, but must not panic or claim something false about a step
        // that was never fingerprinted -- it falls back to `CheckFailed`'s
        // wording.
        let not_offered = factory_reset_confirm_summary(
            "SN",
            "Model",
            &plan,
            FactoryResetPivPreview::NotOffered,
            false,
            false,
        );
        assert_eq!(not_offered, check_failed);

        // A plan without PIV never gets a PIV paragraph, regardless of preview.
        let no_piv = factory_reset_confirm_summary(
            "SN",
            "Model",
            &factory_reset_plan(Caps::OATH),
            FactoryResetPivPreview::Resolved(PivResetPreview::Global),
            false,
            false,
        );
        assert!(!no_piv.contains("PIV:"), "{no_piv}");
    }

    /// `PivExtension::ResetGlobal` resolving `Global` means the PIV step, if
    /// it runs, takes at least one other applet down with it — the "Wipes:"
    /// list must say so up front (`PIV_GLOBAL_RESET_LABEL`), not report the
    /// bare `ResetStep::Piv::label()` a caller would otherwise read as
    /// "PIV, and only PIV, gets touched".
    #[test]
    fn factory_reset_summary_wipes_list_names_the_whole_device_when_global() {
        use keyroost_resolve::{factory_reset_plan, Caps};
        use keyroost_transport::{FactoryResetPlan, PivResetPreview};
        let mut caps = Caps::default();
        for c in [Caps::OATH, Caps::PIV] {
            caps.insert(c);
        }
        let plan = factory_reset_plan(caps);

        let global = factory_reset_confirm_summary(
            "SN",
            "Model",
            &plan,
            FactoryResetPivPreview::Resolved(PivResetPreview::Global),
            false,
            false,
        );
        assert!(
            global.contains(&format!(
                "Wipes: OATH, {}",
                keyroost_resolve::PIV_GLOBAL_RESET_LABEL
            )),
            "{global}"
        );
        assert!(!global.contains("Wipes: OATH, PIV"), "{global}");
        // `PivResetPreview::Global` itself already folds `ResetGlobal`
        // resolving `Supported` *or* `Unverified` into one value (see that
        // variant's own doc) -- there's no separate case to test here, both
        // get this same label for the same reason: an unconfirmed
        // device-wide mechanism might still take other applets with it.

        // A PIV-only mechanism -- confirmed *not* device-wide -- keeps the
        // bare applet label.
        let piv_only = factory_reset_confirm_summary(
            "SN",
            "Model",
            &plan,
            FactoryResetPivPreview::Resolved(PivResetPreview::Piv(
                FactoryResetPlan::BurnPinPukThenReset,
            )),
            false,
            false,
        );
        assert!(piv_only.contains("Wipes: OATH, PIV"), "{piv_only}");
    }

    /// `PivResetPreview::Unsupported` never actually reaches the summary in
    /// practice (`start_factory_reset_confirm` excludes `ResetStep::Piv`
    /// from the plan whenever it's resolved -- see
    /// `factory_reset_piv_unresettable`), but the match still has to handle
    /// it, and defensively (a stale plan built before a fresh fingerprint
    /// changed the answer) it must not claim anything: empty string, same as
    /// its nested-`Unsupported` sibling that `preview_factory_reset` never
    /// actually produces.
    #[test]
    fn factory_reset_summary_unsupported_preview_says_nothing_if_ever_reached() {
        use keyroost_resolve::{factory_reset_plan, Caps};
        use keyroost_transport::{FactoryResetPlan, PivResetPreview};
        let plan = factory_reset_plan(Caps::PIV);
        for preview in [
            PivResetPreview::Unsupported,
            PivResetPreview::Piv(FactoryResetPlan::Unsupported),
        ] {
            let msg = factory_reset_confirm_summary(
                "SN",
                "Model",
                &plan,
                FactoryResetPivPreview::Resolved(preview),
                false,
                false,
            );
            assert!(!msg.contains("PIV:"), "{preview:?} {msg}");
        }
    }

    /// The management-auth credential sentence is gated purely on
    /// `needs_management_auth` (`PivQuirk::ResetNeedsManagementAuth`
    /// applying), independent of which mechanism `piv_preview` says will
    /// actually consume it -- appears exactly once whichever case is active,
    /// never duplicated by the PIV-only note above it (which, for
    /// `NeedsManagementAuth`, now separately says "authenticates ... then
    /// wipes" but doesn't itself repeat "management auth").
    #[test]
    fn factory_reset_summary_credential_sentence_is_gated_on_needs_management_auth_alone() {
        use keyroost_resolve::{factory_reset_plan, Caps};
        use keyroost_transport::{FactoryResetPlan, PivResetPreview};
        let plan = factory_reset_plan(Caps::PIV);
        for preview in [
            PivResetPreview::Global,
            PivResetPreview::Piv(FactoryResetPlan::NeedsManagementAuth),
        ] {
            let with_credential = factory_reset_confirm_summary(
                "SN",
                "Model",
                &plan,
                FactoryResetPivPreview::Resolved(preview),
                true,
                false,
            );
            assert_eq!(
                with_credential.matches("requires management auth").count(),
                1,
                "{preview:?} {with_credential}"
            );

            let without_credential = factory_reset_confirm_summary(
                "SN",
                "Model",
                &plan,
                FactoryResetPivPreview::Resolved(preview),
                false,
                false,
            );
            assert!(
                !without_credential.contains("requires management auth"),
                "{preview:?} {without_credential}"
            );
        }
    }

    /// `PivQuirk::ResetLongRunning` (e.g. ArekinathPivApplet::SwissbitIShield1)
    /// appends the same hint text the PIV pane's "Reset applet" card and
    /// `keyroostctl piv reset` already show, gated purely on the boolean --
    /// independent of which `FactoryResetPivPreview` case is active -- and
    /// only when the plan actually has a PIV step to warn about.
    #[test]
    fn factory_reset_summary_appends_the_long_running_hint_when_set() {
        use keyroost_resolve::{factory_reset_plan, Caps};
        use keyroost_transport::{FactoryResetPlan, PivResetPreview};
        let plan = factory_reset_plan(Caps::PIV);
        let preview = FactoryResetPivPreview::Resolved(PivResetPreview::Piv(
            FactoryResetPlan::BurnPinPukThenReset,
        ));

        let warned = factory_reset_confirm_summary("SN", "Model", &plan, preview, false, true);
        assert!(
            warned.contains(keyroost_piv::compat::PivQuirk::RESET_LONG_RUNNING_HINT),
            "{warned}"
        );

        let not_warned = factory_reset_confirm_summary("SN", "Model", &plan, preview, false, false);
        assert!(
            !not_warned.contains(keyroost_piv::compat::PivQuirk::RESET_LONG_RUNNING_HINT),
            "{not_warned}"
        );

        // A plan without PIV never gets the hint, even if the flag is set --
        // there's no PIV step for it to attach to.
        let no_piv_plan = factory_reset_plan(Caps::OATH);
        let no_piv = factory_reset_confirm_summary(
            "SN",
            "Model",
            &no_piv_plan,
            FactoryResetPivPreview::Resolved(PivResetPreview::Global),
            false,
            true,
        );
        assert!(
            !no_piv.contains(keyroost_piv::compat::PivQuirk::RESET_LONG_RUNNING_HINT),
            "{no_piv}"
        );
    }

    /// Two "Save certificate…" dialogs can be open at once (the busy guard is
    /// released before the extract job's apply closure runs, and the dialogs
    /// are not modal). Each must resolve to the certificate it was opened for —
    /// with the previous single global slot, whichever dialog was answered
    /// first wrote whatever cert happened to be parked.
    #[test]
    fn concurrent_save_cert_dialogs_resolve_to_their_own_certificates() {
        let mut pending = std::collections::HashMap::new();
        pending.insert(
            7,
            PendingSshCert {
                cert_pub: "alice-cert".into(),
                summary: "alice".into(),
            },
        );
        pending.insert(
            8,
            PendingSshCert {
                cert_pub: "bob-cert".into(),
                summary: "bob".into(),
            },
        );

        // Answer alice's dialog (opened first) while bob's is still open.
        let alice = take_pending_cert(&mut pending, 7).expect("alice's cert is parked");
        assert_eq!(alice.cert_pub, "alice-cert");
        // Bob's is untouched and still resolves to bob's cert.
        let bob = take_pending_cert(&mut pending, 8).expect("bob's cert is still parked");
        assert_eq!(bob.cert_pub, "bob-cert");
        // Each id resolves once; a re-run dialog reports "nothing to write"
        // rather than picking up a neighbour's certificate.
        assert!(take_pending_cert(&mut pending, 7).is_none());
        assert!(pending.is_empty());
    }

    /// A cancelled save must drop only its own parked certificate.
    #[test]
    fn cancelled_save_cert_dialog_drops_only_its_own_certificate() {
        let mut app = App::default();
        for (id, name) in [(1u64, "alice"), (2, "bob")] {
            app.security_keys.ssh_cert_pending.insert(
                id,
                PendingSshCert {
                    cert_pub: format!("{name}-cert"),
                    summary: name.into(),
                },
            );
        }
        app.discard_file_target(FileTarget::SshCertSave(1));
        assert!(!app.security_keys.ssh_cert_pending.contains_key(&1));
        assert_eq!(
            app.security_keys
                .ssh_cert_pending
                .get(&2)
                .map(|c| c.cert_pub.as_str()),
            Some("bob-cert")
        );
        // A target that parks nothing is a no-op.
        app.discard_file_target(FileTarget::PivExport);
        assert_eq!(app.security_keys.ssh_cert_pending.len(), 1);
    }

    /// The whole-device factory reset hands its FIDO step to the armed reset
    /// dialog, whose outcome only reaches `security_keys.error` — a pane the
    /// user isn't on. The seeded row keeps the report honest: it reads as not
    /// wiped until the ceremony answers, then flips to wiped or failed.
    #[test]
    fn factory_reset_fido_row_tracks_the_finale() {
        use keyroost_resolve::{ResetStep, StepOutcome, StepReport};
        let seeded = || {
            vec![
                FactoryResetRow::Step(StepReport {
                    step: ResetStep::Oath,
                    outcome: StepOutcome::Wiped,
                }),
                FactoryResetRow::FidoPending,
            ]
        };

        // Seeded: FIDO reads as outstanding, never as wiped.
        let mut rows = seeded();
        let (text, tone) = factory_reset_row_line(&rows[1]);
        assert!(text.starts_with("FIDO2"), "{text}");
        assert!(text.contains("not wiped yet"), "{text}");
        assert_eq!(tone, RowTone::Waiting);

        // The touch landed.
        resolve_fido_reset_row(&mut rows, StepOutcome::Wiped);
        assert_eq!(
            factory_reset_row_line(&rows[1]),
            ("FIDO2  wiped".to_string(), RowTone::Done)
        );
        // The card steps are untouched by the finale.
        assert_eq!(
            factory_reset_row_line(&rows[0]),
            ("OATH  wiped".to_string(), RowTone::Done)
        );

        // No touch in time / the key refused: the row says so.
        let mut rows = seeded();
        resolve_fido_reset_row(&mut rows, StepOutcome::Failed("no touch".into()));
        let (text, tone) = factory_reset_row_line(&rows[1]);
        assert_eq!(text, "FIDO2  failed: no touch");
        assert_eq!(tone, RowTone::Bad);

        // A standalone "Reset key" (no factory reset in flight) must not invent
        // a report row.
        let mut plain = vec![FactoryResetRow::Step(StepReport {
            step: ResetStep::Oath,
            outcome: StepOutcome::Wiped,
        })];
        resolve_fido_reset_row(&mut plain, StepOutcome::Wiped);
        assert_eq!(plain.len(), 1);
        assert_eq!(
            factory_reset_row_line(&plain[0]),
            ("OATH  wiped".to_string(), RowTone::Done)
        );
    }

    /// A FIDO row that has already answered must not freeze that answer. The
    /// report invites a retry after a failed wipe and nothing clears it in
    /// between — the selection is unchanged across the replug, so the report
    /// survives — meaning a row still reading "failed" after a retry that
    /// succeeded tells the user their passkeys and PIN are on a key that is
    /// actually empty. The latest outcome has to win.
    #[test]
    fn factory_reset_fido_row_retry_supersedes_the_earlier_outcome() {
        use keyroost_resolve::{ResetStep, StepOutcome, StepReport};
        let mut rows = vec![
            FactoryResetRow::Step(StepReport {
                step: ResetStep::Piv,
                outcome: StepOutcome::Wiped,
            }),
            FactoryResetRow::FidoPending,
        ];

        // First attempt: no touch in time.
        resolve_fido_reset_row(&mut rows, StepOutcome::Failed("no touch".into()));
        assert_eq!(factory_reset_row_line(&rows[1]).1, RowTone::Bad);

        // The user re-plugs, retries, and the wipe lands.
        resolve_fido_reset_row(&mut rows, StepOutcome::Wiped);
        assert_eq!(
            factory_reset_row_line(&rows[1]),
            ("FIDO2  wiped".to_string(), RowTone::Done)
        );
        assert_eq!(rows.len(), 2, "the retry must not append a second FIDO row");
        assert_eq!(
            factory_reset_row_line(&rows[0]),
            ("PIV  wiped".to_string(), RowTone::Done),
            "the card sweep's rows are the finale's business to leave alone"
        );

        // Still nothing invented when no FIDO row exists — an empty report
        // (standalone "Reset key" with no factory reset ever run) stays empty,
        // and a report of card steps only keeps exactly those steps.
        let mut empty: Vec<FactoryResetRow> = Vec::new();
        resolve_fido_reset_row(&mut empty, StepOutcome::Wiped);
        assert!(empty.is_empty());
        let mut cards = vec![FactoryResetRow::Step(StepReport {
            step: ResetStep::OpenPgp,
            outcome: StepOutcome::Failed("blocked".into()),
        })];
        resolve_fido_reset_row(&mut cards, StepOutcome::Wiped);
        assert_eq!(cards.len(), 1);
        assert_eq!(
            factory_reset_row_line(&cards[0]),
            ("OpenPGP  failed: blocked".to_string(), RowTone::Bad)
        );

        // …but replace-any is the *attempt* caller's privilege alone. Closing a
        // dialog attempts nothing, so a wipe that already landed has to survive
        // it: the report outlives the ceremony (a tab switch and a replug both
        // leave it standing), so the next dialog the user cancels is routinely
        // not the one this row came from.
        resolve_pending_fido_reset_row(
            &mut rows,
            StepOutcome::Failed(
                "cancelled \u{2014} the passkeys and PIN are still on this key".into(),
            ),
        );
        assert_eq!(
            factory_reset_row_line(&rows[1]),
            ("FIDO2  wiped".to_string(), RowTone::Done),
            "a cancel must not rewrite a finished wipe into a failure"
        );
        assert_eq!(rows.len(), 2);
    }

    /// The pending-only resolver still has to answer the row it *is* for: a
    /// factory reset whose FIDO finale the user cancels must stop reading
    /// "waiting for the unplug, replug, and touch" — that ceremony is over and
    /// the passkeys really are still there.
    #[test]
    fn cancelling_the_finale_resolves_a_pending_fido_row() {
        use keyroost_resolve::{ResetStep, StepOutcome, StepReport};
        let mut rows = vec![
            FactoryResetRow::Step(StepReport {
                step: ResetStep::Oath,
                outcome: StepOutcome::Wiped,
            }),
            FactoryResetRow::FidoPending,
        ];
        resolve_pending_fido_reset_row(&mut rows, StepOutcome::Failed("cancelled".into()));
        assert_eq!(
            factory_reset_row_line(&rows[1]),
            ("FIDO2  failed: cancelled".to_string(), RowTone::Bad)
        );
        // A second cancel (the standalone dialog, opened and backed out of) has
        // nothing left to resolve and must leave the answer alone.
        resolve_pending_fido_reset_row(&mut rows, StepOutcome::Failed("cancelled again".into()));
        assert_eq!(
            factory_reset_row_line(&rows[1]),
            ("FIDO2  failed: cancelled".to_string(), RowTone::Bad)
        );
        // And it never invents a row where no factory reset is in flight.
        let mut empty: Vec<FactoryResetRow> = Vec::new();
        resolve_pending_fido_reset_row(&mut empty, StepOutcome::Failed("cancelled".into()));
        assert!(empty.is_empty());
    }

    /// Only `PivSession::factory_reset`'s PIN/PUK burn-dance path blocks the
    /// PIN and PUK before it erases, so only there can a failure in between
    /// leave the applet locked but intact. The confirmation modal promises
    /// the report says so — which means every failure that doesn't already
    /// describe the card's state has to carry the disclosure, matching what
    /// the CLI's factory reset prints for the same failures.
    #[test]
    fn piv_factory_reset_failures_disclose_the_blocked_credentials() {
        // Self-describing variants pass through untouched: appending "run the
        // factory reset again" would contradict them (Unsupported/
        // NeedsManagementAuth never blocked anything; UnverifiedFailed/
        // GlobalFailed/ManagementAuthFailed already explain themselves and
        // never touched a PIN or PUK either; the other two already say what
        // to do).
        let unsupported = piv_factory_reset_message(TransportError::PivResetUnsupported);
        assert_eq!(unsupported, TransportError::PivResetUnsupported.to_string());
        let needs_mgmt_auth =
            piv_factory_reset_message(TransportError::PivResetNeedsManagementAuth);
        assert_eq!(
            needs_mgmt_auth,
            TransportError::PivResetNeedsManagementAuth.to_string()
        );
        let unverified_failed = piv_factory_reset_message(
            TransportError::PivResetUnverifiedFailed(Box::new(TransportError::PivResetNotAllowed)),
        );
        assert_eq!(
            unverified_failed,
            TransportError::PivResetUnverifiedFailed(Box::new(TransportError::PivResetNotAllowed))
                .to_string()
        );
        let global_failed = piv_factory_reset_message(TransportError::PivResetGlobalFailed(
            Box::new(TransportError::PivSecurityNotSatisfied),
        ));
        assert_eq!(
            global_failed,
            TransportError::PivResetGlobalFailed(Box::new(TransportError::PivSecurityNotSatisfied))
                .to_string()
        );
        let mgmt_auth_failed =
            piv_factory_reset_message(TransportError::PivResetManagementAuthFailed(Box::new(
                TransportError::PivManagementAuthFailed,
            )));
        assert_eq!(
            mgmt_auth_failed,
            TransportError::PivResetManagementAuthFailed(Box::new(
                TransportError::PivManagementAuthFailed
            ))
            .to_string()
        );
        let incomplete =
            piv_factory_reset_message(TransportError::PivResetIncomplete("card state here"));
        assert_eq!(incomplete, "card state here");
        let guessed = piv_factory_reset_message(TransportError::PivPukGuessAccepted);
        assert_eq!(guessed, TransportError::PivPukGuessAccepted.to_string());

        // Everything else says nothing about the blocking on its own — an
        // unexpected status word in the PIN/PUK loop renders as a bare APDU
        // failure — so the disclosure is appended.
        let bare = piv_factory_reset_message(TransportError::Apdu {
            label: "piv pin/puk",
            sw1: 0x6a,
            sw2: 0x80,
        });
        assert!(bare.contains("piv pin/puk"), "{bare}");
        assert!(
            bare.contains("locked but not wiped"),
            "the half-wiped state has to be named: {bare}"
        );
        assert!(
            bare.contains("run the factory reset again"),
            "the way out has to be named: {bare}"
        );
        // Not the single-applet reset: a fault in the PUK loop leaves the PUK
        // unblocked, and the card refuses a plain RESET until both are blocked.
        assert!(!bare.contains("piv reset"), "{bare}");
    }

    /// The "Reset applet" card only points at the whole-device factory reset
    /// as a known alternative when a device-wide reset is itself confirmed
    /// (`ResetGlobal` `Supported`, not merely `Unverified`) AND PIV's own
    /// RESET isn't already the known-good path (`Reset` anything but
    /// `Supported`) — matching the spec's three cases (Unsupported -> show
    /// the link, Unverified -> show the link, Supported -> leave as-is) plus
    /// the `ResetGlobal` axis those three cases were silent on.
    #[test]
    fn piv_reset_global_alternative_available_matches_spec() {
        use keyroost_piv::compat::FeatureGate;

        // Reset::Supported -> leave as-is, regardless of ResetGlobal.
        for global in [
            FeatureGate::Supported,
            FeatureGate::Unverified,
            FeatureGate::Unsupported,
        ] {
            assert!(
                !piv_reset_global_alternative_available(FeatureGate::Supported, global),
                "Reset::Supported must never be redirected, ResetGlobal={global:?}"
            );
        }

        // Reset::Unsupported / Unverified, but ResetGlobal isn't a known
        // alternative either (Unverified or Unsupported) -> nothing to point at.
        for reset in [FeatureGate::Unsupported, FeatureGate::Unverified] {
            for global in [FeatureGate::Unverified, FeatureGate::Unsupported] {
                assert!(
                    !piv_reset_global_alternative_available(reset, global),
                    "reset={reset:?} global={global:?}"
                );
            }
        }

        // The two cases the link actually shows for.
        assert!(piv_reset_global_alternative_available(
            FeatureGate::Unsupported,
            FeatureGate::Supported
        ));
        assert!(piv_reset_global_alternative_available(
            FeatureGate::Unverified,
            FeatureGate::Supported
        ));
    }

    /// The Generate Key modal's "Policy other than `default` requires
    /// YubiKey or compatible token." caveat hides only when *both* the PIN
    /// and touch policy gates are confirmed `Supported` — any other
    /// combination (either axis `Unverified` or `Unsupported`) still needs
    /// it, since the per-row markers only warn about one axis at a time.
    #[test]
    fn piv_policy_caveat_hint_needed_only_hides_when_both_gates_are_supported() {
        use keyroost_piv::compat::FeatureGate;

        assert!(!piv_policy_caveat_hint_needed(
            FeatureGate::Supported,
            FeatureGate::Supported
        ));

        for pin in [
            FeatureGate::Supported,
            FeatureGate::Unverified,
            FeatureGate::Unsupported,
        ] {
            for touch in [
                FeatureGate::Supported,
                FeatureGate::Unverified,
                FeatureGate::Unsupported,
            ] {
                if pin == FeatureGate::Supported && touch == FeatureGate::Supported {
                    continue;
                }
                assert!(
                    piv_policy_caveat_hint_needed(pin, touch),
                    "pin={pin:?} touch={touch:?}"
                );
            }
        }
    }

    /// Refusing to arm (KEY-005: no serial to re-identify the key by after a
    /// replug) ends the run — the dialog closes and no reset is ever sent. The
    /// seeded FIDO row has to resolve too, or the report sits forever on
    /// "waiting for the unplug, replug, and touch", asking for a ceremony that
    /// is never coming, with the only explanation buried in a log panel that is
    /// collapsed by default.
    #[test]
    fn refusing_to_arm_resolves_the_pending_fido_row() {
        use keyroost_resolve::{ResetStep, StepOutcome, StepReport};
        let mut app = App::default();
        app.security_keys.reset = ResetDialog {
            open: true,
            ..Default::default()
        };
        app.factory_reset_report = vec![
            FactoryResetRow::Step(StepReport {
                step: ResetStep::Oath,
                outcome: StepOutcome::Wiped,
            }),
            FactoryResetRow::FidoPending,
        ];

        // Nothing selected: no HID serial and no effective serial, which is the
        // refusal branch (the same state a key that exposes neither lands in).
        // Empty device list: no hardware is enumerated, so the outcome does not
        // depend on what is plugged into the machine running the test.
        app.arm_fido_reset_with(Vec::new());

        assert!(
            app.reset_arm.is_none(),
            "a key we can't re-identify must never arm"
        );
        assert!(!app.security_keys.reset.open, "the dialog is dismissed");
        let (text, tone) = factory_reset_row_line(&app.factory_reset_report[1]);
        assert_eq!(tone, RowTone::Bad, "{text}");
        assert!(
            !text.contains("not wiped yet"),
            "the row must not stay pending: {text}"
        );
        assert!(text.contains("not armed"), "{text}");
        assert!(
            text.contains("keyroostctl fido reset --yes"),
            "the row carries the way out: {text}"
        );
        // …and the same wording reaches a surface that isn't the collapsed log
        // panel for a standalone reset, which has no report row at all.
        assert!(
            app.security_keys
                .error
                .as_deref()
                .is_some_and(|e| e.contains("not armed")),
            "{:?}",
            app.security_keys.error
        );
        assert!(app.log.iter().any(|l| l.text.contains("not armed")));
        // The card sweep's own "factory reset finished" line was written
        // before this ceremony even started (see `apply_factory_reset_sweep`)
        // and never otherwise learns how FIDO ended — so the permanent record
        // needs its own line naming the FIDO outcome, not just the earlier
        // per-step summary.
        assert!(
            app.log
                .iter()
                .any(|l| l.text.contains("factory reset") && l.text.contains("FIDO2")),
            "the activity log must record the FIDO finale, not just the card \
             sweep's earlier summary: {:?}",
            app.log.iter().map(|l| &l.text).collect::<Vec<_>>()
        );
    }

    /// The FIDO finale is the one step that survives the job that started it:
    /// it waits for a replug, so its outcome can arrive long after dispatch.
    /// The report pane it writes into is app-global, re-pointed at whatever key
    /// is selected now — so an outcome that arrives for key A must never touch
    /// a report belonging to key B. Green "FIDO2 wiped" under B while B's
    /// passkeys and PIN are untouched is the worst line this pane can print.
    #[test]
    fn a_fido_reset_outcome_cannot_land_on_another_key() {
        use keyroost_resolve::{ResetStep, StepOutcome, StepReport};
        let a: DeviceId = "serial:AAA".into();
        let b: DeviceId = "serial:BBB".into();
        let seeded = |app: &mut App| {
            app.selected_device = Some(b.clone());
            app.security_keys.error = None;
            app.factory_reset_report = vec![
                FactoryResetRow::Step(StepReport {
                    step: ResetStep::Piv,
                    outcome: StepOutcome::Wiped,
                }),
                FactoryResetRow::FidoPending,
            ];
        };
        let mut app = App::default();

        // A's ceremony finishes with A wiped while B is on screen, mid-run.
        seeded(&mut app);
        App::apply_reset_path_outcome(&mut app, Some(&a), Ok(()));
        let (text, tone) = factory_reset_row_line(&app.factory_reset_report[1]);
        assert_eq!(
            tone,
            RowTone::Waiting,
            "B's FIDO row must stay pending: {text}"
        );
        assert!(text.contains("not wiped yet"), "{text}");

        // …and the failure direction is no better: B's pane must not show A's
        // error, which would send the user replugging the wrong key.
        seeded(&mut app);
        App::apply_reset_path_outcome(&mut app, Some(&a), Err("no touch".into()));
        assert_eq!(
            factory_reset_row_line(&app.factory_reset_report[1]).1,
            RowTone::Waiting
        );
        assert!(
            app.security_keys.error.is_none(),
            "{:?}",
            app.security_keys.error
        );

        // An unbound completion (nothing captured, nothing selected) fails
        // closed too, rather than acting on whatever happens to be there.
        seeded(&mut app);
        App::apply_reset_path_outcome(&mut app, None, Ok(()));
        assert_eq!(
            factory_reset_row_line(&app.factory_reset_report[1]).1,
            RowTone::Waiting
        );
        app.selected_device = None;
        App::apply_reset_path_outcome(&mut app, Some(&a), Ok(()));
        assert_eq!(
            factory_reset_row_line(&app.factory_reset_report[1]).1,
            RowTone::Waiting
        );

        // The wipe still happened, so it can't pass in silence: no report on
        // screen can honestly show it, which leaves the log.
        assert!(
            app.log
                .iter()
                .filter(|l| l.text.contains("passkeys and PIN are wiped"))
                .count()
                >= 1,
            "a wipe that lands off-screen must still be recorded"
        );
        assert!(app.log.iter().any(|l| l.text.contains("still on it")));
    }

    /// The device guard must not cost the normal flow its outcome: the same key
    /// is selected throughout the replug (rescans are suppressed while a reset
    /// is armed), so the report has to record the wipe — and a retry after a
    /// failure still has to be able to correct the earlier row.
    #[test]
    fn a_same_device_fido_outcome_is_recorded_and_a_retry_supersedes_it() {
        use keyroost_resolve::{ResetStep, StepOutcome, StepReport};
        let a: DeviceId = "serial:AAA".into();
        let mut app = App {
            selected_device: Some(a.clone()),
            factory_reset_report: vec![
                FactoryResetRow::Step(StepReport {
                    step: ResetStep::Oath,
                    outcome: StepOutcome::Wiped,
                }),
                FactoryResetRow::FidoPending,
            ],
            ..Default::default()
        };

        // First attempt: the key refused (outside its ~10 s window). The row
        // says so, and the FIDO2 pane carries the way out.
        App::apply_reset_path_outcome(&mut app, Some(&a), Err("CTAP2_ERR_NOT_ALLOWED".into()));
        let (text, tone) = factory_reset_row_line(&app.factory_reset_report[1]);
        assert_eq!(tone, RowTone::Bad, "{text}");
        assert!(text.contains("refused the reset"), "{text}");
        assert!(
            app.security_keys
                .error
                .as_deref()
                .is_some_and(|e| e.contains("refused the reset")),
            "{:?}",
            app.security_keys.error
        );
        // The Overview row isn't the only permanent record of this attempt —
        // the activity log needs its own line, or a session that ends here
        // (the user walks away instead of retrying) leaves only the card
        // sweep's earlier "factory reset finished — wiped: OATH" line, with no
        // mention that FIDO was ever attempted, let alone that it failed.
        assert!(
            app.log
                .iter()
                .any(|l| l.text.contains("factory reset") && l.text.contains("refused the reset")),
            "{:?}",
            app.log.iter().map(|l| &l.text).collect::<Vec<_>>()
        );

        // The retry lands: the row must be corrected, not appended to, or the
        // report claims passkeys survived on a key that is actually empty.
        App::apply_reset_path_outcome(&mut app, Some(&a), Ok(()));
        assert_eq!(
            factory_reset_row_line(&app.factory_reset_report[1]),
            ("FIDO2  wiped".to_string(), RowTone::Done)
        );
        assert_eq!(app.factory_reset_report.len(), 2);
        assert_eq!(
            factory_reset_row_line(&app.factory_reset_report[0]),
            ("OATH  wiped".to_string(), RowTone::Done),
            "the card sweep's rows are the finale's business to leave alone"
        );
        assert!(
            app.security_keys.error.is_none(),
            "the retry clears the error"
        );
        // The successful retry gets its own log line too, distinct from the
        // earlier failed attempt's.
        assert!(
            app.log
                .iter()
                .any(|l| l.text.contains("factory reset") && l.text.contains("FIDO2  wiped")),
            "{:?}",
            app.log.iter().map(|l| &l.text).collect::<Vec<_>>()
        );
        // Nothing was dropped on the floor, so nothing to warn about.
        assert!(!app
            .log
            .iter()
            .any(|l| l.text.contains("selection moved on")));
    }

    /// An armed ceremony belongs to the key it was armed for. Selecting another
    /// key drops the dialog, so the arm behind it would go on polling with no
    /// UI at all — and fire on the replug of a key the user has moved off.
    #[test]
    fn selecting_another_key_disarms_the_reset() {
        let mut app = App::default();
        app.selected_device = Some("serial:AAA".into());
        app.reset_arm = Some(ResetArm {
            target_serial: Some("AAA".into()),
            target_path: None,
            target_ids: None,
            target_effective_serial: Some("AAA".into()),
            for_device: app.selected_device.clone(),
            prev_devices: Vec::new(),
            saw_removal: true,
        });

        app.select_device("serial:BBB".into());

        assert!(
            app.reset_arm.is_none(),
            "an arm must not outlive the selection it was armed for"
        );
        // The user was told to unplug and replug; the ceremony ending has to be
        // visible somewhere, or the replug just does nothing forever.
        assert!(
            app.log
                .iter()
                .any(|l| l.text.contains("the armed reset was cancelled")),
            "the cancelled ceremony must be reported"
        );
    }

    /// A test arm for whichever key `for_device` names. The identity fields are
    /// irrelevant to the teardown rules these tests exercise; what matters is
    /// that a live ceremony exists.
    fn armed_for(for_device: &str) -> ResetArm {
        ResetArm {
            target_serial: Some("AAA".into()),
            target_path: None,
            target_ids: None,
            target_effective_serial: Some("AAA".into()),
            for_device: Some(for_device.into()),
            prev_devices: Vec::new(),
            saw_removal: true,
        }
    }

    /// The card sweep wipes four applets before its outcome comes back, so a
    /// selection that moved in between cannot undo any of it. The report is the
    /// only record — PIV's failure text is the one place "wiped" is told apart
    /// from "PIN and PUK blocked but not wiped" — so it cannot be dropped in
    /// silence. And the FIDO finale must NOT open: arming an irreversible wipe
    /// under whichever key is on screen now is what the guard exists to stop.
    #[test]
    fn an_orphaned_card_sweep_is_logged_and_arms_nothing() {
        use keyroost_resolve::{ResetStep, StepOutcome, StepReport};
        let a: DeviceId = "serial:AAA".into();
        let mut app = App {
            selected_device: Some("serial:BBB".into()),
            ..Default::default()
        };
        let piv_failure = "PIN and PUK are blocked but the applet was not wiped";
        let reports = vec![
            StepReport {
                step: ResetStep::Oath,
                outcome: StepOutcome::Wiped,
            },
            StepReport {
                step: ResetStep::OpenPgp,
                outcome: StepOutcome::Wiped,
            },
            StepReport {
                step: ResetStep::Piv,
                outcome: StepOutcome::Failed(piv_failure.into()),
            },
        ];

        App::apply_factory_reset_sweep(&mut app, Some(&a), reports, true);

        // Nothing of A's run is painted under B…
        assert!(
            app.factory_reset_report.is_empty(),
            "A's report must not appear under B"
        );
        // …and above all, B is not armed for a wipe the user confirmed for A.
        assert!(
            !app.security_keys.reset.open,
            "the FIDO finale must never open under another key"
        );
        assert!(app.reset_arm.is_none());

        let warn = app
            .log
            .iter()
            .find(|l| l.text.contains("selection moved on"))
            .unwrap_or_else(|| panic!("a wipe that lands off-screen must still be recorded"));
        assert!(matches!(warn.severity, Severity::Warn));
        let text = &warn.text;
        assert!(text.contains("OATH"), "{text}");
        assert!(text.contains("OpenPGP"), "{text}");
        assert!(text.contains("PIV"), "{text}");
        assert!(
            text.contains(piv_failure),
            "PIV's exact failure is the only thing that says the card is locked \
             but not wiped: {text}"
        );
        assert!(
            text.contains("FIDO2") && text.contains("never started"),
            "the un-wiped finale has to be named: {text}"
        );

        // A plan without FIDO says nothing about a ceremony that was never in it.
        let mut app = App {
            selected_device: Some("serial:BBB".into()),
            ..Default::default()
        };
        App::apply_factory_reset_sweep(
            &mut app,
            Some(&a),
            vec![StepReport {
                step: ResetStep::Oath,
                outcome: StepOutcome::Wiped,
            }],
            false,
        );
        let text = &app
            .log
            .iter()
            .find(|l| l.text.contains("selection moved on"))
            .expect("still logged")
            .text;
        assert!(!text.contains("FIDO2"), "{text}");
    }

    /// The same sweep under the key it ran against still paints its report and
    /// still hands the finale to the armed dialog — the guard must not cost the
    /// normal flow its outcome.
    #[test]
    fn a_same_device_card_sweep_paints_its_report_and_opens_the_finale() {
        use keyroost_resolve::{ResetStep, StepOutcome, StepReport};
        let a: DeviceId = "serial:AAA".into();
        let mut app = App {
            selected_device: Some(a.clone()),
            oath_tried: true,
            piv_tried: true,
            ..Default::default()
        };

        App::apply_factory_reset_sweep(
            &mut app,
            Some(&a),
            vec![
                StepReport {
                    step: ResetStep::Oath,
                    outcome: StepOutcome::Wiped,
                },
                StepReport {
                    step: ResetStep::Piv,
                    outcome: StepOutcome::Failed("card refused".into()),
                },
            ],
            true,
        );

        assert_eq!(app.factory_reset_report.len(), 3);
        assert_eq!(
            factory_reset_row_line(&app.factory_reset_report[0]),
            ("OATH  wiped".to_string(), RowTone::Done)
        );
        assert_eq!(
            factory_reset_row_line(&app.factory_reset_report[1]).1,
            RowTone::Bad
        );
        assert_eq!(
            factory_reset_row_line(&app.factory_reset_report[2]).1,
            RowTone::Waiting,
            "the finale is seeded pending, not reported as done"
        );
        assert!(app.security_keys.reset.open, "the finale's dialog opens");
        // A wiped applet's pane re-lists itself; a failed one keeps its state.
        assert!(!app.oath_tried);
        assert!(app.piv_tried);
        assert!(!app
            .log
            .iter()
            .any(|l| l.text.contains("selection moved on")));
    }

    /// The success path used to report only through `factory_reset_report`
    /// (the Overview pane's list) and never through the activity log — which
    /// silently dropped any captured APDU trace too, since `App::push_log`
    /// (the sole consumer of `App::pending_trace`) was never called. Both
    /// gaps are covered here: a plain-language summary lands in the log
    /// (wiped/failed/skipped, independent of tracing), and a trace captured
    /// for the job actually attaches to that entry instead of being discarded.
    #[test]
    fn a_same_device_card_sweep_logs_a_summary_and_flushes_any_captured_trace() {
        use keyroost_resolve::{ResetStep, StepOutcome, StepReport};
        let a: DeviceId = "serial:AAA".into();
        let mut app = App {
            selected_device: Some(a.clone()),
            pending_trace: Some(vec!["> SELECT".into(), "< 9000".into()]),
            ..Default::default()
        };

        App::apply_factory_reset_sweep(
            &mut app,
            Some(&a),
            vec![
                StepReport {
                    step: ResetStep::Oath,
                    outcome: StepOutcome::Wiped,
                },
                StepReport {
                    step: ResetStep::Piv,
                    outcome: StepOutcome::Skipped("PIV does not support RESET".into()),
                },
                StepReport {
                    step: ResetStep::Token2Otp,
                    outcome: StepOutcome::Failed("card refused".into()),
                },
            ],
            false,
        );

        let entry = app
            .log
            .iter()
            .find(|l| l.text.contains("factory reset finished"))
            .expect("factory reset must log a summary line");
        assert!(matches!(entry.severity, Severity::Warn)); // not everything wiped
        assert!(entry.text.contains("OATH"), "{}", entry.text);
        assert!(
            entry.text.contains("PIV does not support RESET"),
            "{}",
            entry.text
        );
        assert!(entry.text.contains("card refused"), "{}", entry.text);
        // The trace captured for this job attached to the summary line...
        assert_eq!(
            entry.trace.as_deref(),
            Some(&["> SELECT".to_string(), "< 9000".to_string()][..])
        );
        // ...and was consumed, not left to attach to some later, unrelated line.
        assert!(app.pending_trace.is_none());
    }

    /// All-`Wiped` reports log `Ok`, not `Warn` — the severity should read as
    /// success when nothing failed or was skipped.
    #[test]
    fn a_fully_wiped_sweep_logs_ok_severity() {
        use keyroost_resolve::{ResetStep, StepOutcome, StepReport};
        let a: DeviceId = "serial:AAA".into();
        let mut app = App {
            selected_device: Some(a.clone()),
            ..Default::default()
        };
        App::apply_factory_reset_sweep(
            &mut app,
            Some(&a),
            vec![StepReport {
                step: ResetStep::Oath,
                outcome: StepOutcome::Wiped,
            }],
            false,
        );
        let entry = app
            .log
            .iter()
            .find(|l| l.text.contains("factory reset finished"))
            .expect("factory reset must log a summary line");
        assert!(matches!(entry.severity, Severity::Ok));
    }

    /// `WipedWithWarning` still re-initialises the applet's pane (it really
    /// was wiped) but logs `Warn`, not `Ok` (there's still something for the
    /// user to act on) -- the end-to-end path behind the exact scenario
    /// reported: a device-wide reset whose courtesy XAUTH-key restore failed
    /// showed up as "wiped: none; failed: PIV: ..." instead of naming PIV as
    /// wiped.
    #[test]
    fn a_wiped_with_warning_sweep_reinits_the_pane_but_logs_warn_severity() {
        use keyroost_resolve::{ResetStep, StepOutcome, StepReport};
        let a: DeviceId = "serial:AAA".into();
        let mut app = App {
            selected_device: Some(a.clone()),
            piv_tried: true,
            ..Default::default()
        };
        App::apply_factory_reset_sweep(
            &mut app,
            Some(&a),
            vec![StepReport {
                step: ResetStep::Piv,
                outcome: StepOutcome::WipedWithWarning("restoring XAUTH key 1 failed".into()),
            }],
            false,
        );
        assert!(
            !app.piv_tried,
            "the pane must re-list; PIV really was wiped"
        );
        assert_eq!(
            factory_reset_row_line(&app.factory_reset_report[0]),
            (
                "PIV  wiped, but: restoring XAUTH key 1 failed".to_string(),
                RowTone::Warn
            )
        );
        let entry = app
            .log
            .iter()
            .find(|l| l.text.contains("factory reset finished"))
            .expect("factory reset must log a summary line");
        assert!(matches!(entry.severity, Severity::Warn));
        assert!(entry.text.contains("wiped: PIV"), "{}", entry.text);
        assert!(
            entry
                .text
                .contains("warnings: PIV: restoring XAUTH key 1 failed"),
            "{}",
            entry.text
        );
    }

    #[test]
    fn factory_reset_report_summary_names_every_bucket() {
        use keyroost_resolve::{ResetStep, StepOutcome, StepReport};
        let summary = factory_reset_report_summary(&[
            StepReport {
                step: ResetStep::Oath,
                outcome: StepOutcome::Wiped,
            },
            StepReport {
                step: ResetStep::OpenPgp,
                outcome: StepOutcome::Failed("card refused".into()),
            },
            StepReport {
                step: ResetStep::Piv,
                outcome: StepOutcome::Skipped("not supported".into()),
            },
        ]);
        assert!(summary.contains("wiped: OATH"), "{summary}");
        assert!(
            summary.contains("failed: OpenPGP: card refused"),
            "{summary}"
        );
        assert!(summary.contains("skipped: PIV: not supported"), "{summary}");
    }

    /// A device-wide reset whose courtesy XAUTH-key restore fails is still a
    /// wipe: the step must show up in the "wiped" list (a reader scanning
    /// just that list must not conclude PIV was left untouched), and the
    /// restore failure must still get its own line so it isn't lost. Exact
    /// scenario reported: "wiped: none; failed: PIV: device wiped, but
    /// restoring XAUTH key 1..." -- PIV belongs in "wiped", not only in
    /// "failed".
    #[test]
    fn factory_reset_report_summary_counts_a_wiped_with_warning_step_as_wiped() {
        use keyroost_resolve::{ResetStep, StepOutcome, StepReport};
        let summary = factory_reset_report_summary(&[StepReport {
            step: ResetStep::Piv,
            outcome: StepOutcome::WipedWithWarning("restoring XAUTH key 1 failed".into()),
        }]);
        assert!(summary.contains("wiped: PIV"), "{summary}");
        assert!(!summary.contains("wiped: none"), "{summary}");
        assert!(
            summary.contains("warnings: PIV: restoring XAUTH key 1 failed"),
            "{summary}"
        );
        assert!(!summary.contains("failed:"), "{summary}");
    }

    /// A PIV step wiped via the device-wide `ResetGlobal` mechanism took at
    /// least one other applet down with it, so naming only "PIV" undersells
    /// what happened — both the Overview row and the activity-log summary
    /// must name the whole device instead.
    #[test]
    fn factory_reset_global_piv_wipe_names_the_whole_device() {
        use keyroost_resolve::{ResetStep, StepOutcome, StepReport};
        let report = StepReport {
            step: ResetStep::Piv,
            outcome: StepOutcome::WipedGlobal,
        };

        let (text, tone) = factory_reset_row_line(&FactoryResetRow::Step(report.clone()));
        assert_eq!(tone, RowTone::Done, "{text}");
        assert_eq!(text, "Whole device (via PIV)  wiped");
        assert!(!text.starts_with("PIV"), "{text}");

        let summary = factory_reset_report_summary(&[
            report,
            StepReport {
                step: ResetStep::Oath,
                outcome: StepOutcome::Wiped,
            },
        ]);
        assert!(
            summary.contains("wiped: Whole device (via PIV), OATH"),
            "{summary}"
        );
        assert!(!summary.contains("wiped: PIV"), "{summary}");
    }

    #[test]
    fn factory_reset_report_summary_names_none_wiped_when_nothing_wiped() {
        use keyroost_resolve::{ResetStep, StepOutcome, StepReport};
        let summary = factory_reset_report_summary(&[StepReport {
            step: ResetStep::Oath,
            outcome: StepOutcome::Failed("card refused".into()),
        }]);
        assert!(summary.contains("wiped: none"), "{summary}");
        assert!(!summary.contains("skipped"), "{summary}");
    }

    /// Refusing to arm (KEY-005) ends the ceremony, exactly as Cancel does. An
    /// earlier arm can still be live when this branch is reached — the dialog
    /// reverts to its confirm form whenever the arm's key is no longer the
    /// selection, so "Arm reset" is pressable a second time — and telling the
    /// user "not armed" while that arm keeps polling wipes the key on its next
    /// replug after the UI said nothing would happen.
    #[test]
    fn refusing_to_arm_clears_a_live_arm() {
        let mut app = App {
            security_keys: SecurityKeysState {
                reset: ResetDialog {
                    open: true,
                    ..Default::default()
                },
                ..Default::default()
            },
            reset_arm: Some(armed_for("serial:AAA")),
            ..Default::default()
        };

        // Nothing selected: no HID serial and no effective serial — the refusal
        // branch, reached without touching a key.
        // Empty device list: no hardware is enumerated, so the outcome does not
        // depend on what is plugged into the machine running the test.
        app.arm_fido_reset_with(Vec::new());

        assert!(
            app.reset_arm.is_none(),
            "a refusal that says \"not armed\" must not leave a ceremony polling"
        );
        assert!(!app.security_keys.reset.open);
    }

    /// A scan can fail outright (pcscd down, a wedged reader), which empties the
    /// list and the selection. That is a selection change like any other and has
    /// to run the same teardown: otherwise the arm stays live with nothing
    /// selected, the dialog repaints its un-armed confirm form while the poll
    /// keeps watching for the replug, and every rescan path is suppressed while
    /// an arm exists — so the empty list can never recover.
    #[test]
    fn a_failed_scan_disarms_the_reset() {
        let mut app = App {
            selected_device: Some("serial:AAA".into()),
            reset_arm: Some(armed_for("serial:AAA")),
            security_keys: SecurityKeysState {
                reset: ResetDialog {
                    open: true,
                    ..Default::default()
                },
                ..Default::default()
            },
            ..Default::default()
        };

        App::apply_device_scan_failure(&mut app, "pcsc: no service".into());

        assert_eq!(app.devices_error.as_deref(), Some("pcsc: no service"));
        assert!(app.devices.is_empty());
        assert!(app.selected_device.is_none());
        assert!(
            app.reset_arm.is_none(),
            "an armed ceremony must not outlive the selection it was armed for"
        );
        assert!(
            !app.security_keys.reset.open,
            "the dialog behind the ceremony goes with it"
        );
        assert!(
            app.log
                .iter()
                .any(|l| l.text.contains("the armed reset was cancelled")),
            "the user was told to replug; the ceremony ending has to be visible"
        );

        // Already empty: nothing to tear down, and the failure still lands.
        let mut app = App::default();
        App::apply_device_scan_failure(&mut app, "pcsc: no service".into());
        assert_eq!(app.devices_error.as_deref(), Some("pcsc: no service"));
        assert!(app.log.is_empty(), "no ceremony existed to report ending");
    }

    /// Defence in depth for the rule above: the poll refuses to fire for a key
    /// that isn't the selection, whatever any other path forgot to clean up.
    /// It returns before enumerating, so it never reaches a device.
    #[test]
    fn the_poll_refuses_to_fire_for_a_key_that_is_no_longer_selected() {
        let mut app = App {
            selected_device: Some("serial:BBB".into()),
            reset_arm: Some(armed_for("serial:AAA")),
            ..Default::default()
        };

        app.poll_reset_arm();

        assert!(
            app.reset_arm.is_none(),
            "an arm bound to another key must not survive a poll"
        );
        assert!(app
            .log
            .iter()
            .any(|l| l.text.contains("no longer the one selected")));
    }

    /// #81: the Settings tab (home of the only Reset path) must exist for any
    /// CTAP2 key — authenticatorReset is a baseline CTAP 2.0 command, so
    /// gating the tab on authenticatorConfig (a CTAP 2.1 feature) locked
    /// CTAP 2.0-only keys out of reset entirely.
    #[test]
    fn settings_tab_exists_for_any_ctap2_key() {
        let ctap20_only = AuthenticatorInfo {
            versions: vec!["U2F_V2".into(), "FIDO_2_0".into()],
            ..Default::default()
        };
        assert!(
            fido_settings_available(Some(&ctap20_only)),
            "a CTAP 2.0-only key is resettable and must get the Settings tab"
        );

        let ctap21 = AuthenticatorInfo {
            versions: vec!["FIDO_2_1".into()],
            options: vec![("authnrCfg".into(), true)],
            ..Default::default()
        };
        assert!(fido_settings_available(Some(&ctap21)));

        // FIDO_2_1_PRE keys predate the final 2.1 naming but are CTAP2.
        let pre = AuthenticatorInfo {
            versions: vec!["FIDO_2_1_PRE".into()],
            ..Default::default()
        };
        assert!(fido_settings_available(Some(&pre)));
    }

    #[test]
    fn settings_tab_absent_without_a_ctap2_key() {
        // No getInfo yet (or a CTAP1-only key, which can't answer getInfo):
        // nothing to reset over CTAP2 — no tab.
        assert!(!fido_settings_available(None));

        // A hypothetical U2F-only answer offers no CTAP2 reset either.
        let u2f_only = AuthenticatorInfo {
            versions: vec!["U2F_V2".into()],
            ..Default::default()
        };
        assert!(!fido_settings_available(Some(&u2f_only)));
    }

    /// The "Save certificate…" action shows only for resident credentials that
    /// are SSH relying parties (`ssh:*`) AND carry a largeBlob key — the key is
    /// mandatory to decrypt the per-credential cert entry, so without it there
    /// is nothing the action could extract.
    #[test]
    fn ssh_cred_offers_cert_gates_on_ssh_rp_and_key() {
        let key = [7u8; 32];
        // ssh:* with a key → offered.
        assert!(ssh_cred_offers_cert("ssh:demo", Some(&key)));
        assert!(ssh_cred_offers_cert("ssh:", Some(&key)));
        // ssh:* without a key → not offered (nothing to decrypt with).
        assert!(!ssh_cred_offers_cert("ssh:demo", None));
        // non-ssh RP → never offered, key or not.
        assert!(!ssh_cred_offers_cert("example.com", Some(&key)));
        assert!(!ssh_cred_offers_cert("example.com", None));
        // A prefix look-alike that isn't the ssh: scheme is not offered.
        assert!(!ssh_cred_offers_cert("sshy:demo", Some(&key)));
    }

    /// Reset is the recovery for a forgotten/blocked PIN and needs no PIN
    /// itself, so it must stay reachable when the key can't be unlocked —
    /// rendered standalone outside the (unlock-gated) Settings tab.
    #[test]
    fn reset_card_stands_alone_exactly_when_ctap2_but_locked() {
        let ctap2 = AuthenticatorInfo {
            versions: vec!["FIDO_2_0".into()],
            ..Default::default()
        };
        // Locked: forgotten/blocked PIN, no PIN set, or no clientPin at all.
        assert!(show_standalone_reset(false, Some(&ctap2)));
        // Unlocked: the Settings tab owns the card; no duplicate.
        assert!(!show_standalone_reset(true, Some(&ctap2)));
        // No CTAP2 getInfo: nothing reset could talk to.
        assert!(!show_standalone_reset(false, None));
    }

    /// A persisted subview pick must snap to a tab the selected key actually
    /// offers (capabilities differ across keys; the pick outlives selection).
    #[test]
    fn subview_snaps_to_an_offered_tab() {
        let tabs = [
            (FidoSubview::Settings, "Settings"),
            (FidoSubview::LargeBlobs, "Storage"),
        ];
        // Present pick is kept.
        assert_eq!(
            snap_subview(FidoSubview::Settings, &tabs),
            FidoSubview::Settings
        );
        // Stale pick (tab not offered on this key) snaps to the first tab.
        assert_eq!(
            snap_subview(FidoSubview::Fingerprints, &tabs),
            FidoSubview::Settings
        );
        assert_eq!(
            snap_subview(FidoSubview::Passkeys, &tabs),
            FidoSubview::Settings
        );
        // Degenerate empty list falls back to the default.
        assert_eq!(
            snap_subview(FidoSubview::Settings, &[]),
            FidoSubview::Passkeys
        );
    }

    /// `snap_cap_tab`'s own version of the rule directly above, one level up.
    #[test]
    fn cap_tab_snaps_to_an_offered_tab() {
        let tabs = [CapTab::Overview, CapTab::Fido2, CapTab::Oath];
        // Present pick is kept.
        assert_eq!(snap_cap_tab(CapTab::Fido2, &tabs), CapTab::Fido2);
        // Stale pick (tab not offered on this device) snaps to the first tab.
        assert_eq!(snap_cap_tab(CapTab::Piv, &tabs), CapTab::Overview);
        // Degenerate empty list (a Molto2 token, which has no capability
        // tabs at all) falls back to the default.
        assert_eq!(snap_cap_tab(CapTab::Fido2, &[]), CapTab::Overview);
    }

    /// Switching devices remembers each device's own last-shown `cap_tab`,
    /// rather than resetting every device to Overview — the bug this pair
    /// (`App::cap_tab_by_device` + `on_device_selected`) exists to fix.
    #[test]
    fn device_switch_restores_each_devices_own_cap_tab() {
        let mut app = App {
            selected_device: Some("serial:AAA".into()),
            cap_tab: CapTab::Piv,
            ..Default::default()
        };
        // Switch to a second device never seen before: starts fresh.
        let previous = app.selected_device.replace("serial:BBB".into());
        app.on_device_selected(previous);
        assert_eq!(app.cap_tab, CapTab::Overview);
        app.cap_tab = CapTab::Fido2;
        // Switch back to the first device: its own pick (Piv) comes back —
        // not Overview, and not the second device's Fido2 pick.
        let previous = app.selected_device.replace("serial:AAA".into());
        app.on_device_selected(previous);
        assert_eq!(app.cap_tab, CapTab::Piv);
    }

    /// getInfo with no `clientPin` option means the key has no PIN feature —
    /// distinct from "info not read yet", which the pane used to conflate
    /// with it (permanent "Reading key…" on PIN-less authenticators).
    #[test]
    fn pin_support_distinguishes_absent_option_from_missing_info() {
        assert_eq!(pin_support(None), PinSupport::Unknown);
        let no_pin_feature = AuthenticatorInfo {
            versions: vec!["FIDO_2_0".into()],
            ..Default::default()
        };
        assert_eq!(pin_support(Some(&no_pin_feature)), PinSupport::Unsupported);
        let pin_not_set = AuthenticatorInfo {
            options: vec![("clientPin".into(), false)],
            ..Default::default()
        };
        assert_eq!(pin_support(Some(&pin_not_set)), PinSupport::NotSet);
        let pin_set = AuthenticatorInfo {
            options: vec![("clientPin".into(), true)],
            ..Default::default()
        };
        assert_eq!(pin_support(Some(&pin_set)), PinSupport::Set);
    }

    #[test]
    fn duplicate_serial_note_flags_shared_serial() {
        let note = duplicate_serial_note(["ABC", "ABC", "DEF"].into_iter())
            .expect("a shared serial must produce an advisory");
        assert!(note.contains("ABC"), "advisory names the duplicated serial");
        assert!(note.contains('2'), "advisory states how many keys share it");
    }

    #[test]
    fn duplicate_serial_note_silent_when_all_distinct() {
        assert_eq!(duplicate_serial_note(["ABC", "DEF"].into_iter()), None);
        assert_eq!(duplicate_serial_note(std::iter::empty::<&str>()), None);
    }

    #[test]
    fn duplicate_serial_id_suffix_keeps_ids_distinct() {
        // Invariant Section E's correlate() must uphold and this GUI relies on:
        // same-serial keys get distinct, `#`-suffixed ids, so selection (which
        // keys off the full id in selected_device()) resolves each independently.
        let a = "serial:ABC#0";
        let b = "serial:ABC#1";
        assert_ne!(a, b);
    }

    /// egui retains a plaintext snapshot of every typed secret in the text
    /// widget's undo history for the process lifetime; `.password(true)` only
    /// masks display. `clear_edit_undo` must purge that history so a wiped
    /// buffer leaves nothing recoverable from egui memory.
    #[test]
    fn clear_edit_undo_purges_retained_plaintext() {
        let ctx = egui::Context::default();
        let id = egui::Id::new("pin-field-test");
        let empty = (egui::text::CCursorRange::default(), String::new());

        // Simulate egui recording undo history as the user types a PIN. An undo
        // point is committed only once a state has been stable for `stable_time`
        // (1s default), so feed the same secret across a ≥1s gap.
        let secret = (
            egui::text::CCursorRange::default(),
            "1234-secret-pin".to_string(),
        );
        let mut state = egui::TextEdit::load_state(&ctx, id).unwrap_or_default();
        let mut undoer = state.undoer();
        undoer.feed_state(0.0, &empty);
        undoer.feed_state(1.0, &secret);
        undoer.feed_state(2.0, &secret);
        state.set_undoer(undoer);
        egui::TextEdit::store_state(&ctx, id, state);

        // Precondition: history retains a snapshot differing from an empty field.
        let before = egui::TextEdit::load_state(&ctx, id).unwrap();
        assert!(
            before.undoer().has_undo(&empty),
            "test setup should have recorded undo history"
        );

        clear_edit_undo(&ctx, id);

        let after = egui::TextEdit::load_state(&ctx, id).unwrap();
        assert!(
            !after.undoer().has_undo(&empty),
            "undo history (and its plaintext) must be gone after clear_edit_undo"
        );
    }

    /// The scrub-needed check behind `guard_secret_field`: empty history is
    /// skipped, committed undo points / redo stacks / in-flux text are not.
    #[test]
    fn edit_state_scrub_check_detects_retained_plaintext() {
        let empty = (egui::text::CCursorRange::default(), String::new());
        let secret = (egui::text::CCursorRange::default(), "1234-pin".to_string());

        // A fresh state has nothing to scrub.
        let mut state = egui::text_edit::TextEditState::default();
        assert!(!edit_state_needs_scrub(&state));

        // Committed undo history must be detected… (an undo point commits
        // once a state has been stable ≥1s — same technique as
        // clear_edit_undo_purges_retained_plaintext above)
        let mut undoer = state.undoer();
        undoer.feed_state(0.0, &empty);
        undoer.feed_state(1.0, &secret);
        undoer.feed_state(2.0, &secret);
        state.set_undoer(undoer);
        assert!(edit_state_needs_scrub(&state));

        // …and clearing satisfies the check again.
        state.clear_undoer();
        assert!(!edit_state_needs_scrub(&state));

        // Text typed too recently to be a committed undo point still counts:
        // the plaintext lives in the undoer's flux buffer.
        let mut undoer = state.undoer();
        undoer.feed_state(3.0, &empty);
        undoer.feed_state(3.1, &secret);
        state.set_undoer(undoer);
        assert!(edit_state_needs_scrub(&state));
    }

    /// A job that panics inside the worker must not wedge the UI: the worker
    /// catches it, delivers an error apply (so busy clears), and stays alive to
    /// run later jobs. Before the fix the thread unwound, the result channel
    /// disconnected, and busy_jobs stuck at 1 forever.
    #[test]
    fn panicking_job_clears_busy_and_worker_survives() {
        let mut app = App {
            worker: Some(Worker::spawn(egui::Context::default(), Default::default())),
            ..Default::default()
        };
        // Silence the panic backtrace this test intentionally triggers.
        let prev = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));

        app.spawn_job("boom", || -> ApplyFn {
            panic!("simulated device-op panic")
        });
        assert!(app.busy(), "busy set right after dispatch");

        // The worker still delivers an apply despite the panic.
        let apply = app
            .worker
            .as_ref()
            .unwrap()
            .result_rx
            .recv_timeout(std::time::Duration::from_secs(5))
            .expect("worker delivered an apply despite the panicking job");
        std::panic::set_hook(prev);
        app.busy_jobs -= 1;
        apply(&mut app);
        assert!(!app.busy(), "busy must clear after a panicking job");

        // The worker survived: a subsequent job still runs to completion.
        assert!(
            app.spawn_job("after", || Box::new(|app: &mut App| app.slot = 7)),
            "worker should accept jobs after a panic"
        );
        let apply = app
            .worker
            .as_ref()
            .unwrap()
            .result_rx
            .recv_timeout(std::time::Duration::from_secs(5))
            .expect("second job ran on the surviving worker");
        app.busy_jobs -= 1;
        apply(&mut app);
        assert_eq!(app.slot, 7);
    }

    /// A job dispatched to a real worker thread runs off-thread, and its result
    /// applies back to the App with the busy bookkeeping cleared.
    #[test]
    fn worker_round_trip_applies_result_and_clears_busy() {
        let mut app = App {
            worker: Some(Worker::spawn(egui::Context::default(), Default::default())),
            ..Default::default()
        };
        app.spawn_job("test", || Box::new(|app: &mut App| app.slot = 42));
        assert!(app.busy(), "busy should be set right after dispatch");

        // Wait for the worker to produce a result, then drain it.
        let worker = app.worker.as_ref().unwrap();
        let apply = worker
            .result_rx
            .recv_timeout(std::time::Duration::from_secs(5))
            .expect("worker produced a result");
        // Mimic drain_worker: decrement before applying.
        app.busy_jobs -= 1;
        apply(&mut app);

        assert_eq!(app.slot, 42);
        assert!(!app.busy(), "busy should clear once the result is applied");
    }

    /// While a job is in flight, a second dispatch is dropped (device access is
    /// serialized; rapid clicks don't queue overlapping card I/O).
    #[test]
    fn spawn_job_ignored_while_busy() {
        let mut app = App {
            worker: Some(Worker::spawn(egui::Context::default(), Default::default())),
            ..Default::default()
        };
        // Occupy the worker with a job whose result we don't drain.
        app.spawn_job("first", || Box::new(|_: &mut App| {}));
        assert_eq!(app.busy_jobs, 1);
        app.spawn_job("second", || Box::new(|app: &mut App| app.slot = 99));
        assert_eq!(
            app.busy_jobs, 1,
            "second dispatch must be ignored while busy"
        );
    }

    /// With no worker (the default), a job runs inline so headless tests and any
    /// non-GUI use still apply results.
    #[test]
    fn inline_when_no_worker() {
        let mut app = App::default();
        assert!(app.worker.is_none());
        app.spawn_job("inline", || Box::new(|app: &mut App| app.slot = 7));
        assert_eq!(app.slot, 7);
        assert!(!app.busy());
    }

    /// The PIV credential modal's new==confirm guard: matching (or still-empty)
    /// confirm fields pass; a divergent confirm reports the right message.
    #[test]
    fn piv_cred_mismatch_change_pin() {
        let mut piv = PivState::default();
        // Empty confirm is treated as "not yet a mismatch".
        piv.pin_new = "1234".into();
        assert_eq!(piv_cred_mismatch(&piv, PivCredKind::ChangePin), None);
        // Matching new/confirm: no error.
        piv.pin_confirm = "1234".into();
        assert_eq!(piv_cred_mismatch(&piv, PivCredKind::ChangePin), None);
        // Divergent confirm: the PIN-specific message.
        piv.pin_confirm = "9999".into();
        assert_eq!(
            piv_cred_mismatch(&piv, PivCredKind::ChangePin),
            Some("the two new PINs don't match")
        );
    }

    #[test]
    fn piv_cred_mismatch_change_puk() {
        let mut piv = PivState::default();
        piv.puk_new = "12345678".into();
        piv.puk_confirm = "00000000".into();
        assert_eq!(
            piv_cred_mismatch(&piv, PivCredKind::ChangePuk),
            Some("the two new PUKs don't match")
        );
        piv.puk_confirm = "12345678".into();
        assert_eq!(piv_cred_mismatch(&piv, PivCredKind::ChangePuk), None);
    }

    /// Unblock has no confirm field, so the guard never reports a mismatch even
    /// with arbitrary field contents.
    #[test]
    fn piv_cred_mismatch_unblock_never_fires() {
        let mut piv = PivState::default();
        piv.unblock_puk = "12345678".into();
        piv.unblock_new_pin = "1234".into();
        assert_eq!(piv_cred_mismatch(&piv, PivCredKind::UnblockPin), None);
    }

    /// The Pin Policy / Touch Policy dropdowns' initial selection, both on a
    /// fresh `PivState` and after the modal-close reset: `default` / `default`
    /// — the plain PIV APDU every card accepts.
    #[test]
    fn piv_gen_policy_dropdowns_default_to_default() {
        let fresh = PivState::default();
        assert_eq!(fresh.gen_pin_policy, keyroost_piv::PinPolicy::Default);
        assert_eq!(fresh.gen_touch_policy, keyroost_piv::TouchPolicy::Default);

        let mut app = App::default();
        app.piv.gen_pin_policy = keyroost_piv::PinPolicy::Never;
        app.piv.gen_touch_policy = keyroost_piv::TouchPolicy::Always;
        app.piv_cred_modal_close();
        assert_eq!(app.piv.gen_pin_policy, keyroost_piv::PinPolicy::Default);
        assert_eq!(app.piv.gen_touch_policy, keyroost_piv::TouchPolicy::Default);
    }

    /// `PivMgmtAlgSel::Delete` maps to no algorithm at all — the "delete the
    /// management key outright" choice HID Crescendo's own combo offers,
    /// distinct from every real `MgmtAlg`. `to_choice()`, unlike `to_alg()`,
    /// is total: `MgmtAlgChoice` has its own `Delete`-equivalent variant, so
    /// every `PivMgmtAlgSel` (including `Delete` itself) round-trips.
    #[test]
    fn piv_mgmt_alg_sel_delete_has_no_algorithm() {
        use keyroost_piv::compat::MgmtAlgChoice;
        assert_eq!(PivMgmtAlgSel::Delete.to_alg(), None);
        assert_eq!(PivMgmtAlgSel::Delete.label(), "Delete");
        assert_eq!(PivMgmtAlgSel::Delete.to_choice(), MgmtAlgChoice::Delete);
        for alg in [
            PivMgmtAlgSel::Aes192,
            PivMgmtAlgSel::Aes128,
            PivMgmtAlgSel::Aes256,
            PivMgmtAlgSel::TripleDes,
        ] {
            assert!(alg.to_alg().is_some());
            assert_ne!(alg.to_choice(), MgmtAlgChoice::Delete);
        }
    }

    /// The management-key combo offers every algorithm plus `Delete` last, on
    /// every device — `Delete` isn't trimmed off the list for a standard
    /// device the way it used to be; it's still offered there, just gated
    /// disabled live (via `PivExtension::ManagementKeyAlgorithm`) since a
    /// standard device's management key can't be removed outright.
    #[test]
    fn piv_mgmtalg_all_lists_delete_last() {
        assert_eq!(
            PivMgmtAlgSel::ALL,
            [
                PivMgmtAlgSel::TripleDes,
                PivMgmtAlgSel::Aes128,
                PivMgmtAlgSel::Aes192,
                PivMgmtAlgSel::Aes256,
                PivMgmtAlgSel::Delete,
            ]
        );
        assert_eq!(PivMgmtAlgSel::ALL.last(), Some(&PivMgmtAlgSel::Delete));
    }

    /// The Generate key card's initial selection (`App::piv`'s `new_mgmt_alg`
    /// field seeds from [`PivMgmtAlgSel::default`]) stays `Aes192` — a
    /// widely-supported starting point — independent of [`PivMgmtAlgSel::ALL`]'s
    /// own order. The two used to coincide (`Aes192` was `ALL[0]` too, before
    /// `ALL` was alphabetized to `TripleDes` first); this pins the `#[default]`
    /// attribute itself so a future reshuffle of `ALL` can't silently drag the
    /// default combo selection along with it.
    #[test]
    fn piv_mgmtalg_default_stays_aes192_despite_the_alphabetized_all_order() {
        assert_eq!(PivMgmtAlgSel::default(), PivMgmtAlgSel::Aes192);
        assert_ne!(PivMgmtAlgSel::ALL[0], PivMgmtAlgSel::default());
    }

    /// `piv_mgmtalg_clamp` snaps a selection the given options don't offer
    /// back to the first option, and leaves an already-valid selection
    /// alone.
    #[test]
    fn piv_mgmtalg_clamp_snaps_an_unoffered_selection_to_the_first_option() {
        // Already valid: left alone.
        let mut sel = PivMgmtAlgSel::Delete;
        piv_mgmtalg_clamp(&mut sel, &PivMgmtAlgSel::ALL);
        assert_eq!(sel, PivMgmtAlgSel::Delete);

        // A narrower list that excludes `Delete` (e.g. a hypothetical future
        // device the combo restricts further) clamps it away to that list's
        // first entry.
        let without_delete = [
            PivMgmtAlgSel::TripleDes,
            PivMgmtAlgSel::Aes128,
            PivMgmtAlgSel::Aes192,
            PivMgmtAlgSel::Aes256,
        ];
        let mut sel = PivMgmtAlgSel::Delete;
        piv_mgmtalg_clamp(&mut sel, &without_delete);
        assert_eq!(sel, PivMgmtAlgSel::TripleDes);
    }

    /// `piv_mgmtalg_unsupported_fallback` snaps a selection gating
    /// `Unsupported` to the first *selectable* offered option — not
    /// `options[0]` unconditionally, since `options[0]` (`TripleDes` on the
    /// alphabetized `ALL`) can itself be the disabled entry. A regression
    /// test for exactly that bug: the combo used to preselect `options[0]`
    /// even when it was disabled, because the old fallback snapped straight
    /// back to it without checking whether *it* was selectable too.
    #[test]
    fn piv_mgmtalg_unsupported_fallback_skips_a_disabled_first_option() {
        use keyroost_piv::compat::FeatureGate;

        // TripleDes (`options[0]`) is disabled; Aes128 is the next option in
        // `ALL`'s order (`[TripleDes, Aes128, Aes192, Aes256]`) and is
        // selectable, so it's the fallback.
        let gate = |alg: PivMgmtAlgSel| match alg {
            PivMgmtAlgSel::TripleDes => FeatureGate::Unsupported,
            _ => FeatureGate::Supported,
        };
        assert_eq!(
            piv_mgmtalg_unsupported_fallback(PivMgmtAlgSel::TripleDes, &PivMgmtAlgSel::ALL, gate),
            PivMgmtAlgSel::Aes128
        );

        // A selection that isn't `Unsupported` is left alone, even if a
        // *different* option would also be selectable.
        assert_eq!(
            piv_mgmtalg_unsupported_fallback(PivMgmtAlgSel::Aes128, &PivMgmtAlgSel::ALL, gate),
            PivMgmtAlgSel::Aes128
        );

        // Every option disabled: nothing better to select, so it falls back
        // to `options[0]` rather than panicking or leaving `sel` disabled
        // forever with no path back to a selectable state.
        let all_unsupported = |_: PivMgmtAlgSel| FeatureGate::Unsupported;
        assert_eq!(
            piv_mgmtalg_unsupported_fallback(
                PivMgmtAlgSel::TripleDes,
                &PivMgmtAlgSel::ALL,
                all_unsupported
            ),
            PivMgmtAlgSel::TripleDes
        );

        // Empty options: no-op regardless of gate.
        assert_eq!(
            piv_mgmtalg_unsupported_fallback(PivMgmtAlgSel::TripleDes, &[], gate),
            PivMgmtAlgSel::TripleDes
        );
    }

    /// `piv_mgmtalg_unverified_labels` suppresses the per-algorithm
    /// "unverified" warning entirely once `SetManagementKey` itself gates
    /// `Unsupported` — there's nothing to warn about picking an algorithm for
    /// a change that can't be made at all, and the disabled button/combo
    /// already carry their own blocked-hint tooltip.
    #[test]
    fn piv_mgmtalg_unverified_labels_are_suppressed_when_the_extension_is_unsupported() {
        use keyroost_piv::compat::FeatureGate;

        let all_unverified = |_: PivMgmtAlgSel| FeatureGate::Unverified;
        // Extension unsupported: empty, regardless of what the per-algorithm
        // gates would otherwise report.
        assert!(piv_mgmtalg_unverified_labels(
            FeatureGate::Unsupported,
            &PivMgmtAlgSel::ALL,
            all_unverified
        )
        .is_empty());

        // Extension merely unverified, or fully supported: the per-algorithm
        // list still comes through normally.
        assert_eq!(
            piv_mgmtalg_unverified_labels(
                FeatureGate::Unverified,
                &PivMgmtAlgSel::ALL,
                all_unverified
            )
            .len(),
            PivMgmtAlgSel::ALL.len()
        );
        assert_eq!(
            piv_mgmtalg_unverified_labels(
                FeatureGate::Supported,
                &PivMgmtAlgSel::ALL,
                all_unverified
            )
            .len(),
            PivMgmtAlgSel::ALL.len()
        );

        // Extension supported, but no option is individually unverified:
        // empty for an unrelated reason (nothing to report), not the
        // suppression rule.
        assert!(
            piv_mgmtalg_unverified_labels(FeatureGate::Supported, &PivMgmtAlgSel::ALL, |_| {
                FeatureGate::Supported
            })
            .is_empty()
        );
    }

    /// `piv_keyalg_unsupported_fallback` — the slot key-algorithm counterpart
    /// of `piv_mgmtalg_unsupported_fallback` — snaps a selection gating
    /// `Unsupported` to the first selectable algorithm in `KeyAlg::ALL`
    /// rather than unconditionally returning `fallback`: the caller's usual
    /// "widely-supported default" (`EccP256` at the one call site in
    /// `cap_piv`) is just another candidate and could itself be the disabled
    /// entry on some fingerprint.
    #[test]
    fn piv_keyalg_unsupported_fallback_skips_a_disabled_fallback_algorithm() {
        use keyroost_piv::compat::FeatureGate;
        use keyroost_piv::KeyAlg;

        // `EccP256` (the usual `fallback` argument) is itself disabled here;
        // `Rsa1024` is the first selectable algorithm in `ALL`'s order.
        let gate = |alg: KeyAlg| match alg {
            KeyAlg::EccP256 => FeatureGate::Unsupported,
            _ => FeatureGate::Supported,
        };
        assert_eq!(
            piv_keyalg_unsupported_fallback(KeyAlg::EccP256, KeyAlg::EccP256, gate),
            KeyAlg::Rsa1024
        );

        // A selection that isn't `Unsupported` is left alone.
        assert_eq!(
            piv_keyalg_unsupported_fallback(KeyAlg::Rsa2048, KeyAlg::EccP256, gate),
            KeyAlg::Rsa2048
        );

        // Every algorithm disabled: falls back to `fallback` outright —
        // nothing better to select.
        assert_eq!(
            piv_keyalg_unsupported_fallback(KeyAlg::EccP256, KeyAlg::EccP256, |_| {
                FeatureGate::Unsupported
            }),
            KeyAlg::EccP256
        );
    }

    /// `PivMgmtAlgSel::to_choice()` feeds `PivExtension::ManagementKeyAlgorithm`
    /// correctly end to end: a HID Crescendo device gates 3DES/AES-128/Delete
    /// `Supported` and AES-192/AES-256 `Unsupported`, while a YubiKey gates
    /// every real algorithm `Supported` and `Delete` `Unsupported` — the same
    /// verdicts `keyroost_piv::compat`'s own tests confirm directly against
    /// `MgmtAlgChoice`, exercised here through the GUI-side selector instead.
    #[test]
    fn piv_mgmtalg_sel_to_choice_resolves_the_expected_gate_per_fingerprint() {
        use keyroost_piv::compat::{FeatureGate, PivExtension};
        use keyroost_piv::fingerprint::{AppletFingerprint, HidCrescendoVariant};

        let gate = |fp: AppletFingerprint, sel: PivMgmtAlgSel| {
            keyroost_piv::compat::resolve(
                PivExtension::ManagementKeyAlgorithm(sel.to_choice()),
                fp,
                None,
                None,
            )
        };
        let hid = AppletFingerprint::HidCrescendo(HidCrescendoVariant::C2300);
        for sel in [
            PivMgmtAlgSel::TripleDes,
            PivMgmtAlgSel::Aes128,
            PivMgmtAlgSel::Delete,
        ] {
            assert_eq!(gate(hid, sel), FeatureGate::Supported, "{sel:?}");
        }
        for sel in [PivMgmtAlgSel::Aes192, PivMgmtAlgSel::Aes256] {
            assert_eq!(gate(hid, sel), FeatureGate::Unsupported, "{sel:?}");
        }
        for sel in [
            PivMgmtAlgSel::Aes192,
            PivMgmtAlgSel::Aes128,
            PivMgmtAlgSel::Aes256,
            PivMgmtAlgSel::TripleDes,
        ] {
            assert_eq!(
                gate(AppletFingerprint::YubiKey, sel),
                FeatureGate::Supported,
                "{sel:?}"
            );
        }
        assert_eq!(
            gate(AppletFingerprint::YubiKey, PivMgmtAlgSel::Delete),
            FeatureGate::Unsupported
        );
    }

    /// `piv_policy_clamp` — the PIN/touch policy counterpart of
    /// `piv_mgmtalg_clamp` — snaps a selection a `PivQuirk` has dropped from
    /// the offered list (e.g. `Once`/`Cached`) back to `Default`, and leaves
    /// an already-offered selection alone.
    #[test]
    fn piv_policy_clamp_snaps_an_unoffered_selection_to_default() {
        let cached_excluded: Vec<keyroost_piv::TouchPolicy> = keyroost_piv::TouchPolicy::ALL
            .iter()
            .copied()
            .filter(|&opt| opt != keyroost_piv::TouchPolicy::Cached)
            .collect();

        let mut sel = keyroost_piv::TouchPolicy::Cached;
        piv_policy_clamp(&mut sel, &cached_excluded);
        assert_eq!(sel, keyroost_piv::TouchPolicy::Default);

        // Already offered: left alone.
        let mut sel = keyroost_piv::TouchPolicy::Always;
        piv_policy_clamp(&mut sel, &cached_excluded);
        assert_eq!(sel, keyroost_piv::TouchPolicy::Always);

        // The full list never excludes `Default` itself, so a full-list
        // clamp never moves a valid selection.
        let mut sel = keyroost_piv::TouchPolicy::Cached;
        piv_policy_clamp(&mut sel, keyroost_piv::TouchPolicy::ALL);
        assert_eq!(sel, keyroost_piv::TouchPolicy::Cached);
    }

    /// The Compression dropdown: its choices and labels, the transport choice
    /// each maps to, and its initial selection on a fresh state and after
    /// the modal-close reset (Automatic, like the CLI with neither flag).
    #[test]
    fn piv_cert_compression_dropdown() {
        use keyroost_transport::CertCompression;
        let labels: Vec<_> = PivCertCompressionSel::ALL
            .iter()
            .map(|s| s.label())
            .collect();
        assert_eq!(labels, ["Automatic (only if too large)", "Always", "Never"]);
        assert_eq!(
            PivCertCompressionSel::Auto.to_compression(),
            CertCompression::Auto
        );
        assert_eq!(
            PivCertCompressionSel::Always.to_compression(),
            CertCompression::Always
        );
        assert_eq!(
            PivCertCompressionSel::Never.to_compression(),
            CertCompression::Never
        );

        assert_eq!(
            PivState::default().cert_compression,
            PivCertCompressionSel::Auto
        );
        let mut app = App::default();
        app.piv.cert_compression = PivCertCompressionSel::Never;
        app.piv_cred_modal_close();
        assert_eq!(app.piv.cert_compression, PivCertCompressionSel::Auto);
    }

    /// The success notice mirrors the CLI: the stored size when compressed,
    /// and the why-and-compatibility note when Automatic had to compress.
    #[test]
    fn piv_cert_stored_notice_and_detail() {
        assert_eq!(
            piv_cert_stored_notice("Certificate imported", false, 3087, false),
            "Certificate imported."
        );
        assert_eq!(piv_cert_stored_detail(false, 3087, false), None);

        assert_eq!(
            piv_cert_stored_notice("Certificate imported", true, 2900, false),
            "Certificate imported (stored compressed: 2900 bytes on the card)."
        );
        assert_eq!(
            piv_cert_stored_detail(true, 2900, false).as_deref(),
            Some("Stored compressed: 2900 bytes on the card.")
        );

        let auto = piv_cert_stored_notice("Certificate imported", true, 2900, true);
        assert!(
            auto.starts_with("Certificate imported (stored compressed: 2900 bytes on the card)."),
            "{auto}"
        );
        assert!(auto.ends_with(PIV_AUTO_COMPRESSED_NOTE), "{auto}");
        let detail = piv_cert_stored_detail(true, 2900, true).unwrap();
        assert!(detail.contains(PIV_AUTO_COMPRESSED_NOTE), "{detail}");

        let note = PIV_AUTO_COMPRESSED_NOTE;
        assert!(note.contains("did not fit"), "{note}");
        assert!(note.contains("Windows"), "{note}");
        assert!(note.contains("macOS"), "{note}");
        assert!(note.contains("not been verified"), "{note}");
        assert!(!note.to_lowercase().contains("unsupported"), "{note}");
    }

    /// With Compression set to Never, a too-large refusal points at the
    /// dropdown (the CLI names its flags instead).
    #[test]
    fn piv_cert_too_large_hint_only_for_never() {
        let slot = keyroost_piv::Slot::KeyManagement;
        let too_large = TransportError::PivCertTooLarge {
            slot,
            len: 6164,
            compressed_len: None,
        };
        let hint = piv_cert_error_hint(&too_large, PivCertCompressionSel::Never).unwrap();
        assert!(hint.contains("Compression"), "{hint}");
        assert!(hint.contains("Automatic"), "{hint}");
        assert_eq!(
            piv_cert_error_hint(&too_large, PivCertCompressionSel::Auto),
            None
        );
        assert_eq!(
            piv_cert_error_hint(
                &TransportError::PivCardFull { slot },
                PivCertCompressionSel::Never
            ),
            None
        );
    }

    #[test]
    fn piv_retired_slot_state_words() {
        use keyroost_transport::SlotKeyPresence as K;
        assert_eq!(piv_retired_slot_state_text(Some(K::Present)), "key present");
        assert_eq!(piv_retired_slot_state_text(Some(K::NoKey)), "empty");
        assert_eq!(
            piv_retired_slot_state_text(Some(K::Unknown)),
            "no certificate (a key may be present)"
        );
        // Not read yet: as before, the same wording a slot with no key uses.
        assert_eq!(piv_retired_slot_state_text(None), "empty");
        assert_eq!(
            piv_retired_slot_hover("Retired key 3", K::Present),
            "Retired key 3 \u{00B7} holds a key"
        );
        assert_eq!(
            piv_retired_slot_hover("Retired key 3", K::NoKey),
            "Retired key 3 \u{00B7} empty"
        );
        assert_eq!(
            piv_retired_slot_hover("Retired key 3", K::Unknown),
            "Retired key 3 \u{00B7} no certificate (a key may be present)"
        );
    }

    /// The selected slot's state line marks a compressed certificate.
    #[test]
    fn piv_slot_state_text_marks_compression() {
        use keyroost_transport::SlotKeyPresence as K;
        let p256 = Some(keyroost_piv::KeyAlg::EccP256);
        assert_eq!(
            piv_slot_state_text(None, true, true, p256, K::Unknown),
            "certificate present (ECC P-256, compressed)"
        );
        assert_eq!(
            piv_slot_state_text(None, true, false, p256, K::Unknown),
            "certificate present (ECC P-256)"
        );
        assert_eq!(
            piv_slot_state_text(None, true, true, None, K::Unknown),
            "certificate present (compressed)"
        );
        assert_eq!(
            piv_slot_state_text(None, true, false, None, K::Unknown),
            "certificate present"
        );
        assert_eq!(
            piv_slot_state_text(None, false, false, p256, K::Unknown),
            "key present (ECC P-256), no certificate"
        );
        assert_eq!(
            piv_slot_state_text(None, false, false, None, K::NoKey),
            "empty"
        );
        assert_eq!(
            piv_slot_state_text(None, false, false, None, K::Unknown),
            "no certificate (a key may be present)"
        );
        // Same words as `keyroostctl piv info` when no algorithm is known.
        assert_eq!(
            piv_slot_state_text(None, false, false, None, K::Present),
            "key present, no certificate"
        );
        assert_eq!(
            piv_slot_state_text(None, false, false, p256, K::Present),
            "key present (ECC P-256), no certificate"
        );
        assert_eq!(
            piv_slot_state_text(
                Some(keyroost_transport::CertUnreadable::Damaged),
                true,
                false,
                p256,
                K::Unknown
            ),
            format!(
                "certificate present but unreadable ({})",
                keyroost_transport::CertUnreadable::Damaged
            )
        );
    }

    /// Each flow maps to its own title, busy caption, and success text.
    #[test]
    fn piv_cred_kind_strings_are_distinct() {
        let kinds = [
            PivCredKind::ChangePin,
            PivCredKind::ChangePuk,
            PivCredKind::UnblockPin,
        ];
        let titles: Vec<_> = kinds.iter().map(|k| k.title()).collect();
        assert_eq!(titles, ["Change PIN", "Change PUK", "Unblock PIN"]);
        assert_eq!(piv_cred_success(PivCredKind::ChangePin), "PIN changed");
        assert_eq!(piv_cred_success(PivCredKind::ChangePuk), "PUK changed");
        assert_eq!(
            piv_cred_success(PivCredKind::UnblockPin),
            "PIN unblocked and reset"
        );
        // Busy captions are non-empty and unique.
        let busy: Vec<_> = kinds.iter().map(|k| k.busy_label()).collect();
        assert!(busy.iter().all(|s| !s.is_empty()));
        assert_eq!(busy[0], "Changing PIV PIN\u{2026}");
    }

    /// A successful PIV write drops the retired-occupancy cache (so the
    /// section re-reads fresh on next expand). If a retired slot was selected
    /// when that happens, the selection must snap back to a standard slot —
    /// otherwise the Generate overwrite guard reads the now-cleared cache as
    /// "unknown occupancy" and treats that as empty, silently skipping its
    /// warning on what may still be an occupied archived key.
    #[test]
    fn apply_piv_write_success_clears_stale_retired_selection() {
        let mut app = App::default();
        app.piv.selected_slot = PivSlotSel::Retired(3);
        app.piv.retired_occupancy = Some(vec![(
            keyroost_piv::Slot::Retired(3),
            keyroost_transport::SlotKeyPresence::Present,
        )]);
        let status = keyroost_transport::PivStatus::default();
        App::apply_piv_write(&mut app, Ok(status), "did a thing".into());
        assert_eq!(
            app.piv.selected_slot,
            PivSlotSel::Auth,
            "a retired-slot selection must not survive its occupancy cache clearing"
        );
        assert!(app.piv.retired_occupancy.is_none());
    }

    /// A standard-slot selection is left untouched by the same invalidation —
    /// only a stale `Retired` selection needs to be reset.
    #[test]
    fn apply_piv_write_success_leaves_standard_selection_alone() {
        let mut app = App::default();
        app.piv.selected_slot = PivSlotSel::KeyMgmt;
        let status = keyroost_transport::PivStatus::default();
        App::apply_piv_write(&mut app, Ok(status), "did a thing".into());
        assert_eq!(app.piv.selected_slot, PivSlotSel::KeyMgmt);
    }

    /// The management-key-gated flows declare they collect the current
    /// management key (and therefore show the "Use default" toggle); the PIN/PUK
    /// and CSR flows do not.
    #[test]
    fn piv_cred_kind_mgmt_key_mapping() {
        assert!(PivCredKind::GenerateKey.needs_mgmt_key());
        assert!(PivCredKind::ImportCert.needs_mgmt_key());
        assert!(PivCredKind::SelfSign.needs_mgmt_key());
        assert!(PivCredKind::SetRetries.needs_mgmt_key());
        assert!(PivCredKind::ChangeMgmtKey.needs_mgmt_key());
        // Slot deletion is authorized by the management key (like generate).
        assert!(PivCredKind::DeleteCert.needs_mgmt_key());
        assert!(PivCredKind::DeleteKey.needs_mgmt_key());
        // Moving a key is authorized by the management key too.
        assert!(PivCredKind::MoveKey.needs_mgmt_key());
        // CSR signs with the PIN only — no management key.
        assert!(!PivCredKind::RequestCsr.needs_mgmt_key());
        // PIN/PUK flows never collect a management key.
        assert!(!PivCredKind::ChangePin.needs_mgmt_key());
        assert!(!PivCredKind::ChangePuk.needs_mgmt_key());
        assert!(!PivCredKind::UnblockPin.needs_mgmt_key());
    }

    /// Every new gated variant has a distinct, non-empty title / submit label /
    /// busy caption / success line.
    #[test]
    fn piv_cred_kind_gated_strings_are_present() {
        let kinds = [
            PivCredKind::GenerateKey,
            PivCredKind::ImportCert,
            PivCredKind::SelfSign,
            PivCredKind::RequestCsr,
            PivCredKind::SetRetries,
            PivCredKind::ChangeMgmtKey,
            PivCredKind::DeleteCert,
            PivCredKind::DeleteKey,
            PivCredKind::MoveKey,
        ];
        for k in kinds {
            assert!(!k.title().is_empty());
            assert!(!k.submit_label().is_empty());
            assert!(k.busy_label().ends_with('\u{2026}'));
            assert!(!piv_cred_success(k).is_empty());
        }
        // Mismatch guard only fires for the PIN/PUK change flows; gated flows
        // never report a new==confirm mismatch.
        let piv = PivState::default();
        for k in kinds {
            assert_eq!(piv_cred_mismatch(&piv, k), None);
        }
    }

    /// The overwrite-guard occupancy predicate reads the right cache for each
    /// selection kind: standard slots from `slot_keys`, retired slots from the
    /// lazily-populated `retired_occupancy` cache.
    #[test]
    fn piv_slot_occupied_reads_the_right_cache() {
        use keyroost_piv::{KeyAlg, Slot};
        use keyroost_transport::SlotKeyPresence;

        // Standard-slot occupancy comes from `slot_keys`: a carried algorithm
        // means the slot holds a private key; `None` means empty.
        let slot_keys = vec![
            (Slot::Authentication, Some(KeyAlg::EccP256), None),
            (Slot::Signature, None, None),
        ];
        assert!(piv_slot_occupied(PivSlotSel::Auth, &slot_keys, None));
        // alg is None -> empty
        assert!(!piv_slot_occupied(PivSlotSel::Sign, &slot_keys, None));
        // slot absent from the cache -> treated as empty
        assert!(!piv_slot_occupied(PivSlotSel::CardAuth, &slot_keys, None));

        // Retired-slot occupancy comes from the `retired_occupancy` cache.
        let retired = vec![
            (Slot::retired(1).unwrap(), SlotKeyPresence::Present),
            (Slot::retired(2).unwrap(), SlotKeyPresence::NoKey),
            (Slot::retired(4).unwrap(), SlotKeyPresence::Unknown),
        ];
        assert!(piv_slot_occupied(
            PivSlotSel::Retired(1),
            &slot_keys,
            Some(&retired)
        ));
        // listed but empty
        assert!(!piv_slot_occupied(
            PivSlotSel::Retired(2),
            &slot_keys,
            Some(&retired)
        ));
        // can't tell: not counted as occupied (the card refuses an occupied
        // move destination itself)
        assert!(!piv_slot_occupied(
            PivSlotSel::Retired(4),
            &slot_keys,
            Some(&retired)
        ));
        // not listed in the cache -> false
        assert!(!piv_slot_occupied(
            PivSlotSel::Retired(3),
            &slot_keys,
            Some(&retired)
        ));
        // cache absent entirely -> false (unknown treated as empty)
        assert!(!piv_slot_occupied(PivSlotSel::Retired(1), &slot_keys, None));
    }

    /// The Generate / Move "replace?" warning fails closed: a slot keyroost
    /// can't vouch for as empty counts as possibly holding a key, the same
    /// rule the CLI applies before it writes.
    #[test]
    fn piv_slot_occupancy_treats_unknown_as_possibly_occupied() {
        use keyroost_piv::{KeyAlg, Slot};
        use keyroost_transport::SlotKeyPresence as K;

        let slot_keys = vec![
            (Slot::Authentication, Some(KeyAlg::EccP256), None),
            (Slot::Signature, None, None),
            (Slot::KeyManagement, None, None),
            (Slot::CardAuthentication, None, None),
        ];
        let standard = vec![
            (Slot::Authentication, K::Unknown),
            (Slot::Signature, K::NoKey),
            (Slot::KeyManagement, K::Unknown),
            (Slot::CardAuthentication, K::Present),
        ];
        let retired = vec![
            (Slot::retired(1).unwrap(), K::Present),
            (Slot::retired(2).unwrap(), K::NoKey),
            (Slot::retired(4).unwrap(), K::Unknown),
        ];
        let occ =
            |s: Slot, r: Option<&[(Slot, K)]>| piv_slot_occupancy(s, &slot_keys, &standard, r);

        // A carried algorithm is a key, whatever the status says.
        assert_eq!(occ(Slot::Authentication, None), PivOccupancy::Key);
        assert_eq!(occ(Slot::CardAuthentication, None), PivOccupancy::Key);
        // Only a confirmed "no key" is empty.
        assert_eq!(occ(Slot::Signature, None), PivOccupancy::Empty);
        // Can't tell -> may hold a key.
        assert_eq!(occ(Slot::KeyManagement, None), PivOccupancy::MaybeKey);
        assert_eq!(
            piv_slot_occupancy(Slot::KeyManagement, &slot_keys, &[], None),
            PivOccupancy::MaybeKey
        );

        assert_eq!(
            occ(Slot::retired(1).unwrap(), Some(&retired)),
            PivOccupancy::Key
        );
        assert_eq!(
            occ(Slot::retired(2).unwrap(), Some(&retired)),
            PivOccupancy::Empty
        );
        assert_eq!(
            occ(Slot::retired(4).unwrap(), Some(&retired)),
            PivOccupancy::MaybeKey
        );
        // Not read yet (slot not listed, or no cache at all) -> may hold a key.
        assert_eq!(
            occ(Slot::retired(3).unwrap(), Some(&retired)),
            PivOccupancy::MaybeKey
        );
        assert_eq!(occ(Slot::retired(1).unwrap(), None), PivOccupancy::MaybeKey);

        // The warning text names the slot and what would happen.
        assert_eq!(
            piv_replace_warning(PivOccupancy::MaybeKey, "9d (Key Management)").as_deref(),
            Some(
                "9d (Key Management) may already hold a key, which would be replaced. \
                 This cannot be undone."
            )
        );
        assert!(
            piv_replace_warning(PivOccupancy::Key, "9a").is_some_and(|w| w.contains("OVERWRITES"))
        );
        assert_eq!(piv_replace_warning(PivOccupancy::Empty, "9a"), None);
    }

    #[test]
    fn move_destination_never_warns_of_overwriting() {
        let w = piv_move_dest_warning(PivOccupancy::Key, "9a").unwrap();
        assert!(w.contains("already holds a key") && w.contains("delete it first"));
        assert!(!w.contains("OVERWRITES") && !w.contains("replaced"));
        assert_eq!(piv_move_dest_warning(PivOccupancy::MaybeKey, "9a"), None);
        assert_eq!(piv_move_dest_warning(PivOccupancy::Empty, "9a"), None);
    }

    #[test]
    fn move_destination_of_unknown_occupancy_gets_a_neutral_note() {
        assert_eq!(
            piv_move_dest_note(PivOccupancy::MaybeKey, "9a").as_deref(),
            Some("keyroost can't tell whether 9a holds a key; the card decides.")
        );
        assert_eq!(piv_move_dest_note(PivOccupancy::Key, "9a"), None);
        assert_eq!(piv_move_dest_note(PivOccupancy::Empty, "9a"), None);
    }

    #[test]
    fn slot_confirmed_empty_only_fires_on_a_confirmed_empty_slot() {
        use keyroost_piv::compat::FeatureGate;

        // Confirmed empty on a device that can actually tell us -> blocked.
        assert!(slot_confirmed_empty(FeatureGate::Supported, false));
        // Confirmed to hold a key -> never blocked, regardless of the gate.
        assert!(!slot_confirmed_empty(FeatureGate::Supported, true));
        // No reliable device signal (Unverified or Unsupported) -> never
        // blocked on emptiness, even if the (untrustworthy) reading says
        // empty -- this is the whole point of gating on
        // `GetSlotKeyStatus` rather than trusting `selected_has_key` alone.
        assert!(!slot_confirmed_empty(FeatureGate::Unverified, false));
        assert!(!slot_confirmed_empty(FeatureGate::Unsupported, false));
    }

    /// Given occupancy (slot -> has_key), the eligible move destinations are the
    /// empty slots that aren't the source — across standard *and* retired slots.
    #[test]
    fn move_key_destinations_exclude_occupied_and_source() {
        let occupied = |s: keyroost_piv::Slot| {
            s == keyroost_piv::Slot::Authentication // 9A occupied
                || s == keyroost_piv::Slot::retired(1).unwrap()
        };
        let src = keyroost_piv::Slot::KeyManagement;
        let dests = move_key_eligible_destinations(src, &occupied);
        assert!(!dests.contains(&src));
        assert!(!dests.contains(&keyroost_piv::Slot::Authentication)); // occupied
        assert!(!dests.contains(&keyroost_piv::Slot::retired(1).unwrap()));
        assert!(dests.contains(&keyroost_piv::Slot::retired(2).unwrap())); // empty
        assert!(dests.contains(&keyroost_piv::Slot::Signature)); // empty standard
    }

    /// The standard PIV factory default is 24 bytes of `01..08` ×3; Token2 PIN+
    /// ships its own vendor default. Both resolve via
    /// `PivQuirk::Default9bManagementKey`, at any reported version.
    #[test]
    fn piv_default_mgmt_key_is_well_known() {
        let std = piv_default_mgmt_key(
            keyroost_piv::fingerprint::AppletFingerprint::YubiKey,
            Some(&[0]),
            None,
        )
        .expect("YubiKey has a seeded default");
        assert_eq!(&std[..8], &[1, 2, 3, 4, 5, 6, 7, 8]);
        // Repeated three times.
        assert_eq!(&std[8..16], &std[..8]);
        assert_eq!(&std[16..24], &std[..8]);

        let t2 = piv_default_mgmt_key(
            keyroost_piv::fingerprint::AppletFingerprint::Token2,
            Some(&[0]),
            None,
        )
        .expect("Token2 has a seeded default");
        assert_ne!(std, t2);
    }

    /// A fingerprint keyroost has no seeded default for (`IdPrime`) resolves
    /// `None` — the signal `App::piv_modal_mgmt_field` disables the "Use
    /// default management key" checkbox on.
    #[test]
    fn piv_default_mgmt_key_none_for_an_unseeded_fingerprint() {
        // IdPrime no longer fits this test — it now carries its own seeded
        // default (`keyroost_piv::compat::IDPRIME_APPLET_QUIRKS`) — so this
        // uses OpenFips201::Generic instead, which still has none.
        assert_eq!(
            piv_default_mgmt_key(
                keyroost_piv::fingerprint::AppletFingerprint::OpenFips201(
                    keyroost_piv::fingerprint::OpenFips201Variant::Generic
                ),
                Some(&[0]),
                None
            ),
            None
        );
    }

    /// `OathAddDialog::validate` trims the name, requires it, base32-decodes the
    /// secret, and rejects an empty/invalid secret — the same guards the modal's
    /// Submit relies on before dispatching `provision_oath`.
    #[test]
    fn gui_oath_add_validate_caps_solo2() {
        use keyroost_import::plan::OathFamily;
        let mut d = OathAddDialog::opened();
        d.secret = "JBSWY3DPEHPK3PXP".into();
        d.name = "n".repeat(128);
        assert_eq!(
            d.validate(OathFamily::Solo2).unwrap_err(),
            "the name is 128 bytes; a Solo 2 stores names up to 127 bytes \
             (a longer one makes the key stop responding until it is unplugged)"
        );
        assert!(d.validate(OathFamily::YubiKey { version: None }).is_ok());
        assert!(d.validate(OathFamily::Nitrokey3).is_ok());
        d.name = "n".repeat(127);
        assert!(d.validate(OathFamily::Solo2).is_ok());
    }

    #[test]
    fn oath_row_period_from_prefix() {
        assert_eq!(
            OathRow::new("60/GitHub:alice".into(), None, false).period,
            60
        );
        assert_eq!(OathRow::new("GitHub:alice".into(), None, false).period, 30);
        // HOTP names carry no period.
        assert_eq!(OathRow::new("60/x".into(), None, true).period, 30);
    }

    #[test]
    fn oath_add_dialog_validate() {
        // Empty name → error, regardless of the secret.
        let mut d = OathAddDialog::opened();
        d.name = "  ".into();
        d.secret = "JBSWY3DPEHPK3PXP".into();
        assert_eq!(
            d.validate(keyroost_import::plan::OathFamily::Other)
                .unwrap_err(),
            "credential name is required"
        );

        // Empty secret → error.
        d.name = "acme:alice".into();
        d.secret = String::new();
        assert_eq!(
            d.validate(keyroost_import::plan::OathFamily::Other)
                .unwrap_err(),
            "secret is empty"
        );

        // Non-base32 secret → "invalid base32 secret: …".
        d.secret = "not base32!!".into();
        assert!(d
            .validate(keyroost_import::plan::OathFamily::Other)
            .unwrap_err()
            .starts_with("invalid base32 secret"));

        // Valid input → trimmed name + decoded secret bytes.
        d.name = "  acme:alice  ".into();
        d.secret = "JBSWY3DPEHPK3PXP".into();
        let (name, secret) = d
            .validate(keyroost_import::plan::OathFamily::Other)
            .expect("valid");
        assert_eq!(name, "acme:alice");
        assert_eq!(
            secret,
            keyroost_proto::codec::base32_decode("JBSWY3DPEHPK3PXP").unwrap()
        );
        assert!(!secret.is_empty());
    }

    /// `apply_oath_rows` mirrors the provision outcome into the open add modal
    /// (busy clears; success → `Ok`, error → `Err(message)`) and does *not*
    /// double-report into the pane-level `oath.error` while the modal owns the op.
    #[test]
    fn apply_oath_rows_mirrors_into_add_modal() {
        // Success path: modal busy → result Ok, busy cleared, rows applied.
        let mut app = App::default();
        app.oath.add = OathAddDialog::opened();
        app.oath.add.busy = true;
        App::apply_oath_rows(
            &mut app,
            Ok((vec![OathRow::new("x".into(), None, false)], 0)),
            zeroize::Zeroizing::new(String::new()),
        );
        assert!(!app.oath.add.busy);
        assert_eq!(app.oath.add.result, Some(Ok(())));
        assert_eq!(app.oath.creds.len(), 1);
        assert!(app.oath.error.is_none());

        // Error path: wrong password surfaces in the modal, not the pane.
        let mut app = App::default();
        app.oath.add = OathAddDialog::opened();
        app.oath.add.busy = true;
        App::apply_oath_rows(
            &mut app,
            Err(TransportError::OathPasswordRejected),
            zeroize::Zeroizing::new(String::new()),
        );
        assert!(!app.oath.add.busy);
        assert_eq!(app.oath.add.result, Some(Err("wrong OATH password".into())));
        assert!(app.oath.error.is_none());

        // No modal open: the pane-level error path still works (unlock/refresh).
        let mut app = App::default();
        App::apply_oath_rows(
            &mut app,
            Err(TransportError::OathPasswordRejected),
            zeroize::Zeroizing::new(String::new()),
        );
        assert!(!app.oath.add.open);
        assert!(app.oath.locked);
        assert_eq!(app.oath.error.as_deref(), Some("wrong OATH password"));
    }

    /// With "Use default management key" ticked, `piv_current_mgmt_key` ignores
    /// the (possibly empty) hex field and yields this device's well-known
    /// default; with it off, it decodes the typed hex.
    #[test]
    fn piv_current_mgmt_key_honours_use_default() {
        let mut app = App::default();
        app.piv.status = Some(piv_status_with(
            keyroost_piv::fingerprint::AppletFingerprint::YubiKey,
            Some(vec![5, 7]),
        ));
        // Default toggle on, hex field empty → resolves to this device's
        // seeded default (YubiKey's, since that's the live fingerprint).
        app.piv.mgmt_auth_mode = PivMgmtAuthMode::Default;
        app.piv.mgmt_key_input.clear();
        let key = app.piv_current_mgmt_key().expect("default fills");
        assert_eq!(
            &key[..],
            piv_default_mgmt_key(
                keyroost_piv::fingerprint::AppletFingerprint::YubiKey,
                Some(&[5, 7]),
                None
            )
            .unwrap()
        );

        // Toggle off → uses the typed hex.
        app.piv.mgmt_auth_mode = PivMgmtAuthMode::Manual;
        app.piv.mgmt_key_input = "aabbccddeeff00112233445566778899aabbccddeeff0011".into();
        let typed = app.piv_current_mgmt_key().expect("valid hex");
        assert_eq!(typed.len(), 24);
        assert_eq!(typed[0], 0xaa);

        // Toggle off with bad hex → error surfaces.
        app.piv.mgmt_key_input = "nothex".into();
        assert!(app.piv_current_mgmt_key().is_err());
    }

    /// With "Use default management key" ticked but no live status read yet
    /// (or a fingerprint keyroost has no seeded default for), there's no
    /// default to fall back on — `piv_current_mgmt_key` surfaces an error
    /// rather than guessing.
    #[test]
    fn piv_current_mgmt_key_default_errors_without_a_known_default() {
        let mut app = App::default();
        app.piv.mgmt_auth_mode = PivMgmtAuthMode::Default;
        // No status read yet at all.
        assert!(app.piv_current_mgmt_key().is_err());

        // A live status, but for a fingerprint with no seeded default.
        // IdPrime no longer fits here either — see
        // `piv_default_mgmt_key_none_for_an_unseeded_fingerprint`.
        app.piv.status = Some(piv_status_with(
            keyroost_piv::fingerprint::AppletFingerprint::OpenFips201(
                keyroost_piv::fingerprint::OpenFips201Variant::Generic,
            ),
            None,
        ));
        assert!(app.piv_current_mgmt_key().is_err());
    }

    /// With "Use PIN" ticked, `piv_current_mgmt_auth` yields a `Pin`, sourced
    /// from `mgmt_key_input` for a flow with no PIN field of its own — the
    /// same field the checkbox turns from "Management key" into "PIN".
    #[test]
    fn piv_current_mgmt_auth_use_pin_reads_mgmt_key_input_by_default() {
        let mut app = App::default();
        app.piv.mgmt_auth_mode = PivMgmtAuthMode::Pin;
        app.piv.mgmt_key_input = "123456".into();
        match app.piv_current_mgmt_auth(PivCredKind::GenerateKey) {
            Ok(PivMgmtAuth::Pin(pin)) => assert_eq!(&*pin, "123456"),
            other => panic!("expected Pin(\"123456\"), got {}", other.is_ok()),
        }
    }

    /// For `SelfSign`/`SetRetries` — flows that already collect a PIN of
    /// their own — "Use PIN" reuses *that* field instead of
    /// `mgmt_key_input`: PIV has exactly one application PIN, so the two
    /// boxes would otherwise ask for the same value twice.
    #[test]
    fn piv_current_mgmt_auth_use_pin_shares_the_dedicated_pin_field() {
        let mut app = App::default();
        app.piv.mgmt_auth_mode = PivMgmtAuthMode::Pin;
        // Left blank/stale on purpose — must not be what gets read.
        app.piv.mgmt_key_input = "should-not-be-used".into();

        app.piv.sign_pin = "111111".into();
        match app.piv_current_mgmt_auth(PivCredKind::SelfSign) {
            Ok(PivMgmtAuth::Pin(pin)) => assert_eq!(&*pin, "111111"),
            other => panic!("expected Pin(\"111111\"), got {}", other.is_ok()),
        }

        app.piv.retries_pin_auth = "222222".into();
        match app.piv_current_mgmt_auth(PivCredKind::SetRetries) {
            Ok(PivMgmtAuth::Pin(pin)) => assert_eq!(&*pin, "222222"),
            other => panic!("expected Pin(\"222222\"), got {}", other.is_ok()),
        }
    }

    /// With "Use PIN" off, `piv_current_mgmt_auth` falls through to the
    /// existing management-key resolution unchanged.
    #[test]
    fn piv_current_mgmt_auth_without_use_pin_falls_back_to_mgmt_key() {
        let mut app = App::default();
        app.piv.status = Some(piv_status_with(
            keyroost_piv::fingerprint::AppletFingerprint::YubiKey,
            Some(vec![5, 7]),
        ));
        app.piv.mgmt_auth_mode = PivMgmtAuthMode::Default;
        match app.piv_current_mgmt_auth(PivCredKind::GenerateKey) {
            Ok(PivMgmtAuth::Key(key)) => assert_eq!(
                &key[..],
                piv_default_mgmt_key(
                    keyroost_piv::fingerprint::AppletFingerprint::YubiKey,
                    Some(&[5, 7]),
                    None
                )
                .unwrap()
            ),
            other => panic!("expected Key(default), got {}", other.is_ok()),
        }
    }

    /// Regression test for a reported bug: check "Use PIN", check "Use
    /// default management key" (which un-checks "Use PIN"), then un-check
    /// "Use default management key" again. With two independent `bool`s —
    /// each resetting the other on check but not consulting it on uncheck —
    /// the third step left `use_pin` from step 1 stuck, so neither checkbox
    /// was checked yet the field still asked for a PIN. `mgmt_auth_mode` is
    /// a single field precisely to make that state unrepresentable: each
    /// toggle is `piv_mgmt_mode_after_toggle`, applied unconditionally.
    #[test]
    fn mgmt_mode_toggle_sequence_ends_manual_not_stuck_on_pin() {
        // 1. check "Use PIN". (Starting mode is Manual either way — the
        // fresh-modal default — so the first toggle's result doesn't depend
        // on it.)
        let mut mode = piv_mgmt_mode_after_toggle(true, PivMgmtAuthMode::Pin);
        assert_eq!(mode, PivMgmtAuthMode::Pin);
        // 2. check "Use default management key".
        mode = piv_mgmt_mode_after_toggle(true, PivMgmtAuthMode::Default);
        assert_eq!(mode, PivMgmtAuthMode::Default);
        // 3. uncheck "Use default management key" — neither box is checked
        // now, so this must land on Manual (asking for the typed management
        // key), not silently revert to Pin.
        mode = piv_mgmt_mode_after_toggle(false, PivMgmtAuthMode::Default);
        assert_eq!(mode, PivMgmtAuthMode::Manual);
    }

    /// `piv_mgmt_mode_after_toggle` unconditionally: checking always lands on
    /// the given mode, unchecking always lands on `Manual`, regardless of
    /// which mode was current beforehand.
    #[test]
    fn piv_mgmt_mode_after_toggle_ignores_the_other_toggle_entirely() {
        assert_eq!(
            piv_mgmt_mode_after_toggle(true, PivMgmtAuthMode::Default),
            PivMgmtAuthMode::Default
        );
        assert_eq!(
            piv_mgmt_mode_after_toggle(true, PivMgmtAuthMode::Pin),
            PivMgmtAuthMode::Pin
        );
        assert_eq!(
            piv_mgmt_mode_after_toggle(false, PivMgmtAuthMode::Default),
            PivMgmtAuthMode::Manual
        );
        assert_eq!(
            piv_mgmt_mode_after_toggle(false, PivMgmtAuthMode::Pin),
            PivMgmtAuthMode::Manual
        );
    }

    #[test]
    fn reset_mgmt_auth_mode_after_toggle_ignores_the_other_toggle_entirely() {
        assert_eq!(
            reset_mgmt_auth_mode_after_toggle(true, ResetMgmtAuthMode::Default),
            ResetMgmtAuthMode::Default
        );
        assert_eq!(
            reset_mgmt_auth_mode_after_toggle(true, ResetMgmtAuthMode::Pin),
            ResetMgmtAuthMode::Pin
        );
        assert_eq!(
            reset_mgmt_auth_mode_after_toggle(false, ResetMgmtAuthMode::Default),
            ResetMgmtAuthMode::Manual
        );
        assert_eq!(
            reset_mgmt_auth_mode_after_toggle(false, ResetMgmtAuthMode::Pin),
            ResetMgmtAuthMode::Manual
        );
    }

    #[test]
    fn reset_mgmt_current_auth_default_reads_the_armed_dialogs_resolved_key() {
        let app = App {
            reset_mgmt_auth_mode: ResetMgmtAuthMode::Default,
            factory_reset_confirm: Some(FactoryResetConfirmState {
                for_device: "serial:AAA".into(),
                piv_preview: FactoryResetPivPreview::NotOffered,
                needs_reset_mgmt_auth: true,
                default_mgmt_key: Some(
                    &keyroost_piv::fingerprint::HID_CRESCENDO_ACA_FACTORY_XAUTH_KEY,
                ),
                reset_long_running: false,
            }),
            ..Default::default()
        };
        match app.reset_mgmt_current_auth() {
            Ok(ResetMgmtAuth::Key(key)) => assert_eq!(
                &*key,
                &keyroost_piv::fingerprint::HID_CRESCENDO_ACA_FACTORY_XAUTH_KEY
            ),
            other => panic!("expected the factory-default key, got {}", other.is_ok()),
        }
    }

    #[test]
    fn reset_mgmt_current_auth_default_with_no_known_default_errors() {
        // No `factory_reset_confirm` armed at all (e.g. a stale call) is the
        // same "no known default" case as one armed with `default_mgmt_key:
        // None` — both mean keyroost has nothing to offer for this device.
        let app = App {
            reset_mgmt_auth_mode: ResetMgmtAuthMode::Default,
            ..Default::default()
        };
        assert!(app.reset_mgmt_current_auth().is_err());
    }

    #[test]
    fn reset_mgmt_current_auth_pin_reads_the_typed_field() {
        let app = App {
            reset_mgmt_auth_mode: ResetMgmtAuthMode::Pin,
            reset_mgmt_auth_input: "123456".into(),
            ..Default::default()
        };
        match app.reset_mgmt_current_auth() {
            Ok(ResetMgmtAuth::Pin(pin)) => assert_eq!(&*pin, "123456"),
            other => panic!("expected Pin(\"123456\"), got {}", other.is_ok()),
        }
    }

    #[test]
    fn reset_mgmt_current_auth_manual_decodes_typed_hex() {
        let mut app = App {
            reset_mgmt_auth_mode: ResetMgmtAuthMode::Manual,
            reset_mgmt_auth_input: "00".repeat(24),
            ..Default::default()
        };
        match app.reset_mgmt_current_auth() {
            Ok(ResetMgmtAuth::Key(key)) => assert_eq!(&*key, &[0u8; 24]),
            other => panic!("expected a 24-byte zero key, got {}", other.is_ok()),
        }
        // Bad hex surfaces a decode error, same as the PIV modal's field.
        app.reset_mgmt_auth_input = "not hex".into();
        assert!(app.reset_mgmt_current_auth().is_err());
    }

    /// `piv_cred_modal_close` resets `mgmt_auth_mode` to `Manual` — covering
    /// both what `use_default_mgmt = false` already did and the previously
    /// missing `use_pin` reset (a real gap the two-bool design had: closing
    /// the modal left "Use PIN" ticked for the next flow that opens it).
    #[test]
    fn piv_cred_modal_close_resets_mgmt_auth_mode() {
        let mut app = App::default();
        for mode in [PivMgmtAuthMode::Default, PivMgmtAuthMode::Pin] {
            app.piv.mgmt_auth_mode = mode;
            app.piv_cred_modal_close();
            assert_eq!(app.piv.mgmt_auth_mode, PivMgmtAuthMode::Manual);
        }
    }

    /// `PivCredKind::shares_pin_field` covers exactly `SelfSign`/`SetRetries` —
    /// every other management-gated flow gets its own PIN box (or none) from
    /// `piv_modal_mgmt_field`, not a reused one.
    #[test]
    fn shares_pin_field_covers_exactly_self_sign_and_set_retries() {
        for kind in [
            PivCredKind::ChangePin,
            PivCredKind::ChangePuk,
            PivCredKind::UnblockPin,
            PivCredKind::GenerateKey,
            PivCredKind::ImportCert,
            PivCredKind::RequestCsr,
            PivCredKind::ChangeMgmtKey,
            PivCredKind::DeleteCert,
            PivCredKind::DeleteKey,
            PivCredKind::MoveKey,
            PivCredKind::NewChuid,
        ] {
            assert!(!kind.shares_pin_field(), "{kind:?} should not share");
        }
        assert!(PivCredKind::SelfSign.shares_pin_field());
        assert!(PivCredKind::SetRetries.shares_pin_field());
    }

    /// `apply_piv_cred_result` mirrors the pane outcome into the open modal:
    /// no error → `Ok`, error present → `Err(message)`, and `busy` clears.
    #[test]
    fn apply_piv_cred_result_mirrors_outcome() {
        let mut app = App::default();
        // Success path.
        app.piv.cred_modal = Some(PivCredModal {
            kind: PivCredKind::ChangePin,
            busy: true,
            result: None,
            detail: None,
        });
        app.piv.error = None;
        App::apply_piv_cred_result(&mut app);
        let m = app.piv.cred_modal.as_ref().unwrap();
        assert!(!m.busy);
        assert_eq!(m.result, Some(Ok(())));

        // Error path.
        app.piv.cred_modal = Some(PivCredModal::new(PivCredKind::ChangePuk));
        app.piv.cred_modal.as_mut().unwrap().busy = true;
        app.piv.error = Some("wrong PUK".into());
        App::apply_piv_cred_result(&mut app);
        let m = app.piv.cred_modal.as_ref().unwrap();
        assert!(!m.busy);
        assert_eq!(m.result, Some(Err("wrong PUK".into())));
    }

    /// `PivSlotSel::label` maps each selector to the canonical PIV slot name; the
    /// delete flows name this slot in their destructive warning and success line.
    #[test]
    fn piv_slot_sel_labels() {
        assert_eq!(PivSlotSel::Auth.label(), "authentication (9A)");
        assert_eq!(PivSlotSel::Sign.label(), "signature (9C)");
        assert_eq!(PivSlotSel::KeyMgmt.label(), "key management (9D)");
        assert_eq!(PivSlotSel::CardAuth.label(), "card authentication (9E)");
    }

    /// `OpenPgpCredKind::needs_admin_pin` is true for every admin-PIN (PW3)-gated
    /// flow and false for the self-authorising user-PIN change and the PIN-less
    /// reset — this is what decides whether the admin-PIN field + use-default
    /// toggle render in the modal.
    #[test]
    fn openpgp_cred_kind_needs_admin_pin_mapping() {
        use OpenPgpCredKind::*;
        for k in [
            ChangeAdminPin,
            UnblockUserPin,
            SetName,
            SetUrl,
            GenerateKey,
            GenerateImportKey,
            ImportKeyFile,
        ] {
            assert!(k.needs_admin_pin(), "{} should need PW3", k.title());
        }
        for k in [ChangeUserPin, Reset] {
            assert!(!k.needs_admin_pin(), "{} should not need PW3", k.title());
        }
    }

    /// With "Use default admin PIN (PW3)" ticked, `openpgp_admin_pin_value`
    /// ignores the (possibly empty) typed field and yields the well-known factory
    /// default; with it off, it returns the typed PIN verbatim.
    #[test]
    fn openpgp_admin_pin_value_honours_use_default() {
        let mut app = App::default();

        // Default toggle on, field empty → resolves to the factory default.
        app.openpgp.use_default_admin = true;
        app.openpgp.admin_pin.clear();
        assert_eq!(app.openpgp_admin_pin_value(), OPENPGP_DEFAULT_ADMIN_PIN);
        assert_eq!(app.openpgp_admin_pin_value(), "12345678");

        // Toggle off → uses the typed PIN.
        app.openpgp.use_default_admin = false;
        app.openpgp.admin_pin = "7654321".into();
        assert_eq!(app.openpgp_admin_pin_value(), "7654321");
    }

    /// `apply_openpgp_cred_result` mirrors the pane outcome into the open modal:
    /// no error → `Ok`, error present → `Err(message)`, and `busy` clears.
    #[test]
    fn apply_openpgp_cred_result_mirrors_outcome() {
        let mut app = App::default();

        // Success path.
        app.openpgp.cred_modal = Some(OpenPgpCredModal {
            kind: OpenPgpCredKind::SetName,
            busy: true,
            result: None,
            device: None,
        });
        app.openpgp.error = None;
        App::apply_openpgp_cred_result(&mut app);
        let m = app.openpgp.cred_modal.as_ref().unwrap();
        assert!(!m.busy);
        assert_eq!(m.result, Some(Ok(())));

        // Error path.
        app.openpgp.cred_modal = Some(OpenPgpCredModal::new(OpenPgpCredKind::ChangeAdminPin, None));
        app.openpgp.cred_modal.as_mut().unwrap().busy = true;
        app.openpgp.error = Some("wrong admin PIN".into());
        App::apply_openpgp_cred_result(&mut app);
        let m = app.openpgp.cred_modal.as_ref().unwrap();
        assert!(!m.busy);
        assert_eq!(m.result, Some(Err("wrong admin PIN".into())));
    }

    fn test_key(id: &str, serial: &str, name: Option<&str>) -> Device {
        Device {
            id: id.into(),
            name: name.map(str::to_owned),
            vendor: "Yubico".into(),
            model: "YubiKey".into(),
            serial: serial.into(),
            transport: "USB".into(),
            firmware: String::new(),
            caps: Caps::default(),
            unverified: Caps::default(),
            kind: DeviceKind::Key,
            hid_path: None,
            reader: None,
            hid_serial: None,
            naming: keyroost_resolve::Naming::local(name),
        }
    }

    /// Issue #84: a FIDO2 card in a reader must take the in-place reset route,
    /// and nothing else may. The replug ceremony physically cannot complete
    /// for a card (nothing to unplug, no touch surface, and the arm's removal
    /// detector keys on a HID path the card does not have), so routing it
    /// there hangs the dialog forever — which is exactly what was reported.
    #[test]
    fn card_reset_route_is_reader_only_devices_exactly() {
        // A card: FIDO2 over a reader, no HID interface -> in-place route.
        let mut card = test_key("reader:acs", "T2CARD01", None);
        card.caps.insert(Caps::FIDO2);
        card.reader = Some("ACS ACR122U 00 00".into());
        assert_eq!(
            App::card_reset_reader(Some(&card)).as_deref(),
            Some("ACS ACR122U 00 00")
        );

        // A USB key that ALSO exposes a CCID reader keeps the replug ceremony:
        // it has a real replug, whose proof-of-possession must not be bypassed
        // just because a reader name is available.
        let mut usb_both = card.clone();
        usb_both.hid_path = Some(std::path::PathBuf::from("/dev/hidraw9"));
        assert_eq!(App::card_reset_reader(Some(&usb_both)), None);

        // A plain USB key: no reader, no route.
        let mut usb = test_key("serial:U", "USB01", None);
        usb.caps.insert(Caps::FIDO2);
        usb.hid_path = Some(std::path::PathBuf::from("/dev/hidraw9"));
        assert_eq!(App::card_reset_reader(Some(&usb)), None);

        // A card without the FIDO applet (OATH/PIV-only) has nothing to reset
        // over CTAP; the reader alone must not create the route.
        let mut no_fido = test_key("reader:x", "NOFIDO", None);
        no_fido.reader = Some("Some Reader 00 00".into());
        assert_eq!(App::card_reset_reader(Some(&no_fido)), None);

        // No selection at all.
        assert_eq!(App::card_reset_reader(None), None);
    }

    #[test]
    fn rename_pins_target_serial_independent_of_selection() {
        // Opening the rename field pins the device's serial and name-at-open,
        // so a later selection change (e.g. a background rescan of a flapping
        // reader) can't retarget the save.
        let mut app = App::default();
        let a = test_key("serial:A", "AAA", Some("old-a"));
        app.apply_rename_actions(&a, /*open*/ true, false, false);
        assert!(app.rename_target.is_some());
        let t = app.rename_target.clone().expect("target pinned on open");
        assert_eq!(t.serials, vec!["AAA".to_string()]);
        assert_eq!(t.name_at_open.as_deref(), Some("old-a"));

        // Selection moves to another key mid-edit — the pin is unchanged.
        app.devices = vec![test_key("serial:B", "BBB", Some("old-b"))];
        app.selected_device = Some("serial:B".into());
        let still = app.rename_target.clone().unwrap();
        assert_eq!(still.serials[0], "AAA", "pin must not follow the selection");

        // Cancel clears the pin and the field.
        app.apply_rename_actions(&a, false, /*cancel*/ true, false);
        assert!(app.rename_target.is_none());
    }

    #[test]
    fn rename_refuses_a_serial_less_device() {
        // A device with no serial can't be named — the field never opens and no
        // target is pinned.
        let mut app = App::default();
        let no_serial = test_key("winfido:x", "", None);
        app.apply_rename_actions(&no_serial, true, false, false);
        assert!(app.rename_target.is_none());
    }

    /// A FIDO2 key on USB with large-blob storage, named on the key as `on_key`
    /// says (`None`: storage, no name).
    fn key_with_storage(on_key: Option<&str>) -> Device {
        let mut d = test_key("serial:A", "AAA", on_key);
        d.caps.insert(Caps::FIDO2);
        d.hid_path = Some(std::path::PathBuf::from("/dev/hidraw9"));
        d.naming = match on_key {
            Some(n) => keyroost_resolve::Naming {
                plain: Some(n.into()),
                source: Some(keyroost_resolve::NameSource::Key),
                selectable: true,
                on_key: keyroost_resolve::KeyLabel::Present(n.into()),
                missing_on_key: None,
            },
            None => keyroost_resolve::Naming {
                on_key: keyroost_resolve::KeyLabel::Absent,
                ..Default::default()
            },
        };
        d
    }

    #[test]
    fn naming_dialog_offers_the_key_and_preselects_where_the_name_lives() {
        let mut app = App::default();
        app.apply_rename_actions(&key_with_storage(None), true, false, false);
        let t = app.rename_target.clone().unwrap();
        assert_eq!(
            t.choices,
            vec![
                device::NameStoreChoice::Computer,
                device::NameStoreChoice::Key
            ]
        );
        assert_eq!(t.store, device::NameStoreChoice::Computer);
        app.close_rename();
        app.apply_rename_actions(&key_with_storage(Some("Desk")), true, false, false);
        let t = app.rename_target.clone().unwrap();
        assert_eq!(t.store, device::NameStoreChoice::Key);
        assert_eq!(app.rename_input, "Desk");
        // Unchanged: nothing goes to the key, so no PIN field.
        assert!(!app.rename_goes_on_key());
        // A rename does; without an unlocked session it needs a typed PIN.
        app.rename_input = "Lab".into();
        assert!(app.rename_goes_on_key());
        assert!(app.rename_needs_pin());
    }

    #[test]
    fn a_changed_key_name_is_stale_not_a_retry() {
        use keyroost_ctap::device_label::LabelError;
        // A changed array can't succeed on retry from the same dialog.
        assert_eq!(
            key_name_failure(LabelError::Changed, 0),
            KeyNameFailure::Stale
        );
        assert!(!KEY_NAME_STALE.contains("Try again"));
        match key_name_failure(LabelError::NoPin, 0) {
            KeyNameFailure::Failed(m) => assert!(m.contains("Set a PIN"), "{m}"),
            other => panic!("{other:?}"),
        }
        assert_eq!(
            key_name_failure(LabelError::Unsupported, 0),
            KeyNameFailure::Failed(KEY_NAME_NO_STORAGE.into())
        );
    }

    #[test]
    fn write_back_offer_opens_the_key_field_or_hides_for_the_session() {
        let mut app = App::default();
        let mut d = key_with_storage(None);
        d.naming.missing_on_key = Some("Desk".into());
        assert_eq!(device::write_back_offer(&d, false), Some("Desk"));
        // No unlocked session: the field opens on the key with the name,
        // asking for the PIN; nothing is written yet.
        app.apply_write_back(&d, WriteBack::Write, "Desk");
        let t = app.rename_target.clone().expect("field open");
        assert_eq!(t.store, device::NameStoreChoice::Key);
        assert_eq!(app.rename_input, "Desk");
        assert!(app.rename_goes_on_key());
        assert!(app.rename_needs_pin());
        assert!(!t.saving);
        app.close_rename();
        // "Not now" hides the offer for this row only.
        app.apply_write_back(&d, WriteBack::Dismiss, "Desk");
        assert!(app.write_back_dismissed.contains(&d.id));
        assert_eq!(
            device::write_back_offer(&d, app.write_back_dismissed.contains(&d.id)),
            None
        );
    }

    #[test]
    fn naming_dialog_blocks_a_local_rename_of_a_name_on_the_key() {
        let mut app = App::default();
        app.apply_rename_actions(&key_with_storage(Some("Desk")), true, false, false);
        app.rename_target.as_mut().unwrap().store = device::NameStoreChoice::Computer;
        app.rename_input = "Lab".into();
        assert!(app.rename_blocked());
        app.save_device_name();
        let t = app.rename_target.clone().expect("field stays open");
        assert_eq!(t.error.as_deref(), Some(device::NAME_IS_ON_THE_KEY));
        // Clearing is allowed from either choice: it goes to the key.
        app.rename_input.clear();
        assert!(!app.rename_blocked());
        assert!(app.rename_goes_on_key());
    }

    #[test]
    fn naming_dialog_reports_a_certain_refusal_before_asking_for_the_pin() {
        // Removing the name stays clear of keys.json until the write, so
        // this never loads the real file.
        let mut app = App::default();
        app.apply_rename_actions(&key_with_storage(Some("Desk")), true, false, false);
        // No HID path at save time: the save can't work, which shows
        // without a PIN typed (the PIN is asked for only after planning).
        app.rename_target.as_mut().unwrap().hid_path = None;
        app.rename_input.clear();
        assert!(app.rename_needs_pin());
        app.save_device_name();
        assert!(app.rename_target.as_ref().unwrap().confirm.is_some());
        app.apply_rename_question(true, false);
        let t = app.rename_target.clone().expect("field stays open");
        assert_eq!(t.error.as_deref(), Some(KEY_NAME_NO_STORAGE));
        assert!(!t.saving);
    }

    #[test]
    fn naming_dialog_asks_before_removing_the_name_on_the_key_and_wipes_the_pin() {
        let mut app = App::default();
        let mut d = key_with_storage(Some("Desk"));
        // No HID path at save time: the write is refused without any I/O.
        app.apply_rename_actions(&d, true, false, false);
        app.rename_target.as_mut().unwrap().hid_path = None;
        app.rename_input.clear();
        app.rename_pin = "1234".into();
        app.save_device_name();
        let t = app.rename_target.clone().unwrap();
        assert_eq!(
            t.confirm,
            Some((
                "Remove the name \"Desk\" stored on the key?".to_string(),
                None
            ))
        );
        assert_eq!(app.rename_pin, "1234", "kept until the answer");
        // Cancel the question: nothing happens, the field stays open.
        app.apply_rename_question(false, true);
        assert!(app.rename_target.as_ref().unwrap().confirm.is_none());
        // Ask again and confirm: the PIN is taken (and wiped) at once.
        app.save_device_name();
        app.apply_rename_question(true, false);
        assert!(app.rename_pin.is_empty());
        let t = app.rename_target.clone().unwrap();
        assert_eq!(t.error.as_deref(), Some(KEY_NAME_NO_STORAGE));
        // Closing wipes a typed PIN too.
        app.rename_pin = "1234".into();
        app.close_rename();
        assert!(app.rename_pin.is_empty());
        d.naming.on_key = keyroost_resolve::KeyLabel::Unsupported;
        app.apply_rename_actions(&d, true, false, false);
        let t = app.rename_target.clone().unwrap();
        assert!(t.lacks_storage);
        assert_eq!(t.choices, vec![device::NameStoreChoice::Computer]);
    }

    /// The OpenPGP mismatch guard is inert (the PIN forms have no confirm field),
    /// so it returns `None` for every flow — locks in the documented behaviour.
    #[test]
    fn openpgp_cred_mismatch_never_fires() {
        use OpenPgpCredKind::*;
        let pgp = OpenPgpState {
            user_pin_new: "111111".into(),
            admin_pin_new: "22222222".into(),
            ..Default::default()
        };
        for k in [
            ChangeUserPin,
            ChangeAdminPin,
            UnblockUserPin,
            SetName,
            SetUrl,
            GenerateKey,
            GenerateImportKey,
            ImportKeyFile,
            Reset,
        ] {
            assert!(openpgp_cred_mismatch(&pgp, k).is_none());
        }
    }

    /// The shared device-binding guard: a completion or modal submission may
    /// act only when the device captured at dispatch/open time still equals
    /// the current selection.
    #[test]
    fn completion_guard_requires_matching_selection() {
        let a: DeviceId = "serial:AAA".into();
        let b: DeviceId = "serial:BBB".into();
        assert!(completion_still_valid(Some(&a), Some(&a)));
        assert!(!completion_still_valid(Some(&a), Some(&b)));
    }

    /// `None` on either side fails closed: an unbound completion must never
    /// act on whatever happens to be selected, and a captured target must
    /// never fire with nothing selected.
    #[test]
    fn completion_guard_fails_closed_without_capture_or_selection() {
        let a: DeviceId = "serial:AAA".into();
        assert!(!completion_still_valid(None, Some(&a)));
        assert!(!completion_still_valid(Some(&a), None));
        assert!(!completion_still_valid(None, None));
    }

    /// KEY-004: the stored Molto2 session is bound to the device it was
    /// opened for; once the selection moves, no mutating op may take it.
    #[test]
    fn molto_session_stays_bound_to_the_device_it_opened_for() {
        let mut app = App {
            selected_device: Some("serial:AAA".into()),
            molto_session_device: Some("serial:AAA".into()),
            ..Default::default()
        };
        assert!(app.molto_session_usable());

        // The user switches selection: the binding no longer matches…
        app.selected_device = Some("serial:BBB".into());
        assert!(!app.molto_session_usable());
        // …and take_molto_session refuses, dropping the stale binding.
        assert!(app.take_molto_session().is_none());
        assert!(app.molto_session_device.is_none());
    }

    /// A selection change always severs the Molto session binding, so a
    /// handed-back session from an in-flight job can never be used later.
    #[test]
    fn selection_change_clears_the_molto_session_binding() {
        let mut app = App {
            molto_session_device: Some("serial:AAA".into()),
            ..Default::default()
        };
        app.on_device_selected(None);
        assert!(app.molto_session_device.is_none());
    }

    /// KEY-007: Apply on the advanced dialog is rejected (and the dialog
    /// dropped, wiping its PIN via the Drop impl) once the selection has
    /// moved from the device the dialog opened for.
    #[test]
    fn advanced_dialog_apply_rejected_after_selection_change() {
        let mut app = App {
            selected_device: Some("serial:AAA".into()),
            ..Default::default()
        };
        app.security_keys.advanced = Some(AdvancedDialog {
            action: AdvancedAction::ForcePinChange,
            pin_input: "123456".into(),
            min_pin_input: String::new(),
            force_change: false,
            device: Some("serial:AAA".into()),
        });
        app.selected_device = Some("serial:BBB".into());
        app.run_advanced_action();
        assert!(
            app.security_keys.advanced.is_none(),
            "a stale dialog must be dropped, not dispatched"
        );
        assert!(app.security_keys.error.is_some(), "the refusal is surfaced");
    }

    /// Selecting another device closes (and thereby zeroizes) the dialog.
    #[test]
    fn selection_change_clears_the_advanced_dialog() {
        let mut app = App::default();
        app.security_keys.advanced = Some(AdvancedDialog {
            action: AdvancedAction::SetMinPin,
            pin_input: "123456".into(),
            min_pin_input: "6".into(),
            force_change: false,
            device: Some("serial:AAA".into()),
        });
        app.on_device_selected(None);
        assert!(app.security_keys.advanced.is_none());
    }

    /// KEY-012: a selection change severs the FIDO session binding and every
    /// piece of pending fingerprint state, and signals cancel to a live
    /// enroll worker.
    #[test]
    fn selection_change_clears_fido_session_binding_and_fingerprint_state() {
        let mut app = App::default();
        app.security_keys.session_device = Some("serial:AAA".into());
        app.security_keys.fingerprints = Some(Vec::new());
        app.security_keys.fp_new_name = "index".into();
        app.security_keys.fp_confirm_delete = Some(vec![1, 2]);
        app.security_keys.fp_rename = Some((vec![1, 2], "thumb".into()));
        let progress = std::sync::Arc::new(std::sync::Mutex::new(EnrollProgress::default()));
        let cancel = progress.lock().unwrap().cancel.clone();
        app.security_keys.fp_progress = Some(progress);

        app.on_device_selected(None);

        assert!(app.security_keys.session_device.is_none());
        assert!(app.security_keys.fingerprints.is_none());
        assert!(app.security_keys.fp_new_name.is_empty());
        assert!(app.security_keys.fp_confirm_delete.is_none());
        assert!(app.security_keys.fp_rename.is_none());
        assert!(app.security_keys.fp_progress.is_none());
        assert!(
            cancel.load(std::sync::atomic::Ordering::Relaxed),
            "an in-flight enroll must be told to cancel"
        );
    }

    /// The HOTP-read regression: a successful listing consumes the typed
    /// password but retains the accepted copy, so a later on-demand HOTP
    /// read can still unlock the protected applet.
    #[test]
    fn oath_listing_retains_the_accepted_password_for_on_demand_reads() {
        let mut app = App::default();
        app.oath.password_input = "hunter2".into();
        let password = oath_effective_password(&app.oath);
        assert_eq!(&*password, "hunter2", "typed entry wins while present");

        App::apply_oath_rows(&mut app, Ok((Vec::new(), 0)), password);
        assert!(
            app.oath.password_input.is_empty(),
            "typed entry is consumed"
        );
        assert_eq!(
            app.oath.unlocked_password.as_deref().map(String::as_str),
            Some("hunter2"),
            "the accepted password is retained for on-demand reads"
        );
        // …which is exactly what read_hotp_code will now pick up:
        assert_eq!(&*oath_effective_password(&app.oath), "hunter2");
    }

    /// A rejected password is never retained (and re-locks the pane).
    #[test]
    fn oath_rejected_password_is_not_retained() {
        let mut app = App::default();
        app.oath.unlocked_password = Some(zeroize::Zeroizing::new("stale".into()));
        App::apply_oath_rows(
            &mut app,
            Err(TransportError::OathPasswordRejected),
            zeroize::Zeroizing::new("wrong".into()),
        );
        assert!(app.oath.unlocked_password.is_none());
        assert!(app.oath.locked);
    }

    /// KEY-008 / KEY-013: destructive confirmations (OATH delete, OpenPGP
    /// reset modal, FIDO reset dialog) are dropped the moment the selection
    /// changes — a confirmation opened for one key must never render over,
    /// or dispatch against, another.
    #[test]
    fn selection_change_clears_destructive_confirmations() {
        let mut app = App::default();
        app.oath.confirm_delete = Some(("serial:AAA".into(), "acct".into()));
        app.openpgp.cred_modal = Some(OpenPgpCredModal::new(
            OpenPgpCredKind::Reset,
            Some("serial:AAA".into()),
        ));
        app.security_keys.reset.open = true;

        app.on_device_selected(None);

        assert!(app.oath.confirm_delete.is_none());
        assert!(app.openpgp.cred_modal.is_none());
        assert!(!app.security_keys.reset.open);
    }

    /// The OATH delete confirmation is only armed with a concrete device
    /// captured; the guard then rejects a mismatch at confirm time.
    #[test]
    fn oath_delete_confirmation_is_device_bound() {
        let captured: DeviceId = "serial:AAA".into();
        let other: DeviceId = "serial:BBB".into();
        assert!(completion_still_valid(Some(&captured), Some(&captured)));
        assert!(!completion_still_valid(Some(&captured), Some(&other)));
    }

    /// KEY-005, the audited failure: the armed key exposes no serial of any
    /// kind and a same-VID/PID key appears on a fresh path. It must NOT be
    /// accepted — being the first same-model key to show up is not identity.
    #[test]
    fn reset_rearm_never_accepts_a_serial_less_same_model_key() {
        assert!(!reset_reinsert_matches(
            None,
            None,
            Some((0x1050, 0x0407)),
            None,
            None,
            (0x1050, 0x0407),
        ));
    }

    /// Only a matching *stable* identity re-arms the reset: the HID serial
    /// when both sides have one, else the resolver's effective (CCID) serial.
    /// An unreadable candidate identity fails closed (the poll retries).
    #[test]
    fn reset_rearm_matches_only_the_same_stable_identity() {
        let ids = Some((0x1050, 0x0407));
        // Effective (CCID-read) serial decides when there is no HID serial.
        assert!(reset_reinsert_matches(
            None,
            Some("15731286"),
            ids,
            None,
            Some("15731286"),
            (0x1050, 0x0407)
        ));
        assert!(!reset_reinsert_matches(
            None,
            Some("15731286"),
            ids,
            None,
            Some("9990001"),
            (0x1050, 0x0407)
        ));
        // Candidate identity not readable (yet): fail closed, retry later.
        assert!(!reset_reinsert_matches(
            None,
            Some("15731286"),
            ids,
            None,
            None,
            (0x1050, 0x0407)
        ));
        // HID serial decides when both sides expose one.
        assert!(reset_reinsert_matches(
            Some("S1"),
            None,
            ids,
            Some("S1"),
            None,
            (0x1050, 0x0407)
        ));
        assert!(!reset_reinsert_matches(
            Some("S1"),
            None,
            ids,
            Some("S2"),
            None,
            (0x1050, 0x0407)
        ));
        // A different model never matches, whatever the serials say.
        assert!(!reset_reinsert_matches(
            None,
            Some("15731286"),
            ids,
            None,
            Some("15731286"),
            (0x20a0, 0x42b2)
        ));
    }

    /// The bug this guards against: the kernel reuses a freed hidraw minor
    /// number, so a replug can hand the reinserted key the exact same
    /// `/dev/hidrawN` path the unplugged one had, while its USB device number
    /// (bus/address) has moved on. Reproduced on hardware: `hidraw0` before
    /// and after, `usb 1-3: ... device number 8` then `device number 9`. A
    /// path-only diff would call this candidate "not fresh" and the armed
    /// reset would never fire — the GUI hangs on the touch prompt forever.
    #[test]
    fn same_hid_connection_tells_a_recycled_path_apart_from_the_old_device() {
        let before = HidIdentity {
            path: "/dev/hidraw0".into(),
            usb_bus: Some(1),
            usb_address: Some(8),
        };
        let after_replug = HidIdentity {
            path: "/dev/hidraw0".into(), // recycled by the kernel
            usb_bus: Some(1),
            usb_address: Some(9), // advanced: a genuinely new attach
        };
        assert!(
            !same_hid_connection(&before, &after_replug),
            "same path, different device number: must count as a fresh connection"
        );
    }

    /// A device that never left keeps its bus/address, even if some unrelated
    /// churn elsewhere reshuffled other devices' hidraw paths.
    #[test]
    fn same_hid_connection_recognises_a_device_that_never_left() {
        let seen_before = HidIdentity {
            path: "/dev/hidraw1".into(),
            usb_bus: Some(1),
            usb_address: Some(4),
        };
        let seen_again = HidIdentity {
            path: "/dev/hidraw1".into(),
            usb_bus: Some(1),
            usb_address: Some(4),
        };
        assert!(same_hid_connection(&seen_before, &seen_again));
    }

    /// Without USB topology (the hidapi backend on macOS/Windows exposes
    /// none), identity falls back to the path — the pre-fix behaviour, kept
    /// as the best available signal on those platforms.
    #[test]
    fn same_hid_connection_falls_back_to_path_without_usb_topology() {
        let a = HidIdentity {
            path: "/dev/hidraw0".into(),
            usb_bus: None,
            usb_address: None,
        };
        let b = HidIdentity {
            path: "/dev/hidraw0".into(),
            usb_bus: None,
            usb_address: None,
        };
        let c = HidIdentity {
            path: "/dev/hidraw1".into(),
            usb_bus: None,
            usb_address: None,
        };
        assert!(same_hid_connection(&a, &b));
        assert!(!same_hid_connection(&a, &c));
    }
}

/// Randomized coverage (proptest, dev-only) on top of the example-based tests
/// above, for the pure device-binding guards the audit called out: these are
/// the GUI's fail-closed decisions and live in a binary crate the libfuzzer
/// workspace cannot reach.
#[cfg(test)]
mod prop_tests {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        /// A completion may act only when both the captured and the current
        /// selection exist — `None` on either side always fails closed.
        #[test]
        fn completion_fails_closed_on_any_unbound_side(id in proptest::option::of(".*")) {
            prop_assert!(!completion_still_valid(None, id.as_ref()));
            prop_assert!(!completion_still_valid(id.as_ref(), None));
        }

        /// With both sides bound, the completion acts iff the ids are equal.
        #[test]
        fn completion_requires_exact_id_match(a in ".*", b in ".*") {
            prop_assert_eq!(completion_still_valid(Some(&a), Some(&b)), a == b);
            prop_assert!(completion_still_valid(Some(&a), Some(&a)));
        }

        /// KEY-005: a candidate with no stable identity (no HID serial, no
        /// effective serial) is NEVER accepted for an armed reset, whatever
        /// the armed target looks like — first-same-model-to-appear is not
        /// an identity.
        #[test]
        fn reset_never_accepts_a_serial_less_candidate(
            t_hid in proptest::option::of("[ -~]{0,12}"),
            t_eff in proptest::option::of("[ -~]{0,12}"),
            t_ids in proptest::option::of(any::<(u16, u16)>()),
            cand_ids in any::<(u16, u16)>(),
        ) {
            prop_assert!(!reset_reinsert_matches(
                t_hid.as_deref(),
                t_eff.as_deref(),
                t_ids,
                None,
                None,
                cand_ids,
            ));
        }

        /// A vendor/product-id mismatch rejects the candidate no matter how
        /// well the serials agree.
        #[test]
        fn reset_rejects_model_mismatch_regardless_of_serials(
            serial in "[ -~]{0,12}",
            t_ids in any::<(u16, u16)>(),
            cand_ids in any::<(u16, u16)>(),
        ) {
            prop_assume!(t_ids != cand_ids);
            prop_assert!(!reset_reinsert_matches(
                Some(&serial),
                Some(&serial),
                Some(t_ids),
                Some(&serial),
                Some(&serial),
                cand_ids,
            ));
        }

        /// Acceptance requires a *stable* identity match: when both sides
        /// expose a HID serial that comparison decides alone (the effective
        /// serial can't override it); otherwise both effective serials must
        /// exist and match. Any accepted candidate therefore matched on one
        /// of the two.
        #[test]
        fn reset_accepts_only_on_a_stable_serial_match(
            t_hid in proptest::option::of("[ -~]{0,4}"),
            t_eff in proptest::option::of("[ -~]{0,4}"),
            c_hid in proptest::option::of("[ -~]{0,4}"),
            c_eff in proptest::option::of("[ -~]{0,4}"),
            ids in any::<(u16, u16)>(),
        ) {
            let accepted = reset_reinsert_matches(
                t_hid.as_deref(),
                t_eff.as_deref(),
                Some(ids),
                c_hid.as_deref(),
                c_eff.as_deref(),
                ids,
            );
            let expected = match (&t_hid, &c_hid) {
                (Some(t), Some(c)) => t == c,
                _ => matches!((&t_eff, &c_eff), (Some(t), Some(c)) if t == c),
            };
            prop_assert_eq!(accepted, expected);
        }

        /// The duplicate-serial advisory fires iff some serial repeats, and
        /// names a serial that really is duplicated.
        #[test]
        fn duplicate_note_iff_some_serial_repeats(
            serials in proptest::collection::vec("[A-Z0-9]{0,4}", 0..8),
        ) {
            let note = duplicate_serial_note(serials.iter().map(|s| s.as_str()));
            let mut counts = std::collections::BTreeMap::<&str, usize>::new();
            for s in &serials {
                *counts.entry(s).or_insert(0) += 1;
            }
            let dup = counts.iter().find(|&(_, &n)| n > 1).map(|(s, _)| *s);
            match (note, dup) {
                (None, None) => {}
                (Some(note), Some(serial)) => prop_assert!(
                    note.contains(serial),
                    "advisory must name a duplicated serial: {note:?}"
                ),
                (note, dup) => prop_assert!(
                    false,
                    "advisory presence must track duplication: note={note:?} dup={dup:?}"
                ),
            }
        }
    }
}

#[cfg(test)]
mod piv_relax_tests {
    use super::*;
    use keyroost_piv::compat::{FeatureGate, MgmtAlgChoice, PivExtension};

    #[test]
    fn relax_turns_unsupported_into_unverified_except_reset() {
        let u = FeatureGate::Unsupported;
        assert_eq!(piv_relax(PivExtension::MoveKey, u), FeatureGate::Unverified);
        assert_eq!(piv_relax(PivExtension::Reset, u), FeatureGate::Unsupported);
        assert_eq!(
            piv_relax(PivExtension::GetMetadata, u),
            FeatureGate::Unsupported
        );
        assert_eq!(piv_relax(PivExtension::Attest, u), FeatureGate::Unsupported);
        assert_eq!(
            piv_relax(PivExtension::GetSlotKeyStatus, u),
            FeatureGate::Unsupported
        );
        assert_eq!(
            piv_relax(PivExtension::ResetGlobal, u),
            FeatureGate::Unsupported
        );
        assert_eq!(
            piv_relax(
                PivExtension::ManagementKeyAlgorithm(MgmtAlgChoice::Delete),
                u
            ),
            FeatureGate::Unsupported
        );
        assert_eq!(
            piv_relax(PivExtension::MoveKey, FeatureGate::Supported),
            FeatureGate::Supported
        );
    }
}

#[cfg(test)]
mod key_usage_tests {
    use super::*;
    use keyroost_piv::x509::{KeyUsage as K, KeyUsageExt};

    fn ext(usages: K, critical: bool) -> KeyUsageExt {
        KeyUsageExt { usages, critical }
    }

    #[test]
    fn enciphering_only_bits_pull_in_key_agreement_and_exclude_each_other() {
        let ku = toggle_key_usage(K::EMPTY, K::ENCIPHER_ONLY, true);
        assert!(ku.contains(K::KEY_AGREEMENT) && ku.contains(K::ENCIPHER_ONLY));
        let ku = toggle_key_usage(ku, K::DECIPHER_ONLY, true);
        assert!(ku.contains(K::DECIPHER_ONLY) && !ku.contains(K::ENCIPHER_ONLY));
        let ku = toggle_key_usage(ku, K::KEY_AGREEMENT, false);
        assert!(ku.is_empty());
    }

    #[test]
    fn summary_marks_critical_and_slot_default() {
        let d = ext(K::DIGITAL_SIGNATURE, true);
        assert_eq!(
            key_usage_summary(ext(K::EMPTY, false), d, false),
            "Undefined"
        );
        // A default degraded to undefined (Ed25519 in 9D) keeps its name.
        let none = ext(K::EMPTY, false);
        assert_eq!(
            key_usage_summary(none, none, true),
            "Slot default (undefined)"
        );
        assert_eq!(
            key_usage_summary(d, d, false),
            "Slot default (Digital signature, critical)"
        );
        // Same usages but not critical is not the slot default.
        assert_eq!(
            key_usage_summary(ext(K::DIGITAL_SIGNATURE, false), d, false),
            "Digital signature"
        );
        assert_eq!(
            key_usage_summary(ext(K::DIGITAL_SIGNATURE, true), ext(K::EMPTY, false), false),
            "Digital signature, critical"
        );
    }

    #[test]
    fn remembered_usage_follows_the_key_algorithm() {
        use keyroost_piv::{KeyAlg, Slot};
        let km = Slot::KeyManagement;
        // A hand-picked set containing keyEncipherment swaps to keyAgreement
        // on an ECC key, keeping the rest (and critical), and back again.
        let picked = ext(
            K::KEY_ENCIPHERMENT
                .union(K::DIGITAL_SIGNATURE)
                .union(K::DATA_ENCIPHERMENT),
            false,
        );
        let ecc = reconcile_key_usage(km, picked, Some(KeyAlg::Rsa2048), KeyAlg::EccP256);
        assert_eq!(
            ecc,
            ext(K::KEY_AGREEMENT.union(K::DIGITAL_SIGNATURE), false)
        );
        let rsa = reconcile_key_usage(km, ecc, Some(KeyAlg::EccP256), KeyAlg::Rsa2048);
        assert_eq!(
            rsa,
            ext(K::KEY_ENCIPHERMENT.union(K::DIGITAL_SIGNATURE), false)
        );
        let crit = reconcile_key_usage(
            km,
            ext(K::KEY_ENCIPHERMENT.union(K::DIGITAL_SIGNATURE), true),
            Some(KeyAlg::Rsa2048),
            KeyAlg::EccP256,
        );
        assert!(crit.critical);
        // The plain slot default (critical included) follows the new
        // algorithm's default.
        assert_eq!(
            reconcile_key_usage(
                km,
                ext(K::KEY_ENCIPHERMENT, true),
                Some(KeyAlg::Rsa2048),
                KeyAlg::EccP256
            ),
            ext(K::KEY_AGREEMENT, true)
        );
        // An explicit Undefined survives a known-algorithm change.
        assert_eq!(
            reconcile_key_usage(
                Slot::Authentication,
                ext(K::EMPTY, false),
                Some(KeyAlg::Rsa2048),
                KeyAlg::EccP256
            ),
            ext(K::EMPTY, false)
        );
    }
}