runner-manager 0.4.7

Local-first autoscaling manager for ephemeral GitHub Actions self-hosted runners, with a CLI and a Ratatui TUI.
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
// owner: g1-tui-shell-input

//! Terminal ownership, merged input, focus, and the TUI reducer.
//! Rendering accepts only immutable [`PresentationState`], so a frame has no
//! filesystem, store, or network capability.

use std::collections::{HashMap, HashSet};
use std::io::{self, IsTerminal, Write};
use std::str::FromStr;
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use std::time::{Duration, Instant};

use crossterm::event::{
    DisableBracketedPaste, DisableFocusChange, DisableMouseCapture, EnableBracketedPaste,
    EnableFocusChange, EnableMouseCapture, Event, EventStream, KeyCode, KeyEvent, KeyEventKind,
    KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
};
use crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use crossterm::{Command, execute};
use futures::{Stream, StreamExt};
use ratatui::Frame;
use ratatui::backend::Backend;
use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span, Text};
use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap};
use tokio::sync::mpsc;

use runner_manager_domain::attempt::{AttemptOutcome, AttemptState, FailureReason, RunnerAttempt};
use runner_manager_domain::model::{Org, OwnerRepo, ScaleTarget, StartMode};
use runner_manager_domain::store::Store as _;
use runner_manager_github::rest::{
    ActivityScope, CancelToken, InventoryError, InventoryGateway, RefreshState, RestInventory,
};
use runner_manager_github::{AuthenticatedClient, UserAccessToken};

use super::screens::{
    self, AgentHealth, Availability, DashboardMetrics, PolicyMode, ReadOnlyScreen, RepositoryRow,
    RunnerOwnership, RunnerRow, ScreenAction, ScreenModel, Snapshot,
};
use super::settings::{self, SettingsCommand, SettingsUi, SettingsView};
use super::table::Skin;

#[cfg(test)]
pub const FRAME_BUDGET: Duration = Duration::from_millis(16);
pub const TICK_RATE: Duration = Duration::from_millis(250);
const LOCAL_AGENT_POLL_RATE: Duration = Duration::from_secs(60);
const MAX_ACTIVITY_HISTORY: usize = 256;
const REDACTED: &str = "[REDACTED]";

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Screen {
    Dashboard,
    Repositories,
    Runners,
    RepositorySettings,
    HostSettings,
    Activity,
}

fn contains(area: Rect, column: u16, row: u16) -> bool {
    column >= area.x && column < area.right() && row >= area.y && row < area.bottom()
}

const DASHBOARD_PRIVACY_WARNING_HEIGHT: u16 = 5;

fn dashboard_privacy_warning_area(size: Rect) -> Rect {
    let content = Rect::new(
        size.x,
        size.y.saturating_add(2),
        size.width,
        size.height.saturating_sub(3),
    );
    Rect {
        height: content.height.min(DASHBOARD_PRIVACY_WARNING_HEIGHT),
        ..content
    }
}

impl Screen {
    pub const ALL: [Self; 6] = [
        Self::Dashboard,
        Self::Repositories,
        Self::Runners,
        Self::RepositorySettings,
        Self::HostSettings,
        Self::Activity,
    ];

    pub const fn title(self) -> &'static str {
        match self {
            Self::Dashboard => "Dashboard",
            Self::Repositories => "Repositories",
            Self::Runners => "Runners",
            Self::RepositorySettings => "Repository settings",
            Self::HostSettings => "Host settings",
            Self::Activity => "Activity & errors",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Focus {
    Navigation,
    Content,
    Status,
}

impl Focus {
    fn next(self, backwards: bool) -> Self {
        match (self, backwards) {
            (Self::Navigation, false) | (Self::Status, true) => Self::Content,
            (Self::Content, false) | (Self::Navigation, true) => Self::Status,
            (Self::Status, false) | (Self::Content, true) => Self::Navigation,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(
    dead_code,
    reason = "g2 presentation states construct every health value"
)]
pub enum Health {
    Ready,
    Busy,
    Offline,
    Error,
}

impl Health {
    fn presentation(self) -> (&'static str, &'static str, Color) {
        match self {
            Self::Ready => ("OK", "Ready", Color::Green),
            Self::Busy => ("*", "Busy", Color::Yellow),
            Self::Offline => ("!", "Offline - no new runners will start", Color::Gray),
            Self::Error => ("X", "Error - open Activity for remediation", Color::Red),
        }
    }
}

/// Immutable, already-collected values a frame may display. The two sensitive
/// fields are never rendered; they drive unconditional boundary redaction.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PresentationState {
    pub heading: String,
    pub body: Vec<String>,
    pub diagnostics: Vec<String>,
    pub health: Health,
    pub privacy_access_denied: bool,
    /// Version reported by the binary registered for the local service.
    pub service_version: Option<String>,
    pub access_token: Option<String>,
    pub jit_configuration: Option<String>,
}

impl Default for PresentationState {
    fn default() -> Self {
        Self {
            heading: "Local runner manager".to_owned(),
            body: vec!["Waiting for the first local status snapshot...".to_owned()],
            diagnostics: vec!["No activity recorded.".to_owned()],
            health: Health::Ready,
            privacy_access_denied: false,
            service_version: None,
            access_token: None,
            jit_configuration: None,
        }
    }
}

impl PresentationState {
    fn redact(&self, value: &str) -> String {
        let mut safe = value.to_owned();
        for secret in [
            self.access_token.as_deref(),
            self.jit_configuration.as_deref(),
        ]
        .into_iter()
        .flatten()
        .filter(|secret| !secret.is_empty())
        {
            safe = safe.replace(secret, REDACTED);
        }
        safe
    }

    fn copy_text(&self) -> String {
        self.diagnostics
            .iter()
            .map(|line| self.redact(line))
            .collect::<Vec<_>>()
            .join("\n")
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgentEvent {
    pub summary: String,
    pub health: Health,
    /// The daemon's durable root-refusal record says macOS denied Full Disk
    /// Access to a boot service on a privacy-gated volume.
    pub privacy_access_denied: bool,
    /// The registered service binary's own `--version` result. Older or
    /// unreadable installations intentionally report `None`.
    pub service_version: Option<String>,
    /// A fully collected GitHub inventory snapshot when the embedding agent
    /// has one. The standalone local journal reader supplies `None`; it never
    /// invents GitHub workload counts from local attempt counts.
    pub snapshot: Option<Snapshot>,
}

/// Polls the durable lifecycle/status view written by the already-running
/// daemon. This is deliberately a local journal reader, not an IPC listener:
/// the product exposes no inbound control surface and `q` owns only this
/// reader thread.
struct LocalAgentEventSource {
    control: Arc<(Mutex<SourceState>, Condvar)>,
    worker: Option<thread::JoinHandle<()>>,
}

struct SourceState {
    stopped: bool,
    refresh_pending: bool,
    next_generation: u64,
    active: Option<(u64, CancelToken)>,
}

impl LocalAgentEventSource {
    fn start(
        context: Arc<crate::cli::Context>,
        poll_rate: Duration,
    ) -> io::Result<(Self, mpsc::UnboundedReceiver<AgentEvent>)> {
        Self::start_with(move |cancel| local_agent_event(&context, cancel), poll_rate)
    }

    fn start_with(
        produce: impl Fn(&CancelToken) -> AgentEvent + Send + 'static,
        poll_rate: Duration,
    ) -> io::Result<(Self, mpsc::UnboundedReceiver<AgentEvent>)> {
        let (events, receiver) = mpsc::unbounded_channel();
        let control = Arc::new((
            Mutex::new(SourceState {
                stopped: false,
                refresh_pending: true,
                next_generation: 1,
                active: None,
            }),
            Condvar::new(),
        ));
        let worker_control = Arc::clone(&control);
        let worker = thread::Builder::new()
            .name("runner-manager-tui-events".to_owned())
            .spawn(move || {
                loop {
                    let (state_lock, wake) = &*worker_control;
                    let mut state = state_lock.lock().unwrap();
                    while !state.stopped && !state.refresh_pending {
                        let (next, timeout) = wake.wait_timeout(state, poll_rate).unwrap();
                        state = next;
                        if timeout.timed_out() {
                            state.refresh_pending = true;
                        }
                    }
                    if state.stopped {
                        break;
                    }
                    // A pending refresh is a bit, not a counter. Any number of
                    // F5 presses while this collection is active can request
                    // exactly one latest follow-up and nothing more.
                    state.refresh_pending = false;
                    let generation = state.next_generation;
                    state.next_generation = state.next_generation.saturating_add(1);
                    let cancel = CancelToken::new();
                    // Publication happens while holding the same lock used by
                    // refresh and stop, so neither can slip through before an
                    // active token exists to cancel.
                    state.active = Some((generation, cancel.clone()));
                    drop(state);

                    let event = produce(&cancel);
                    let mut state = state_lock.lock().unwrap();
                    let publish =
                        !state.stopped && !state.refresh_pending && !cancel.is_cancelled();
                    if state
                        .active
                        .as_ref()
                        .is_some_and(|(active_generation, _)| *active_generation == generation)
                    {
                        state.active = None;
                    }
                    if state.stopped {
                        break;
                    }
                    // Keep the control lock through the non-blocking publish.
                    // This linearizes a refresh request either before publish
                    // (and suppresses this result) or after it; there is no
                    // unlocked stale-send window between the generation check
                    // and delivery.
                    if publish && events.send(event).is_err() {
                        break;
                    }
                }
            })?;
        Ok((
            Self {
                control,
                worker: Some(worker),
            },
            receiver,
        ))
    }

    fn request_refresh(&self) -> io::Result<()> {
        let (state_lock, wake) = &*self.control;
        let mut state = state_lock.lock().unwrap();
        if state.stopped {
            return Err(io::Error::other("the TUI snapshot source stopped"));
        }
        state.refresh_pending = true;
        if let Some((_, cancel)) = &state.active {
            cancel.cancel();
        }
        wake.notify_one();
        Ok(())
    }
}

impl Drop for LocalAgentEventSource {
    fn drop(&mut self) {
        let (state_lock, wake) = &*self.control;
        {
            let mut state = state_lock.lock().unwrap();
            state.stopped = true;
            if let Some((_, cancel)) = &state.active {
                cancel.cancel();
            }
            wake.notify_one();
        }
        if let Some(worker) = self.worker.take() {
            let _ = worker.join();
        }
    }
}

pub trait RefreshRequester {
    fn request_refresh(&self) -> io::Result<()>;
}

impl RefreshRequester for LocalAgentEventSource {
    fn request_refresh(&self) -> io::Result<()> {
        LocalAgentEventSource::request_refresh(self)
    }
}

#[allow(dead_code, reason = "used by the injected-agent embedding seam")]
struct NoopRefreshRequester;
impl RefreshRequester for NoopRefreshRequester {
    fn request_refresh(&self) -> io::Result<()> {
        Ok(())
    }
}

fn local_agent_event(context: &crate::cli::Context, cancel: &CancelToken) -> AgentEvent {
    let runtime = match tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
    {
        Ok(runtime) => runtime,
        Err(error) => {
            return AgentEvent {
                summary: format!("GitHub inventory runtime could not start: {error}"),
                health: Health::Error,
                privacy_access_denied: false,
                service_version: None,
                snapshot: None,
            };
        }
    };
    runtime.block_on(production_agent_event(context, cancel))
}

async fn production_agent_event(context: &crate::cli::Context, cancel: &CancelToken) -> AgentEvent {
    match crate::cli::status::snapshot(context) {
        Ok(local) => {
            let privacy_access_denied =
                match runner_manager_platform::service::runner_root_refusals(context.paths()) {
                    Ok(refusals) => refusals
                        .iter()
                        .any(|refusal| refusal.kind == "denied_by_privacy_policy"),
                    Err(error) => {
                        return AgentEvent {
                            summary: format!(
                                "Local runner-root refusal record could not be read: {error}"
                            ),
                            health: Health::Error,
                            privacy_access_denied: false,
                            service_version: local.product.service_binary_version.clone(),
                            snapshot: None,
                        };
                    }
                };
            let summary = format!(
                "Local agent journal: {} active runner attempt(s), {} configured policy/policies.",
                local.host.in_use,
                local.policies.len()
            );
            match production_screen_snapshot(context, &local, cancel).await {
                Ok(snapshot) => AgentEvent {
                    health: if snapshot.metrics.busy_runners > 0 {
                        Health::Busy
                    } else {
                        Health::Ready
                    },
                    summary,
                    privacy_access_denied,
                    service_version: local.product.service_binary_version.clone(),
                    snapshot: Some(snapshot),
                },
                Err((availability, detail)) => AgentEvent {
                    summary: format!("{summary} GitHub inventory refresh failed: {detail}"),
                    health: Health::Error,
                    privacy_access_denied,
                    service_version: local.product.service_binary_version.clone(),
                    snapshot: Some(Snapshot {
                        activity: production_activity(context)
                            .unwrap_or_default()
                            .into_iter()
                            .chain(std::iter::once(refresh_activity(
                                &availability,
                                &detail,
                                context.clock().now(),
                            )))
                            .collect(),
                        availability,
                        ..Snapshot::default()
                    }),
                },
            }
        }
        Err(error) => AgentEvent {
            summary: format!("Local agent journal could not be read: {error}"),
            health: Health::Error,
            privacy_access_denied: false,
            service_version: None,
            snapshot: None,
        },
    }
}

async fn production_screen_snapshot(
    context: &crate::cli::Context,
    local: &crate::cli::status::StatusDocument,
    cancel: &CancelToken,
) -> Result<Snapshot, (Availability, String)> {
    let activity =
        production_activity(context).map_err(|detail| offline_failure(context, detail))?;
    let start_mode = StartMode::from_str(&local.host.service_start_mode).map_err(|error| {
        offline_failure(context, format!("invalid service start mode: {error}"))
    })?;
    let secrets = context
        .secret_store(start_mode)
        .map_err(|error| offline_failure(context, error.to_string()))?;
    let Some(secret) = secrets
        .load()
        .map_err(|error| offline_failure(context, error.to_string()))?
    else {
        return Err((
            Availability::Unauthorized,
            "no GitHub credential is stored; run `runner-manager auth login`".into(),
        ));
    };
    if local.policies.is_empty() {
        return Ok(Snapshot {
            availability: Availability::Ready,
            activity,
            ..Snapshot::default()
        });
    }

    let clock = context.clock();
    let client = Arc::new(
        AuthenticatedClient::new(
            context.endpoints().clone(),
            UserAccessToken::from_stored(secret),
            Arc::clone(&clock),
        )
        .map_err(|error| offline_failure(context, error.to_string()))?,
    );
    let inventory = RestInventory::new(Arc::clone(&client), Arc::clone(&clock));
    let reachable = if local
        .policies
        .iter()
        .any(|policy| policy.scope == "organization")
    {
        let app = context
            .app_registration()
            .map_err(|error| (Availability::Unauthorized, error.to_string()))?;
        Some(
            cancel
                .run(async {
                    client
                        .discover_installations(&app)
                        .await
                        .map_err(InventoryError::from)
                })
                .await
                .map_err(|error| inventory_failure(context, &clock, error))?,
        )
    } else {
        None
    };
    let reachable_repositories = reachable
        .as_ref()
        .and_then(|discovery| discovery.targets())
        .map_or_else(Vec::new, |targets| targets.repositories());

    let mut repositories = Vec::with_capacity(local.policies.len());
    let mut runners = Vec::new();
    let mut seen_runners = HashSet::new();
    let mut in_progress_workflows = 0_u32;
    let mut busy_runners = 0_u32;
    let mut assigned_jobs = 0_u32;
    let mut online_runners = 0_u32;

    for policy in &local.policies {
        let (target, scope) = if policy.scope == "repository" {
            let repository = OwnerRepo::from_str(&policy.target)
                .map_err(|error| offline_failure(context, error.to_string()))?;
            (
                ScaleTarget::Repository(repository.clone()),
                ActivityScope::repository(repository),
            )
        } else {
            let org = Org::from_str(&policy.target)
                .map_err(|error| offline_failure(context, error.to_string()))?;
            let repositories: Vec<_> = reachable_repositories
                .iter()
                .filter(|repository| repository.owner().eq_ignore_ascii_case(org.as_str()))
                .cloned()
                .collect();
            (
                ScaleTarget::Organization(org.clone()),
                ActivityScope::organization(org, repositories),
            )
        };
        let refreshed = inventory
            .snapshot(&scope, cancel)
            .await
            .map_err(|error| inventory_failure(context, &clock, error))?;
        let workflow_count = refreshed.activity.total();
        in_progress_workflows = in_progress_workflows.saturating_add(workflow_count);
        repositories.push(RepositoryRow {
            id: policy.id.clone(),
            target: policy.target.clone(),
            in_progress_workflows: workflow_count,
            mode: if policy.mode == "monitor_only" {
                PolicyMode::MonitorOnly
            } else {
                PolicyMode::Autoscale
            },
            max_capacity: policy.max_capacity,
            health: if policy.enabled && policy.state == "active" {
                AgentHealth::Healthy
            } else {
                AgentHealth::Degraded
            },
            // `PolicySnapshot::routing_labels` is `RoutingLabels::iter` flattened
            // -- host label first, then the optional labels in sorted order --
            // so the split is positional here and nowhere else. A monitor-only
            // policy reserves no label at all and yields an empty vector, which
            // is the `None` the row draws as "not reserved".
            host_label: policy.routing_labels.first().cloned(),
            extra_labels: policy.routing_labels.iter().skip(1).cloned().collect(),
        });
        for runner in refreshed.runners.runners() {
            if !seen_runners.insert(runner.id) {
                continue;
            }
            let locally_owned = policy.mode != "monitor_only"
                && !policy.routing_labels.is_empty()
                && policy
                    .routing_labels
                    .iter()
                    .all(|label| runner.has_label(label));
            let (ephemeral, ownership) =
                classify_runner(&runner.name, runner.ephemeral, locally_owned);
            busy_runners = busy_runners.saturating_add(u32::from(runner.busy));
            assigned_jobs = assigned_jobs.saturating_add(u32::from(runner.busy && locally_owned));
            online_runners = online_runners.saturating_add(u32::from(runner.status.is_online()));
            runners.push(RunnerRow {
                id: runner.id.to_string(),
                name: runner.name.clone(),
                owner: target.slug(),
                os: runner.os.clone(),
                labels: runner.labels.clone(),
                online: runner.status.is_online(),
                busy: runner.busy,
                ephemeral,
                ownership,
            });
        }
    }

    Ok(Snapshot {
        availability: Availability::Ready,
        metrics: DashboardMetrics {
            in_progress_workflows,
            assigned_jobs,
            busy_runners,
            online_runners,
            host_capacity_used: local.host.in_use,
            host_capacity_total: local.host.capacity,
        },
        repositories,
        runners,
        activity,
    })
}

/// Recognise the exact name emitted by `agent::lifecycle::runner_name`.
///
/// Checking the UUID as well as the prefix prevents an arbitrary legacy name
/// such as `runner-manager-backup` from being presented as product-managed.
fn is_runner_manager_name(name: &str) -> bool {
    name.strip_prefix("runner-manager-")
        .is_some_and(|attempt| uuid::Uuid::parse_str(attempt).is_ok())
}

/// Preserve GitHub's lifetime fact, filling only the omission for a runner
/// whose name has the exact product-generated shape. Ownership stays relative
/// to the current host: a recognised product runner from WSL is managed, but
/// remote, when it appears in the Windows host's inventory.
fn classify_runner(
    name: &str,
    github_ephemeral: Option<bool>,
    locally_owned: bool,
) -> (Option<bool>, RunnerOwnership) {
    let managed_runner = is_runner_manager_name(name);
    let ephemeral = github_ephemeral.or(managed_runner.then_some(true));
    let ownership = if locally_owned {
        RunnerOwnership::Local
    } else if managed_runner {
        RunnerOwnership::ManagedRemote
    } else {
        RunnerOwnership::External
    };
    (ephemeral, ownership)
}

fn production_activity(context: &crate::cli::Context) -> Result<Vec<screens::ActivityRow>, String> {
    let store = context.store().map_err(|error| error.to_string())?;
    let attempts = store.attempts().map_err(|error| error.to_string())?;
    let policies = store.policies().map_err(|error| error.to_string())?;
    let targets = policies
        .into_iter()
        .map(|policy| (policy.id, policy.target.slug()))
        .collect::<HashMap<_, _>>();
    Ok(activity_rows(&attempts, &targets))
}

fn activity_rows(
    attempts: &[RunnerAttempt],
    targets: &HashMap<runner_manager_domain::model::PolicyId, String>,
) -> Vec<screens::ActivityRow> {
    let mut rows = Vec::new();
    for attempt in attempts {
        let target = targets
            .get(&attempt.policy_id)
            .map_or("removed policy", String::as_str);
        let attempt_id = attempt.id.to_string();
        let occurred_at = compact_activity_time(
            attempt
                .terminal_at()
                .unwrap_or_else(|| attempt.last_state_change_at()),
        );
        match attempt.outcome() {
            Some(AttemptOutcome::CompletedJob) => rows.push(screens::ActivityRow {
                id: format!("{attempt_id}:outcome"),
                occurred_at: occurred_at.clone(),
                outcome: screens::ActivityOutcome::Info,
                summary: format!("Runner attempt {attempt_id} for {target} ran one job."),
                remediation: "No remediation required.".into(),
            }),
            Some(AttemptOutcome::ExitedIdleWithoutWork) => rows.push(screens::ActivityRow {
                id: format!("{attempt_id}:outcome"),
                occurred_at: occurred_at.clone(),
                outcome: screens::ActivityOutcome::ExitedIdleWithoutWork,
                summary: format!(
                    "Runner attempt {attempt_id} for {target} exited idle without accepting work."
                ),
                remediation: "No remediation required; this is a normal surplus-runner exit."
                    .into(),
            }),
            Some(AttemptOutcome::Failed { reason }) => {
                rows.push(screens::ActivityRow {
                    id: format!("{attempt_id}:outcome"),
                    occurred_at: occurred_at.clone(),
                    outcome: screens::ActivityOutcome::Failed,
                    summary: format!("Runner attempt {attempt_id} for {target} failed: {reason}."),
                    remediation: failure_remediation(reason).into(),
                });
                rows.push(screens::ActivityRow {
                    id: format!("{attempt_id}:retry"),
                    occurred_at: occurred_at.clone(),
                    outcome: screens::ActivityOutcome::Retry,
                    summary: format!(
                        "Attempt {attempt_id} is terminal; a new attempt is retried only while demand remains."
                    ),
                    remediation: "Wait for the bounded automatic retry or address the failure above."
                        .into(),
                });
            }
            Some(AttemptOutcome::Orphaned) => rows.push(screens::ActivityRow {
                id: format!("{attempt_id}:outcome"),
                occurred_at: occurred_at.clone(),
                outcome: screens::ActivityOutcome::Failed,
                summary: format!("Runner attempt {attempt_id} for {target} became orphaned."),
                remediation:
                    "Inspect the local runner process and logs, then restart the service if safe."
                        .into(),
            }),
            None => rows.push(screens::ActivityRow {
                id: format!("{attempt_id}:state"),
                occurred_at: occurred_at.clone(),
                outcome: screens::ActivityOutcome::Info,
                summary: format!(
                    "Runner attempt {attempt_id} for {target} is {}.",
                    attempt.state()
                ),
                remediation: "No action required while the lifecycle continues.".into(),
            }),
        }
        if attempt.state() == AttemptState::Cleaned {
            rows.push(screens::ActivityRow {
                id: format!("{attempt_id}:cleanup"),
                occurred_at: compact_activity_time(attempt.last_state_change_at()),
                outcome: screens::ActivityOutcome::CleanupComplete,
                summary: format!("Runtime cleanup completed for attempt {attempt_id} ({target})."),
                remediation: "No remediation required; local resources were released.".into(),
            });
        }
    }
    rows
}

fn failure_remediation(reason: &FailureReason) -> &'static str {
    match reason {
        FailureReason::JitRequestFailed | FailureReason::JitExpired => {
            "Verify GitHub connectivity and authorization; retry occurs only while demand remains."
        }
        FailureReason::RunnerPackageUnverified => {
            "Purge the runner package cache and verify the published checksum before retrying."
        }
        FailureReason::RunnerVersionRejected => {
            "Install a supported runner version; retrying the rejected version will not help."
        }
        FailureReason::ProcessStartFailed | FailureReason::ProcessExitedUnexpectedly => {
            "Inspect the local runner log, executable permissions, and process exit details."
        }
        FailureReason::RegistrationTimedOut | FailureReason::TerminatedAfterRegistrationTimeout => {
            "Check this host's network, DNS, proxy, firewall, and GitHub authorization."
        }
        FailureReason::Other(_) => "Inspect the local runner log and the copy-safe diagnostic.",
    }
}

fn refresh_activity(
    availability: &Availability,
    detail: &str,
    occurred_at: runner_manager_domain::model::Timestamp,
) -> screens::ActivityRow {
    let (outcome, remediation) = match availability {
        Availability::RateLimited { .. } => (
            screens::ActivityOutcome::RateLimit,
            "Wait for the displayed retry delay; F5 requests are coalesced.",
        ),
        Availability::Cancelled => (
            screens::ActivityOutcome::Info,
            "No action is required when a newer refresh superseded this one.",
        ),
        Availability::Unauthorized => (
            screens::ActivityOutcome::Failed,
            "Run `runner-manager auth login`.",
        ),
        Availability::Forbidden { .. } => (
            screens::ActivityOutcome::Failed,
            "Verify repository access and GitHub App/user permissions.",
        ),
        Availability::Offline { .. } => (
            screens::ActivityOutcome::Retry,
            "Check network, DNS, proxy, and system clock; retry is automatic.",
        ),
        Availability::Failed { .. } | Availability::Loading | Availability::Ready => (
            screens::ActivityOutcome::Failed,
            "Inspect the copy-safe diagnostic and retry with F5.",
        ),
    };
    screens::ActivityRow {
        id: format!(
            "github-inventory-refresh:{}",
            occurred_at.timestamp_nanos_opt().unwrap_or_default()
        ),
        occurred_at: compact_activity_time(occurred_at),
        outcome,
        summary: screens::copy_safe(detail),
        remediation: remediation.into(),
    }
}

/// Compact, unambiguous UTC time for the narrow Activity table. Its
/// year-first shape also preserves the existing lexical newest-first sort.
fn compact_activity_time(at: runner_manager_domain::model::Timestamp) -> String {
    at.format("%Y-%m-%d %H:%M:%SZ").to_string()
}

fn inventory_failure(
    context: &crate::cli::Context,
    clock: &Arc<dyn runner_manager_domain::model::Clock>,
    error: InventoryError,
) -> (Availability, String) {
    let state = RefreshState::from_error(&error);
    let availability = availability_from_refresh_state(context, clock, &state);
    (availability, error.to_string())
}

fn availability_from_refresh_state(
    context: &crate::cli::Context,
    clock: &Arc<dyn runner_manager_domain::model::Clock>,
    state: &RefreshState,
) -> Availability {
    match state {
        RefreshState::Unauthorized => Availability::Unauthorized,
        RefreshState::RateLimited(_) | RefreshState::LockedOut { .. } => {
            Availability::RateLimited {
                retry_after_seconds: state
                    .retry_delay(clock.now())
                    .unwrap_or(LOCAL_AGENT_POLL_RATE)
                    .as_secs(),
            }
        }
        RefreshState::Offline => offline_availability(context),
        RefreshState::Forbidden { message } => Availability::Forbidden {
            message: message.clone(),
        },
        RefreshState::Failed { message, .. } => Availability::Failed {
            detail: message.clone(),
        },
        RefreshState::Cancelled => Availability::Cancelled,
        RefreshState::Ready(_) => Availability::Failed {
            detail: "inventory failure unexpectedly mapped to a ready state".into(),
        },
    }
}

fn offline_failure(context: &crate::cli::Context, detail: String) -> (Availability, String) {
    (offline_availability(context), detail)
}

fn offline_availability(context: &crate::cli::Context) -> Availability {
    let last = runner_manager_platform::service::last_github_contact(context.paths())
        .ok()
        .flatten()
        .map_or_else(|| "none recorded".into(), |at| at.to_rfc3339());
    Availability::Offline {
        last_successful_contact: last,
        retry_after_seconds: LOCAL_AGENT_POLL_RATE.as_secs(),
    }
}

/// All terminal, timer, and agent events feed the same reducer through here.
#[derive(Debug)]
pub enum AppEvent {
    Key(KeyEvent),
    Mouse(MouseEvent),
    Resize(u16, u16),
    Paste(String),
    FocusGained,
    FocusLost,
    Timer(Instant),
    Agent(AgentEvent),
    InputFailed(String),
}

impl From<Event> for AppEvent {
    fn from(event: Event) -> Self {
        match event {
            Event::Key(event) => Self::Key(event),
            Event::Mouse(event) => Self::Mouse(event),
            Event::Resize(width, height) => Self::Resize(width, height),
            Event::Paste(text) => Self::Paste(text),
            Event::FocusGained => Self::FocusGained,
            Event::FocusLost => Self::FocusLost,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Effect {
    Refresh,
    Copy(String),
    SetMouseCapture(bool),
    OpenFullDiskAccess,
    ActivateFocusedControl,
    Settings(SettingsCommand),
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct NavigationItem {
    screen: Screen,
    label: String,
    area: Rect,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct NavigationLayout {
    items: Vec<NavigationItem>,
}

impl NavigationLayout {
    fn for_area(area: Rect) -> Self {
        let labels: Vec<String> = Screen::ALL
            .into_iter()
            .map(|screen| navigation_label(screen, area.width))
            .collect();
        let gaps = labels.len().saturating_sub(1) as u16;
        let labels_width = labels
            .iter()
            .map(|label| u16::try_from(label.chars().count()).unwrap_or(u16::MAX))
            .sum::<u16>();
        let leading = area.width.saturating_sub(labels_width.saturating_add(gaps)) / 2;
        let mut x = area.x.saturating_add(leading);
        let mut items = Vec::with_capacity(labels.len());
        for (screen, label) in Screen::ALL.into_iter().zip(labels) {
            let width = u16::try_from(label.chars().count())
                .unwrap_or(u16::MAX)
                .min(area.right().saturating_sub(x));
            if width == 0 {
                break;
            }
            items.push(NavigationItem {
                screen,
                label,
                area: Rect::new(x, area.y, width, 1),
            });
            x = x.saturating_add(width).saturating_add(1);
        }
        Self { items }
    }

    fn hit(&self, column: u16, row: u16) -> Option<Screen> {
        self.items
            .iter()
            .find(|item| {
                column >= item.area.x
                    && column < item.area.right()
                    && row >= item.area.y
                    && row < item.area.bottom()
            })
            .map(|item| item.screen)
    }
}

fn navigation_label(screen: Screen, width: u16) -> String {
    let key = screen_key(screen);
    if width < 60 {
        format!("[{key}]")
    } else if width < 110 {
        let short = match screen {
            Screen::Dashboard => "Dash",
            Screen::Repositories => "Repos",
            Screen::Runners => "Run",
            Screen::RepositorySettings => "RepoCfg",
            Screen::HostSettings => "HostCfg",
            Screen::Activity => "Activity",
        };
        format!("[{key}]{short}")
    } else {
        format!("[{key}] {}", screen.title())
    }
}

fn navigation_area(size: Rect) -> Rect {
    Rect::new(size.x, size.y.saturating_add(1), size.width, 1)
}

/// The first terminal row a settings form draws on: one status row, one
/// navigation row, and the block's own top border.
const SETTINGS_FIRST_ROW: u16 = 3;

/// Whether this frame is drawn in the constrained layout.
///
/// One definition, because [`render`] and [`reduce_mouse`] have to agree: the
/// compact frame drops rows, so a click resolved against the full layout lands
/// on a control the operator was not shown.
const fn compact_layout(area: Rect) -> bool {
    area.width < 60 || area.height < 18
}

/// Whether the frame is too small to draw at all.
///
/// One definition for the same reason [`compact_layout`] is one: below this
/// [`render`] draws a one-line fallback instead of a screen, so there is no
/// form on it and no row for a click to reach.
const fn below_minimum_frame(area: Rect) -> bool {
    area.width < 12 || area.height < 5
}

/// How many form rows a settings frame of this size actually puts on screen.
///
/// The pane keeps a status row, a navigation row, its own two borders and the
/// footer, and `Paragraph` clips whatever does not fit rather than scrolling.
/// A click below the last drawn row — on the footer, or anywhere on a form
/// taller than the pane — must therefore reach nothing: resolved against the
/// unclipped row list it would activate a control the operator never saw, which
/// on these screens means *Save* instead of *Reset*.
const fn settings_content_rows(size: Rect) -> u16 {
    if below_minimum_frame(size) {
        return 0;
    }
    size.height.saturating_sub(SETTINGS_FIRST_ROW + 2)
}

/// Full-screen list capacity after the shell header, navigation, and footer.
fn read_only_list_rows(size: Rect) -> usize {
    screens::list_viewport_rows(size.height.saturating_sub(3))
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AppState {
    pub screen: Screen,
    pub focus: Focus,
    pub presentation: PresentationState,
    pub screen_model: ScreenModel,
    pub size: Rect,
    pub help_open: bool,
    pub filtering: bool,
    pub filter: String,
    pub mouse_capture: bool,
    pub terminal_focused: bool,
    pub should_exit: bool,
    pub ticks: u64,
    pub last_tick: Option<Instant>,
    pub settings: SettingsUi,
    /// Glyphs and colour, resolved once here so no frame has to ask the
    /// environment what the terminal can print.
    pub skin: Skin,
    navigation: NavigationLayout,
}

impl AppState {
    pub fn new(presentation: PresentationState, width: u16, height: u16) -> Self {
        let size = Rect::new(0, 0, width, height);
        let mut screen_model = ScreenModel::new(Snapshot::default());
        screen_model.apply(ScreenAction::SetViewportRows(read_only_list_rows(size)));
        Self {
            screen: Screen::Dashboard,
            focus: Focus::Content,
            presentation,
            screen_model,
            size,
            help_open: false,
            filtering: false,
            filter: String::new(),
            mouse_capture: true,
            terminal_focused: true,
            should_exit: false,
            ticks: 0,
            last_tick: None,
            settings: SettingsUi::default(),
            skin: Skin::detect(),
            navigation: NavigationLayout::for_area(navigation_area(Rect::new(0, 0, width, height))),
        }
    }

    fn relayout(&mut self) {
        self.navigation = NavigationLayout::for_area(navigation_area(self.size));
    }

    fn open_screen(&mut self, screen: Screen) {
        // A path control captures the keyboard, and only a settings screen
        // draws one. Leaving by mouse is the one navigation an open editor
        // cannot swallow, so the editor is closed here rather than left to eat
        // every key pressed on the screen the operator went to.
        self.settings.cancel_editing();
        self.screen = screen;
        if let Some(read_only) = read_only_screen(screen) {
            self.screen_model.apply(ScreenAction::Open(read_only));
        }
    }
}

const fn read_only_screen(screen: Screen) -> Option<ReadOnlyScreen> {
    match screen {
        Screen::Dashboard => Some(ReadOnlyScreen::Dashboard),
        Screen::Repositories => Some(ReadOnlyScreen::Repositories),
        Screen::Runners => Some(ReadOnlyScreen::Runners),
        Screen::Activity => Some(ReadOnlyScreen::Activity),
        Screen::RepositorySettings | Screen::HostSettings => None,
    }
}

/// Pure state transition. Effects are performed by the shell, never render.
pub fn reduce(state: &mut AppState, event: AppEvent) -> Vec<Effect> {
    match event {
        AppEvent::Key(key) if matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) => {
            reduce_key(state, key)
        }
        AppEvent::Mouse(mouse) => reduce_mouse(state, mouse),
        AppEvent::Resize(width, height) => {
            state.size = Rect::new(0, 0, width, height);
            state.relayout();
            state
                .screen_model
                .apply(ScreenAction::SetViewportRows(read_only_list_rows(
                    state.size,
                )));
            Vec::new()
        }
        AppEvent::Paste(text) => {
            // Redacted on the way in, not on the way out: a path is not a
            // secret, but a token pasted into a path control by accident would
            // otherwise be drawn on screen and copied out of it. Any value that
            // needed redacting was never a usable runner root anyway.
            let safe = state.presentation.redact(&text);
            if state.filtering {
                state.filter.push_str(&safe);
                state
                    .screen_model
                    .apply(ScreenAction::Filter(state.filter.clone()));
            } else if state.settings.is_editing() {
                state.settings.paste(&safe);
            }
            Vec::new()
        }
        AppEvent::FocusGained => {
            state.terminal_focused = true;
            Vec::new()
        }
        AppEvent::FocusLost => {
            state.terminal_focused = false;
            Vec::new()
        }
        AppEvent::Timer(instant) => {
            state.ticks = state.ticks.saturating_add(1);
            state.last_tick = Some(instant);
            Vec::new()
        }
        AppEvent::Agent(agent) => {
            state.presentation.health = agent.health;
            state.presentation.privacy_access_denied = agent.privacy_access_denied;
            state.presentation.service_version = agent.service_version;
            let summary = state.presentation.redact(&agent.summary);
            state.presentation.diagnostics.push(summary);
            if let Some(mut snapshot) = agent.snapshot {
                snapshot.activity = merge_activity_history(
                    &state.screen_model.snapshot.activity,
                    snapshot.activity,
                );
                state.screen_model.apply(ScreenAction::Refresh(snapshot));
            }
            Vec::new()
        }
        AppEvent::InputFailed(message) => {
            state.presentation.health = Health::Error;
            state
                .presentation
                .diagnostics
                .push(format!("terminal input failed: {message}"));
            Vec::new()
        }
        AppEvent::Key(_) => Vec::new(),
    }
}

fn merge_activity_history(
    previous: &[screens::ActivityRow],
    mut current: Vec<screens::ActivityRow>,
) -> Vec<screens::ActivityRow> {
    let mut ids = current
        .iter()
        .map(|row| row.id.clone())
        .collect::<HashSet<_>>();
    current.extend(
        previous
            .iter()
            .filter(|row| ids.insert(row.id.clone()))
            .cloned(),
    );
    current.sort_by(|left, right| right.occurred_at.cmp(&left.occurred_at));
    current.truncate(MAX_ACTIVITY_HISTORY);
    current
}

fn reduce_key(state: &mut AppState, key: KeyEvent) -> Vec<Effect> {
    if state.filtering {
        match key.code {
            KeyCode::Esc => {
                state.filtering = false;
                state.filter.clear();
                state
                    .screen_model
                    .apply(ScreenAction::Filter(String::new()));
                return Vec::new();
            }
            KeyCode::Enter => {
                state.filtering = false;
                return Vec::new();
            }
            KeyCode::Backspace => {
                state.filter.pop();
                state
                    .screen_model
                    .apply(ScreenAction::Filter(state.filter.clone()));
                return Vec::new();
            }
            KeyCode::Char(character)
                if !key
                    .modifiers
                    .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
            {
                state.filter.push(character);
                state
                    .screen_model
                    .apply(ScreenAction::Filter(state.filter.clone()));
                return Vec::new();
            }
            _ => {}
        }
    }

    // ------------------------------------------------------------------------
    // A PATH CONTROL BEING EDITED OWNS THE WHOLE KEYBOARD.
    // ------------------------------------------------------------------------
    // Before this, every letter was a screen shortcut, so typing `C:\home\rman`
    // would have jumped to Host Settings on the `h` and quit on a `q`. Modified
    // chords are dropped rather than typed: Ctrl-C is not the letter `c`.
    if state.settings.is_editing() {
        if matches!(key.code, KeyCode::Char(_))
            && key
                .modifiers
                .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
        {
            return Vec::new();
        }
        return state
            .settings
            .key(key.code)
            .map(|command| vec![Effect::Settings(command)])
            .unwrap_or_default();
    }

    if matches!(
        state.screen,
        Screen::HostSettings | Screen::RepositorySettings
    ) && matches!(
        key.code,
        KeyCode::Up
            | KeyCode::Down
            | KeyCode::Left
            | KeyCode::Right
            | KeyCode::BackTab
            | KeyCode::Enter
            | KeyCode::Char('-' | '+' | ' ')
    ) {
        return state
            .settings
            .key(key.code)
            .map(|command| vec![Effect::Settings(command)])
            .unwrap_or_default();
    }

    match key.code {
        KeyCode::Char('d') => state.open_screen(Screen::Dashboard),
        KeyCode::Char('r') => state.open_screen(Screen::Repositories),
        KeyCode::Char('n') => state.open_screen(Screen::Runners),
        KeyCode::Char('s') => {
            state.open_screen(Screen::RepositorySettings);
            // ----------------------------------------------------------------
            // THERE MAY BE NO REPOSITORY TO CONFIGURE, AND THAT IS NOT AN ERROR.
            // ----------------------------------------------------------------
            // `unwrap_or_default()` here sent an EMPTY target into the policy
            // loader, which parsed it and failed with "an organization login
            // must not be empty" -- a message about a parser, shown to somebody
            // who pressed `s` on a host that has no policies yet. The screen
            // then sat on "Loading settings..." forever, because nothing was
            // ever going to load.
            //
            // A host with no policies is the state every new install starts in,
            // so it gets an answer rather than a diagnostic.
            return open_repository_settings(state);
        }
        KeyCode::Char('h') => {
            state.open_screen(Screen::HostSettings);
            return vec![Effect::Settings(SettingsCommand::LoadHost)];
        }
        KeyCode::Char('a') => state.open_screen(Screen::Activity),
        KeyCode::Char('p')
            if state.screen == Screen::Dashboard && state.presentation.privacy_access_denied =>
        {
            return vec![Effect::OpenFullDiskAccess];
        }
        KeyCode::Char('o') => {
            let current = match state.screen_model.screen {
                ReadOnlyScreen::Repositories => state.screen_model.repositories.sort_order,
                ReadOnlyScreen::Runners => state.screen_model.runners.sort_order,
                ReadOnlyScreen::Activity => state.screen_model.activity.sort_order,
                ReadOnlyScreen::Dashboard => screens::SortOrder::NameAscending,
            };
            let next = match (state.screen_model.screen, current) {
                (ReadOnlyScreen::Repositories, screens::SortOrder::NameAscending) => {
                    screens::SortOrder::NameDescending
                }
                (ReadOnlyScreen::Repositories, screens::SortOrder::NameDescending) => {
                    screens::SortOrder::WorkloadDescending
                }
                (_, screens::SortOrder::NameAscending) => screens::SortOrder::NameDescending,
                _ => screens::SortOrder::NameAscending,
            };
            state.screen_model.apply(ScreenAction::SetSort(next));
        }
        KeyCode::Char('/') => state.filtering = true,
        KeyCode::F(5) => return vec![Effect::Refresh],
        KeyCode::Char('?') => state.help_open = !state.help_open,
        KeyCode::Char('q') => state.should_exit = true,
        KeyCode::Char('c') => {
            // `05-user-workflows.md`: paths are "copyable from detail view".
            if matches!(
                state.screen,
                Screen::HostSettings | Screen::RepositorySettings
            ) && let Some(path) = state.settings.copy_text()
            {
                return vec![Effect::Copy(path)];
            }
            let copy = if state.screen == Screen::RepositorySettings {
                match &state.settings.view {
                    SettingsView::Policy(form) => {
                        form.copyable_runs_on.clone().unwrap_or_else(|| {
                            "monitor-only: no routing label is reserved until promotion".into()
                        })
                    }
                    _ => "repository settings are not loaded".into(),
                }
            } else if read_only_screen(state.screen) == Some(ReadOnlyScreen::Activity) {
                screens::render_text(&state.screen_model)
            } else {
                state.presentation.copy_text()
            };
            return vec![Effect::Copy(copy)];
        }
        KeyCode::Char('m') => {
            state.mouse_capture = !state.mouse_capture;
            return vec![Effect::SetMouseCapture(state.mouse_capture)];
        }
        KeyCode::Esc => {
            if state.help_open {
                state.help_open = false;
            } else if state.screen_model.repository_detail.is_some()
                || state.screen_model.runner_detail.is_some()
            {
                state
                    .screen_model
                    .apply(ScreenAction::CloseRepositoryDetail);
            } else if state.filtering || !state.filter.is_empty() {
                state.filtering = false;
                state.filter.clear();
                state
                    .screen_model
                    .apply(ScreenAction::Filter(String::new()));
            } else if state.screen != Screen::Dashboard {
                state.open_screen(Screen::Dashboard);
            }
        }
        KeyCode::Tab => {
            state.focus = state
                .focus
                .next(key.modifiers.contains(KeyModifiers::SHIFT))
        }
        KeyCode::Up
            if state.focus == Focus::Content && read_only_screen(state.screen).is_some() =>
        {
            state.screen_model.apply(ScreenAction::MoveSelection(-1));
        }
        KeyCode::Down
            if state.focus == Focus::Content && read_only_screen(state.screen).is_some() =>
        {
            state.screen_model.apply(ScreenAction::MoveSelection(1));
        }
        KeyCode::BackTab | KeyCode::Up | KeyCode::Left => state.focus = state.focus.next(true),
        KeyCode::Down | KeyCode::Right => state.focus = state.focus.next(false),
        KeyCode::Enter => {
            if state.focus == Focus::Content && read_only_screen(state.screen).is_some() {
                state.screen_model.apply(ScreenAction::Activate);
            }
            return vec![Effect::ActivateFocusedControl];
        }
        _ => {}
    }
    Vec::new()
}

fn reduce_mouse(state: &mut AppState, mouse: MouseEvent) -> Vec<Effect> {
    match mouse.kind {
        MouseEventKind::Down(MouseButton::Left) => {
            if let Some(screen) = state.navigation.hit(mouse.column, mouse.row) {
                state.open_screen(screen);
                state.focus = Focus::Navigation;
                return match screen {
                    Screen::HostSettings => vec![Effect::Settings(SettingsCommand::LoadHost)],
                    Screen::RepositorySettings => open_repository_settings(state),
                    _ => Vec::new(),
                };
            } else {
                state.focus = Focus::Content;
                if state.screen == Screen::Dashboard
                    && state.presentation.privacy_access_denied
                    && contains(
                        dashboard_privacy_warning_area(state.size),
                        mouse.column,
                        mouse.row,
                    )
                {
                    return vec![Effect::OpenFullDiskAccess];
                } else if state.screen == Screen::Dashboard
                    && !state.presentation.privacy_access_denied
                    && let Some((table, column)) = screens::dashboard_sort_column_at(
                        &state.screen_model,
                        &state.skin,
                        state.size.width,
                        state.size.height,
                        mouse.column,
                        mouse.row,
                    )
                {
                    state
                        .screen_model
                        .apply(ScreenAction::SortDashboardColumn(table, column));
                } else if matches!(state.screen, Screen::Repositories | Screen::Runners)
                    && mouse.row == screens::INVENTORY_HEADER_ROW
                    && let Some(column) = screens::inventory_sort_column_at(
                        &state.screen_model,
                        &state.skin,
                        state.size.width,
                        mouse.column,
                    )
                {
                    state.screen_model.apply(ScreenAction::SortColumn(column));
                } else if state.screen == Screen::Repositories {
                    let content_first_row = screens::REPOSITORY_ROW_ORIGIN;
                    if mouse.row >= content_first_row
                        && let Some(id) =
                            state
                                .screen_model
                                .repository_id_at_viewport_offset(usize::from(
                                    mouse.row - content_first_row,
                                ))
                    {
                        state
                            .screen_model
                            .apply(ScreenAction::OpenRepositoryByMouse(id));
                    }
                } else if matches!(
                    state.screen,
                    Screen::HostSettings | Screen::RepositorySettings
                ) && mouse.row >= SETTINGS_FIRST_ROW
                    && mouse.row - SETTINGS_FIRST_ROW < settings_content_rows(state.size)
                    && let Some(command) = state.settings.click(
                        mouse.row - SETTINGS_FIRST_ROW,
                        settings::content_width(state.size.width),
                        compact_layout(state.size),
                    )
                {
                    return vec![Effect::Settings(command)];
                }
            }
        }
        MouseEventKind::ScrollUp => state.focus = state.focus.next(true),
        MouseEventKind::ScrollDown => state.focus = state.focus.next(false),
        _ => {}
    }
    Vec::new()
}

/// What Repository Settings loads, whichever way the operator asked for it.
///
/// -------------------------------------------------------------------------
/// THERE MAY BE NO REPOSITORY TO CONFIGURE, AND THAT IS NOT AN ERROR.
/// -------------------------------------------------------------------------
/// `unwrap_or_default()` here sent an EMPTY target into the policy loader,
/// which parsed it and failed with "an organization login must not be empty" —
/// a message about a parser, shown to somebody who opened the screen on a host
/// that has no policies yet. The screen then sat on "Loading settings..."
/// forever, because nothing was ever going to load.
///
/// A host with no policies is the state every new install starts in, so it gets
/// an answer rather than a diagnostic — and it gets the same answer from the
/// `s` key and from the navigation bar, which is why both go through here.
fn open_repository_settings(state: &mut AppState) -> Vec<Effect> {
    let Some(target) = selected_repository_target(state) else {
        state.settings.show_notice(
            "No repository is configured on this host yet.\n\n\
             Add one from a terminal:\n  \
             runner-manager repo add OWNER/REPO --host-label <host> --max-capacity 1\n\n\
             Then press [r] to select it and [s] to configure it.",
        );
        return Vec::new();
    };
    vec![Effect::Settings(SettingsCommand::LoadPolicy(target))]
}

fn selected_repository_target(state: &AppState) -> Option<String> {
    let selected = state.screen_model.repositories.selected_id.as_deref();
    state
        .screen_model
        .snapshot
        .repositories
        .iter()
        .find(|row| selected == Some(row.id.as_str()))
        .or_else(|| state.screen_model.snapshot.repositories.first())
        .map(|row| row.target.clone())
}

/// Draw one frame from memory only.
pub fn render(frame: &mut Frame<'_>, state: &AppState) {
    let area = frame.area();
    if below_minimum_frame(area) {
        frame.render_widget(
            Paragraph::new("runner-manager\n? help").wrap(Wrap { trim: true }),
            area,
        );
        return;
    }
    let compact = compact_layout(area);
    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1),
            Constraint::Length(1),
            Constraint::Min(1),
            Constraint::Length(1),
        ])
        .split(area);
    let (icon, health, colour) = state.presentation.health.presentation();
    frame.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled(
                " runner-manager ",
                Style::default().add_modifier(Modifier::BOLD),
            ),
            Span::styled(format!("{icon} {health}"), Style::default().fg(colour)),
        ])),
        rows[0],
    );
    frame.render_widget(
        Paragraph::new(Span::styled(
            format!(
                "service v{}  app v{} ",
                state
                    .presentation
                    .service_version
                    .as_deref()
                    .unwrap_or("unknown"),
                env!("CARGO_PKG_VERSION"),
            ),
            Style::default().fg(Color::DarkGray),
        ))
        .alignment(Alignment::Right),
        rows[0],
    );

    let navigation = NavigationLayout::for_area(rows[1]);
    for item in &navigation.items {
        let style = if item.screen == state.screen {
            Style::default().add_modifier(Modifier::REVERSED)
        } else {
            Style::default()
        };
        frame.render_widget(Paragraph::new(item.label.as_str()).style(style), item.area);
    }

    if matches!(
        state.screen,
        Screen::HostSettings | Screen::RepositorySettings
    ) {
        settings::render(frame, rows[2], &state.settings, compact);
    } else if let Some(read_only) = read_only_screen(state.screen) {
        let content =
            if state.screen == Screen::Dashboard && state.presentation.privacy_access_denied {
                let warning = dashboard_privacy_warning_area(state.size);
                frame.render_widget(
                    Paragraph::new(vec![
                        Line::from(Span::styled(
                            "FULL DISK ACCESS REQUIRED",
                            Style::default()
                                .fg(Color::Yellow)
                                .add_modifier(Modifier::BOLD),
                        )),
                        Line::from("macOS denied the boot service access to the runner volume."),
                        Line::from(Span::styled(
                            "[p] Open Full Disk Access settings",
                            Style::default()
                                .fg(Color::Yellow)
                                .add_modifier(Modifier::BOLD | Modifier::REVERSED),
                        )),
                    ])
                    .block(
                        Block::default()
                            .borders(Borders::ALL)
                            .border_style(Style::default().fg(Color::Yellow)),
                    )
                    .wrap(Wrap { trim: true }),
                    warning,
                );
                Rect {
                    y: warning.bottom(),
                    height: rows[2].bottom().saturating_sub(warning.bottom()),
                    ..rows[2]
                }
            } else {
                rows[2]
            };
        let mut model = state.screen_model.clone();
        model.apply(ScreenAction::Open(read_only));
        screens::render(frame, content, &model, &state.skin);
    } else {
        let content = if compact {
            let filter = if state.filtering {
                format!("\nFilter: {}", state.presentation.redact(&state.filter))
            } else {
                String::new()
            };
            format!(
                "{}\n{}{}\n\nCompact layout active. Press ? for every control.",
                state.screen.title(),
                state.presentation.redact(&state.presentation.heading),
                filter
            )
        } else {
            let source = if state.screen == Screen::Activity {
                &state.presentation.diagnostics
            } else {
                &state.presentation.body
            };
            let mut lines = vec![Line::from(Span::styled(
                state.presentation.redact(&state.presentation.heading),
                Style::default().add_modifier(Modifier::BOLD),
            ))];
            lines.extend(
                source
                    .iter()
                    .map(|line| Line::from(state.presentation.redact(line))),
            );
            Text::from(lines).to_string()
        };
        frame.render_widget(
            Paragraph::new(content)
                .block(
                    Block::default()
                        .title(state.screen.title())
                        .borders(Borders::ALL),
                )
                .wrap(Wrap { trim: false }),
            rows[2],
        );
    }
    let capture = if state.mouse_capture {
        "mouse:on"
    } else {
        "mouse:released"
    };
    let terminal_focus = if state.terminal_focused {
        "focused"
    } else {
        "unfocused"
    };
    let footer = if compact {
        format!("? help | q quit | {capture}")
    } else {
        format!(
            "Tab/arrows focus | Enter activate | / filter | o sort | F5 refresh | p privacy settings | c copy | m release mouse | Esc back | q quit | {capture} | {terminal_focus}"
        )
    };
    frame.render_widget(Paragraph::new(footer).alignment(Alignment::Center), rows[3]);
    if state.help_open || compact {
        render_help(frame, area, compact);
    }
}

fn render_help(frame: &mut Frame<'_>, area: Rect, compact: bool) {
    let width = area
        .width
        .saturating_sub(2)
        .min(if compact { 48 } else { 72 });
    let height = area
        .height
        .saturating_sub(2)
        .min(if compact { 10 } else { 14 });
    if width < 8 || height < 3 {
        return;
    }
    let popup_y = if compact {
        area.y.saturating_add(3)
    } else {
        area.y + area.height.saturating_sub(height) / 2
    };
    let height = height.min(area.bottom().saturating_sub(popup_y).saturating_sub(1));
    let popup = Rect::new(
        area.x + area.width.saturating_sub(width) / 2,
        popup_y,
        width,
        height,
    );
    let help = if compact {
        "d Dashboard  r Repositories  n Runners\ns Repo settings  h Host settings  a Activity\n/ Filter F5 Refresh ? Help Esc Back q Quit\nTab Shift-Tab Arrows Focus  Enter Activate\nc Copy diagnostics  m Mouse capture  o Sort\nKeys mirror every mouse action"
    } else {
        "d Dashboard   r Repositories   n Runners\ns Repository settings   h Host settings   a Activity\n/ filter   o sort   F5 refresh   ? help   Esc close/back   q quit\nTab / Shift-Tab / arrows focus   Enter activate\nc copy diagnostics   m release/re-enable mouse capture\nPath fields: Enter edit   type or paste   Esc cancel   Enter accept\nMouse actions always have the keyboard equivalents above."
    };
    frame.render_widget(Clear, popup);
    let title = if compact {
        "Key help - compact layout"
    } else {
        "Key help"
    };
    frame.render_widget(
        Paragraph::new(help)
            .block(Block::default().title(title).borders(Borders::ALL))
            .wrap(Wrap { trim: true }),
        popup,
    );
}

const fn screen_key(screen: Screen) -> char {
    match screen {
        Screen::Dashboard => 'd',
        Screen::Repositories => 'r',
        Screen::Runners => 'n',
        Screen::RepositorySettings => 's',
        Screen::HostSettings => 'h',
        Screen::Activity => 'a',
    }
}

trait TerminalActions {
    fn enable_raw(&mut self) -> io::Result<()>;
    fn disable_raw(&mut self) -> io::Result<()>;
    fn enter_alternate_screen(&mut self) -> io::Result<()>;
    fn leave_alternate_screen(&mut self) -> io::Result<()>;
    fn enable_mouse_capture(&mut self) -> io::Result<()>;
    fn disable_mouse_capture(&mut self) -> io::Result<()>;
    fn enable_focus_change(&mut self) -> io::Result<()>;
    fn disable_focus_change(&mut self) -> io::Result<()>;
    fn enable_bracketed_paste(&mut self) -> io::Result<()>;
    fn disable_bracketed_paste(&mut self) -> io::Result<()>;
}

trait RawModeActions {
    fn enable(&mut self) -> io::Result<()>;
    fn disable(&mut self) -> io::Result<()>;
}

struct SystemRawMode;
impl RawModeActions for SystemRawMode {
    fn enable(&mut self) -> io::Result<()> {
        enable_raw_mode()
    }
    fn disable(&mut self) -> io::Result<()> {
        disable_raw_mode()
    }
}

trait MouseCaptureActions<W: Write> {
    fn enable(&mut self, writer: &mut W) -> io::Result<()>;
    fn disable(&mut self, writer: &mut W) -> io::Result<()>;
}

struct CrosstermMouseCapture;

impl<W: Write> MouseCaptureActions<W> for CrosstermMouseCapture {
    fn enable(&mut self, writer: &mut W) -> io::Result<()> {
        execute!(writer, EnableMouseCapture).map(|_| ())
    }

    fn disable(&mut self, writer: &mut W) -> io::Result<()> {
        execute!(writer, DisableMouseCapture).map(|_| ())
    }
}

struct CrosstermActions<W: Write, R: RawModeActions, M: MouseCaptureActions<W>> {
    writer: W,
    raw_mode: R,
    mouse_capture: M,
}

impl<W: Write, R: RawModeActions> CrosstermActions<W, R, CrosstermMouseCapture> {
    fn new(writer: W, raw_mode: R) -> Self {
        Self {
            writer,
            raw_mode,
            mouse_capture: CrosstermMouseCapture,
        }
    }
}

impl<W: Write, R: RawModeActions, M: MouseCaptureActions<W>> CrosstermActions<W, R, M> {
    #[cfg(test)]
    fn with_mouse_capture(writer: W, raw_mode: R, mouse_capture: M) -> Self {
        Self {
            writer,
            raw_mode,
            mouse_capture,
        }
    }

    fn emit(&mut self, command: impl Command) -> io::Result<()> {
        execute!(self.writer, command).map(|_| ())
    }
}

impl<W: Write, R: RawModeActions, M: MouseCaptureActions<W>> TerminalActions
    for CrosstermActions<W, R, M>
{
    fn enable_raw(&mut self) -> io::Result<()> {
        self.raw_mode.enable()
    }
    fn disable_raw(&mut self) -> io::Result<()> {
        self.raw_mode.disable()
    }
    fn enter_alternate_screen(&mut self) -> io::Result<()> {
        self.emit(EnterAlternateScreen)
    }
    fn leave_alternate_screen(&mut self) -> io::Result<()> {
        self.emit(LeaveAlternateScreen)
    }
    fn enable_mouse_capture(&mut self) -> io::Result<()> {
        self.mouse_capture.enable(&mut self.writer)
    }
    fn disable_mouse_capture(&mut self) -> io::Result<()> {
        self.mouse_capture.disable(&mut self.writer)
    }
    fn enable_focus_change(&mut self) -> io::Result<()> {
        self.emit(EnableFocusChange)
    }
    fn disable_focus_change(&mut self) -> io::Result<()> {
        self.emit(DisableFocusChange)
    }
    fn enable_bracketed_paste(&mut self) -> io::Result<()> {
        self.emit(EnableBracketedPaste)
    }
    fn disable_bracketed_paste(&mut self) -> io::Result<()> {
        self.emit(DisableBracketedPaste)
    }
}

/// Owns all terminal modes. `Drop` is also the panic restoration path.
struct TerminalSession<A: TerminalActions> {
    actions: A,
    raw: bool,
    alternate: bool,
    mouse: bool,
    focus_change: bool,
    paste: bool,
}

impl<A: TerminalActions> TerminalSession<A> {
    fn start(actions: A) -> io::Result<Self> {
        let mut session = Self {
            actions,
            raw: false,
            alternate: false,
            mouse: false,
            focus_change: false,
            paste: false,
        };
        session.actions.enable_raw()?;
        session.raw = true;
        session.actions.enter_alternate_screen()?;
        session.alternate = true;
        session.actions.enable_mouse_capture()?;
        session.mouse = true;
        session.actions.enable_focus_change()?;
        session.focus_change = true;
        session.actions.enable_bracketed_paste()?;
        session.paste = true;
        Ok(session)
    }

    fn set_mouse_capture(&mut self, enabled: bool) -> io::Result<()> {
        if enabled == self.mouse {
            return Ok(());
        }
        if enabled {
            self.actions.enable_mouse_capture()?;
        } else {
            self.actions.disable_mouse_capture()?;
        }
        self.mouse = enabled;
        Ok(())
    }

    fn restore(&mut self) {
        if self.paste {
            let _ = self.actions.disable_bracketed_paste();
            self.paste = false;
        }
        if self.focus_change {
            let _ = self.actions.disable_focus_change();
            self.focus_change = false;
        }
        if self.mouse {
            let _ = self.actions.disable_mouse_capture();
            self.mouse = false;
        }
        if self.alternate {
            let _ = self.actions.leave_alternate_screen();
            self.alternate = false;
        }
        if self.raw {
            let _ = self.actions.disable_raw();
            self.raw = false;
        }
    }
}

impl<A: TerminalActions> Drop for TerminalSession<A> {
    fn drop(&mut self) {
        self.restore();
    }
}

pub fn copy_to_terminal_clipboard(writer: &mut dyn Write, text: &str) -> io::Result<()> {
    write!(writer, "\x1b]52;c;{}\x07", base64(text.as_bytes()))?;
    writer.flush()
}

fn base64(bytes: &[u8]) -> String {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut output = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let a = chunk[0];
        let b = chunk.get(1).copied().unwrap_or(0);
        let c = chunk.get(2).copied().unwrap_or(0);
        output.push(ALPHABET[(a >> 2) as usize] as char);
        output.push(ALPHABET[(((a & 3) << 4) | (b >> 4)) as usize] as char);
        output.push(if chunk.len() > 1 {
            ALPHABET[(((b & 15) << 2) | (c >> 6)) as usize] as char
        } else {
            '='
        });
        output.push(if chunk.len() > 2 {
            ALPHABET[(c & 63) as usize] as char
        } else {
            '='
        });
    }
    output
}

pub trait SessionControl {
    fn set_mouse_capture(&mut self, enabled: bool) -> io::Result<()>;
    fn mouse_capture_enabled(&self) -> bool;
}
impl<A: TerminalActions> SessionControl for TerminalSession<A> {
    fn set_mouse_capture(&mut self, enabled: bool) -> io::Result<()> {
        TerminalSession::set_mouse_capture(self, enabled)
    }
    fn mouse_capture_enabled(&self) -> bool {
        self.mouse
    }
}

/// Crossterm, timer, and agent sources are merged by `select!`; exactly one
/// resulting [`AppEvent`] is sent to [`reduce`] each iteration.
pub async fn run_loop<B, I>(
    terminal: &mut ratatui::Terminal<B>,
    session: &mut impl SessionControl,
    mut input: I,
    mut agent_events: mpsc::UnboundedReceiver<AgentEvent>,
    refresh: &impl RefreshRequester,
    context: Option<&crate::cli::Context>,
) -> io::Result<AppState>
where
    B: Backend,
    B::Error: std::error::Error + Send + Sync + 'static,
    I: Stream<Item = io::Result<Event>> + Unpin,
{
    let size = terminal.size().map_err(io::Error::other)?;
    let mut state = AppState::new(PresentationState::default(), size.width, size.height);
    let mut timer = tokio::time::interval(TICK_RATE);
    let mut agent_events_open = true;
    loop {
        terminal
            .draw(|frame| render(frame, &state))
            .map_err(io::Error::other)?;
        if state.should_exit {
            return Ok(state);
        }
        let event = tokio::select! {
            input = input.next() => match input {
                Some(Ok(event)) => AppEvent::from(event),
                Some(Err(error)) => AppEvent::InputFailed(error.to_string()),
                None => return Ok(state),
            },
            instant = timer.tick() => AppEvent::Timer(instant.into_std()),
            agent = agent_events.recv(), if agent_events_open => match agent {
                Some(agent) => AppEvent::Agent(agent),
                None => {
                    agent_events_open = false;
                    continue;
                }
            },
        };
        if matches!(event, AppEvent::Mouse(_)) && !session.mouse_capture_enabled() {
            continue;
        }
        for effect in reduce(&mut state, event) {
            match effect {
                Effect::SetMouseCapture(enabled) => session.set_mouse_capture(enabled)?,
                Effect::Copy(text) => copy_to_terminal_clipboard(&mut io::stdout(), &text)?,
                Effect::Refresh => refresh.request_refresh()?,
                Effect::OpenFullDiskAccess => {
                    crate::cli::open_in_browser(
                        runner_manager_platform::os::FULL_DISK_ACCESS_SETTINGS_URL,
                        crate::cli::Styling::for_stdout(),
                    );
                }
                Effect::ActivateFocusedControl => {
                    // Read-only controls activate in the reducer.
                }
                Effect::Settings(command) => {
                    if let Some(context) = context {
                        if let Some(copy) = state.settings.execute(context, command) {
                            copy_to_terminal_clipboard(&mut io::stdout(), &copy)?;
                        }
                    } else {
                        state.settings.message = Some(
                            "error: settings mutations require the local application context"
                                .into(),
                        );
                    }
                }
            }
        }
    }
}

fn require_interactive_terminal(
    input_is_terminal: bool,
    output_is_terminal: bool,
) -> io::Result<()> {
    if input_is_terminal && output_is_terminal {
        Ok(())
    } else {
        Err(io::Error::other(
            "the terminal UI requires interactive stdin and stdout",
        ))
    }
}

/// Runs the production terminal against an injected agent-event receiver.
///
/// This is the composition seam for an in-process agent. The standalone
/// `runner-manager tui` process uses [`run_terminal`], while an embedding host
/// passes its real receiver here; the loop test exercises this exact path.
#[allow(dead_code, reason = "public embedding seam for an in-process agent")]
pub fn run_terminal_with_agent_events(
    agent_events: mpsc::UnboundedReceiver<AgentEvent>,
) -> io::Result<()> {
    require_interactive_terminal(io::stdin().is_terminal(), io::stdout().is_terminal())?;
    let mut session = TerminalSession::start(CrosstermActions::new(io::stdout(), SystemRawMode))?;
    let backend = ratatui::backend::CrosstermBackend::new(io::stdout());
    let mut terminal = ratatui::Terminal::new(backend)?;
    terminal.clear()?;
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?;
    let result = runtime
        .block_on(run_loop(
            &mut terminal,
            &mut session,
            EventStream::new(),
            agent_events,
            &NoopRefreshRequester,
            None,
        ))
        .map(|_| ());
    let _ = terminal.show_cursor();
    result
}

pub fn run_terminal(context: Arc<crate::cli::Context>) -> io::Result<()> {
    require_interactive_terminal(io::stdin().is_terminal(), io::stdout().is_terminal())?;
    let (source, agent_events) =
        LocalAgentEventSource::start(Arc::clone(&context), LOCAL_AGENT_POLL_RATE)?;
    let mut session = TerminalSession::start(CrosstermActions::new(io::stdout(), SystemRawMode))?;
    let backend = ratatui::backend::CrosstermBackend::new(io::stdout());
    let mut terminal = ratatui::Terminal::new(backend)?;
    terminal.clear()?;
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?;
    let result = runtime
        .block_on(run_loop(
            &mut terminal,
            &mut session,
            EventStream::new(),
            agent_events,
            &source,
            Some(context.as_ref()),
        ))
        .map(|_| ());
    let _ = terminal.show_cursor();
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use crossterm::event::KeyEventState;
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;
    use std::panic::{AssertUnwindSafe, catch_unwind};
    use std::sync::{Arc, Mutex};

    #[test]
    fn only_the_exact_product_uuid_name_is_recognised_as_managed() {
        assert!(is_runner_manager_name(
            "runner-manager-1522f949-7875-4752-8cf9-7854dca2a0c2"
        ));
        for unrelated in [
            "runner-manager-backup",
            "runner-manager-1522f949-7875-4752-8cf9-7854dca2a0c2-extra",
            "my-runner-manager-1522f949-7875-4752-8cf9-7854dca2a0c2",
        ] {
            assert!(!is_runner_manager_name(unrelated), "{unrelated}");
        }
    }

    #[test]
    fn omitted_lifetime_for_a_managed_runner_is_ephemeral_and_remote_not_external() {
        let managed = "runner-manager-1522f949-7875-4752-8cf9-7854dca2a0c2";
        assert_eq!(
            classify_runner(managed, None, false),
            (Some(true), RunnerOwnership::ManagedRemote)
        );
        assert_eq!(
            classify_runner(managed, None, true),
            (Some(true), RunnerOwnership::Local)
        );
        assert_eq!(
            classify_runner("legacy-runner", None, false),
            (None, RunnerOwnership::External)
        );
        assert_eq!(
            classify_runner(managed, Some(false), false),
            (Some(false), RunnerOwnership::ManagedRemote),
            "an explicit GitHub fact wins over the name-based fallback"
        );
    }

    fn crossterm_key(code: KeyCode) -> KeyEvent {
        KeyEvent {
            code,
            modifiers: KeyModifiers::NONE,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        }
    }
    fn key(code: KeyCode) -> AppEvent {
        AppEvent::Key(crossterm_key(code))
    }
    fn crossterm_mouse(kind: MouseEventKind, column: u16, row: u16) -> MouseEvent {
        MouseEvent {
            kind,
            column,
            row,
            modifiers: KeyModifiers::NONE,
        }
    }
    fn mouse(kind: MouseEventKind, column: u16, row: u16) -> AppEvent {
        AppEvent::Mouse(crossterm_mouse(kind, column, row))
    }
    fn rendered(width: u16, height: u16, state: &AppState) -> String {
        let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
        terminal.draw(|frame| render(frame, state)).unwrap();
        super::super::buffer_text(terminal.backend().buffer())
    }

    #[test]
    fn header_shows_client_and_service_versions_compactly() {
        let state = AppState::new(
            PresentationState {
                service_version: Some("0.4.4".into()),
                ..PresentationState::default()
            },
            120,
            30,
        );
        let frame = rendered(120, 30, &state);
        let header = frame.lines().next().unwrap();
        let service = header.find("service v0.4.4").unwrap();
        let application = header
            .find(concat!("app v", env!("CARGO_PKG_VERSION")))
            .unwrap();
        assert!(service < application, "{header}");
        assert!(
            application > 90,
            "the app version must be right-aligned: {header}"
        );
    }

    #[test]
    fn activity_time_is_short_utc_and_lexically_sortable() {
        let earlier = chrono::DateTime::from_timestamp(1_700_000_000, 123_000_000).unwrap();
        let later = chrono::DateTime::from_timestamp(1_700_000_060, 0).unwrap();
        let earlier = compact_activity_time(earlier);
        let later = compact_activity_time(later);
        assert_eq!(earlier, "2023-11-14 22:13:20Z");
        assert!(earlier < later);
        assert_eq!(earlier.len(), 20);
    }

    #[test]
    fn reducer_covers_key_mouse_resize_paste_timer_agent_and_focus() {
        let mut state = AppState::new(PresentationState::default(), 120, 30);
        reduce(&mut state, key(KeyCode::Char('r')));
        assert_eq!(state.screen, Screen::Repositories);
        let frame = rendered(120, 30, &state);
        let x = frame
            .lines()
            .nth(1)
            .unwrap()
            .find("[a] Activity & errors")
            .expect("the rendered Activity label") as u16;
        reduce(
            &mut state,
            mouse(MouseEventKind::Down(MouseButton::Left), x, 1),
        );
        assert_eq!(
            state.screen,
            Screen::Activity,
            "captured click must dispatch, not merely parse"
        );
        reduce(&mut state, AppEvent::from(Event::Resize(42, 12)));
        assert_eq!(state.size, Rect::new(0, 0, 42, 12));
        reduce(&mut state, key(KeyCode::Char('/')));
        reduce(
            &mut state,
            AppEvent::from(Event::Paste("needle".to_owned())),
        );
        assert_eq!(state.filter, "needle");
        reduce(&mut state, AppEvent::Timer(Instant::now()));
        assert_eq!(state.ticks, 1);
        reduce(
            &mut state,
            AppEvent::Agent(AgentEvent {
                summary: "runner busy".to_owned(),
                health: Health::Busy,
                privacy_access_denied: false,
                service_version: None,
                snapshot: None,
            }),
        );
        assert_eq!(state.presentation.health, Health::Busy);
        reduce(&mut state, AppEvent::from(Event::FocusLost));
        assert!(!state.terminal_focused);
        reduce(&mut state, AppEvent::from(Event::FocusGained));
        assert!(state.terminal_focused);
    }

    #[test]
    fn dashboard_privacy_warning_is_yellow_and_opens_settings_from_key_or_click() {
        let mut state = AppState::new(PresentationState::default(), 120, 30);
        state.presentation.privacy_access_denied = true;

        let frame = rendered(120, 30, &state);
        assert!(
            frame.contains("FULL DISK ACCESS REQUIRED"),
            "dashboard must name the actionable macOS access failure: {frame}"
        );
        assert!(
            frame.contains("[p] Open Full Disk Access settings"),
            "dashboard must render the settings action: {frame}"
        );
        assert_eq!(
            reduce(&mut state, key(KeyCode::Char('p'))),
            [Effect::OpenFullDiskAccess]
        );
        assert_eq!(
            reduce(
                &mut state,
                mouse(MouseEventKind::Down(MouseButton::Left), 4, 4),
            ),
            [Effect::OpenFullDiskAccess]
        );
    }

    #[test]
    fn dashboard_hides_privacy_warning_and_disables_its_action_after_access_is_restored() {
        let mut state = AppState::new(PresentationState::default(), 120, 30);

        let frame = rendered(120, 30, &state);
        assert!(
            !frame.contains("FULL DISK ACCESS REQUIRED"),
            "a healthy host must not show a stale privacy warning: {frame}"
        );
        assert!(
            reduce(&mut state, key(KeyCode::Char('p'))).is_empty(),
            "the settings action must not be available without a recorded denial"
        );
        assert!(
            reduce(
                &mut state,
                mouse(MouseEventKind::Down(MouseButton::Left), 4, 4),
            )
            .is_empty(),
            "the dashboard warning hitbox must not be active when it is not drawn"
        );
    }

    #[test]
    fn compact_and_full_click_targets_follow_the_labels_actually_rendered() {
        for (width, height, rendered_label) in [(48, 12, "[a]"), (120, 30, "[a] Activity & errors")]
        {
            let mut state = AppState::new(PresentationState::default(), width, height);
            let frame = rendered(width, height, &state);
            let nav_row = frame.lines().nth(1).expect("navigation row");
            let x = nav_row
                .find(rendered_label)
                .unwrap_or_else(|| panic!("{rendered_label:?} was not rendered at width {width}"))
                as u16;

            reduce(
                &mut state,
                mouse(MouseEventKind::Down(MouseButton::Left), x, 1),
            );
            assert_eq!(
                state.screen,
                Screen::Activity,
                "the pixels spelling Activity at width {width} must be its hitbox"
            );
        }
    }

    #[test]
    fn every_screen_is_one_unique_key_away_from_every_other_screen() {
        let bindings = [
            ('d', Screen::Dashboard),
            ('r', Screen::Repositories),
            ('n', Screen::Runners),
            ('s', Screen::RepositorySettings),
            ('h', Screen::HostSettings),
            ('a', Screen::Activity),
        ];
        let mut keys = std::collections::HashSet::new();
        for (binding, destination) in bindings {
            assert!(keys.insert(binding), "key {binding} is bound twice");
            for origin in Screen::ALL {
                let mut state = AppState::new(PresentationState::default(), 80, 24);
                state.screen = origin;
                reduce(&mut state, key(KeyCode::Char(binding)));
                assert_eq!(state.screen, destination, "{binding} from {origin:?}");
            }
        }
        let every_binding = [
            "d",
            "r",
            "n",
            "s",
            "h",
            "a",
            "/",
            "F5",
            "?",
            "Esc",
            "q",
            "c",
            "m",
            "Tab",
            "Shift-Tab",
            "Enter",
            "Up",
            "Down",
            "Left",
            "Right",
        ];
        let unique = every_binding
            .into_iter()
            .collect::<std::collections::HashSet<_>>();
        assert_eq!(
            unique.len(),
            every_binding.len(),
            "no shell key may be bound twice"
        );
    }

    #[test]
    fn q_only_exits_client_and_emits_no_daemon_effect() {
        let mut state = AppState::new(PresentationState::default(), 80, 24);
        let effects = reduce(&mut state, key(KeyCode::Char('q')));
        assert!(state.should_exit);
        assert!(effects.is_empty());

        let shell_source = include_str!("shell.rs");
        let key_reducer = shell_source
            .split_once("fn reduce_key")
            .unwrap()
            .1
            .split_once("fn reduce_mouse")
            .unwrap()
            .0;
        assert!(!key_reducer.contains("daemon"));
        assert!(!key_reducer.contains("stop("));

        let cli_source = include_str!("../cli/mod.rs");
        assert!(
            cli_source.contains("crate::tui::run(cli.data_dir.as_deref())"),
            "the real `runner-manager tui` route must pass its selected data root"
        );
        let tui_source = include_str!("mod.rs");
        assert!(tui_source.contains("Context::resolve(data_dir"));
        assert!(tui_source.contains("shell::run_terminal(context)"));
    }

    #[derive(Clone, Default)]
    struct SharedWriter(Arc<Mutex<Vec<u8>>>);

    impl Write for SharedWriter {
        fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
            self.0.lock().unwrap().extend_from_slice(buffer);
            Ok(buffer.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    struct NoopRawMode;
    impl RawModeActions for NoopRawMode {
        fn enable(&mut self) -> io::Result<()> {
            Ok(())
        }
        fn disable(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    #[derive(Clone)]
    struct RecordingMouseCapture(Arc<Mutex<Vec<&'static str>>>);

    impl MouseCaptureActions<SharedWriter> for RecordingMouseCapture {
        fn enable(&mut self, _writer: &mut SharedWriter) -> io::Result<()> {
            self.0.lock().unwrap().push("mouse:on");
            Ok(())
        }

        fn disable(&mut self, _writer: &mut SharedWriter) -> io::Result<()> {
            self.0.lock().unwrap().push("mouse:off");
            Ok(())
        }
    }

    #[tokio::test]
    async fn capture_seam_and_merged_loop_causally_deliver_mouse_and_agent_events() {
        let output = SharedWriter::default();
        let capture_log = Arc::new(Mutex::new(Vec::new()));
        let mut session = TerminalSession::start(CrosstermActions::with_mouse_capture(
            output,
            NoopRawMode,
            RecordingMouseCapture(Arc::clone(&capture_log)),
        ))
        .expect("terminal setup through the injected capture seam");
        assert_eq!(*capture_log.lock().unwrap(), ["mouse:on"]);

        let width = 80;
        let height = 24;
        let initial = AppState::new(PresentationState::default(), width, height);
        let frame = rendered(width, height, &initial);
        let activity_x = frame
            .lines()
            .nth(1)
            .expect("navigation row")
            .find("[a]Activity")
            .expect("rendered Activity label") as u16;

        let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
        let (input_sender, input) = futures::channel::mpsc::unbounded::<io::Result<Event>>();
        let data_root = tempfile::tempdir().unwrap();
        let mut warnings = Vec::new();
        let context = Arc::new(
            crate::cli::Context::resolve(Some(data_root.path()), &mut warnings)
                .expect("production TUI context"),
        );
        let (_source, mut produced_events) =
            LocalAgentEventSource::start(context, Duration::from_secs(60))
                .expect("production local-agent source");
        let initial_event = tokio::time::timeout(Duration::from_secs(5), produced_events.recv())
            .await
            .expect("production snapshot deadline")
            .expect("production source event");
        let (event_sender, agent_events) = mpsc::unbounded_channel();
        event_sender.send(initial_event).unwrap();
        let producer = async move {
            input_sender
                .unbounded_send(Ok(Event::Mouse(crossterm_mouse(
                    MouseEventKind::Down(MouseButton::Left),
                    activity_x,
                    1,
                ))))
                .unwrap();
            tokio::time::sleep(Duration::from_millis(5)).await;
            input_sender
                .unbounded_send(Ok(Event::Key(crossterm_key(KeyCode::Char('q')))))
                .unwrap();
        };

        let (result, ()) = tokio::join!(
            run_loop(
                &mut terminal,
                &mut session,
                input,
                agent_events,
                &NoopRefreshRequester,
                None,
            ),
            producer
        );
        let final_state = result.expect("merged loop");
        assert_eq!(final_state.screen, Screen::Activity);
        assert_ne!(
            final_state.screen_model.snapshot.availability,
            Availability::Loading,
            "the shipped local source must replace the initial Loading snapshot"
        );
        assert!(
            final_state
                .presentation
                .diagnostics
                .iter()
                .any(|line| line.starts_with("Local agent journal:")),
            "the actual `tui` composition source must reach the reducer"
        );
        assert!(final_state.should_exit);
        drop(session);
        assert_eq!(
            *capture_log.lock().unwrap(),
            ["mouse:on", "mouse:off"],
            "the same capture controller must pair enable and disable"
        );
    }

    #[tokio::test]
    async fn shipped_source_produces_a_snapshot_and_f5_requests_an_immediate_refresh() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let produced = Arc::new(AtomicUsize::new(0));
        let producer_count = Arc::clone(&produced);
        let (source, mut source_events) = LocalAgentEventSource::start_with(
            move |_| {
                let refresh = producer_count.fetch_add(1, Ordering::SeqCst);
                let snapshot = if refresh == 0 {
                    Snapshot::default()
                } else {
                    Snapshot {
                        availability: Availability::Ready,
                        repositories: vec![RepositoryRow {
                            id: "f5-repository".into(),
                            target: "acme/refreshed-by-f5".into(),
                            in_progress_workflows: 9,
                            mode: PolicyMode::Autoscale,
                            max_capacity: Some(4),
                            health: AgentHealth::Healthy,
                            host_label: Some("rm-home-win-x64".into()),
                            extra_labels: vec![],
                        }],
                        ..Snapshot::default()
                    }
                };
                AgentEvent {
                    summary: format!("production refresh {refresh}"),
                    health: Health::Ready,
                    privacy_access_denied: false,
                    service_version: None,
                    snapshot: Some(snapshot),
                }
            },
            Duration::from_secs(60),
        )
        .expect("production source thread");

        // The refreshed snapshot, not a deadline, decides when the input task
        // quits, and the signal is raised *after* the event is queued for the
        // loop rather than from inside the source closure: a source thread
        // preempted between the two would otherwise let `q` win and exit
        // before the refreshed snapshot was ever applied. Forwarding from a
        // separate task, plus the `biased` join below, then orders the loop's
        // poll ahead of the input task, so `q` can only be sent once the
        // refreshed snapshot has been reduced.
        let (agent_sender, agent_events) = mpsc::unbounded_channel();
        let refreshed = Arc::new(tokio::sync::Notify::new());
        let forward_refreshed = Arc::clone(&refreshed);
        let _forwarder = tokio::spawn(async move {
            while let Some(event) = source_events.recv().await {
                let is_refresh = event
                    .snapshot
                    .as_ref()
                    .is_some_and(|snapshot| snapshot.availability == Availability::Ready);
                if agent_sender.send(event).is_err() {
                    break;
                }
                if is_refresh {
                    forward_refreshed.notify_one();
                }
            }
        });

        let output = SharedWriter::default();
        let capture_log = Arc::new(Mutex::new(Vec::new()));
        let mut session = TerminalSession::start(CrosstermActions::with_mouse_capture(
            output,
            NoopRawMode,
            RecordingMouseCapture(capture_log),
        ))
        .unwrap();
        let mut terminal = Terminal::new(TestBackend::new(120, 30)).unwrap();
        let (input_sender, input) = futures::channel::mpsc::unbounded::<io::Result<Event>>();
        let input_refreshed = Arc::clone(&refreshed);
        let input_producer = async move {
            input_sender
                .unbounded_send(Ok(Event::Key(crossterm_key(KeyCode::F(5)))))
                .unwrap();
            // Generous only so a genuine hang fails the test instead of
            // hanging CI; `q` is sent even on timeout so the assertions below
            // report the real condition.
            let _ = tokio::time::timeout(Duration::from_secs(30), input_refreshed.notified()).await;
            input_sender
                .unbounded_send(Ok(Event::Key(crossterm_key(KeyCode::Char('q')))))
                .unwrap();
        };
        let (result, ()) = tokio::join!(
            biased;
            run_loop(
                &mut terminal,
                &mut session,
                input,
                agent_events,
                &source,
                None,
            ),
            input_producer
        );
        let final_state = result.unwrap();
        assert!(produced.load(Ordering::SeqCst) >= 2);
        assert_eq!(
            final_state.screen_model.snapshot.availability,
            Availability::Ready
        );
        assert_eq!(
            final_state.screen_model.snapshot.repositories[0].target,
            "acme/refreshed-by-f5"
        );
    }

    #[test]
    fn production_mouse_and_focus_commands_keep_crossterm_platform_dispatch() {
        let source = include_str!("shell.rs");
        let runtime_source = source
            .split_once("mod tests {")
            .expect("test module boundary")
            .0;
        assert!(runtime_source.contains("execute!(self.writer, command)"));
        assert!(runtime_source.contains("mouse_capture: CrosstermMouseCapture"));
        let native_capture = source
            .split_once("impl<W: Write> MouseCaptureActions<W> for CrosstermMouseCapture")
            .expect("native mouse capture implementation")
            .1
            .split_once("struct CrosstermActions")
            .expect("end of native mouse capture implementation")
            .0;
        assert!(native_capture.contains("execute!(writer, EnableMouseCapture)"));
        assert!(native_capture.contains("execute!(writer, DisableMouseCapture)"));

        let production_actions = source
            .split_once(
                "impl<W: Write, R: RawModeActions, M: MouseCaptureActions<W>> TerminalActions",
            )
            .expect("production terminal actions")
            .1
            .split_once("/// Owns all terminal modes")
            .expect("end of production terminal actions")
            .0;
        assert!(production_actions.contains("self.emit(EnableFocusChange)"));
        assert!(production_actions.contains("self.emit(DisableFocusChange)"));
    }

    #[test]
    fn tui_refuses_captured_or_redirected_stdio_instead_of_waiting_for_events() {
        assert!(require_interactive_terminal(true, true).is_ok());
        for (input, output) in [(false, true), (true, false), (false, false)] {
            let error = require_interactive_terminal(input, output).unwrap_err();
            assert_eq!(
                error.to_string(),
                "the terminal UI requires interactive stdin and stdout"
            );
        }
    }

    #[derive(Clone)]
    struct RecordingActions(Arc<Mutex<Vec<&'static str>>>);
    impl RecordingActions {
        fn record(&self, action: &'static str) {
            self.0.lock().unwrap().push(action);
        }
    }
    impl TerminalActions for RecordingActions {
        fn enable_raw(&mut self) -> io::Result<()> {
            self.record("raw:on");
            Ok(())
        }
        fn disable_raw(&mut self) -> io::Result<()> {
            self.record("raw:off");
            Ok(())
        }
        fn enter_alternate_screen(&mut self) -> io::Result<()> {
            self.record("alternate:on");
            Ok(())
        }
        fn leave_alternate_screen(&mut self) -> io::Result<()> {
            self.record("alternate:off");
            Ok(())
        }
        fn enable_mouse_capture(&mut self) -> io::Result<()> {
            self.record("mouse:on");
            Ok(())
        }
        fn disable_mouse_capture(&mut self) -> io::Result<()> {
            self.record("mouse:off");
            Ok(())
        }
        fn enable_focus_change(&mut self) -> io::Result<()> {
            self.record("focus:on");
            Ok(())
        }
        fn disable_focus_change(&mut self) -> io::Result<()> {
            self.record("focus:off");
            Ok(())
        }
        fn enable_bracketed_paste(&mut self) -> io::Result<()> {
            self.record("paste:on");
            Ok(())
        }
        fn disable_bracketed_paste(&mut self) -> io::Result<()> {
            self.record("paste:off");
            Ok(())
        }
    }

    #[test]
    fn recorded_session_enables_input_modes_and_restores_normally() {
        let log = Arc::new(Mutex::new(Vec::new()));
        {
            let _session = TerminalSession::start(RecordingActions(Arc::clone(&log))).unwrap();
        }
        assert_eq!(
            *log.lock().unwrap(),
            [
                "raw:on",
                "alternate:on",
                "mouse:on",
                "focus:on",
                "paste:on",
                "paste:off",
                "focus:off",
                "mouse:off",
                "alternate:off",
                "raw:off"
            ]
        );
    }

    #[test]
    fn terminal_restores_during_panic_unwind() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let caught = catch_unwind(AssertUnwindSafe({
            let log = Arc::clone(&log);
            move || {
                let _session = TerminalSession::start(RecordingActions(log)).unwrap();
                panic!("simulated panic");
            }
        }));
        assert!(caught.is_err());
        assert!(log.lock().unwrap().ends_with(&[
            "paste:off",
            "focus:off",
            "mouse:off",
            "alternate:off",
            "raw:off"
        ]));
    }

    struct FailingActions {
        log: Arc<Mutex<Vec<&'static str>>>,
    }

    impl FailingActions {
        fn record(&self, action: &'static str) {
            self.log.lock().unwrap().push(action);
        }
    }

    impl TerminalActions for FailingActions {
        fn enable_raw(&mut self) -> io::Result<()> {
            self.record("raw:on");
            Ok(())
        }
        fn disable_raw(&mut self) -> io::Result<()> {
            self.record("raw:off");
            Ok(())
        }
        fn enter_alternate_screen(&mut self) -> io::Result<()> {
            self.record("alternate:on");
            Ok(())
        }
        fn leave_alternate_screen(&mut self) -> io::Result<()> {
            self.record("alternate:off");
            Ok(())
        }
        fn enable_mouse_capture(&mut self) -> io::Result<()> {
            self.record("mouse:on");
            Ok(())
        }
        fn disable_mouse_capture(&mut self) -> io::Result<()> {
            self.record("mouse:off");
            Ok(())
        }
        fn enable_focus_change(&mut self) -> io::Result<()> {
            self.record("focus:on");
            Ok(())
        }
        fn disable_focus_change(&mut self) -> io::Result<()> {
            self.record("focus:off");
            Ok(())
        }
        fn enable_bracketed_paste(&mut self) -> io::Result<()> {
            self.record("paste:on:error");
            Err(io::Error::other("injected paste setup failure"))
        }
        fn disable_bracketed_paste(&mut self) -> io::Result<()> {
            self.record("paste:off");
            Ok(())
        }
    }

    #[test]
    fn terminal_restores_completed_setup_steps_on_error_exit() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let result = TerminalSession::start(FailingActions {
            log: Arc::clone(&log),
        });
        assert!(result.is_err());
        assert_eq!(
            *log.lock().unwrap(),
            [
                "raw:on",
                "alternate:on",
                "mouse:on",
                "focus:on",
                "paste:on:error",
                "focus:off",
                "mouse:off",
                "alternate:off",
                "raw:off"
            ]
        );
    }

    #[test]
    fn release_restores_selection_and_copy_works_during_capture() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let mut session = TerminalSession::start(RecordingActions(Arc::clone(&log))).unwrap();
        let mut state = AppState::new(
            PresentationState {
                diagnostics: vec!["copy me".to_owned()],
                ..PresentationState::default()
            },
            80,
            24,
        );
        let effects = reduce(&mut state, key(KeyCode::Char('c')));
        let Effect::Copy(text) = &effects[0] else {
            panic!("c must copy")
        };
        let mut output = Vec::new();
        copy_to_terminal_clipboard(&mut output, text).unwrap();
        assert_eq!(output, b"\x1b]52;c;Y29weSBtZQ==\x07");
        let release = reduce(&mut state, key(KeyCode::Char('m')));
        assert_eq!(release, [Effect::SetMouseCapture(false)]);
        session.set_mouse_capture(false).unwrap();
        assert!(log.lock().unwrap().ends_with(&["mouse:off"]));
    }

    #[test]
    fn small_terminal_snapshot_is_compact_with_help_and_no_clipping() {
        let state = AppState::new(
            PresentationState {
                heading: "Overview".to_owned(),
                health: Health::Offline,
                ..PresentationState::default()
            },
            48,
            12,
        );
        let frame = rendered(48, 12, &state);
        for visible_control in [
            "Key help - compact layout",
            "d Dashboard",
            "r Repositories",
            "n Runners",
            "s Repo settings",
            "h Host settings",
            "a Activity",
            "/ Filter",
            "F5 Refresh",
            "? Help",
            "Esc Back",
            "q Quit",
            "Tab Shift-Tab Arrows Focus",
            "Enter Activate",
            "c Copy diagnostics",
            "m Mouse capture",
            "Keys mirror every mouse action",
        ] {
            assert!(
                frame.contains(visible_control),
                "compact help clipped or omitted {visible_control:?}:\n{frame}"
            );
        }
        assert!(frame.lines().nth(1).unwrap().contains("[a]"));
        assert_eq!(frame.lines().count(), 12);
        assert!(frame.lines().all(|line| line.chars().count() == 48));
    }

    #[test]
    fn render_boundary_redacts_every_sensitive_value() {
        let token = "ghu_1234567890abcdefghijklmnopqrstuvwxyz";
        let jit =
            "eyJlbmNvZGVkX2ppdF9jb25maWciOiJ0aGlzLWlzLWEtbGl2ZS1zaG9ydC1saXZlZC1jcmVkZW50aWFsIn0=";
        let mut state = AppState::new(PresentationState::default(), 120, 30);
        state.open_screen(Screen::Activity);
        state.screen_model = ScreenModel::new(Snapshot {
            availability: screens::Availability::Ready,
            activity: vec![screens::ActivityRow {
                id: "sensitive".into(),
                occurred_at: "now".into(),
                outcome: screens::ActivityOutcome::Failed,
                summary: format!("VISIBLE_DIAGNOSTIC credential={token}"),
                remediation: format!("runner --jitconfig={jit}"),
            }],
            ..Snapshot::default()
        });
        state.open_screen(Screen::Activity);
        let frame = rendered(120, 30, &state);
        assert!(!frame.contains(token));
        assert!(!frame.contains(jit));
        assert!(frame.contains(runner_manager_platform::logging::REDACTION));
        assert!(frame.contains("VISIBLE_DIAGNOSTIC"));
        let Effect::Copy(copy) = &reduce(&mut state.clone(), key(KeyCode::Char('c')))[0] else {
            panic!()
        };
        assert!(!copy.contains(token) && !copy.contains(jit));
    }

    #[test]
    fn production_shell_routes_navigation_filter_activation_and_render_to_screen_model() {
        let snapshot = Snapshot {
            availability: screens::Availability::Ready,
            repositories: vec![screens::RepositoryRow {
                id: "wired-repo".into(),
                target: "acme/production-wiring".into(),
                in_progress_workflows: 3,
                mode: screens::PolicyMode::MonitorOnly,
                max_capacity: None,
                health: screens::AgentHealth::Healthy,
                host_label: None,
                extra_labels: vec![],
            }],
            ..Snapshot::default()
        };
        let mut state = AppState::new(PresentationState::default(), 120, 30);
        reduce(
            &mut state,
            AppEvent::Agent(AgentEvent {
                summary: "GitHub inventory refreshed".into(),
                health: Health::Ready,
                privacy_access_denied: false,
                service_version: None,
                snapshot: Some(snapshot),
            }),
        );

        reduce(&mut state, key(KeyCode::Char('r')));
        let list = rendered(120, 30, &state);
        assert!(list.contains("acme/production-wiring"), "{list}");
        assert!(list.contains("[monitor-only]"), "{list}");

        reduce(&mut state, key(KeyCode::Char('/')));
        reduce(&mut state, AppEvent::Paste("production-wiring".to_owned()));
        assert_eq!(state.screen_model.repositories.filter, "production-wiring");
        reduce(&mut state, key(KeyCode::Enter));
        reduce(&mut state, key(KeyCode::Enter));
        let detail = rendered(120, 30, &state);
        assert!(detail.contains("REPOSITORY DETAIL"), "{detail}");
        assert!(
            detail.contains("Target: acme/production-wiring"),
            "{detail}"
        );

        let mut mouse_state = AppState::new(PresentationState::default(), 120, 30);
        mouse_state.screen_model = state.screen_model.clone();
        mouse_state
            .screen_model
            .apply(ScreenAction::CloseRepositoryDetail);
        reduce(&mut mouse_state, key(KeyCode::Char('r')));
        reduce(
            &mut mouse_state,
            mouse(
                MouseEventKind::Down(MouseButton::Left),
                10,
                screens::REPOSITORY_ROW_ORIGIN,
            ),
        );
        let mouse_detail = rendered(120, 30, &mouse_state);
        assert!(mouse_detail.contains("REPOSITORY DETAIL"), "{mouse_detail}");
    }

    #[test]
    fn production_keys_sort_inspect_runners_and_acknowledge_the_displayed_activity() {
        let snapshot = Snapshot {
            availability: Availability::Ready,
            runners: vec![
                RunnerRow {
                    id: "runner-a".into(),
                    name: "alpha".into(),
                    owner: "acme/alpha".into(),
                    os: "linux".into(),
                    labels: vec!["self-hosted".into()],
                    online: true,
                    busy: false,
                    ephemeral: Some(true),
                    ownership: RunnerOwnership::Local,
                },
                RunnerRow {
                    id: "runner-z".into(),
                    name: "zulu".into(),
                    owner: "acme/zulu".into(),
                    os: "windows".into(),
                    labels: vec!["external".into()],
                    online: false,
                    busy: false,
                    ephemeral: Some(false),
                    ownership: RunnerOwnership::External,
                },
            ],
            activity: vec![screens::ActivityRow {
                id: "visible-activity".into(),
                occurred_at: "now".into(),
                outcome: screens::ActivityOutcome::Failed,
                summary: "visible failure".into(),
                remediation: "inspect the runner log".into(),
            }],
            ..Snapshot::default()
        };
        let mut state = AppState::new(PresentationState::default(), 120, 30);
        reduce(
            &mut state,
            AppEvent::Agent(AgentEvent {
                summary: "production snapshot".into(),
                health: Health::Ready,
                privacy_access_denied: false,
                service_version: None,
                snapshot: Some(snapshot),
            }),
        );

        reduce(&mut state, key(KeyCode::Char('n')));
        reduce(&mut state, key(KeyCode::Char('o')));
        assert_eq!(
            state.screen_model.runners.sort_order,
            screens::SortOrder::NameDescending
        );
        let sorted = screens::render_text(&state.screen_model);
        assert!(
            sorted.find("zulu").unwrap() < sorted.find("alpha").unwrap(),
            "{sorted}"
        );
        reduce(&mut state, key(KeyCode::Enter));
        assert!(screens::render_text(&state.screen_model).contains("RUNNER INSPECTION"));
        assert!(screens::render_text(&state.screen_model).contains("Name: alpha"));

        reduce(&mut state, key(KeyCode::Char('a')));
        assert!(screens::render_text(&state.screen_model).contains("[new]"));
        reduce(&mut state, key(KeyCode::Enter));
        let activity = screens::render_text(&state.screen_model);
        assert!(activity.contains("[acknowledged]"), "{activity}");
        assert!(!activity.contains("> [new]"), "{activity}");
    }

    #[test]
    fn clicking_an_inventory_header_selects_a_column_and_toggles_its_direction() {
        let mut state = AppState::new(PresentationState::default(), 120, 30);
        state.screen_model.apply(ScreenAction::Refresh(Snapshot {
            availability: Availability::Ready,
            repositories: vec![
                RepositoryRow {
                    id: "busy".into(),
                    target: "acme/busy".into(),
                    in_progress_workflows: 9,
                    mode: PolicyMode::Autoscale,
                    max_capacity: Some(2),
                    health: AgentHealth::Healthy,
                    host_label: Some("rm-home-win-x64".into()),
                    extra_labels: vec![],
                },
                RepositoryRow {
                    id: "idle".into(),
                    target: "acme/idle".into(),
                    in_progress_workflows: 0,
                    mode: PolicyMode::MonitorOnly,
                    max_capacity: None,
                    health: AgentHealth::Degraded,
                    host_label: None,
                    extra_labels: vec![],
                },
            ],
            runners: vec![
                RunnerRow {
                    id: "z-owner".into(),
                    name: "runner-a".into(),
                    owner: "zeta/repo".into(),
                    os: "linux".into(),
                    labels: vec!["self-hosted".into()],
                    online: true,
                    busy: false,
                    ephemeral: Some(true),
                    ownership: RunnerOwnership::Local,
                },
                RunnerRow {
                    id: "a-owner".into(),
                    name: "runner-z".into(),
                    owner: "alpha/repo".into(),
                    os: "windows".into(),
                    labels: vec!["self-hosted".into()],
                    online: false,
                    busy: false,
                    ephemeral: Some(false),
                    ownership: RunnerOwnership::External,
                },
            ],
            ..Snapshot::default()
        }));

        reduce(&mut state, key(KeyCode::Char('r')));
        let frame = rendered(120, 30, &state);
        let workflows = frame
            .lines()
            .nth(usize::from(screens::INVENTORY_HEADER_ROW))
            .unwrap()
            .find("Workflows")
            .unwrap() as u16;
        reduce(
            &mut state,
            mouse(
                MouseEventKind::Down(MouseButton::Left),
                workflows,
                screens::INVENTORY_HEADER_ROW,
            ),
        );
        assert_eq!(state.screen_model.repositories.sort_column, 1);
        assert!(!state.screen_model.repositories.sort_descending);
        reduce(
            &mut state,
            mouse(
                MouseEventKind::Down(MouseButton::Left),
                workflows,
                screens::INVENTORY_HEADER_ROW,
            ),
        );
        assert!(state.screen_model.repositories.sort_descending);

        reduce(&mut state, key(KeyCode::Char('n')));
        let frame = rendered(120, 30, &state);
        let repository = frame
            .lines()
            .nth(usize::from(screens::INVENTORY_HEADER_ROW))
            .unwrap()
            .find("Repository")
            .unwrap() as u16;
        reduce(
            &mut state,
            mouse(
                MouseEventKind::Down(MouseButton::Left),
                repository,
                screens::INVENTORY_HEADER_ROW,
            ),
        );
        assert_eq!(state.screen_model.runners.sort_column, 0);
        assert!(!state.screen_model.runners.sort_descending);

        state.skin = Skin::ASCII;
        reduce(&mut state, key(KeyCode::Char('d')));
        let frame = rendered(120, 30, &state);
        let (repository_header_row, workflows) = frame
            .lines()
            .enumerate()
            .find_map(|(row, line)| {
                line.find("Workflows")
                    .map(|column| (u16::try_from(row).unwrap(), column as u16))
            })
            .unwrap();
        reduce(
            &mut state,
            mouse(
                MouseEventKind::Down(MouseButton::Left),
                workflows,
                repository_header_row,
            ),
        );
        assert_eq!(state.screen_model.dashboard_repository_sort, (1, false));
        let sorted = rendered(120, 30, &state);
        assert!(sorted.contains("Workflows ^"), "{sorted}");

        let (runner_header_row, status) = sorted
            .lines()
            .enumerate()
            .find_map(|(row, line)| {
                (line.contains("Runner") && line.contains("Status")).then(|| {
                    (
                        u16::try_from(row).unwrap(),
                        line.find("Status").unwrap() as u16,
                    )
                })
            })
            .unwrap();
        reduce(
            &mut state,
            mouse(
                MouseEventKind::Down(MouseButton::Left),
                status,
                runner_header_row,
            ),
        );
        assert_eq!(state.screen_model.dashboard_runner_sort, (1, false));
        reduce(
            &mut state,
            mouse(
                MouseEventKind::Down(MouseButton::Left),
                status,
                runner_header_row,
            ),
        );
        assert_eq!(state.screen_model.dashboard_runner_sort, (1, true));
    }

    #[test]
    fn durable_attempts_render_outcomes_retry_cleanup_and_remediation() {
        use runner_manager_domain::model::{AttemptId, PolicyId};

        let at = chrono::DateTime::parse_from_rfc3339("2026-08-23T10:00:00Z")
            .unwrap()
            .to_utc();
        let policy = PolicyId::from_u128(7);
        let mut idle = RunnerAttempt::allocate(AttemptId::from_u128(1), policy, "idle", at);
        idle.jit_received(at).unwrap();
        idle.started(10, at).unwrap();
        idle.registered_idle(100, at).unwrap();
        idle.conclude(AttemptOutcome::ExitedIdleWithoutWork, at)
            .unwrap();
        idle.clean(at).unwrap();
        let mut failed = RunnerAttempt::allocate(AttemptId::from_u128(2), policy, "failed", at);
        failed
            .conclude(
                AttemptOutcome::failed(FailureReason::RegistrationTimedOut),
                at,
            )
            .unwrap();
        let targets = HashMap::from([(policy, "acme/repo".to_owned())]);

        let rows = activity_rows(&[idle, failed], &targets);
        assert!(rows.iter().any(|row| {
            row.outcome == screens::ActivityOutcome::ExitedIdleWithoutWork
                && row.summary.contains("exited idle without accepting work")
        }));
        assert!(rows.iter().any(|row| {
            row.outcome == screens::ActivityOutcome::Failed
                && row.remediation.contains("network, DNS, proxy, firewall")
        }));
        assert!(
            rows.iter()
                .any(|row| row.outcome == screens::ActivityOutcome::Retry)
        );
        assert!(
            rows.iter()
                .any(|row| row.outcome == screens::ActivityOutcome::CleanupComplete)
        );
    }

    #[test]
    fn production_inventory_mapping_preserves_non_transport_meaning() {
        let root = tempfile::tempdir().unwrap();
        let mut warnings = Vec::new();
        let context = crate::cli::Context::resolve(Some(root.path()), &mut warnings).unwrap();
        let clock = context.clock();
        let offline = availability_from_refresh_state(&context, &clock, &RefreshState::Offline);
        let forbidden = availability_from_refresh_state(
            &context,
            &clock,
            &RefreshState::Forbidden {
                message: Some("missing administration grant".into()),
            },
        );
        let failed = availability_from_refresh_state(
            &context,
            &clock,
            &RefreshState::Failed {
                status: Some(500),
                message: "server error".into(),
            },
        );
        let cancelled = availability_from_refresh_state(&context, &clock, &RefreshState::Cancelled);
        assert!(matches!(offline, Availability::Offline { .. }));
        assert_eq!(
            forbidden,
            Availability::Forbidden {
                message: Some("missing administration grant".into())
            }
        );
        assert_eq!(
            failed,
            Availability::Failed {
                detail: "server error".into()
            }
        );
        assert_eq!(cancelled, Availability::Cancelled);
    }

    #[test]
    fn rate_limited_activity_opens_acknowledges_copies_and_survives_ready_refresh() {
        let row = screens::ActivityRow {
            id: "rate-limit-1".into(),
            occurred_at: "2026-08-23T10:00:00Z".into(),
            outcome: screens::ActivityOutcome::RateLimit,
            summary: "GitHub primary rate limit was reached".into(),
            remediation: "wait 90 seconds before retrying".into(),
        };
        let mut state = AppState::new(PresentationState::default(), 120, 30);
        reduce(
            &mut state,
            AppEvent::Agent(AgentEvent {
                summary: "rate limited".into(),
                health: Health::Error,
                privacy_access_denied: false,
                service_version: None,
                snapshot: Some(Snapshot {
                    availability: Availability::RateLimited {
                        retry_after_seconds: 90,
                    },
                    activity: vec![row],
                    ..Snapshot::default()
                }),
            }),
        );
        reduce(&mut state, key(KeyCode::Char('a')));
        let detail = screens::render_text(&state.screen_model);
        assert!(detail.contains("RATE LIMITED"), "{detail}");
        assert!(detail.contains("RATE-LIMIT"), "{detail}");
        assert!(
            detail.contains("wait 90 seconds before retrying"),
            "{detail}"
        );
        reduce(&mut state, key(KeyCode::Enter));
        assert!(screens::render_text(&state.screen_model).contains("[acknowledged]"));
        let Effect::Copy(copied) = &reduce(&mut state, key(KeyCode::Char('c')))[0] else {
            panic!("Activity copy effect")
        };
        assert!(copied.contains("wait 90 seconds before retrying"));

        reduce(
            &mut state,
            AppEvent::Agent(AgentEvent {
                summary: "ready again".into(),
                health: Health::Ready,
                privacy_access_denied: false,
                service_version: None,
                snapshot: Some(Snapshot {
                    availability: Availability::Ready,
                    ..Snapshot::default()
                }),
            }),
        );
        let retained = screens::render_text(&state.screen_model);
        assert!(retained.contains("RATE-LIMIT"), "{retained}");
        assert!(retained.contains("[acknowledged]"), "{retained}");
    }

    #[test]
    fn repeated_f5_cancels_stale_work_and_publishes_only_the_latest_collection() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        for round in 0..50 {
            let collections = Arc::new(AtomicUsize::new(0));
            let worker_collections = Arc::clone(&collections);
            let release_first = Arc::new((Mutex::new(false), Condvar::new()));
            let worker_release = Arc::clone(&release_first);
            let (first_started, first_started_rx) = std::sync::mpsc::sync_channel(0);
            let (source, mut events) = LocalAgentEventSource::start_with(
                move |_| {
                    let number = worker_collections.fetch_add(1, Ordering::SeqCst) + 1;
                    if number == 1 {
                        first_started.send(()).unwrap();
                        let (released, wake) = &*worker_release;
                        let mut released = released.lock().unwrap();
                        while !*released {
                            released = wake.wait(released).unwrap();
                        }
                    }
                    AgentEvent {
                        summary: format!("collection {number}"),
                        health: Health::Ready,
                        privacy_access_denied: false,
                        service_version: None,
                        snapshot: None,
                    }
                },
                Duration::from_secs(60),
            )
            .unwrap();
            first_started_rx
                .recv_timeout(Duration::from_secs(1))
                .unwrap();
            for _ in 0..100 {
                source.request_refresh().unwrap();
            }
            {
                let (released, wake) = &*release_first;
                *released.lock().unwrap() = true;
                wake.notify_one();
            }
            let published = events.blocking_recv().unwrap();
            assert_eq!(published.summary, "collection 2", "stress round {round}");
            assert!(matches!(
                events.try_recv(),
                Err(mpsc::error::TryRecvError::Empty)
            ));
            thread::sleep(Duration::from_millis(1));
            assert_eq!(
                collections.load(Ordering::SeqCst),
                2,
                "stress round {round}"
            );
            drop(source);
        }
    }

    #[test]
    fn drop_cancels_blocked_preflight_with_bounded_join_and_no_post_exit_calls() {
        use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

        let calls = Arc::new(AtomicUsize::new(0));
        let finished = Arc::new(AtomicBool::new(false));
        let worker_calls = Arc::clone(&calls);
        let worker_finished = Arc::clone(&finished);
        let (started, started_rx) = std::sync::mpsc::sync_channel(0);
        let (source, _events) = LocalAgentEventSource::start_with(
            move |cancel| {
                worker_calls.fetch_add(1, Ordering::SeqCst);
                started.send(()).unwrap();
                let runtime = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .unwrap();
                let result = runtime.block_on(
                    cancel
                        .run(async { std::future::pending::<Result<(), InventoryError>>().await }),
                );
                assert!(matches!(result, Err(InventoryError::Cancelled)));
                worker_finished.store(true, Ordering::SeqCst);
                AgentEvent {
                    summary: "cancelled blocked preflight".into(),
                    health: Health::Ready,
                    privacy_access_denied: false,
                    service_version: None,
                    snapshot: None,
                }
            },
            Duration::from_secs(60),
        )
        .unwrap();
        started_rx.recv_timeout(Duration::from_secs(1)).unwrap();
        let started_drop = Instant::now();
        drop(source);
        assert!(
            started_drop.elapsed() < Duration::from_millis(250),
            "quit waited {:?} for a cancelled preflight",
            started_drop.elapsed()
        );
        assert!(
            finished.load(Ordering::SeqCst),
            "Drop returned before worker exit"
        );
        let calls_at_exit = calls.load(Ordering::SeqCst);
        thread::sleep(Duration::from_millis(10));
        assert_eq!(calls.load(Ordering::SeqCst), calls_at_exit);
        assert_eq!(calls_at_exit, 1);
    }

    #[test]
    fn in_memory_frame_meets_budget_and_render_has_no_io_capability() {
        let mut state = AppState::new(PresentationState::default(), 120, 40);
        state.presentation.body = (0..100).map(|n| format!("row {n}")).collect();
        // --------------------------------------------------------------------
        // THE FRAME A USER ACTUALLY GETS, NOT THE EMPTY ONE.
        // --------------------------------------------------------------------
        // A default `AppState` is still `Loading`, which draws a three-line
        // panel and touches none of the table code -- the column solver, the
        // per-cell layout, and the sort behind every visible row -- that the
        // per-frame cost now lives in. Measuring that frame would have said
        // nothing about any of it.
        state.screen_model = ScreenModel::new(Snapshot {
            availability: Availability::Ready,
            repositories: (0..1_000)
                .map(|ordinal| RepositoryRow {
                    id: format!("repo-{ordinal}"),
                    target: format!("acme/repository-{ordinal:05}"),
                    in_progress_workflows: ordinal % 7,
                    mode: PolicyMode::Autoscale,
                    max_capacity: Some(4),
                    health: AgentHealth::Healthy,
                    host_label: Some("rm-home-win-x64".into()),
                    extra_labels: vec![],
                })
                .collect(),
            ..Snapshot::default()
        });
        state.open_screen(Screen::Repositories);

        // --------------------------------------------------------------------
        // THE FASTEST OF SEVERAL RENDERS, NOT THE FIRST ONE.
        // --------------------------------------------------------------------
        // The property is that drawing a frame costs less than one 60fps tick,
        // which is a statement about this code rather than about the machine it
        // happens to run on. A single cold measurement is not that: it carries
        // the first-touch page faults and allocator growth of the process's
        // first render, and on a shared CI runner it also carries whatever else
        // the host was doing during those microseconds. Measured: this
        // assertion failed the macOS leg of release 0.1.2 at step 3 -- before
        // the tag, so nothing was published, but a wall-clock coin flip had
        // just blocked a release.
        //
        // A warm-up render followed by the MINIMUM of several is the standard
        // reading of a noisy timer: noise can only ever make a sample slower,
        // so the smallest one is the closest to the cost being asserted. A
        // render that genuinely got slow fails every sample and still reds.
        let _warm_up = rendered(120, 40, &state);
        let fastest = (0..5)
            .map(|_| {
                let started = Instant::now();
                let _ = rendered(120, 40, &state);
                started.elapsed()
            })
            .min()
            .expect("five samples");
        assert!(
            fastest < FRAME_BUDGET,
            "frame exceeded {FRAME_BUDGET:?}: fastest of five renders took {fastest:?}"
        );
        let _structural_proof: fn(&mut Frame<'_>, &AppState) = render;

        let source = include_str!("shell.rs");
        let render_source = source
            .split_once("pub fn render(")
            .expect("render function")
            .1
            .split_once("const fn screen_key")
            .expect("end of render-only section")
            .0;
        for forbidden_capability in [
            "std::fs",
            "std::net",
            "reqwest",
            "Context",
            "Store",
            "Gateway",
            "File::",
            "TcpStream",
            "read_to_",
            "block_on",
            ".await",
        ] {
            assert!(
                !render_source.contains(forbidden_capability),
                "render acquired forbidden I/O capability {forbidden_capability:?}"
            );
        }
    }

    #[test]
    fn pressing_settings_with_no_repository_explains_rather_than_failing_to_parse() {
        // --------------------------------------------------------------------
        // THE SCREEN A NEW INSTALL ACTUALLY SEES.
        // --------------------------------------------------------------------
        // `s` used to send `unwrap_or_default()` -- an EMPTY target -- into the
        // policy loader on a host with no policies. The loader parsed it and
        // failed with "an organization login must not be empty": a parser's
        // complaint, shown to somebody whose only mistake was pressing a key
        // before adding a repository, on a screen that then sat on "Loading
        // settings..." forever because nothing was ever going to load.
        let mut state = AppState::new(PresentationState::default(), 120, 40);
        assert!(
            state.screen_model.snapshot.repositories.is_empty(),
            "this test is about the empty case, so it must start empty"
        );

        let effects = reduce(&mut state, key(KeyCode::Char('s')));

        assert!(
            effects.is_empty(),
            "nothing may be loaded when there is nothing to load: {effects:?}"
        );
        let screen = rendered(120, 30, &state);
        assert!(
            !screen.contains("must not be empty"),
            "a parser error must not reach the screen:\n{screen}"
        );
        assert!(
            !screen.contains("Loading settings..."),
            "and it must not claim to be loading something that never will:\n{screen}"
        );
        assert!(
            screen.contains("repo add"),
            "it must say what to do instead:\n{screen}"
        );
    }

    #[test]
    fn production_settings_keyboard_and_mouse_paths_render_edit_copy_and_persist() {
        use std::num::NonZeroU16;

        use runner_manager_domain::model::{
            Arch, CachePolicy, Host, HostId, HostLabel, Os, PolicyId, ScaleTarget,
        };
        use runner_manager_domain::policy::{PolicyMode as DomainMode, RoutingLabels, ScalePolicy};

        let root = tempfile::TempDir::new().unwrap();
        let context = crate::cli::Context::resolve(Some(root.path()), &mut Vec::new()).unwrap();
        let store = context.store().unwrap();
        let host = Host::new(
            HostId::from_u128(901),
            "production-settings-host",
            Os::Linux,
            Arch::X64,
            NonZeroU16::new(4).unwrap(),
            chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap(),
        )
        .unwrap();
        store.put_host(&host).unwrap();
        let target = ScaleTarget::repository("octo/production-settings").unwrap();
        let policy = ScalePolicy::new_for_host_label(
            PolicyId::from_u128(902),
            target.clone(),
            7,
            host.id,
            HostLabel::new("home").unwrap(),
            DomainMode::autoscale(
                RoutingLabels::derive(&HostLabel::new("home").unwrap(), Os::Linux, Arch::X64),
                0,
                NonZeroU16::new(2).unwrap(),
            )
            .unwrap(),
            CachePolicy::default(),
        );
        store.insert_policy(&policy).unwrap();
        drop(store);

        let mut state = AppState::new(PresentationState::default(), 120, 30);
        state.screen_model = ScreenModel::new(Snapshot {
            availability: Availability::Ready,
            repositories: vec![RepositoryRow {
                id: "production-settings".into(),
                target: target.to_string(),
                in_progress_workflows: 0,
                mode: PolicyMode::Autoscale,
                max_capacity: Some(2),
                health: AgentHealth::Healthy,
                host_label: Some("rm-home-win-x64".into()),
                extra_labels: vec![],
            }],
            ..Snapshot::default()
        });
        state.screen_model.repositories.selected_id = Some("production-settings".into());

        let host_nav = state
            .navigation
            .items
            .iter()
            .find(|item| item.screen == Screen::HostSettings)
            .unwrap()
            .area;
        let effects = reduce(
            &mut state,
            mouse(
                MouseEventKind::Down(MouseButton::Left),
                host_nav.x,
                host_nav.y,
            ),
        );
        let Effect::Settings(command) = effects.into_iter().next().unwrap() else {
            panic!("host navigation must load the form")
        };
        state.settings.execute(&context, command);
        assert!(rendered(120, 30, &state).contains("Current capacity: 4"));

        // Three mouse actions total for this form: open, edit, confirm.
        reduce(
            &mut state,
            mouse(MouseEventKind::Down(MouseButton::Left), 10, 6),
        );
        let effects = reduce(
            &mut state,
            mouse(MouseEventKind::Down(MouseButton::Left), 10, 12),
        );
        let Effect::Settings(command) = effects.into_iter().next().unwrap() else {
            panic!("host confirmation must dispatch")
        };
        state.settings.execute(&context, command);
        assert_eq!(
            crate::cli::host::local_host(&context.store().unwrap())
                .unwrap()
                .unwrap()
                .host_capacity(),
            5
        );

        let effects = reduce(&mut state, key(KeyCode::Char('s')));
        let Effect::Settings(command) = effects.into_iter().next().unwrap() else {
            panic!("s must load selected policy settings")
        };
        state.settings.execute(&context, command);
        assert!(rendered(120, 30, &state).contains("runs-on: rm-home-linux-x64"));

        // Four focused actions: enable, capacity, cache, confirm. Arrow moves
        // only move focus and are not form actions.
        for code in [
            KeyCode::Right,
            KeyCode::Down,
            KeyCode::Right,
            KeyCode::Down,
            KeyCode::Right,
        ] {
            reduce(&mut state, key(code));
        }
        let warning = rendered(120, 30, &state);
        assert!(
            warning.contains("fork and untrusted pull-request"),
            "{warning}"
        );
        let Effect::Copy(copy) = reduce(&mut state, key(KeyCode::Char('c'))).remove(0) else {
            panic!("c must expose the routing label")
        };
        assert_eq!(copy, "rm-home-linux-x64");
        reduce(&mut state, key(KeyCode::Down));
        let effects = reduce(&mut state, key(KeyCode::Enter));
        let Effect::Settings(command) = effects.into_iter().next().unwrap() else {
            panic!("policy confirmation must dispatch")
        };
        state.settings.execute(&context, command);
        let stored = context.store().unwrap().policies().unwrap().remove(0);
        assert!(stored.enabled());
        assert_eq!(stored.max_capacity().unwrap().get(), 3);
        assert_eq!(stored.cache_policy, CachePolicy::DiscardRunnerPackage);
    }

    // -----------------------------------------------------------------------
    // e1-workspace-tui
    // -----------------------------------------------------------------------

    /// A host and one repository policy, on a disposable data directory.
    fn workspace_context() -> (tempfile::TempDir, crate::cli::Context, ScaleTarget) {
        use std::num::NonZeroU16;

        use runner_manager_domain::model::{
            Arch, CachePolicy, Host, HostId, HostLabel, Os, PolicyId,
        };
        use runner_manager_domain::policy::{PolicyMode as DomainMode, RoutingLabels, ScalePolicy};

        let root = tempfile::TempDir::new().unwrap();
        let context = crate::cli::Context::resolve(Some(root.path()), &mut Vec::new()).unwrap();
        let store = context.store().unwrap();
        let host = Host::new(
            HostId::from_u128(801),
            "workspace-host",
            Os::Linux,
            Arch::X64,
            NonZeroU16::new(4).unwrap(),
            chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap(),
        )
        .unwrap();
        store.put_host(&host).unwrap();
        let target = ScaleTarget::repository("octo/workspace").unwrap();
        store
            .insert_policy(&ScalePolicy::new_for_host_label(
                PolicyId::from_u128(802),
                target.clone(),
                7,
                host.id,
                HostLabel::new("home").unwrap(),
                DomainMode::autoscale(
                    RoutingLabels::derive(&HostLabel::new("home").unwrap(), Os::Linux, Arch::X64),
                    0,
                    NonZeroU16::new(2).unwrap(),
                )
                .unwrap(),
                CachePolicy::default(),
            ))
            .unwrap();
        drop(store);
        (root, context, target)
    }

    /// Opens Host Settings the way an operator does — the `h` key, then the
    /// load the shell's effect boundary hands back.
    fn open_host_settings(state: &mut AppState, context: &crate::cli::Context) {
        let effects = reduce(state, key(KeyCode::Char('h')));
        let Effect::Settings(command) = effects.into_iter().next().unwrap() else {
            panic!("h must load the host form")
        };
        state.settings.execute(context, command);
    }

    /// Walks the focus to one control with the arrow keys alone.
    ///
    /// Deliberately not `state.settings.focus = n`: a control that cannot be
    /// reached from the keyboard is an accessibility defect, and assigning the
    /// index would hide it.
    fn focus_control(state: &mut AppState, control: settings::Control) {
        let index = state
            .settings
            .controls()
            .iter()
            .position(|candidate| *candidate == control)
            .unwrap_or_else(|| panic!("{control:?} is not on this screen"));
        for _ in 0..index {
            reduce(state, key(KeyCode::Down));
        }
        assert_eq!(state.settings.focused(), Some(control));
    }

    /// The reducer's half of `05-user-workflows.md`'s interaction rules.
    ///
    /// A path control that did not own the keyboard was the whole risk here:
    /// every letter on these screens is a navigation shortcut, so typing
    /// `C:\home\rman` would have jumped to Host Settings on the `h`, opened
    /// Repositories on the `r`, and quit on nothing at all — while the field
    /// stayed empty.
    #[test]
    fn typing_a_path_owns_the_keyboard_and_a_pasted_secret_is_redacted_first() {
        let (_root, context, _target) = workspace_context();
        let mut state = AppState::new(
            PresentationState {
                access_token: Some("ghu_this_must_not_escape".into()),
                ..PresentationState::default()
            },
            120,
            30,
        );

        open_host_settings(&mut state, &context);

        // Open the path editor with the keyboard alone.
        focus_control(&mut state, settings::Control::HostRunnerRoot);
        reduce(&mut state, key(KeyCode::Enter));
        assert!(state.settings.is_editing());

        for character in "C:/home/rman".chars() {
            reduce(&mut state, key(KeyCode::Char(character)));
        }
        assert_eq!(state.settings.host_root.text(), "C:/home/rman");
        assert_eq!(
            state.screen,
            Screen::HostSettings,
            "no letter typed into a path may navigate"
        );
        assert!(!state.should_exit, "and none of them may quit");

        // A modified chord is a command, not a character.
        reduce(
            &mut state,
            AppEvent::Key(KeyEvent {
                code: KeyCode::Char('c'),
                modifiers: KeyModifiers::CONTROL,
                kind: KeyEventKind::Press,
                state: KeyEventState::NONE,
            }),
        );
        assert_eq!(state.settings.host_root.text(), "C:/home/rman");

        // Bracketed paste reaches the field, and a credential in it does not.
        reduce(
            &mut state,
            AppEvent::Paste("/srv/ghu_this_must_not_escape".into()),
        );
        let typed = state.settings.host_root.text();
        assert!(typed.contains(REDACTED), "{typed}");
        assert!(!typed.contains("ghu_this_must_not_escape"), "{typed}");
        assert!(
            !rendered(120, 30, &state).contains("ghu_this_must_not_escape"),
            "a pasted credential must never be drawn"
        );

        // Escape leaves the editor without leaving the screen.
        reduce(&mut state, key(KeyCode::Esc));
        assert!(!state.settings.is_editing());
        assert_eq!(state.screen, Screen::HostSettings);
    }

    /// Navigating away with the mouse closes the editor that owns the keyboard.
    ///
    /// The editor swallows every key, so the navigation bar is the one way out
    /// of a settings screen it cannot intercept. Left open, it went on
    /// swallowing keys on the screen the operator had moved to: `q` typed a `q`
    /// into a field nothing was drawing any more, and the TUI could not be
    /// quit.
    #[test]
    fn leaving_a_settings_screen_by_mouse_closes_the_path_editor() {
        let (_root, context, _target) = workspace_context();
        let mut state = AppState::new(PresentationState::default(), 120, 30);
        open_host_settings(&mut state, &context);
        focus_control(&mut state, settings::Control::HostRunnerRoot);
        reduce(&mut state, key(KeyCode::Enter));
        assert!(state.settings.is_editing());

        let dashboard = state
            .navigation
            .items
            .iter()
            .find(|item| item.screen == Screen::Dashboard)
            .expect("the navigation bar always offers the dashboard")
            .area;
        reduce(
            &mut state,
            mouse(
                MouseEventKind::Down(MouseButton::Left),
                dashboard.x,
                dashboard.y,
            ),
        );
        assert_eq!(state.screen, Screen::Dashboard);
        assert!(
            !state.settings.is_editing(),
            "a field no frame draws may not keep the keyboard"
        );

        reduce(&mut state, key(KeyCode::Char('q')));
        assert!(state.should_exit, "q must still quit");
    }

    /// The key help names the path-control keys, because a control whose only
    /// documentation is that it happens to respond to Enter is not discoverable.
    #[test]
    fn the_key_help_names_the_path_control_keys() {
        let mut state = AppState::new(PresentationState::default(), 120, 30);
        state.help_open = true;
        let help = rendered(120, 30, &state);
        for control in ["Path fields", "Enter edit", "Esc cancel", "Enter accept"] {
            assert!(help.contains(control), "{control} missing from {help}");
        }
    }

    /// `c` copies the path the operator is looking at rather than the
    /// diagnostics buffer.
    #[test]
    fn c_copies_the_focused_path_control_on_a_settings_screen() {
        let (_root, context, _target) = workspace_context();
        let mut state = AppState::new(PresentationState::default(), 120, 30);
        open_host_settings(&mut state, &context);
        focus_control(&mut state, settings::Control::HostRunnerRoot);
        let Effect::Copy(copied) = reduce(&mut state, key(KeyCode::Char('c'))).remove(0) else {
            panic!("c must copy the focused path")
        };
        let SettingsView::Host(form) = &state.settings.view else {
            unreachable!()
        };
        assert_eq!(copied, form.runner_root.rendered());
    }

    /// The mouse map and the keyboard walk resolve to the same control, at the
    /// same row, in both layouts.
    ///
    /// This is the assertion the old hard-coded row table could not make: it
    /// listed row numbers, so adding a control above one of them moved a click
    /// from *Save* to *Reset* with nothing to catch it.
    #[test]
    fn a_click_reaches_the_control_the_frame_drew_on_that_row() {
        let (_root, context, target) = workspace_context();
        for (width, height) in [(120u16, 30u16), (58, 20)] {
            let mut state = AppState::new(PresentationState::default(), width, height);
            state.size = Rect::new(0, 0, width, height);
            state.screen = Screen::RepositorySettings;
            state
                .settings
                .execute(&context, SettingsCommand::LoadPolicy(target.to_string()));

            let compact = compact_layout(state.size);
            let content_width = settings::content_width(width);
            let rows = state.settings.control_rows(content_width, compact);
            let (offset, expected) = rows
                .iter()
                .enumerate()
                .find_map(|(index, control)| {
                    control.map(|control| (u16::try_from(index).unwrap(), control))
                })
                .expect("a settings frame always draws at least one control");

            let effects = reduce(
                &mut state,
                mouse(
                    MouseEventKind::Down(MouseButton::Left),
                    4,
                    SETTINGS_FIRST_ROW + offset,
                ),
            );
            assert_eq!(
                state.settings.focus, expected,
                "width={width}: a click must focus the control drawn on that row"
            );
            assert!(
                effects.len() <= 1,
                "one click is at most one effect: {effects:?}"
            );
        }
    }
}