devsandbox 0.9.0

Manage devcontainer-style sandboxes on docker, podman, or Apple container — many throwaway instances per repo from one TOML config.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
//! Immediate-mode rendering for the dashboard. Layout: tab bar on top, content
//! area in the middle, help bar at the bottom. The Instances tab renders real
//! data from the latest snapshot.

use ratatui::Frame;
use ratatui::layout::{Alignment, Constraint, Layout, Position, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Borders, Cell, Paragraph, Row, Table, TableState};
use tui_term::widget::{Cursor, PseudoTerminal};

use super::app::{
    chip, form_lines, form_title, forms_offset, pane_feed, pane_header, pinned_forms, short_age, title_of, App,
    BuildLogModal, ConfigView, ConfirmModal, Extract, Focus, FormSpot, HeaderRow, HelpModal, InboxFocus, Modal, PaneLine, Pane, PortRow, Side, Tab,
    TextModal, Thread, Tone, View,
};
use super::settings::SETTINGS;
use super::data::{
    humanize_secs, identity_line, sandbox_stats, totals_line, ContainerStatus, InstanceRow, Node, SandboxRow,
    ServiceRow, Snapshot,
};
use super::procs::{is_agent, ProcState, MESSAGE_ROW};
use super::markdown;
use super::prompt::Prompt;
use super::textarea::{self, TextArea};
use super::select::{self, RegionId};
use crate::devsbd::notify::Level;
use crate::inbox::{Kind, State};
use crate::render::JsonLine;
use crate::snapshot::PhaseRow;

pub(super) const ACCENT: Color = Color::Rgb(175, 135, 255);
const SELECTION: Color = Color::Rgb(0, 215, 135);

pub fn draw(frame: &mut Frame, app: &App) {
    // Every pane drawn below registers its selectable text area anew.
    app.clear_regions();
    // The prompt needs a second bottom line for its candidates/error hint.
    let bottom = if app.prompt.is_some() { 2 } else { 1 };
    let [tab_area, content_area, bottom_area] = Layout::vertical([
        Constraint::Length(1),
        Constraint::Min(0),
        Constraint::Length(bottom),
    ])
    .areas(frame.area());

    draw_tabs(frame, app, tab_area);
    draw_content(frame, app, content_area);
    if let Some(prompt) = &app.prompt {
        draw_prompt(frame, prompt, bottom_area);
    } else {
        draw_help(frame, app, bottom_area);
    }

    // A modal draws over everything, using the full frame: only its own
    // regions may be hit, not the panes it hides.
    if !matches!(app.modal, Modal::None) {
        app.clear_regions();
    }
    match &app.modal {
        Modal::None => {}
        Modal::Config(view) => draw_config_modal(frame, app, view),
        Modal::Help(view) => draw_help_modal(frame, app, view),
        Modal::Logs(view) => draw_text_modal(frame, app, view),
        Modal::BuildLog(view) => draw_build_log_modal(frame, app, view),
        Modal::Confirm(view) => draw_confirm_modal(frame, view),
    }

    // Last, so nothing drawn hides it; and the copy (or the count a release
    // without copy on select shows) reads the very cells this frame shows.
    let extract = app.take_extract_request();
    if let Some((region, sel)) = app.selection_in_frame() {
        let buf = frame.buffer_mut();
        if let Some(extract) = extract {
            let text = match region.source {
                // Off the vt100 screen, scrollback included; the panel's
                // lock is long released.
                select::Source::Terminal { .. } => terminal_selection_text(app, &sel),
                _ => select::extract(buf, &region, &sel),
            };
            match extract {
                Extract::Copy => app.set_clipboard(text),
                Extract::Measure => app.set_measured(&text),
            }
        }
        select::highlight(buf, &region, &sel);
    }
}

/// The text of a terminal selection, read from the active session's screen.
fn terminal_selection_text(app: &App, sel: &select::Selection) -> String {
    let Some(Ok(mut parser)) = app.terms.active_session().map(|s| s.parser().lock()) else {
        return String::new();
    };
    let (from, to) = sel.range();
    select::extract_terminal(parser.screen_mut(), from, to)
}

/// Register the inner text area of a bordered pane drawn at `area` as
/// selectable. Every dashboard pane is a `Borders::ALL` block with its title
/// on the top border, so the inner rect is the same as the drawn block's.
fn selectable(app: &App, id: RegionId, area: Rect) {
    app.add_region(id, Block::bordered().inner(area));
}

/// The tab bar row's `(tabs, totals)` split, plus the totals text. The
/// right-aligned totals share the row; the tabs take the rest. Shared by the
/// draw path and [`tab_hit`], so a click can't land on a clipped title.
fn tab_bar_areas(app: &App, area: Rect) -> (Rect, Rect, Option<String>) {
    let totals = app
        .snapshot
        .as_ref()
        .map(|s| {
            let line = totals_line(s, s.collected_at.elapsed(), app.snapshot_error.as_ref());
            // A machine with no rows yet says why in place of its rows, when
            // that leaves the tabs their room.
            let tabs_w = tab_spans(app).last().map_or(0, |(_, _, r)| r.end);
            let with = |why| super::remote::pending_note(&app.machines, s, why).map(|note| format!("{note} · {line}"));
            match with(true) {
                Some(full) if tabs_w + full.chars().count() as u16 + 2 <= area.width => full,
                _ => with(false).unwrap_or(line),
            }
        });
    let totals_w = totals.as_deref().map_or(0, |t| t.chars().count() as u16);
    // Leave a gap before the totals; drop them entirely when the row is too narrow.
    let reserve = if totals_w > 0 && area.width > totals_w + 4 {
        totals_w + 2
    } else {
        0
    };
    let [tabs_area, totals_area] =
        Layout::horizontal([Constraint::Min(0), Constraint::Length(reserve)]).areas(area);
    (tabs_area, totals_area, (reserve > 0).then_some(totals).flatten())
}

/// Padding on each side of a tab title, and the divider between tabs: what
/// ratatui's `Tabs` drew (its default padding, our `" "` divider) before the
/// bar was rendered by hand for click hit-testing.
const TAB_PAD: u16 = 1;
const TAB_DIVIDER: u16 = 1;

/// Every listed tab ([`App::tabs`]) with its title and the columns it covers
/// (title plus its padding), relative to the tab area's left edge and
/// unclipped. The one layout both [`draw_tabs`] and [`tab_hit`] read, so a
/// click lands on the tab drawn there; `Tabs`' internal layout isn't exposed
/// to mirror.
pub(crate) fn tab_spans(app: &App) -> Vec<(Tab, String, std::ops::Range<u16>)> {
    let mut x = 0;
    app.tabs()
        .into_iter()
        .map(|tab| {
            let title = app.tab_title(tab);
            let end = x + TAB_PAD + cols(&title) as u16 + TAB_PAD;
            let span = (tab, title, x..end);
            x = end + TAB_DIVIDER;
            span
        })
        .collect()
}

/// The tab under a click at `(col, row)` on a frame of size `frame`: the tab
/// bar is the frame's first row (see [`draw`]).
pub(crate) fn tab_hit(app: &App, frame: Rect, col: u16, row: u16) -> Option<Tab> {
    if row != frame.y || frame.height == 0 {
        return None;
    }
    let (tabs_area, _, _) = tab_bar_areas(app, Rect { height: 1, ..frame });
    if col < tabs_area.x || col >= tabs_area.right() {
        return None;
    }
    let rel = col - tabs_area.x;
    tab_spans(app).into_iter().find(|(_, _, r)| r.contains(&rel)).map(|(t, _, _)| t)
}

fn draw_tabs(frame: &mut Frame, app: &App, area: Rect) {
    let (tabs_area, totals_area, totals) = tab_bar_areas(app, area);

    let highlight = Style::default().fg(ACCENT).add_modifier(Modifier::BOLD);
    let pad = " ".repeat(TAB_PAD as usize);
    let mut spans = Vec::new();
    for (i, (tab, title, _)) in tab_spans(app).into_iter().enumerate() {
        if i > 0 {
            spans.push(Span::raw(" ".repeat(TAB_DIVIDER as usize)));
        }
        let style = if tab == app.tab { highlight } else { Style::default() };
        spans.push(Span::raw(pad.clone()));
        spans.push(Span::styled(title, style));
        spans.push(Span::raw(pad.clone()));
    }
    frame.render_widget(Paragraph::new(Line::from(spans)), tabs_area);

    if let Some(totals) = totals {
        let line = Line::from(Span::styled(totals, Style::default().add_modifier(Modifier::DIM)))
            .alignment(Alignment::Right);
        frame.render_widget(Paragraph::new(line), totals_area);
    }
}

fn draw_content(frame: &mut Frame, app: &App, area: Rect) {
    match app.tab {
        Tab::Instances => draw_instances(frame, app, area),
        Tab::Services => draw_services(frame, app, area),
        Tab::Ports => draw_ports(frame, app, area),
        Tab::Inbox => draw_inbox(frame, app, area),
        Tab::Machines => draw_machines(frame, app, area),
    }
}

/// Split a tab's content `area` into the top part (error line + table) and the
/// bottom section (Detail, plus the terminal panel when terminals are open).
///
/// The split is deliberately independent of snapshot state: the error line is
/// carved *inside* `top` by the caller, never here. That keeps the bottom
/// geometry — and therefore [`term_pane_size`] — a pure function of the frame
/// size and whether any terminal exists, so the event loop's PTY-resize math
/// can't drift from what the draw path actually laid out.
///
/// Returns `(top, detail, Some(terms))` when `!app.terms.is_empty()`: the bottom
/// section is 50% of the content area, split `[Detail 30%, terminal Min(0)]`.
/// Returns `(top, detail, None)` otherwise: today's `Length(9)` full-width
/// Detail, no terminal panel.
fn content_areas(app: &App, area: Rect) -> (Rect, Rect, Option<Rect>) {
    if app.terms.is_empty() {
        let [top, detail] =
            Layout::vertical([Constraint::Min(0), Constraint::Length(9)]).areas(area);
        (top, detail, None)
    } else {
        let (top, detail, terms) = open_bottom_split(area);
        (top, detail, Some(terms))
    }
}

/// The terminals-open split of a content area: `(top, detail, terminal panel)`.
/// The single home for the 50% bottom / 30-70 horizontal constants, shared by
/// the draw path ([`content_areas`]) and the PTY-sizing math ([`term_pane_size`])
/// so the two cannot drift.
fn open_bottom_split(area: Rect) -> (Rect, Rect, Rect) {
    let [top, bottom] =
        Layout::vertical([Constraint::Min(0), Constraint::Percentage(50)]).areas(area);
    let [detail, terms] =
        Layout::horizontal([Constraint::Percentage(30), Constraint::Min(0)]).areas(bottom);
    (top, detail, terms)
}

/// `(rows, cols)` of the active terminal's *inner* screen — the terminal panel
/// Rect minus its one-cell block border on each side. Derived from the same
/// layout functions the draw path uses ([`draw`] for the bottom-bar height,
/// [`content_areas`] for the panel), so the event loop can size the PTY to
/// exactly what gets rendered. Returns `None` when no terminal panel is laid out.
pub fn term_pane_size(frame: Rect, prompt_open: bool) -> Option<(u16, u16)> {
    let panel = terminal_panel_rect(frame, prompt_open);
    // Inner screen = panel minus the block border (1 cell each side).
    let rows = panel.height.saturating_sub(2);
    let cols = panel.width.saturating_sub(2);
    if rows == 0 || cols == 0 {
        None
    } else {
        Some((rows, cols))
    }
}

/// The full terminal-panel Rect (border included) for a frame of size `frame`,
/// mirroring `draw()`'s vertical split and the `open_bottom_split` bottom split.
/// Independent of whether terminals are actually open — callers gate on
/// `!app.terms.is_empty()` — so the mouse hit-test and the PTY-size math share
/// exactly one layout definition. `pub(crate)` for the event loop's mouse routing.
pub(crate) fn terminal_panel_rect(frame: Rect, prompt_open: bool) -> Rect {
    let (_top, _detail, panel) = open_bottom_split(frame_content_area(frame, prompt_open));
    panel
}

/// The content area of a frame of size `frame`, mirroring `draw()`'s vertical
/// split: tab bar (1), content (Min 0), bottom bar (2 rows with the prompt
/// open, else 1). Shared by the mouse hit-tests that only know the frame size.
fn frame_content_area(frame: Rect, prompt_open: bool) -> Rect {
    let bottom = if prompt_open { 2 } else { 1 };
    let [_tab_area, content_area, _bottom_area] = Layout::vertical([
        Constraint::Length(1),
        Constraint::Min(0),
        Constraint::Length(bottom),
    ])
    .areas(frame);
    content_area
}

/// Mouse hit-test for the terminal panel's tab strip. Given the panel Rect, the
/// focus flag (a focused panel prepends the `▶ ` mark, shifting labels right),
/// and a click `(col, row)`, return the index of the tab whose label span the
/// click lands on — or `None` when the click is not on the title row or misses
/// every label. The label spans are derived from the SAME strings the strip
/// renders ([`terminal_tab_labels`]), so a hit can only land where a tab is drawn.
pub(crate) fn terminal_tab_hit(
    app: &App,
    panel: Rect,
    focused: bool,
    col: u16,
    row: u16,
) -> Option<usize> {
    // The tab strip lives in the block's top border row.
    if row != panel.y {
        return None;
    }
    // Title starts one cell in from the left border corner, then the focus mark.
    let mut x = panel.x + 1;
    if focused {
        x += FOCUS_MARK_WIDTH;
    }
    for (i, label) in terminal_tab_labels(app).into_iter().enumerate() {
        if i > 0 {
            x += TAB_SEP_WIDTH; // the two-space separator between tabs
        }
        let width = label.chars().count() as u16;
        if col >= x && col < x + width {
            return Some(i);
        }
        x += width;
    }
    None
}

/// The lines above a view's table, each one row and only while it has
/// something to say: the red `Snapshot.error`, then the yellow
/// [`identity_line`]. Returns what's left of `top` for the table.
fn draw_status_lines(frame: &mut Frame, snapshot: Option<&Snapshot>, top: Rect) -> Rect {
    let error = snapshot.and_then(|s| s.error.as_deref());
    let identity = snapshot.and_then(identity_line);
    let [err_area, identity_area, rest] = Layout::vertical([
        Constraint::Length(if error.is_some() { 1 } else { 0 }),
        Constraint::Length(if identity.is_some() { 1 } else { 0 }),
        Constraint::Min(0),
    ])
    .areas(top);
    if let Some(err) = error {
        let line = Line::from(Span::styled(err.to_string(), Style::default().fg(Color::Red)));
        frame.render_widget(Paragraph::new(line), err_area);
    }
    if let Some(text) = identity {
        let line = Line::from(Span::styled(text, Style::default().fg(Color::Yellow)));
        frame.render_widget(Paragraph::new(line), identity_area);
    }
    rest
}

/// Display width of the `▶ ` focus mark prepended to the tab strip when the
/// terminal is focused (`▶` is one column plus a trailing space).
const FOCUS_MARK_WIDTH: u16 = 2;
/// Width of the two-space separator between tab labels.
const TAB_SEP_WIDTH: u16 = 2;

fn draw_services(frame: &mut Frame, app: &App, area: Rect) {
    let snapshot = app.snapshot.as_ref();
    let rows: &[ServiceRow] = snapshot.map_or(&[], |s| s.services.as_slice());

    let (top, detail_area, terms_area) = content_areas(app, area);
    // Carve the status lines out of the top part (never the bottom), so the
    // terminal panel's geometry stays independent of snapshot state.
    let table_area = draw_status_lines(frame, snapshot, top);

    // Terminal focused ⇒ the terminal panel is the accented one; dim the rest.
    let panel_focused = app.focus == Focus::Terminal;

    if rows.is_empty() {
        draw_services_empty(frame, table_area, panel_focused);
        draw_service_detail(frame, None, detail_area, panel_focused);
    } else {
        draw_services_table(frame, app, rows, table_area, panel_focused);
        draw_service_detail(frame, rows.get(app.selected()), detail_area, panel_focused);
    }
    selectable(app, RegionId::ServicesTable, table_area);
    selectable(app, RegionId::ServiceDetail, detail_area);
    if let Some(terms_area) = terms_area {
        draw_terminal_panel(frame, app, terms_area);
    }
}

fn draw_services_empty(frame: &mut Frame, area: Rect, term_focused: bool) {
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(dash_border_style(term_focused))
        .title(Tab::Services.title());
    let text = Line::from(Span::styled(
        "no services defined in devsandboxes.toml",
        Style::default().add_modifier(Modifier::DIM),
    ))
    .alignment(Alignment::Center);
    frame.render_widget(Paragraph::new(text).block(block), area);
}

fn draw_services_table(
    frame: &mut Frame,
    app: &App,
    rows: &[ServiceRow],
    area: Rect,
    term_focused: bool,
) {
    let header = Row::new(
        ["NAME", "SCOPE", "SOURCE", "PORTS", "STATUS", "USED BY"]
            .into_iter()
            .map(Cell::from),
    )
    .style(Style::default().add_modifier(Modifier::DIM));

    let table_rows: Vec<Row> = rows.iter().map(service_row).collect();

    let widths = [
        Constraint::Length(14),
        Constraint::Length(9),
        Constraint::Min(20),
        Constraint::Length(14),
        Constraint::Length(12),
        Constraint::Min(12),
    ];

    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(dash_border_style(term_focused))
        .title(Tab::Services.title());

    let table = Table::new(table_rows, widths)
        .header(header)
        .block(block)
        .column_spacing(1)
        .row_highlight_style(Style::default().fg(SELECTION).add_modifier(Modifier::BOLD));

    let mut state = TableState::default().with_selected(Some(app.selected()));
    frame.render_stateful_widget(table, area, &mut state);
}

fn service_row(r: &ServiceRow) -> Row<'_> {
    let ports = if r.ports.is_empty() {
        "-".to_string()
    } else {
        r.ports.join(",")
    };
    let used_by = if r.used_by.is_empty() {
        "-".to_string()
    } else {
        r.used_by.join(",")
    };
    // Drifted services get a subtle yellow `!` suffix on the NAME cell (the
    // Instances tab only shows drift in the Detail panel; the Services table is
    // flatter, so a name marker is the least-noisy live signal). The Detail
    // panel spells the drift out.
    let name = if r.drift {
        Cell::from(Line::from(vec![
            Span::raw(r.name.clone()),
            Span::styled(" !", Style::default().fg(Color::Yellow)),
        ]))
    } else {
        Cell::from(r.name.clone())
    };
    Row::new(vec![
        name,
        Cell::from(Span::styled(r.scope.clone(), scope_style(&r.scope))),
        Cell::from(Span::styled(r.source.clone(), source_style(&r.source))),
        Cell::from(ports),
        service_status_cell(r),
        Cell::from(used_by),
    ])
}

fn scope_style(scope: &str) -> Style {
    match scope {
        "global" => Style::default().fg(Color::Blue),
        _ => Style::default().fg(Color::Magenta),
    }
}

/// Color the SOURCE column like `ls`: image green, dockerfile yellow, `?` dim.
fn source_style(source: &str) -> Style {
    if source.starts_with("image ") {
        Style::default().fg(Color::Green)
    } else if source.starts_with("dockerfile ") {
        Style::default().fg(Color::Yellow)
    } else {
        Style::default().add_modifier(Modifier::DIM)
    }
}

/// Summarize a service's backing containers into one STATUS cell: `N running`
/// (green) when any are up, else `N exited` (red) when any exist, else `-` dim
/// (`…` dim while the runtime hasn't been listed yet).
fn service_status_cell(r: &ServiceRow) -> Cell<'static> {
    if r.containers.iter().any(|(_, s)| *s == ContainerStatus::Unknown) {
        return Cell::from(Span::styled("…", Style::default().add_modifier(Modifier::DIM)));
    }
    let running = r
        .containers
        .iter()
        .filter(|(_, s)| matches!(s, ContainerStatus::Running(_)))
        .count();
    let present = r
        .containers
        .iter()
        .filter(|(_, s)| !matches!(s, ContainerStatus::Missing))
        .count();
    if running > 0 {
        Cell::from(Span::styled(
            format!("{running} running"),
            Style::default().fg(Color::Green),
        ))
    } else if present > 0 {
        Cell::from(Span::styled(
            format!("{present} exited"),
            Style::default().fg(Color::Red),
        ))
    } else {
        Cell::from(Span::styled("-", Style::default().add_modifier(Modifier::DIM)))
    }
}

fn draw_service_detail(
    frame: &mut Frame,
    row: Option<&ServiceRow>,
    area: Rect,
    term_focused: bool,
) {
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(dash_border_style(term_focused))
        .title("Detail");

    let Some(r) = row else {
        frame.render_widget(Paragraph::new("").block(block), area);
        return;
    };

    let mut lines: Vec<Line> = Vec::new();
    if r.containers.is_empty() {
        lines.push(Line::from(Span::styled(
            "no containers",
            Style::default().add_modifier(Modifier::DIM),
        )));
    } else {
        for (name, status) in &r.containers {
            lines.push(Line::from(vec![
                Span::raw(name.clone()),
                Span::raw("  "),
                Span::styled(status.label().to_string(), status_style(status)),
            ]));
        }
    }
    let ports = if r.ports.is_empty() {
        "-".to_string()
    } else {
        r.ports.join(",")
    };
    lines.push(kv("ports", &ports));
    lines.push(kv("env", &r.env_len.to_string()));
    if let Some(cmd) = &r.command {
        lines.push(kv("command", cmd));
    }
    if !r.config_hash.is_empty() {
        lines.push(kv("config hash", &r.config_hash));
    }
    if r.drift {
        lines.push(Line::from(Span::styled(
            "drift: config or dockerfile changed since the container was created (:rebuild)",
            Style::default().fg(Color::Yellow),
        )));
    }

    frame.render_widget(Paragraph::new(lines).block(block), area);
}

fn draw_ports(frame: &mut Frame, app: &App, area: Rect) {
    let rows: &[PortRow] = &app.ports;

    let (top, detail_area, terms_area) = content_areas(app, area);
    // The Ports tab has no snapshot error line; keep the top part whole.
    let panel_focused = app.focus == Focus::Terminal;

    if rows.is_empty() {
        draw_ports_empty(frame, top, panel_focused);
    } else {
        draw_ports_table(frame, app, rows, top, panel_focused);
    }
    selectable(app, RegionId::PortsTable, top);
    // No per-row detail for forwards; a plain block keeps the layout aligned with
    // the other tabs (and reserves the terminal-panel geometry).
    let detail = Block::default()
        .borders(Borders::ALL)
        .border_style(dash_border_style(panel_focused))
        .title("Detail");
    frame.render_widget(Paragraph::new("").block(detail), detail_area);
    if let Some(terms_area) = terms_area {
        draw_terminal_panel(frame, app, terms_area);
    }
}

fn draw_ports_empty(frame: &mut Frame, area: Rect, term_focused: bool) {
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(dash_border_style(term_focused))
        .title(Tab::Ports.title());
    let text = Line::from(Span::styled(
        "no forwards — press p on an instance or service, or :port <instance> <port>",
        Style::default().add_modifier(Modifier::DIM),
    ))
    .alignment(Alignment::Center);
    frame.render_widget(Paragraph::new(text).block(block), area);
}

fn draw_ports_table(
    frame: &mut Frame,
    app: &App,
    rows: &[PortRow],
    area: Rect,
    term_focused: bool,
) {
    let mut titles = vec!["LOCAL", "TARGET", "PROCESS", "STATE", "CONNS"];
    let mut widths = vec![
        Constraint::Length(20),
        Constraint::Min(24),
        Constraint::Length(18),
        Constraint::Length(14),
        Constraint::Length(6),
    ];
    // MACHINE like the Instances tab's: only once a machine is registered
    // (or a row reaches one), after the first column.
    let show_machine = !app.machines.is_empty() || rows.iter().any(|r| r.machine.is_some());
    if show_machine {
        let names = app.machines.iter().map(|m| m.name.chars().count());
        let row_names = rows.iter().filter_map(|r| r.machine.as_ref()).map(|m| m.chars().count());
        let width = names.chain(row_names).max().unwrap_or(0).max("MACHINE".len());
        titles.insert(1, "MACHINE");
        widths.insert(1, Constraint::Length(width as u16));
    }
    let header = Row::new(titles.into_iter().map(Cell::from))
        .style(Style::default().add_modifier(Modifier::DIM));

    let table_rows: Vec<Row> = rows.iter().map(|r| port_row(r, show_machine)).collect();

    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(dash_border_style(term_focused))
        .title(Tab::Ports.title());

    let table = Table::new(table_rows, widths)
        .header(header)
        .block(block)
        .column_spacing(1)
        .row_highlight_style(Style::default().fg(SELECTION).add_modifier(Modifier::BOLD));

    let mut state = TableState::default().with_selected(Some(app.selected()));
    frame.render_stateful_widget(table, area, &mut state);
}

/// One forward's cells. With the MACHINE column, a remote target's own
/// `<machine>/` prefix (the daemon's label) is left to that column.
fn port_row(r: &PortRow, show_machine: bool) -> Row<'_> {
    let process = r.process.clone().unwrap_or_else(|| "-".to_string());
    let label = match &r.machine {
        Some(m) if show_machine => r.target.strip_prefix(&format!("{m}/")).unwrap_or(&r.target).to_string(),
        _ => r.target.clone(),
    };
    let mut target = vec![Span::raw(label)];
    if r.configured {
        target.push(Span::styled(" (config)", Style::default().add_modifier(Modifier::DIM)));
    }
    let mut cells = vec![Cell::from(r.local.clone())];
    if show_machine {
        cells.push(Cell::from(Span::styled(r.machine.clone().unwrap_or_default(), Style::default().fg(ACCENT))));
    }
    cells.extend([
        Cell::from(Line::from(target)),
        Cell::from(process),
        Cell::from(Span::styled(r.state.clone(), port_state_style(&r.state))),
        Cell::from(r.conns.to_string()),
    ]);
    Row::new(cells)
}

/// Color the STATE column like the siblings: active green, connecting yellow,
/// error red; anything else uncolored.
fn port_state_style(state: &str) -> Style {
    if state == "active" {
        Style::default().fg(Color::Green)
    } else if state == "connecting" {
        Style::default().fg(Color::Yellow)
    } else if state.starts_with("error") {
        Style::default().fg(Color::Red)
    } else {
        Style::default()
    }
}

/// The registered machines, in the snapshot's order: rows laid out like the
/// Ports tab; `a` changes `agent` through `machines.set`
/// (docs/architecture/dashboard/tabs-and-actions.md, *Tabs*).
fn draw_machines(frame: &mut Frame, app: &App, area: Rect) {
    let (top, detail_area, terms_area) = content_areas(app, area);
    let panel_focused = app.focus == Focus::Terminal;

    // Never empty here: `App::set_machines` leaves the tab with the last one.
    draw_machines_table(frame, app, top, panel_focused);
    selectable(app, RegionId::MachinesTable, top);
    // No per-row detail (STATE carries the error); a plain block keeps the
    // layout aligned with the other tabs.
    let detail = Block::default()
        .borders(Borders::ALL)
        .border_style(dash_border_style(panel_focused))
        .title("Detail");
    frame.render_widget(Paragraph::new("").block(detail), detail_area);
    if let Some(terms_area) = terms_area {
        draw_terminal_panel(frame, app, terms_area);
    }
}

fn draw_machines_table(frame: &mut Frame, app: &App, area: Rect, term_focused: bool) {
    let name_width = app.machines.iter().map(|m| machine_name_text(m).chars().count()).max().unwrap_or(0).max("NAME".len());
    let room_width = app
        .machines
        .iter()
        .map(|m| capacity_text(m.capacity.as_ref()).chars().count())
        .max()
        .unwrap_or(0)
        .max("CAPACITY".len());
    let widths = [
        Constraint::Length(name_width as u16),
        Constraint::Length(24),
        Constraint::Min(14),
        Constraint::Length(5),
        Constraint::Length(12),
        Constraint::Length(room_width as u16),
    ];
    let header = Row::new(["NAME", "TARGET", "STATE", "AGENT", "VERSION", "CAPACITY"].map(Cell::from))
        .style(Style::default().add_modifier(Modifier::DIM));
    let rows: Vec<Row> = app.machines.iter().map(machine_row).collect();
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(dash_border_style(term_focused))
        .title(Tab::Machines.title());
    let table = Table::new(rows, widths)
        .header(header)
        .block(block)
        .column_spacing(1)
        .row_highlight_style(Style::default().fg(SELECTION).add_modifier(Modifier::BOLD));
    let mut state = TableState::default().with_selected(Some(app.selected()));
    frame.render_stateful_widget(table, area, &mut state);
}

/// The CAPACITY cell's text: `8 cpu · 12/32G · 120G free · 3 run`, then
/// `  over cap: mem 18G/16G` when a soft cap is exceeded; `-` without a
/// report (`serve::capacity`).
fn capacity_text(c: Option<&crate::serve::capacity::Capacity>) -> String {
    use crate::serve::capacity;
    let summary = capacity::summary(c);
    match c.and_then(capacity::over_note) {
        Some(note) => format!("{summary}  {note}"),
        None => summary,
    }
}

/// A machine's NAME: its name, then `  exposed via <dialer>` while it's
/// `worker` and exposed (`SnapshotMachine::exposed_by`).
fn machine_name_text(m: &crate::serve::snapshots::SnapshotMachine) -> String {
    match crate::serve::fleet::graph::exposed_note(m.exposed_by.as_deref()) {
        Some(note) => format!("{}  {note}", m.name),
        None => m.name.clone(),
    }
}

/// One machine's cells: STATE is the link state, with `: <error>` when the
/// last attempt said why; CAPACITY from its last snapshot's
/// capacity report (last known while it isn't connected).
fn machine_row(m: &crate::serve::snapshots::SnapshotMachine) -> Row<'_> {
    use crate::serve::snapshots::LinkState;
    let state = match &m.error {
        Some(e) => format!("{}: {e}", m.state.as_str()),
        None => m.state.as_str().to_string(),
    };
    let style = match m.state {
        LinkState::Connected => Style::default().fg(Color::Green),
        LinkState::Connecting => Style::default().fg(Color::Yellow),
        LinkState::Unreachable => Style::default().fg(Color::Red),
        LinkState::Idle => Style::default(),
    };
    let name = match crate::serve::fleet::graph::exposed_note(m.exposed_by.as_deref()) {
        Some(note) => Line::from(vec![
            Span::styled(m.name.clone(), Style::default().fg(ACCENT)),
            Span::styled(format!("  {note}"), Style::default().fg(Color::Yellow)),
        ]),
        None => Line::from(Span::styled(m.name.clone(), Style::default().fg(ACCENT))),
    };
    Row::new([
        Cell::from(name),
        // An inbound machine has no ssh target: its kind instead; one seen
        // through the hub, the hub.
        match (&m.via, &m.target) {
            (Some(hub), _) => Cell::from(Span::styled(format!("via {hub}"), Style::default().add_modifier(Modifier::DIM))),
            (None, Some(target)) => Cell::from(target.clone()),
            (None, None) => Cell::from(Span::styled("inbound", Style::default().add_modifier(Modifier::DIM))),
        },
        Cell::from(Span::styled(state, style)),
        // This host's agent grant for the member, whatever the kind.
        Cell::from(if m.agent { "on" } else { "off" }),
        Cell::from(m.version.clone().unwrap_or_else(|| "-".to_string())),
        {
            let over = m.capacity.as_ref().is_some_and(|c| !crate::serve::capacity::over_caps(c).is_empty());
            let style = if over { Style::default().fg(Color::Yellow) } else { Style::default() };
            Cell::from(Span::styled(capacity_text(m.capacity.as_ref()), style))
        },
    ])
}

fn draw_inbox(frame: &mut Frame, app: &App, area: Rect) {
    let (_top, _detail, terms_area) = content_areas(app, area);
    let region = inbox_region(area, terms_area.is_some());
    let (list_area, thread_area) = inbox_areas(region, app.inbox.split_pct);
    draw_inbox_list(frame, app, list_area);
    draw_inbox_pane(frame, app, thread_area);
    if let Some(terms_area) = terms_area {
        draw_terminal_panel(frame, app, terms_area);
    }
}

/// The part of a tab's content `area` the Inbox's list/thread split fills.
/// The Inbox has no Detail box (the thread pane is its detail): without
/// terminals that's the whole content area; with them, the top, the terminal
/// panel staying where it is on every tab. Derived from [`content_areas`]'s
/// own splits so it can't drift from them.
fn inbox_region(area: Rect, terms_open: bool) -> Rect {
    if terms_open {
        open_bottom_split(area).0
    } else {
        area
    }
}

/// The Rect [`inbox_areas`] splits for a frame of size `frame`: what
/// [`draw_inbox`] lays out, computed from the frame size alone so the
/// divider's mouse hit-test (in the I/O-free `App`) matches the drawing.
pub(crate) fn inbox_split_rect(frame: Rect, prompt_open: bool, terms_open: bool) -> Rect {
    inbox_region(frame_content_area(frame, prompt_open), terms_open)
}

/// Column of the list/thread divider in `region` at `split_pct`: the thread
/// pane's left border, right next to the list's right one; a press on
/// either border grabs it.
pub(crate) fn inbox_divider_col(region: Rect, split_pct: u16) -> u16 {
    inbox_areas(region, split_pct).1.x
}

/// The Inbox's `(list, thread)` split of `area`, the list taking `split_pct`
/// percent of the width. The one place the split is computed, so a mouse
/// hit-test on the divider can't drift from what was drawn.
fn inbox_areas(area: Rect, split_pct: u16) -> (Rect, Rect) {
    let [list, thread] =
        Layout::horizontal([Constraint::Percentage(split_pct), Constraint::Min(0)]).areas(area);
    (list, thread)
}

/// Border of an Inbox zone: accented while it has the keys, dim otherwise
/// (also while a terminal has them), like the config modal's panes.
fn zone_border_style(app: &App, zone: InboxFocus) -> Style {
    if app.focus == Focus::Dashboard && app.inbox.focus == zone {
        Style::default().fg(ACCENT).add_modifier(Modifier::BOLD)
    } else {
        Style::default().add_modifier(Modifier::DIM)
    }
}

/// Display width of `s` in terminal columns. Through ratatui's `Span::width`
/// (unicode-width underneath), so a wide glyph in a title counts as the two
/// cells it takes, without a direct dependency.
fn cols(s: &str) -> usize {
    Span::raw(s).width()
}

/// `s` cut to at most `width` columns, ending in `…` when anything was cut.
pub(crate) fn truncate(s: &str, width: usize) -> String {
    if cols(s) <= width {
        return s.to_string();
    }
    if width == 0 {
        return String::new();
    }
    let mut out = String::new();
    let mut used = 0;
    let mut buf = [0u8; 4];
    for ch in s.chars() {
        let w = cols(ch.encode_utf8(&mut buf));
        if used + w > width - 1 {
            break;
        }
        out.push(ch);
        used += w;
    }
    out.push('…');
    out
}

/// Fewest columns the left text keeps before the right text is dropped: a
/// title cut to a couple of letters says less than no age at all.
const FIT_MIN_LEFT: usize = 8;

/// `left` and `right` laid out in `width` columns with at least one space
/// between them: the left text is truncated with `…` to make room, and when
/// even that leaves it fewer than [`FIT_MIN_LEFT`] columns (or its whole
/// self, if shorter) the right text is dropped (returned empty) instead.
fn fit(left: &str, right: &str, width: usize) -> (String, String) {
    let (lw, rw) = (cols(left), cols(right));
    if rw == 0 {
        return (truncate(left, width), String::new());
    }
    if lw + 1 + rw <= width {
        return (left.to_string(), right.to_string());
    }
    if width >= rw + 1 + lw.min(FIT_MIN_LEFT) {
        return (truncate(left, width - rw - 1), right.to_string());
    }
    (truncate(left, width), String::new())
}

/// Re-applies `parts`' styles to `fitted`, a [`fit`] of their concatenation:
/// truncation only cuts a tail and adds `…`, so the fitted text's chars line
/// up with the parts' in order (the `…` takes the style of the part it lands
/// in).
fn restyle(parts: &[(String, Style)], fitted: &str) -> Vec<Span<'static>> {
    let mut chars = fitted.chars();
    let mut out = Vec::new();
    for (text, style) in parts {
        let piece: String = chars.by_ref().take(text.chars().count()).collect();
        if piece.is_empty() {
            break;
        }
        out.push(Span::styled(piece, *style));
    }
    out
}

/// A card's state chip ([`chip`], shared with the pane head) as styled
/// parts: the tones' styles, a status as inline markdown.
fn card_chip(t: &Thread) -> Vec<(String, Style)> {
    chip(t)
        .into_iter()
        .flat_map(|(tone, text)| match tone {
            Tone::Text => styled_parts(markdown::inline_spans(&text), tone_style(tone)),
            _ => vec![(text, tone_style(tone))],
        })
        .collect()
}

/// Inline-markdown `spans` as [`card_line`] parts, each on `base`.
fn styled_parts(spans: Vec<Span<'static>>, base: Style) -> Vec<(String, Style)> {
    spans.into_iter().map(|s| (s.content.into_owned(), base.patch(s.style))).collect()
}

/// Background of the selected card. A mid-dark gray, paired with an explicit
/// foreground ([`CARD_SELECTED_FG`]) so the text reads the same on dark and
/// light terminal themes (a bare tint under the theme's own dark text would
/// vanish on a light one); `REVERSED` would be anything but subtle.
const CARD_TINT: Color = Color::Indexed(236);
const CARD_SELECTED_FG: Color = Color::Indexed(252);
/// The selection bar while the list has no keys: still there, quieter.
const ACCENT_DIM: Color = Color::Rgb(110, 85, 160);

/// Rows a card takes: two content lines and a spacer (dropped after the last
/// card when it doesn't fit).
const CARD_ROWS: usize = 3;

/// One line of a card, exactly `width` columns: column 0 holds the selection
/// bar (or a space, so text aligns), then the left parts, padding, the right
/// text, and one trailing space off the border. Padded explicitly so the
/// selected card's tint spans the whole width.
fn card_line(
    left: &[(String, Style)],
    right: (String, Style),
    width: usize,
    bar: Option<Color>,
    base: Style,
) -> Line<'static> {
    let mut spans = vec![match bar {
        Some(color) => Span::styled("▌", Style::default().fg(color)),
        None => Span::raw(" "),
    }];
    let avail = width.saturating_sub(2);
    let plain: String = left.iter().map(|(s, _)| s.as_str()).collect();
    let (l, r) = fit(&plain, &right.0, avail);
    let used = cols(&l) + cols(&r);
    spans.extend(restyle(left, &l));
    spans.push(Span::raw(" ".repeat(avail.saturating_sub(used))));
    if !r.is_empty() {
        spans.push(Span::styled(r, right.1));
    }
    if width >= 2 {
        spans.push(Span::raw(" "));
    }
    Line::from(spans).style(base)
}

/// A card's two content lines: title (bold while unread, `↗` with a link,
/// ` · archived` when its instance is gone) with the age, then the state chip
/// with the sender. Archived cards are dimmed throughout; the selected one
/// gets the bar ([`ACCENT`] while the list has the keys) and the tint.
fn card_lines(t: &Thread, width: usize, selected: bool, focused: bool, now: u64, utc_offset: i64) -> [Line<'static>; 2] {
    let dim = Style::default().add_modifier(Modifier::DIM);
    let fade = |s: Style| if t.archived { s.add_modifier(Modifier::DIM) } else { s };
    let title_style = if t.unread { Style::default().add_modifier(Modifier::BOLD) } else { Style::default() };
    let mut title = styled_parts(markdown::inline_spans(&title_of(t)), fade(title_style));
    if t.link.is_some() || t.head().is_some_and(|r| r.link.is_some()) {
        title.push((" ↗".into(), fade(Style::default().fg(Color::Blue))));
    }
    if t.archived {
        title.push((" · archived".into(), dim));
    }
    let chip: Vec<(String, Style)> = card_chip(t).into_iter().map(|(s, style)| (s, fade(style))).collect();
    let age = (short_age(t.changed_at(), now, utc_offset), dim);
    let from = (t.owner_name.clone(), dim);
    let (bar, base) = if selected {
        let bar = if focused { ACCENT } else { ACCENT_DIM };
        (Some(bar), Style::default().bg(CARD_TINT).fg(CARD_SELECTED_FG))
    } else {
        (None, Style::default())
    };
    [
        card_line(&title, age, width, bar, base),
        card_line(&chip, from, width, bar, base),
    ]
}

/// First card to show so `selected` is fully visible in `height` rows,
/// moving `prev` (last frame's) as little as possible: the list holds still
/// while the cursor moves inside it. Also pulled back so a shrunk list or a
/// taller pane doesn't leave blank rows under the last card.
fn card_offset(prev: usize, selected: usize, len: usize, height: usize) -> usize {
    // n cards need 3n - 1 rows: the last one's spacer can go.
    let fit = ((height + 1) / CARD_ROWS).max(1);
    let mut off = prev.min(len.saturating_sub(fit));
    if selected < off {
        off = selected;
    } else if selected >= off + fit {
        off = selected + 1 - fit;
    }
    off
}

/// Short view names, for a strip too narrow for the full ones.
fn view_short(view: View) -> &'static str {
    match view {
        View::NeedsYou => "Needs",
        other => other.title(),
    }
}

/// The view switcher above the list: `‹ Needs you 3 │ Active 5 │ Done │ All ›`,
/// the current view accented, the arrows dim at the ends (the views clamp,
/// see `View::step`), zero counts left out. Narrower widths drop the counts,
/// then shorten the names.
fn view_strip(current: View, counts: [usize; 4], width: usize) -> Line<'static> {
    Line::from(view_strip_parts(current, counts, width).into_iter().map(|(s, _)| s).collect::<Vec<_>>())
}

/// What a click on a view-strip span does.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum StripHit {
    /// `‹`: one view left.
    Prev,
    /// `›`: one view right.
    Next,
    /// A view's name (or its count).
    View(View),
}

/// [`view_strip`]'s spans, each tagged with what a click on it does, so
/// drawing and [`view_strip_hit`] can't disagree on where a name sits.
fn view_strip_parts(current: View, counts: [usize; 4], width: usize) -> Vec<(Span<'static>, Option<StripHit>)> {
    let dim = Style::default().add_modifier(Modifier::DIM);
    let build = |counts_on: bool, short: bool| {
        let first = current == View::ALL[0];
        let last = current == View::ALL[View::ALL.len() - 1];
        let mut spans = vec![
            (Span::raw(" "), None),
            (Span::styled("‹ ", if first { dim } else { Style::default() }), Some(StripHit::Prev)),
        ];
        for (i, view) in View::ALL.iter().enumerate() {
            if i > 0 {
                spans.push((Span::styled(" │ ", dim), None));
            }
            let style = if *view == current {
                Style::default().fg(ACCENT).add_modifier(Modifier::BOLD)
            } else {
                dim
            };
            let hit = Some(StripHit::View(*view));
            spans.push((Span::styled(if short { view_short(*view) } else { view.title() }, style), hit));
            if counts_on && counts[i] > 0 {
                spans.push((Span::styled(format!(" {}", counts[i]), dim), hit));
            }
        }
        spans.push((Span::styled(" ›", if last { dim } else { Style::default() }), Some(StripHit::Next)));
        spans
    };
    let width_of = |parts: &[(Span, Option<StripHit>)]| parts.iter().map(|(s, _)| s.width()).sum::<usize>();
    [(true, false), (false, false)]
        .into_iter()
        .map(|(c, s)| build(c, s))
        .find(|p| width_of(p) <= width)
        .unwrap_or_else(|| build(false, true))
}

/// What a click `x` columns into a `width`-wide view strip hits.
pub(crate) fn view_strip_hit(current: View, counts: [usize; 4], width: usize, x: u16) -> Option<StripHit> {
    let mut start = 0;
    for (span, hit) in view_strip_parts(current, counts, width) {
        let end = start + span.width();
        if (start..end).contains(&(x as usize)) {
            return hit;
        }
        start = end;
    }
    None
}

/// The list column's `(view strip, list block)` split.
fn inbox_list_areas(area: Rect) -> (Rect, Rect) {
    let [strip, list] = Layout::vertical([Constraint::Length(1), Constraint::Min(0)]).areas(area);
    (strip, list)
}

/// Position (into `InboxView::rows`) of the card drawn at `row` in the list
/// block's `inner` area, cards starting at `offset`: three rows per card, the
/// third a spacer that hits nothing (see [`draw_inbox_list`]).
fn card_at(inner: Rect, offset: usize, len: usize, row: u16) -> Option<usize> {
    if row < inner.y || row >= inner.bottom() {
        return None;
    }
    let rel = (row - inner.y) as usize;
    let pos = offset + rel / CARD_ROWS;
    (rel % CARD_ROWS != CARD_ROWS - 1 && pos < len).then_some(pos)
}

/// The reply text the input box shows: only while it has focus (unfocused,
/// it shows the placeholder). Shared by drawing and hit-testing so both size
/// the box alike.
fn focused_reply(app: &App) -> Option<&TextArea> {
    app.inbox.reply.as_ref().filter(|_| app.inbox.focus == InboxFocus::Input).map(|r| &r.line)
}

/// What the composer box holds: a form's text question being edited (the
/// box is shared with it), else the focused reply.
fn composer_text(app: &App) -> Option<&TextArea> {
    app.form_text_edit().or_else(|| focused_reply(app))
}

/// A thread's `compose.hint`, when it says anything: one dim row under the
/// input box.
fn compose_hint(t: &Thread) -> Option<&str> {
    t.compose.as_ref()?.hint.as_deref().filter(|h| !h.trim().is_empty())
}

/// Rows the thread pane keeps under its feed, `width` the pane's inner
/// width: the composer (a thread taking replies), i.e. the input box's border
/// plus 1 to [`textarea::MAX_ROWS`] rows of wrapped `reply`, and a row for
/// `compose.hint` when there is one; a one-line hint (a dispatcher thread that
/// takes no replies); or none (a notify thread, which can't be replied to).
fn pane_bottom_rows(t: &Thread, reply: Option<&TextArea>, form_edit: bool, width: u16) -> u16 {
    if let (true, Some(edit)) = (form_edit, reply) {
        // A form's text edit: the box alone, on any thread.
        return 2 + edit.height(width.saturating_sub(2));
    }
    match (t.kind, &t.compose) {
        (_, Some(_)) => {
            2 + reply.map_or(1, |r| r.height(width.saturating_sub(2))) + u16::from(compose_hint(t).is_some())
        }
        (Kind::Thread, None) => 1,
        (Kind::Notify, None) => 0,
    }
}

/// The thread pane's areas inside its block, top to bottom: the pinned
/// header, the separator row under it, the pinned open forms, the scrolling
/// feed and the composer (or the no-replies line). Room goes to the composer
/// first, then the header, the separator, then the forms (at most half the
/// pane: past that their box scrolls), and the feed gets the rest, so a
/// short pane keeps what the keys act on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct PaneAreas {
    header: Rect,
    sep: Rect,
    forms: Rect,
    feed: Rect,
    bottom: Rect,
}

fn pane_areas(inner: Rect, header: u16, forms: u16, bottom: u16) -> PaneAreas {
    let bottom = bottom.min(inner.height);
    let header = header.min(inner.height - bottom);
    let sep = 1.min(inner.height - bottom - header);
    let rest = inner.height - bottom - header - sep;
    let forms = forms.min(inner.height / 2).min(rest);
    let feed = rest - forms;
    let row = |y: u16, height: u16| Rect { y, height, ..inner };
    let top = inner.y + header + sep;
    PaneAreas {
        header: row(inner.y, header),
        sep: row(inner.y + header, sep),
        forms: row(top, forms),
        feed: row(top + forms, feed),
        bottom: row(top + forms + feed, bottom),
    }
}

/// The pinned forms as drawn: every box's rows (borders included), which
/// form and question each row belongs to, and the focused question's rows.
struct FormRows {
    lines: Vec<Line<'static>>,
    spots: Vec<FormSpot>,
    focus: Option<std::ops::Range<usize>>,
}

/// The thread pane's layout for `t`: the pinned header as the rows drawn at
/// the pane's inner width, the pinned forms' rows and the areas. Shared by
/// drawing and hit-testing, so a click lands where things are.
struct PaneLayout {
    header: Vec<Line<'static>>,
    forms: FormRows,
    areas: PaneAreas,
}

fn thread_pane_layout(app: &App, t: &Thread, inner: Rect) -> PaneLayout {
    let child = app.thread_child(t);
    let header = header_lines(&pane_header(t, child.as_ref(), app.thread_target_stopped(t), app.utc_offset), inner.width, app.inbox.raw);
    let rows = header.len().min(u16::MAX as usize) as u16;
    let forms = form_rows(app, t, inner.width);
    let want = forms.lines.len().min(u16::MAX as usize) as u16;
    let bottom = pane_bottom_rows(t, composer_text(app), app.form_text_edit().is_some(), inner.width);
    let areas = pane_areas(inner, rows, want, bottom);
    PaneLayout { header, forms, areas }
}

/// `t`'s open forms (newest first) as rounded boxes `width` wide: the
/// form's title on the top border with ` open form ` on the right, the
/// content ([`form_lines`]) wrapped inside a one-column margin. The box
/// with the form cursor is accented while the dashboard has the keys.
fn form_rows(app: &App, t: &Thread, width: u16) -> FormRows {
    let mut out = FormRows { lines: Vec::new(), spots: Vec::new(), focus: None };
    let width = width as usize;
    if width < 8 {
        return out;
    }
    let inner = width - 4;
    for (fi, p) in pinned_forms(t).iter().enumerate() {
        let cursor = app.form_cursor(t.id, p.message);
        let style = if cursor.is_some() && app.focus == Focus::Dashboard {
            Style::default().fg(ACCENT).add_modifier(Modifier::BOLD)
        } else {
            Style::default().add_modifier(Modifier::DIM)
        };
        let spot = |question| FormSpot { form: fi, question };
        let title = truncate(&crate::inbox::sanitize(form_title(p.form)), width.saturating_sub(6));
        let right = if cols(&title) + 17 <= width { " open form " } else { "" };
        let fill = width.saturating_sub(cols(&title) + cols(right) + 4);
        out.lines.push(Line::from(vec![
            Span::styled("╭ ", style),
            Span::styled(title, style.remove_modifier(Modifier::DIM).add_modifier(Modifier::BOLD)),
            Span::styled(format!(" {}{right}╮", "─".repeat(fill)), style),
        ]));
        out.spots.push(spot(None));
        let content = form_lines(p.form, p.record, cursor.as_ref(), inner);
        for (li, line) in content.lines.iter().enumerate() {
            let question = content.questions.iter().position(|r| r.contains(&li));
            let start = out.lines.len();
            for (row, _) in pane_rows(line, inner as u16, app.inbox.raw) {
                let pad = inner.saturating_sub(row.width());
                let mut spans = vec![Span::styled("│ ", style)];
                spans.extend(row.spans);
                spans.push(Span::raw(" ".repeat(pad)));
                spans.push(Span::styled(" │", style));
                out.lines.push(Line::from(spans));
                out.spots.push(spot(question));
            }
            if let (Some(c), Some(q)) = (&cursor, question) {
                if c.question == q {
                    let r = out.focus.get_or_insert(start..start);
                    r.end = out.lines.len();
                }
            }
        }
        out.lines.push(Line::from(Span::styled(format!("╰{}╯", "─".repeat(width - 2)), style)));
        out.spots.push(spot(None));
    }
    out
}

/// `spans` cut to `width` columns, ending in `…` when cut, styles kept.
fn cut_spans(spans: Vec<Span<'static>>, width: usize) -> Vec<Span<'static>> {
    let parts: Vec<(String, Style)> = spans.into_iter().map(|s| (s.content.into_owned(), s.style)).collect();
    let plain: String = parts.iter().map(|(s, _)| s.as_str()).collect();
    restyle(&parts, &truncate(&plain, width))
}

/// The header's rows at `width` columns ([`HeaderRow`]): a line is one row,
/// cut with `…`, its right text right-aligned when both fit ([`fit`]); the
/// buttons are packed two spaces apart and wrap between buttons, a button
/// wider than the pane cut on its own row.
fn header_lines(rows: &[HeaderRow], width: u16, raw: bool) -> Vec<Line<'static>> {
    let width = width as usize;
    let dim = Style::default().add_modifier(Modifier::DIM);
    let mut out = Vec::new();
    for row in rows {
        match row {
            HeaderRow::Line { left, right } => {
                let parts: Vec<(String, Style)> =
                    pane_spans(left, raw).into_iter().map(|s| (s.content.into_owned(), s.style)).collect();
                let plain: String = parts.iter().map(|(s, _)| s.as_str()).collect();
                let right = right.as_deref().map(crate::inbox::sanitize).unwrap_or_default();
                let (l, r) = fit(&plain, &right, width);
                let mut spans = restyle(&parts, &l);
                if !r.is_empty() {
                    spans.push(Span::raw(" ".repeat(width.saturating_sub(cols(&l) + cols(&r)))));
                    spans.push(Span::styled(r, dim));
                }
                out.push(Line::from(spans));
            }
            HeaderRow::Buttons(buttons) => {
                let mut cur: Vec<Span<'static>> = Vec::new();
                let mut used = 0;
                for b in buttons {
                    let spans = pane_spans(b, raw);
                    let w: usize = spans.iter().map(Span::width).sum();
                    if used > 0 && used + 2 + w > width {
                        out.push(Line::from(std::mem::take(&mut cur)));
                        used = 0;
                    }
                    if used > 0 {
                        cur.push(Span::raw("  "));
                        used += 2;
                    }
                    used += w.min(width);
                    cur.extend(cut_spans(spans, width));
                }
                if !cur.is_empty() {
                    out.push(Line::from(cur));
                }
            }
        }
    }
    out
}

/// What a click on the Inbox tab lands on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum InboxHit {
    Strip(StripHit),
    /// A card, by position in `InboxView::rows`.
    Card(usize),
    /// The list block off any card: a spacer, a border, blank rows.
    ListBlank,
    /// The thread pane above its composer or hint: header, separator,
    /// feed (borders included).
    Thread,
    /// The pinned forms: the form and question under the row, if any; or
    /// (`None`) the composer box while it holds a form's text edit.
    Form(Option<FormSpot>),
    /// The composer: the reply input box and its `compose.hint` row.
    Input,
    /// The "takes no replies" hint row.
    Hint,
}

/// What's under `(col, row)` on the Inbox tab for a frame of size `frame`,
/// from the same layout functions [`draw_inbox`] uses and the list offset it
/// last drew with, so a click hits what is on screen.
pub(crate) fn inbox_hit(app: &App, frame: Rect, col: u16, row: u16) -> Option<InboxHit> {
    let at = Position::new(col, row);
    let region = inbox_split_rect(frame, app.prompt.is_some(), !app.terms.is_empty());
    if !region.contains(at) {
        return None;
    }
    let (list, thread) = inbox_areas(region, app.inbox.split_pct);
    if list.contains(at) {
        let (strip, block) = inbox_list_areas(list);
        if strip.contains(at) {
            let counts = View::ALL.map(|v| app.inbox.count(v));
            return view_strip_hit(app.inbox.view, counts, strip.width as usize, col - strip.x).map(InboxHit::Strip);
        }
        let inner = Block::bordered().inner(block);
        let card = card_at(inner, app.inbox.list_offset(), app.inbox.rows().len(), row);
        return Some(match card {
            Some(pos) if inner.contains(at) => InboxHit::Card(pos),
            _ => InboxHit::ListBlank,
        });
    }
    let Some(t) = app.selected_inbox_thread() else {
        return Some(InboxHit::Thread);
    };
    let inner = Block::bordered().inner(thread);
    let PaneLayout { forms, areas, .. } = thread_pane_layout(app, t, inner);
    if areas.forms.contains(at) {
        let row = (row - areas.forms.y) as usize + app.inbox.forms_scroll();
        return Some(InboxHit::Form(forms.spots.get(row).copied()));
    }
    // The header, separator and feed are all the thread; the composer's
    // hint row is part of it, so a click there doesn't drop a typed reply.
    if !areas.bottom.contains(at) {
        Some(InboxHit::Thread)
    } else if app.form_text_edit().is_some() {
        Some(InboxHit::Form(None))
    } else if t.compose.is_some() {
        Some(InboxHit::Input)
    } else {
        Some(InboxHit::Hint)
    }
}

fn draw_inbox_list(frame: &mut Frame, app: &App, area: Rect) {
    let (strip_area, list_area) = inbox_list_areas(area);
    let counts = View::ALL.map(|v| app.inbox.count(v));
    frame.render_widget(Paragraph::new(view_strip(app.inbox.view, counts, strip_area.width as usize)), strip_area);
    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(zone_border_style(app, InboxFocus::List))
        .title(" Inbox ");
    let inner = block.inner(list_area);
    frame.render_widget(block, list_area);
    app.add_region(RegionId::InboxList, inner);
    let dim = Style::default().add_modifier(Modifier::DIM);
    let rows = app.inbox.rows();
    if rows.is_empty() {
        let text = if app.inbox.threads().is_empty() {
            "no notifications — containers send them with `devsbd notify \"…\"`".to_string()
        } else {
            format!("nothing in {} — ←/→ switch views", app.inbox.view.title())
        };
        let mut lines = vec![Line::default(); (inner.height as usize).saturating_sub(1) / 2];
        lines.push(Line::from(Span::styled(text, dim)).alignment(Alignment::Center));
        frame.render_widget(Paragraph::new(lines), inner);
        return;
    }
    // Wall clock read per frame, so relative times tick between snapshots.
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_secs());
    let selected = app.selected().min(rows.len() - 1);
    let height = inner.height as usize;
    let off = card_offset(app.inbox.list_offset(), selected, rows.len(), height);
    app.inbox.set_list_offset(off);
    let focused = app.focus == Focus::Dashboard && app.inbox.focus == InboxFocus::List;
    let threads = app.inbox.threads();
    let width = inner.width as usize;
    let mut lines: Vec<Line> = Vec::with_capacity(height + CARD_ROWS);
    for (pos, &i) in rows.iter().enumerate().skip(off) {
        if lines.len() >= height {
            break;
        }
        if pos > off {
            lines.push(Line::default());
        }
        lines.extend(card_lines(&threads[i], width, pos == selected, focused, now, app.utc_offset));
    }
    frame.render_widget(Paragraph::new(lines), inner);
}

fn level_style(level: Level) -> Style {
    match level {
        Level::Info => Style::default().add_modifier(Modifier::DIM),
        Level::Warn => Style::default().fg(Color::Yellow),
        Level::Error => Style::default().fg(Color::Red),
    }
}

fn state_style(state: State) -> Style {
    match state {
        State::NeedsYou => Style::default().fg(Color::Yellow),
        State::Active => Style::default(),
        State::Done => Style::default().add_modifier(Modifier::DIM),
    }
}

fn tone_style(tone: Tone) -> Style {
    match tone {
        Tone::Plain | Tone::Text | Tone::Markdown => Style::default(),
        Tone::Cursor => Style::default().add_modifier(Modifier::REVERSED),
        Tone::Dim => Style::default().add_modifier(Modifier::DIM),
        Tone::Bold | Tone::Title => Style::default().add_modifier(Modifier::BOLD),
        Tone::Link => Style::default().fg(Color::Blue),
        Tone::State(s) => state_style(s),
        Tone::Level(l) => level_style(l),
    }
}

/// One pane line as the rows it takes at `width` columns. The pane draws
/// exactly these rows (no `Paragraph` wrap), so their count is what bounds
/// its scroll. A [`Tone::Markdown`] line is a whole document, rendered as
/// blocks; elsewhere [`Tone::Text`]/[`Tone::Title`] segments are inline
/// markdown on their tone's style, the rest plain; then the line is word
/// wrapped by display width. `raw` (`m`) shows the markdown as its source.
/// Every segment is sanitized: it may be stored text from before the
/// apply-boundary pass. Each row comes with how a copy joins it
/// ([`select::RowMeta`]).
fn pane_rows(line: &PaneLine, width: u16, raw: bool) -> Vec<(Line<'static>, select::RowMeta)> {
    if let [(Tone::Markdown, md)] = line.as_slice() {
        return if raw { markdown::raw_rows(md, width) } else { markdown::render_rows(md, width) };
    }
    markdown::wrap_rows(&pane_spans(line, raw), width as usize, &[], &[], false)
}

/// One non-document pane line as styled spans, unwrapped (see [`pane_rows`]).
fn pane_spans(line: &PaneLine, raw: bool) -> Vec<Span<'static>> {
    let mut spans = Vec::new();
    for (tone, text) in line {
        let base = tone_style(*tone);
        match tone {
            Tone::Text | Tone::Title | Tone::Markdown if !raw => spans.extend(
                markdown::inline_spans(text).into_iter().map(|s| {
                    let style = base.patch(s.style);
                    s.style(style)
                }),
            ),
            Tone::Text | Tone::Title | Tone::Markdown => spans.push(Span::styled(markdown::fold(text), base)),
            _ => spans.push(Span::styled(crate::inbox::sanitize(text), base)),
        }
    }
    spans
}

/// The thread pane (layout v3, docs/architecture/dashboard/inbox-tab.md *Thread pane*): the
/// pinned header ([`pane_header`]: title, chip, child, action row), a
/// separator joined to the border, the feed newest first ([`pane_feed`]),
/// scrolling on its own, then the composer (the input box and its
/// `compose.hint`), a one-line no-replies hint, or nothing (a notify thread).
/// Records the feed's scroll bound for the scroll keys
/// (`InboxView::set_pane_max`), since only here are the size and wrapping
/// known. The thread's open forms are pinned between the separator and the
/// feed ([`form_rows`]), their box scrolled to the form cursor
/// ([`forms_offset`]); a form's text edit takes the composer box.
fn draw_inbox_pane(frame: &mut Frame, app: &App, area: Rect) {
    let border = zone_border_style(app, InboxFocus::Thread);
    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(border)
        .title(if app.inbox.raw { " Thread · raw " } else { " Thread " });
    let inner = block.inner(area);
    frame.render_widget(block, area);
    let dim = Style::default().add_modifier(Modifier::DIM);
    let Some(t) = app.selected_inbox_thread() else {
        let text = Line::from(Span::styled("no thread selected", dim)).alignment(Alignment::Center);
        frame.render_widget(Paragraph::new(text), inner);
        return;
    };
    let PaneLayout { header, forms, areas } = thread_pane_layout(app, t, inner);
    // Screen cells: the header never scrolls, so what's drawn is the text.
    app.add_region(RegionId::InboxHeader, areas.header);
    frame.render_widget(Paragraph::new(header), areas.header);
    if areas.sep.height > 0 && area.width >= 2 {
        let rule = format!("├{}┤", "─".repeat(area.width as usize - 2));
        let row = Rect { x: area.x, width: area.width, ..areas.sep };
        frame.render_widget(Paragraph::new(Span::styled(rule, border)), row);
    }
    let (total, height) = (forms.lines.len(), areas.forms.height as usize);
    let follow = app.inbox.take_forms_follow();
    let off = forms_offset(app.inbox.forms_scroll(), forms.focus, total, height, follow);
    app.inbox.set_forms_scroll(off, total.saturating_sub(height));
    if height > 0 {
        let off = off.min(u16::MAX as usize) as u16;
        frame.render_widget(Paragraph::new(forms.lines).scroll((off, 0)), areas.forms);
    }
    let feed = areas.feed;
    let (lines, texts): (Vec<Line>, Vec<select::RowText>) = pane_feed(t, app.utc_offset)
        .iter()
        .flat_map(|l| pane_rows(l, feed.width, app.inbox.raw))
        .map(|(line, meta)| {
            let text = select::RowText::new(&line, meta);
            (line, text)
        })
        .unzip();
    let rows = lines.len().min(u16::MAX as usize) as u16;
    let max = rows.saturating_sub(feed.height);
    app.inbox.set_pane_max(max);
    let scroll = app.inbox.scroll.min(max);
    // The feed only: the header and the composer are not message text.
    app.add_rows_region(RegionId::InboxThread, feed, scroll as usize, texts);
    frame.render_widget(Paragraph::new(lines).scroll((scroll, 0)), feed);
    let bottom = areas.bottom;
    if let (Some(edit), Some(q)) = (app.form_text_edit(), app.editing_question()) {
        let multiline = matches!(q.kind, crate::inbox::form::QuestionKind::Text { multiline: true, .. });
        let keys = if multiline { "enter/esc keep · alt-enter newline" } else { "enter/esc keep" };
        let label = markdown::fold(&q.label);
        let title = format!(" {} · {keys} ", truncate(&label, (bottom.width as usize).saturating_sub(cols(keys) + 8)));
        let placeholder = match &q.kind {
            crate::inbox::form::QuestionKind::Text { placeholder: Some(p), .. } => p.as_str(),
            _ => "",
        };
        draw_text_box(frame, app, Some(edit), &title, placeholder, InboxFocus::Form, bottom);
        return;
    }
    match &t.compose {
        Some(compose) => {
            let hint = compose_hint(t).filter(|_| bottom.height > 0);
            let input = Rect { height: bottom.height - u16::from(hint.is_some()), ..bottom };
            draw_reply_input(frame, app, compose.placeholder.as_deref(), input);
            if let Some(hint) = hint {
                let text = truncate(&crate::inbox::sanitize(hint), bottom.width as usize);
                let row = Rect { y: bottom.bottom() - 1, height: 1, ..bottom };
                frame.render_widget(Paragraph::new(Span::styled(text, dim)), row);
            }
        }
        None if bottom.height > 0 => {
            frame.render_widget(Paragraph::new(Span::styled("this thread takes no replies", dim)), bottom);
        }
        None => {}
    }
}

/// The thread pane's reply input: a rounded box holding the text being typed,
/// wrapped and scrolled to the cursor ([`TextArea::view`]), or the thread's
/// placeholder dim while it's empty. The caret is placed (like the `:`
/// prompt's) only while the input has focus, so it doesn't blink in a box the
/// keys don't reach.
fn draw_reply_input(frame: &mut Frame, app: &App, placeholder: Option<&str>, area: Rect) {
    let reply = focused_reply(app);
    let title = if reply.is_some() { " enter sends · esc back " } else { " r reply " };
    let placeholder = placeholder.unwrap_or("reply to the owner");
    draw_text_box(frame, app, reply, title, placeholder, InboxFocus::Input, area);
}

/// The composer box: `text` (the focused reply, or a form's text edit)
/// wrapped and scrolled to the cursor, else `placeholder` dim; the caret
/// placed while the dashboard has the keys. Its border follows `zone`.
fn draw_text_box(
    frame: &mut Frame,
    app: &App,
    text: Option<&TextArea>,
    title: &str,
    placeholder: &str,
    zone: InboxFocus,
    area: Rect,
) {
    let reply = text;
    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(zone_border_style(app, zone))
        .title(title.to_string());
    let inner = block.inner(area);
    let view = reply.map(|r| r.view(inner.width, inner.height));
    let lines: Vec<Line> = match &view {
        Some(v) if reply.is_some_and(|r| !r.input().is_empty()) => {
            v.lines.iter().map(|l| Line::from(l.clone())).collect()
        }
        _ => {
            vec![Line::from(Span::styled(placeholder.to_string(), Style::default().add_modifier(Modifier::DIM)))]
        }
    };
    frame.render_widget(Paragraph::new(lines).block(block), area);
    if let Some(v) = view {
        if app.focus == Focus::Dashboard && inner.width > 0 && inner.height > 0 {
            let (col, row) = v.caret;
            frame.set_cursor_position((inner.x + col.min(inner.width - 1), inner.y + row.min(inner.height - 1)));
        }
    }
}

/// Pure tab labels for the terminal panel, one per open session: `{i+1}:{title}`
/// with a ` (reconnecting…)` suffix on a remote tab between dials
/// (`TermSession::reconnecting`; ` (reconnecting… N)` from its second
/// re-dial of an outage), ` (exited)` on dead tabs. The single source of truth for both
/// the rendered strip ([`terminal_tab_specs`]) and the mouse hit-test
/// ([`terminal_tab_hit`]), so a click can't land on a column the strip doesn't
/// actually draw.
pub(crate) fn terminal_tab_labels(app: &App) -> Vec<String> {
    app.terms
        .sessions()
        .iter()
        .enumerate()
        .map(|(i, s)| {
            if s.reconnecting() {
                match s.redial.as_ref().and_then(|r| r.attempt()).filter(|n| *n > 1) {
                    Some(n) => format!("{}:{} (reconnecting… {n})", i + 1, s.title),
                    None => format!("{}:{} (reconnecting…)", i + 1, s.title),
                }
            } else if s.exited() {
                format!("{}:{} (exited)", i + 1, s.title)
            } else {
                format!("{}:{}", i + 1, s.title)
            }
        })
        .collect()
}

/// Pure tab-strip model for the terminal panel: one entry per open session as
/// `(label, active, exited)`. Kept free of styling so it's unit-testable; the
/// styling lives in [`terminal_tab_line`].
fn terminal_tab_specs(app: &App) -> Vec<(String, bool, bool)> {
    let active = app.terms.active();
    terminal_tab_labels(app)
        .into_iter()
        .zip(app.terms.sessions())
        .enumerate()
        .map(|(i, (label, s))| (label, i == active, s.exited()))
        .collect()
}

/// Build the terminal panel's block title as a styled tab strip. The active
/// (live) tab is ACCENT+BOLD, inactive live tabs DIM, exited tabs always DIM.
/// When the terminal holds focus, `▶ ` is prepended to match `pane_block`'s
/// focus mark. Tabs are separated by two spaces, matching the plan's example.
fn terminal_tab_line(app: &App) -> Line<'static> {
    let mut spans: Vec<Span> = Vec::new();
    if app.focus == Focus::Terminal {
        // `▶ ` is FOCUS_MARK_WIDTH columns; keep the string and constant in sync.
        spans.push(Span::styled(
            "▶ ",
            Style::default().fg(ACCENT).add_modifier(Modifier::BOLD),
        ));
    }
    for (i, (label, active, exited)) in terminal_tab_specs(app).into_iter().enumerate() {
        if i > 0 {
            spans.push(Span::raw("  "));
        }
        let style = if active && !exited {
            Style::default().fg(ACCENT).add_modifier(Modifier::BOLD)
        } else {
            Style::default().add_modifier(Modifier::DIM)
        };
        spans.push(Span::styled(label, style));
    }
    Line::from(spans)
}

/// The integrated-terminal panel: a bordered block whose title is the tab strip,
/// showing the active session's vt100 screen. Border is ACCENT+BOLD when focused,
/// DIM otherwise. Assumes at least one terminal is open (only called then).
fn draw_terminal_panel(frame: &mut Frame, app: &App, area: Rect) {
    let focused = app.focus == Focus::Terminal;
    let border_style = if focused {
        Style::default().fg(ACCENT).add_modifier(Modifier::BOLD)
    } else {
        Style::default().add_modifier(Modifier::DIM)
    };
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(border_style)
        .title(terminal_tab_line(app));

    let Some(session) = app.terms.active_session() else {
        frame.render_widget(block, area);
        return;
    };

    // Lock the active screen to render it. A poisoned lock (a reader thread
    // panicked) is unrecoverable here — skip the body but still show the block.
    let Ok(mut parser) = session.parser().lock() else {
        frame.render_widget(block, area);
        return;
    };
    // The body is selectable unless the child tracks the mouse (it gets the
    // buttons then, `App::terminal_mouse`); an exited one tracks nothing.
    let screen = parser.screen_mut();
    if screen.mouse_protocol_mode() == vt100::MouseProtocolMode::None || session.exited() {
        app.add_terminal_region(block.inner(area), select::terminal_top(screen));
    }
    let screen = parser.screen();

    // Show the cursor only when the terminal is focused; hide it otherwise so a
    // background terminal doesn't compete with the dashboard's own cursor.
    let mut cursor = Cursor::default();
    if !focused {
        cursor.hide();
    }
    let widget = PseudoTerminal::new(screen).block(block).cursor(cursor);
    frame.render_widget(&widget, area);
}

fn draw_instances(frame: &mut Frame, app: &App, area: Rect) {
    let snapshot = app.snapshot.as_ref();
    let nodes = app.visible_nodes();

    let (top, detail_area, terms_area) = content_areas(app, area);
    // Optional status lines reserved above the table, carved out of the top part
    // (never the bottom) so the terminal panel geometry is snapshot-independent.
    let table_area = draw_status_lines(frame, snapshot, top);

    // Terminal focused ⇒ the terminal panel is the accented one; dim the rest.
    let panel_focused = app.focus == Focus::Terminal;

    if nodes.is_empty() {
        // No snapshot yet means the first one is still on its way (or the
        // daemon can't be reached: say why), not that the config is empty.
        let message = match (snapshot, &app.snapshot_error) {
            (Some(_), _) => "no sandboxes defined — check devsandboxes.toml".to_string(),
            (None, Some(e)) => e.line(),
            (None, None) => "loading…".to_string(),
        };
        draw_empty(frame, table_area, panel_focused, &message);
        draw_detail(frame, snapshot, None, None, None, &app.machines, detail_area, panel_focused);
        selectable(app, RegionId::InstancesTree, table_area);
        selectable(app, RegionId::Detail, detail_area);
    } else {
        let snapshot = snapshot.expect("non-empty nodes imply a snapshot");
        draw_tree(frame, app, snapshot, &nodes, table_area, panel_focused);
        let selected = nodes.get(app.selected()).copied();
        // Agent count for the selected instance (or a proc row's parent), read
        // from the proc cache; `None` until its forest is fetched.
        let agent_count = match selected {
            Some(Node::Instance(i)) | Some(Node::Proc { instance: i, .. }) => {
                snapshot.instances.get(i).and_then(|r| app.agent_count(&super::remote::instance_key(r)))
            }
            _ => None,
        };
        let sessions = match selected {
            Some(Node::Instance(i)) | Some(Node::Proc { instance: i, .. }) => {
                snapshot.instances.get(i).and_then(|r| app.session_count(&super::remote::instance_key(r)))
            }
            _ => None,
        };
        draw_detail(
            frame,
            Some(snapshot),
            selected,
            agent_count,
            sessions,
            &app.machines,
            detail_area,
            panel_focused,
        );
        selectable(app, RegionId::InstancesTree, table_area);
        selectable(app, RegionId::Detail, detail_area);
    }
    if let Some(terms_area) = terms_area {
        draw_terminal_panel(frame, app, terms_area);
    }
}

fn draw_empty(frame: &mut Frame, area: Rect, term_focused: bool, message: &str) {
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(dash_border_style(term_focused))
        .title(Tab::Instances.title());
    let text = Line::from(Span::styled(
        message,
        Style::default().add_modifier(Modifier::DIM),
    ))
    .alignment(Alignment::Center);
    let paragraph = Paragraph::new(text).block(block);
    frame.render_widget(paragraph, area);
}

fn draw_tree(
    frame: &mut Frame,
    app: &App,
    snapshot: &Snapshot,
    nodes: &[Node],
    area: Rect,
    term_focused: bool,
) {
    // TYPE only earns its width when some sandbox is a dispatcher.
    let show_type = snapshot.sandboxes.iter().any(|s| s.dispatcher);
    let mut titles = vec!["TREE", "STATUS", "UPTIME", "CPU", "MEM", "FOLDER", "SERVICES"];
    // STATUS widens only while a phase (`postCreateCommand`, …) needs it.
    let status = snapshot
        .instances
        .iter()
        .map(|r| instance_status_label(app, r).chars().count())
        .max()
        .unwrap_or(0)
        .max(9);
    let mut widths = vec![
        Constraint::Min(20),
        Constraint::Length(status as u16),
        Constraint::Length(7),
        Constraint::Length(7),
        Constraint::Length(16),
        Constraint::Min(20),
        Constraint::Min(12),
    ];
    if show_type {
        // SERVICES hugs its longest value and a trailing spacer takes the slack,
        // so TYPE sits next to the services instead of at the far right edge.
        let services = snapshot
            .instances
            .iter()
            .map(|r| r.services.join(",").chars().count())
            .chain([titles[6].len()])
            .max()
            .unwrap_or_default();
        widths[6] = Constraint::Length(services as u16);
        titles.extend(["TYPE", ""]);
        widths.extend([Constraint::Length(10), Constraint::Min(0)]);
    }
    // MACHINE only once a machine is registered (docs/architecture/daemon/machines.md): without
    // one the tree is exactly as before.
    let show_machine = !app.machines.is_empty();
    if show_machine {
        let width = app.machines.iter().map(|m| m.name.chars().count()).max().unwrap_or(0).max("MACHINE".len());
        titles.insert(1, "MACHINE");
        widths.insert(1, Constraint::Length(width as u16));
    }
    let header = Row::new(titles.into_iter().map(Cell::from))
        .style(Style::default().add_modifier(Modifier::DIM));

    let table_rows: Vec<Row> = nodes
        .iter()
        .map(|node| {
            let cells = tree_cells(app, snapshot, *node, show_type);
            let (cells, style) = match cells {
                Some((cells, style)) => (cells, style),
                None => return Row::new(vec![Cell::from("")]),
            };
            let cells = if show_machine { with_machine_cell(cells, node_machine(snapshot, *node)) } else { cells };
            Row::new(cells).style(style)
        })
        .collect();

    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(dash_border_style(term_focused))
        .title(Tab::Instances.title());

    let table = Table::new(table_rows, widths)
        .header(header)
        .block(block)
        .column_spacing(1)
        .row_highlight_style(
            Style::default().fg(SELECTION).add_modifier(Modifier::BOLD),
        );

    let mut state = TableState::default().with_selected(Some(app.selected()));
    frame.render_stateful_widget(table, area, &mut state);
}

/// The MACHINE cell's text for `node`: its machine's name, blank for this
/// host's rows and for rows that span machines (the orphan group).
fn node_machine(snapshot: &Snapshot, node: Node) -> Option<String> {
    match node {
        Node::Sandbox(i) => snapshot.sandboxes.get(i)?.machine.clone(),
        Node::Instance(i) => snapshot.instances.get(i)?.machine.clone(),
        Node::Empty(_) | Node::Proc { .. } | Node::Orphans => None,
    }
}

/// `cells` with the MACHINE cell after TREE. A one-cell row (a message
/// spanning the TREE column) stays as is.
fn with_machine_cell(mut cells: Vec<Cell<'_>>, machine: Option<String>) -> Vec<Cell<'_>> {
    if cells.len() > 1 {
        let text = Span::styled(machine.unwrap_or_default(), Style::default().fg(ACCENT));
        cells.insert(1, Cell::from(text));
    }
    cells
}

/// Render one tree node into a table row's cells and style (`None`: an
/// index out of range). Sandbox / orphan-group rows carry their stats in the
/// STATUS column and leave the instance columns blank; instance rows fill the
/// columns and indent the TREE cell. `show_type`: the TYPE column is present
/// (some sandbox is a dispatcher).
fn tree_cells<'a>(app: &App, snapshot: &'a Snapshot, node: Node, show_type: bool) -> Option<(Vec<Cell<'a>>, Style)> {
    Some(match node {
        Node::Sandbox(i) => (sandbox_tree_row(app, snapshot, i, snapshot.sandboxes.get(i)?), Style::default()),
        Node::Instance(i) => {
            let inst = snapshot.instances.get(i)?;
            instance_tree_row(
                inst,
                instance_status_label(app, inst),
                app.inbox.needs_you_for(&inst.instance_id),
                app.session_count(&super::remote::instance_key(inst)),
                super::data::dispatcher_label(inst, &snapshot.instances),
                show_type.then(|| {
                    let group = super::data::group_of(&snapshot.sandboxes, inst);
                    let dispatcher = group.is_some_and(|g| snapshot.sandboxes[g].dispatcher);
                    if dispatcher { "dispatcher" } else { "-" }
                }),
            )
        }
        Node::Empty(i) => {
            let name = snapshot.sandboxes.get(i).map(super::remote::sandbox_key).unwrap_or_default();
            let cells = vec![Cell::from(Span::styled(
                format!("    no instances — : run {name}"),
                Style::default().add_modifier(Modifier::DIM),
            ))];
            (cells, Style::default())
        }
        Node::Proc { instance, row } => (proc_tree_row(app, snapshot, instance, row), Style::default()),
        Node::Orphans => {
            let count = snapshot
                .instances
                .iter()
                .filter(|inst| super::data::group_of(&snapshot.sandboxes, inst).is_none())
                .count();
            let marker = if app.is_collapsed_group(super::data::ORPHANS_NAME) {
                '▸'
            } else {
                '▾'
            };
            let cells = vec![
                Cell::from(Span::styled(
                    format!("{marker} (not in config)"),
                    Style::default().add_modifier(Modifier::DIM),
                )),
                Cell::from(Span::styled(
                    format!("{count} orphan"),
                    Style::default().add_modifier(Modifier::DIM),
                )),
            ];
            (cells, Style::default())
        }
    })
}

/// Sandbox row `si`'s (instances, running), over [`super::data::group_of`].
fn group_counts(snapshot: &Snapshot, si: usize) -> (usize, usize) {
    let members = snapshot.instances.iter().filter(|r| super::data::group_of(&snapshot.sandboxes, r) == Some(si));
    members.fold((0, 0), |(total, running), r| {
        (total + 1, running + usize::from(matches!(r.status, ContainerStatus::Running(_))))
    })
}

fn sandbox_tree_row<'a>(app: &App, snapshot: &Snapshot, si: usize, sb: &'a SandboxRow) -> Vec<Cell<'a>> {
    let collapsed = app.is_collapsed_group(&super::remote::sandbox_key(sb));
    let marker = if collapsed { '▸' } else { '▾' };
    let (total, running) = group_counts(snapshot, si);
    let stats = sandbox_stats(total, running);
    // Green when any running, dim when the sandbox has no instances at all.
    let stats_style = if running > 0 {
        Style::default().fg(Color::Green)
    } else if total == 0 {
        Style::default().add_modifier(Modifier::DIM)
    } else {
        Style::default()
    };
    vec![
        Cell::from(Span::styled(
            format!("{marker} {}", sb.name),
            Style::default().fg(ACCENT).add_modifier(Modifier::BOLD),
        )),
        Cell::from(Span::styled(stats, stats_style)),
        Cell::from(""),
        Cell::from(""),
        Cell::from(""),
        Cell::from(source_folder_cell(sb)),
        Cell::from(""),
    ]
}

/// Combined source + folder for the sandbox row's FOLDER column: source colored
/// like `ls`, then a dim folder when set.
fn source_folder_cell(sb: &SandboxRow) -> Line<'static> {
    let mut spans = vec![Span::styled(sb.source.clone(), source_style(&sb.source))];
    if let Some(folder) = &sb.folder {
        spans.push(Span::raw(" "));
        spans.push(Span::styled(
            folder.clone(),
            Style::default().add_modifier(Modifier::DIM),
        ));
    }
    Line::from(spans)
}

/// `unread`: the instance's Inbox threads waiting on the user (needs-you
/// threads + unread notify records), shown as a yellow `✉N` after the name.
/// `sessions`: the cached helper session count ([`App::session_count`]), a
/// [`SESSION_BADGE`]`N` of the running ones when any, yellow while some are
/// detached, else dim. `owner`: a dispatcher child's dim
/// `⇠ <dispatcher>` suffix (`data::dispatcher_label`). `kind`: the TYPE cell,
/// `None` when that column is hidden. `status`: the STATUS text
/// ([`instance_status_label`]).
fn instance_tree_row(
    r: &InstanceRow,
    status: &str,
    unread: usize,
    sessions: Option<crate::runtime::procs::SessionCount>,
    owner: Option<String>,
    kind: Option<&'static str>,
) -> (Vec<Cell<'static>>, Style) {
    let style = if status == UNREACHABLE { status_style(&ContainerStatus::Missing) } else { instance_status_style(r) };
    let status = Cell::from(Span::styled(status.to_string(), style));
    let folder = if r.worktree {
        format!("⎇ {}", r.folder)
    } else {
        r.folder.clone()
    };
    let services = if r.services.is_empty() {
        "-".to_string()
    } else {
        r.services.join(",")
    };
    let mut name = vec![Span::raw(format!("  {}", r.name))];
    if unread > 0 {
        name.push(Span::styled(format!(" ✉{unread}"), Style::default().fg(Color::Yellow)));
    }
    if let Some(s) = sessions.filter(|s| s.running > 0) {
        let style = if s.detached > 0 { Style::default().fg(Color::Yellow) } else { Style::default().add_modifier(Modifier::DIM) };
        name.push(Span::styled(format!(" {SESSION_BADGE}{}", s.running), style));
    }
    if let Some(owner) = owner {
        name.push(Span::styled(format!(" {owner}"), Style::default().add_modifier(Modifier::DIM)));
    }
    if r.done {
        name.push(Span::raw(" ✓"));
    }
    let name = Cell::from(Line::from(name));
    let mut cells = vec![
        name,
        status,
        Cell::from(humanize_secs(r.uptime_secs)),
        Cell::from(r.cpu.clone().unwrap_or_else(|| "-".to_string())),
        Cell::from(r.mem.clone().unwrap_or_else(|| "-".to_string())),
        Cell::from(folder),
        Cell::from(services),
    ];
    cells.extend(kind.map(Cell::from));
    // Done: kept as is until removed, so it stays listed but recedes.
    let style = if r.done { Style::default().add_modifier(Modifier::DIM) } else { Style::default() };
    (cells, style)
}

/// The tree-row badge before an instance's running session count.
const SESSION_BADGE: &str = "▣";

/// The STATUS of a row whose machine isn't connected (docs/architecture/daemon/machines.md):
/// its last known row, styled like `missing`.
const UNREACHABLE: &str = "unreachable";

/// An instance's STATUS text: [`UNREACHABLE`] on a machine that isn't
/// connected, else its phase or container status.
fn instance_status_label<'a>(app: &App, r: &'a InstanceRow) -> &'a str {
    if super::remote::unreachable(&app.machines, r.machine.as_deref()) { UNREACHABLE } else { r.status_label() }
}

/// Render a process row (or its placeholder) for the instance at `instance`.
/// Dim throughout. Process rows put the PID in the TREE gutter (indented deeper
/// than the instance row) and the `\_`-indented args in the FOLDER column; the
/// status/uptime/cpu/mem columns stay empty. A [`ProcState::Message`] (and the
/// `MESSAGE_ROW` placeholder) renders as one dim message in the TREE column.
fn proc_tree_row<'a>(app: &App, snapshot: &'a Snapshot, instance: usize, row: usize) -> Vec<Cell<'a>> {
    let dim = Style::default().add_modifier(Modifier::DIM);
    let key = snapshot.instances.get(instance).map(super::remote::instance_key);
    let state = key.and_then(|k| app.procs.get(&k));

    // A real process row: only when we have a Rows state and a valid index.
    if row != MESSAGE_ROW {
        if let Some(ProcState::Rows { rows, .. }) = state {
            if let Some(p) = rows.get(row) {
                let pid = Cell::from(Span::styled(format!("      {}", p.pid), dim));
                let indent = "\\_ ".repeat(p.depth);
                // Coding-agent processes are highlighted blue+bold; the tree
                // connectors stay dim so the agent name itself is what pops.
                let args = if is_agent(&p.args) {
                    Cell::from(Line::from(vec![
                        Span::styled(indent, dim),
                        Span::styled(
                            p.args.clone(),
                            Style::default().fg(Color::Blue).add_modifier(Modifier::BOLD),
                        ),
                    ]))
                } else {
                    Cell::from(Span::styled(format!("{indent}{}", p.args), dim))
                };
                return vec![
                    pid,
                    Cell::from(""),
                    Cell::from(""),
                    Cell::from(""),
                    Cell::from(""),
                    args,
                    Cell::from(""),
                ];
            }
        }
    }

    // Placeholder / message row.
    let msg = match state {
        Some(ProcState::Message(m)) => m.clone(),
        _ => "(loading…)".to_string(),
    };
    vec![Cell::from(Span::styled(format!("      {msg}"), dim))]
}

/// An instance's STATUS style: its phase's while set (yellow in flight, bold
/// red failed, apart from an exited container's plain red), else the
/// container's.
fn instance_status_style(r: &InstanceRow) -> Style {
    match &r.phase {
        Some(PhaseRow::InFlight { .. }) => Style::default().fg(Color::Yellow),
        Some(PhaseRow::Failed { .. }) => Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
        None => status_style(&r.status),
    }
}

fn status_style(status: &ContainerStatus) -> Style {
    match status {
        ContainerStatus::Running(_) => Style::default().fg(Color::Green),
        ContainerStatus::Exited(_) => Style::default().fg(Color::Red),
        ContainerStatus::Missing | ContainerStatus::Unknown => {
            Style::default().add_modifier(Modifier::DIM)
        }
    }
}

/// Detail panel for the selected tree node: sandbox summary for sandbox / empty
/// nodes, the existing instance detail for instances, and a hint for the orphan
/// group. Empty when nothing is selected.
fn draw_detail(
    frame: &mut Frame,
    snapshot: Option<&Snapshot>,
    node: Option<Node>,
    agent_count: Option<usize>,
    sessions: Option<crate::runtime::procs::SessionCount>,
    machines: &[crate::serve::snapshots::SnapshotMachine],
    area: Rect,
    term_focused: bool,
) {
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(dash_border_style(term_focused))
        .title("Detail");

    let lines: Vec<Line> = match (snapshot, node) {
        (Some(s), Some(Node::Sandbox(i))) | (Some(s), Some(Node::Empty(i))) => {
            match s.sandboxes.get(i) {
                Some(sb) => sandbox_detail(s, i, sb),
                None => Vec::new(),
            }
        }
        (Some(s), Some(Node::Instance(i)))
        | (Some(s), Some(Node::Proc { instance: i, .. })) => match s.instances.get(i) {
            Some(r) => {
                let mut lines = machine_detail(machines, r.machine.as_deref());
                lines.extend(instance_detail(r, agent_count, sessions));
                lines
            }
            None => Vec::new(),
        },
        (_, Some(Node::Orphans)) => vec![Line::from(Span::styled(
            "instances whose sandbox is no longer in devsandboxes.toml",
            Style::default().add_modifier(Modifier::DIM),
        ))],
        _ => Vec::new(),
    };

    frame.render_widget(Paragraph::new(lines).block(block), area);
}

/// Sandbox summary: source, folder, services, extends chain, config hash, and
/// instance counts.
fn sandbox_detail<'a>(snapshot: &Snapshot, si: usize, sb: &'a SandboxRow) -> Vec<Line<'a>> {
    let (total, running) = group_counts(snapshot, si);
    let services = if sb.services.is_empty() {
        "-".to_string()
    } else {
        sb.services.join(", ")
    };
    let extends = if sb.extends.is_empty() {
        "-".to_string()
    } else {
        sb.extends.join(" → ")
    };
    let mut lines = vec![
        kv("source", &sb.source),
        kv("folder", sb.folder.as_deref().unwrap_or("-")),
        kv("services", &services),
        kv("extends", &extends),
    ];
    if !sb.config_hash.is_empty() {
        lines.push(kv("config hash", &sb.config_hash));
    }
    lines.push(kv("instances", &format!("{total} ({running} running)")));
    for issue in &sb.issues {
        lines.push(Line::from(Span::styled(
            format!("⚠ {issue}"),
            Style::default().fg(Color::Red),
        )));
    }
    // Identity notes: yellow, dimmed once acked ("continue as is").
    for note in &sb.identity {
        let mut style = Style::default().fg(Color::Yellow);
        if note.acked {
            style = style.add_modifier(Modifier::DIM);
        }
        lines.push(Line::from(Span::styled(format!("⚠ {}", note.text), style)));
    }
    lines
}

/// A machine row's first Detail line while its machine isn't connected:
/// why (the link's `error`), the row being its last known one.
fn machine_detail(machines: &[crate::serve::snapshots::SnapshotMachine], machine: Option<&str>) -> Vec<Line<'static>> {
    let Some(name) = machine.filter(|m| super::remote::unreachable(machines, Some(m))) else { return Vec::new() };
    let why = super::remote::machine(machines, name).and_then(|m| m.error.as_deref().map(|e| super::remote::why_of(name, e)));
    let text = match why {
        Some(why) => format!("{name} unreachable: {why} (last known)"),
        None => format!("{name} unreachable (last known)"),
    };
    vec![Line::from(Span::styled(text, Style::default().fg(Color::Red)))]
}

fn instance_detail(
    r: &InstanceRow,
    agent_count: Option<usize>,
    sessions: Option<crate::runtime::procs::SessionCount>,
) -> Vec<Line<'_>> {
    let mut lines: Vec<Line> = Vec::new();
    // First, so the panel's few rows never clip it: what failed and why.
    if let Some(PhaseRow::Failed { step, error }) = &r.phase {
        lines.push(Line::from(Span::styled(
            // A child's stderr folded into the error may carry newlines.
            format!("failed at {step}: {}", error.replace('\n', " ")),
            Style::default().fg(Color::Red),
        )));
    }
    lines.extend([
        kv("container", &r.container),
        kv("workspace", &r.workspace),
        kv("remoteUser", r.remote_user.as_deref().unwrap_or("-")),
        kv("remoteEnv", &r.remote_env_len.to_string()),
        agents_line(r, agent_count),
    ]);
    lines.extend(sessions_line(r, sessions));
    if r.worktree {
        lines.push(kv2("base", &r.base_folder, "worktree", &r.folder));
    } else {
        lines.push(kv("base folder", &r.base_folder));
    }
    if r.drift {
        lines.push(Line::from(Span::styled(
            "drift: config or dockerfile changed since the container was created",
            Style::default().fg(Color::Yellow),
        )));
    }
    lines
}

/// The `agents:` Detail line for an instance. A stopped/missing container shows
/// a dim `-` (nothing to count); a running one shows the count — blue+bold when
/// any agents are present, dim `0`, or a dim `…` while its forest is still being
/// fetched.
fn agents_line(r: &InstanceRow, agent_count: Option<usize>) -> Line<'static> {
    let (text, style) = if !matches!(r.status, ContainerStatus::Running(_)) {
        ("-".to_string(), Style::default().add_modifier(Modifier::DIM))
    } else {
        match agent_count {
            Some(0) => ("0".to_string(), Style::default().add_modifier(Modifier::DIM)),
            Some(n) => (
                n.to_string(),
                Style::default().fg(Color::Blue).add_modifier(Modifier::BOLD),
            ),
            None => ("…".to_string(), Style::default().add_modifier(Modifier::DIM)),
        }
    };
    Line::from(vec![
        Span::styled("agents: ", Style::default().add_modifier(Modifier::DIM)),
        Span::styled(text, style),
    ])
}

/// The `sessions: N (M detached)` Detail line for a running instance whose
/// helper answered a count; none otherwise (stopped, not fetched yet, or a
/// helper predating sessions). The detached part is yellow and only there
/// when some are.
fn sessions_line(r: &InstanceRow, sessions: Option<crate::runtime::procs::SessionCount>) -> Option<Line<'static>> {
    let s = sessions.filter(|_| matches!(r.status, ContainerStatus::Running(_)))?;
    let dim = Style::default().add_modifier(Modifier::DIM);
    let mut spans = vec![
        Span::styled("sessions: ", dim),
        Span::styled(s.running.to_string(), if s.running == 0 { dim } else { Style::default() }),
    ];
    if s.detached > 0 {
        spans.push(Span::styled(format!(" ({} detached)", s.detached), Style::default().fg(Color::Yellow)));
    }
    Some(Line::from(spans))
}

/// `key: value` with a dim key.
fn kv<'a>(key: &'a str, value: &str) -> Line<'a> {
    Line::from(vec![
        Span::styled(format!("{key}: "), Style::default().add_modifier(Modifier::DIM)),
        Span::raw(value.to_string()),
    ])
}

/// Two `key: value` pairs on one line (base folder vs worktree).
fn kv2<'a>(k1: &'a str, v1: &str, k2: &'a str, v2: &str) -> Line<'a> {
    Line::from(vec![
        Span::styled(format!("{k1}: "), Style::default().add_modifier(Modifier::DIM)),
        Span::raw(v1.to_string()),
        Span::raw("   "),
        Span::styled(format!("{k2}: "), Style::default().add_modifier(Modifier::DIM)),
        Span::raw(v2.to_string()),
    ])
}

fn draw_help(frame: &mut Frame, app: &App, area: Rect) {
    // A status line (e.g. `code` outcome) preempts the help hint until the
    // next key clears it.
    if let Some(status) = &app.status {
        let line = Line::from(Span::styled(
            status.clone(),
            Style::default().fg(Color::Yellow),
        ));
        frame.render_widget(Paragraph::new(line), area);
        return;
    }
    // Terminal focus (no modal) has its own hints, independent of the tab.
    if app.focus == Focus::Terminal && matches!(app.modal, Modal::None) {
        let exited = app.terms.active_session().is_some_and(|s| s.exited());
        let reconnecting = app.terms.active_session().is_some_and(|s| s.reconnecting());
        let text = if reconnecting {
            "connection lost, reconnecting — ctrl-]/F12 back · x closes"
        } else if exited {
            "terminal exited — ctrl-]/F12 back · x closes"
        } else {
            "ctrl-] / F12 back to dashboard · all other keys go to the shell"
        };
        let help = Line::from(text).style(Style::default().add_modifier(Modifier::DIM));
        frame.render_widget(Paragraph::new(help), area);
        return;
    }

    let base = match app.modal {
        Modal::Config(_) => "t toggle · tab pane · <> resize · ↑↓ scroll · esc close".to_string(),
        Modal::Help(_) => {
            "tab/S-tab setting · space/enter/click toggle · ↑↓ scroll · pgup/pgdn · g/G · esc/? close"
                .to_string()
        }
        Modal::Logs(_) => "↑↓ scroll · pgup/pgdn · g/G · esc close".to_string(),
        Modal::BuildLog(_) => "↑↓ scroll · pgup/pgdn · g/G (G follows) · esc close".to_string(),
        Modal::Confirm(ref view) => view.keys_hint().to_string(),
        Modal::None => match app.tab {
            // A process row acts only on itself: signals, nothing forwarded to
            // the parent instance. Signals need container-namespace pids, so a
            // `top` fallback listing (or a placeholder row) drops them.
            Tab::Instances if app.on_proc_row() => {
                if app.proc_row_signalable() {
                    "q quit · tab switch · ↑↓ select · ← parent · t SIGTERM · K SIGKILL · : cmd · ? help"
                        .to_string()
                } else {
                    "q quit · tab switch · ↑↓ select · ← parent · : cmd · ? help".to_string()
                }
            }
            // `r`, `s` and `d` mirror what the key would do to the
            // selection: run vs rename, stop vs start, rm vs cancel.
            Tab::Instances => format!(
                "q quit · tab switch · ↑↓ select · ←→ fold · enter config · r {} · o vscode · s {} · d {} · l logs · b build log · p forward · t term · : cmd · ? help",
                app.run_rename_hint(),
                app.stop_start_hint(),
                app.remove_hint()
            ),
            Tab::Services => {
                "q quit · tab switch · ↑↓ select · enter config · t term · p forward · : cmd · ? help"
                    .to_string()
            }
            Tab::Ports => {
                "q quit · tab switch · ↑↓ select · d stop forward · : port … · ? help".to_string()
            }
            Tab::Machines => "q quit · tab switch · ↑↓ select · a agent on/off · : cmd · ? help".to_string(),
            Tab::Inbox => match app.inbox.focus {
                InboxFocus::List => {
                    "q quit · tab switch · ↑↓ select · ←→ view · enter thread · r reply · d dismiss/done · u reopen · D clear notify · o vscode · t term · l logs · p forward · ? help"
                        .to_string()
                }
                InboxFocus::Thread => {
                    "esc list · ↑↓ scroll · tab form/reply · enter open link · 1-9 actions · r reply · d done · u reopen · o vscode · t term · l logs · p forward · m raw · q quit · ? help".to_string()
                }
                InboxFocus::Input => {
                    "enter send · alt-enter newline · esc back to thread · ←→↑↓ home end edit · ctrl-u clear · ctrl-w delete word"
                        .to_string()
                }
                InboxFocus::Form => match &app.inbox.form {
                    Some(e) if e.editing.is_some() => {
                        "enter/esc keep the edit · alt-enter newline · ←→↑↓ home end edit · ctrl-u clear · ctrl-w delete word"
                            .to_string()
                    }
                    Some(e) if e.confirming => "enter submit · esc cancel".to_string(),
                    _ => "tab/S-tab question · ↑↓ option · space pick · e edit text · enter confirm · r reply · esc thread · q quit · ? help"
                        .to_string(),
                },
            },
        },
    };
    // On the dashboard with terminals open, append the terminal-cycle hints.
    // Not over a focused Inbox thread or input: they shadow those keys.
    let shadowed = app.tab == Tab::Inbox && app.inbox.focus != InboxFocus::List;
    let text = if matches!(app.modal, Modal::None) && !app.terms.is_empty() && !shadowed {
        format!("{base} · [/] terms · ctrl-] focus term · x close term")
    } else {
        base
    };
    let help = Line::from(text).style(Style::default().add_modifier(Modifier::DIM));
    frame.render_widget(Paragraph::new(help), area);
}

/// Render the command prompt in the bottom bar: `: <input>` on the first line
/// with the caret placed via `set_cursor_position`, and a second hint line for
/// completion candidates or a red parse error.
fn draw_prompt(frame: &mut Frame, prompt: &Prompt, area: Rect) {
    let [input_area, hint_area] = Layout::vertical([
        Constraint::Length(1),
        Constraint::Length(1),
    ])
    .areas(area);

    let prefix = ": ";
    // Scrolled sideways so the caret stays in view past the right edge.
    let room = input_area.width.saturating_sub(prefix.len() as u16);
    let (_, shown, caret) = textarea::hscroll(prompt.input(), prompt.cursor(), room as usize);
    let line = Line::from(vec![Span::styled(prefix, Style::default().fg(ACCENT)), Span::raw(shown)]);
    frame.render_widget(Paragraph::new(line), input_area);

    let col = input_area.x + prefix.len() as u16 + caret;
    frame.set_cursor_position((col.min(input_area.right().saturating_sub(1)), input_area.y));

    // Hint line: parse error (red) takes precedence over completion candidates.
    let hint = if let Some(err) = &prompt.error {
        Line::from(Span::styled(err.clone(), Style::default().fg(Color::Red)))
    } else {
        prompt_candidates_line(prompt)
    };
    frame.render_widget(Paragraph::new(hint), hint_area);
}

/// Completion-candidate hint: candidates space-joined, the active one bold cyan.
/// Empty line when no cycle is in flight.
fn prompt_candidates_line(prompt: &Prompt) -> Line<'static> {
    let candidates = prompt.candidates();
    if candidates.is_empty() {
        return Line::from(String::new());
    }
    let active = prompt.cycle_index();
    let mut spans: Vec<Span> = Vec::new();
    for (i, cand) in candidates.iter().enumerate() {
        if i > 0 {
            spans.push(Span::raw(" "));
        }
        let style = if i == active {
            Style::default().fg(ACCENT).add_modifier(Modifier::BOLD)
        } else {
            Style::default().add_modifier(Modifier::DIM)
        };
        spans.push(Span::styled(cand.clone(), style));
    }
    Line::from(spans)
}

/// Render the config explorer full-screen over the dashboard: config (TOML) on
/// the left, `docker inspect` (JSON) on the right, split at `split_pct` with the
/// two panes' shared border acting as the divider. The focused pane is marked in
/// its title.
fn draw_config_modal(frame: &mut Frame, app: &App, view: &ConfigView) {
    let area = frame.area();

    // Clear whatever is underneath so the modal is opaque, then split.
    frame.render_widget(ratatui::widgets::Clear, area);
    let [left_area, right_area] = Layout::horizontal([
        Constraint::Percentage(view.split_pct),
        Constraint::Min(0),
    ])
    .areas(area);

    let (side, other) = match view.showing {
        Side::Original => ("original", "resolved"),
        Side::Resolved => ("resolved", "original"),
    };
    let hash = if view.hash.is_empty() {
        String::new()
    } else {
        format!(" — {}", view.hash)
    };
    let config_focused = matches!(view.focus, Pane::Config);
    let config_mark = if config_focused { "▶ " } else { "" };
    let config_title = format!(
        " {config_mark}config: {} — {side} (t: {other}){hash} ",
        view.title
    );
    let config_lines: Vec<Line> = view.body().lines().map(highlight_toml_line).collect();
    frame.render_widget(
        Paragraph::new(config_lines)
            .block(pane_block(config_title, config_focused))
            .scroll((view.scroll, 0)),
        left_area,
    );
    selectable_lines(app, RegionId::ConfigLeft, left_area, view.scroll, view.body());

    let inspect_mark = if config_focused { "" } else { "▶ " };
    let inspect_title = if view.inspect_container.is_empty() {
        format!(" {inspect_mark}inspect ")
    } else {
        format!(" {inspect_mark}inspect — {} ", view.inspect_container)
    };
    let inspect_lines: Vec<Line> = view.inspect.lines().map(highlight_json_line).collect();
    frame.render_widget(
        Paragraph::new(inspect_lines)
            .block(pane_block(inspect_title, !config_focused))
            .scroll((view.inspect_scroll, 0)),
        right_area,
    );
    selectable_lines(app, RegionId::ConfigRight, right_area, view.inspect_scroll, &view.inspect);
}

/// Border style for the dashboard's table / Detail blocks: normally ACCENT, but
/// DIM when the integrated terminal holds focus (the terminal panel becomes the
/// accented one). Titles stay unchanged — only the border color shifts.
fn dash_border_style(term_focused: bool) -> Style {
    if term_focused {
        Style::default().add_modifier(Modifier::DIM)
    } else {
        Style::default().fg(ACCENT)
    }
}

/// A config-modal pane block. The focused pane's border is accented + bold; the
/// unfocused one is dim so the shared column reads as the divider.
fn pane_block(title: String, focused: bool) -> Block<'static> {
    let border_style = if focused {
        Style::default().fg(ACCENT).add_modifier(Modifier::BOLD)
    } else {
        Style::default().add_modifier(Modifier::DIM)
    };
    Block::default()
        .borders(Borders::ALL)
        .border_style(border_style)
        .title(title)
}

/// Render a plain scrollable text modal (help, logs) full-screen. No per-line
/// highlighting — the body is shown verbatim.
fn draw_text_modal(frame: &mut Frame, app: &App, view: &TextModal) {
    let area = frame.area();
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(ACCENT))
        .title(view.title.clone());
    let paragraph = Paragraph::new(view.body.clone()).block(block).scroll((view.scroll, 0));
    frame.render_widget(ratatui::widgets::Clear, area);
    frame.render_widget(paragraph, area);
    selectable_lines(app, RegionId::TextModal, area, view.scroll, &view.body);
}

/// [`draw_text_modal`] for the build log, shown from [`BuildLogModal::top`]
/// (the bottom while following), with the body height recorded for `App`'s
/// stick-to-bottom math. A read log is drawn from its styled lines (the
/// shown ones only), which line up with the plain body's.
fn draw_build_log_modal(frame: &mut Frame, app: &App, view: &BuildLogModal) {
    let area = frame.area();
    let height = Block::bordered().inner(area).height;
    view.height.set(height);
    let top = view.top();
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(ACCENT))
        .title(view.text.title.clone());
    let paragraph = if view.styled.is_empty() {
        Paragraph::new(view.text.body.clone()).scroll((top, 0))
    } else {
        let shown = view.styled.iter().skip(usize::from(top)).take(usize::from(height)).cloned();
        Paragraph::new(shown.collect::<Vec<_>>())
    };
    let paragraph = paragraph.block(block);
    frame.render_widget(ratatui::widgets::Clear, area);
    frame.render_widget(paragraph, area);
    selectable_lines(app, RegionId::TextModal, area, top, &view.text.body);
}

/// A small centered yes/no box over the dashboard.
fn draw_confirm_modal(frame: &mut Frame, view: &ConfirmModal) {
    let full = frame.area();
    let widest = std::iter::once(&view.question)
        .chain(&view.body)
        .map(|l| l.chars().count())
        .chain([view.choices().chars().count()])
        .max()
        .unwrap_or(0);
    let width = (widest.min(u16::MAX as usize) as u16).saturating_add(6).max(24).min(full.width);
    let height = (view.body.len().min(u16::MAX as usize) as u16).saturating_add(4).min(full.height);
    let area = Rect {
        x: full.x + (full.width - width) / 2,
        y: full.y + (full.height - height) / 2,
        width,
        height,
    };
    let block = Block::default().borders(Borders::ALL).border_style(Style::default().fg(ACCENT));
    let choices = Line::from(view.choices()).style(Style::default().add_modifier(Modifier::DIM));
    frame.render_widget(ratatui::widgets::Clear, area);
    if view.body.is_empty() {
        let lines = vec![Line::from(view.question.clone()), choices];
        frame.render_widget(Paragraph::new(lines).alignment(Alignment::Center).block(block), area);
        return;
    }
    // The identity modals: a listing, left-aligned under the question.
    let mut lines = vec![Line::from(view.question.clone())];
    lines.extend(view.body.iter().map(|l| Line::from(l.clone()).style(Style::default().fg(Color::Yellow))));
    lines.push(choices);
    frame.render_widget(Paragraph::new(lines).block(block), area);
}

/// The `?` modal's `(settings, help body)` areas inside its border over the
/// full frame `area`: one row per [`SETTINGS`] entry, a blank row, then the
/// help text. Shared by the draw and [`help_setting_hit`].
fn help_layout(area: Rect) -> (Rect, Rect) {
    let inner = Block::bordered().inner(area);
    let n = (SETTINGS.len() as u16).min(inner.height);
    let settings = Rect { height: n, ..inner };
    let gap = (n + 1).min(inner.height);
    let body = Rect { y: inner.y + gap, height: inner.height - gap, ..inner };
    (settings, body)
}

/// The [`SETTINGS`] row under `(col, row)` of the `?` modal drawn over the
/// full frame `area`, if any.
pub fn help_setting_hit(area: Rect, col: u16, row: u16) -> Option<usize> {
    let (settings, _) = help_layout(area);
    settings.contains(Position::new(col, row)).then(|| (row - settings.y) as usize)
}

/// The `?` Settings & help modal: the settings rows on top (`[x]` per
/// value, the cursor row accented), the key reference below, scrolling and
/// selectable like any [`TextModal`] (the settings rows are no region: a
/// press there is a toggle, not a selection).
fn draw_help_modal(frame: &mut Frame, app: &App, view: &HelpModal) {
    let area = frame.area();
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(ACCENT))
        .title(view.text.title.clone());
    frame.render_widget(ratatui::widgets::Clear, area);
    frame.render_widget(block, area);
    let (settings_area, body_area) = help_layout(area);
    let width = SETTINGS.iter().map(|s| s.label.chars().count()).max().unwrap_or(0);
    let rows: Vec<Line> = SETTINGS
        .iter()
        .enumerate()
        .map(|(i, spec)| {
            let on = if (spec.get)(&app.settings) { 'x' } else { ' ' };
            let cursor = i == view.cursor;
            let style = if cursor {
                Style::default().fg(ACCENT).add_modifier(Modifier::BOLD)
            } else {
                Style::default()
            };
            Line::from(vec![
                Span::styled(format!("{} [{on}] {:<width$}  ", if cursor { '›' } else { ' ' }, spec.label), style),
                Span::styled((spec.help)(app.copy_key_intercepted), Style::default().add_modifier(Modifier::DIM)),
            ])
        })
        .collect();
    frame.render_widget(Paragraph::new(rows), settings_area);
    let body = &view.text.body;
    frame.render_widget(Paragraph::new(body.clone()).scroll((view.text.scroll, 0)), body_area);
    let rows = body.lines().map(select::RowText::plain).collect();
    app.add_rows_region(RegionId::TextModal, body_area, view.text.scroll as usize, rows);
}

/// [`selectable`] for a bordered `Paragraph` of `body` scrolled to `scroll`
/// without wrap: one row per line, copied whole past the pane's right edge
/// ([`select::extract_rows`]).
fn selectable_lines(app: &App, id: RegionId, area: Rect, scroll: u16, body: &str) {
    let rows = body.lines().map(select::RowText::plain).collect();
    app.add_rows_region(id, Block::bordered().inner(area), scroll as usize, rows);
}

/// Light per-line TOML highlighting: `[section]` headers cyan bold, comments
/// dim, the `key =` part of an assignment green, and the rest default.
fn highlight_toml_line(line: &str) -> Line<'static> {
    let trimmed = line.trim_start();
    if trimmed.starts_with('#') {
        return Line::from(Span::styled(
            line.to_string(),
            Style::default().add_modifier(Modifier::DIM),
        ));
    }
    if trimmed.starts_with('[') {
        return Line::from(Span::styled(
            line.to_string(),
            Style::default().fg(ACCENT).add_modifier(Modifier::BOLD),
        ));
    }
    // Split a `key = value` assignment at the first `=`, styling the key half
    // (through the `=`) green and leaving the value default.
    if let Some(eq) = line.find('=') {
        let (key, value) = line.split_at(eq + 1);
        return Line::from(vec![
            Span::styled(key.to_string(), Style::default().fg(Color::Green)),
            Span::raw(value.to_string()),
        ]);
    }
    Line::from(Span::raw(line.to_string()))
}

/// Light per-line JSON highlighting mirroring [`highlight_toml_line`]: a
/// `"key":` prefix (through the colon) is green, structural punctuation-only
/// lines (`{`, `}`, `[`, `],`) are dim, and everything else is default. The
/// classification is shared with the CLI `inspect` command
/// ([`crate::render::classify_json_line`]) so both highlight identically.
fn highlight_json_line(line: &str) -> Line<'static> {
    match crate::render::classify_json_line(line) {
        JsonLine::Structural => Line::from(Span::styled(
            line.to_string(),
            Style::default().add_modifier(Modifier::DIM),
        )),
        JsonLine::KeyValue(split) => {
            let (key, value) = line.split_at(split);
            Line::from(vec![
                Span::styled(key.to_string(), Style::default().fg(Color::Green)),
                Span::raw(value.to_string()),
            ])
        }
        JsonLine::Plain => Line::from(Span::raw(line.to_string())),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tui::app::App;
    use crate::tui::term::TermSession;
    use std::path::PathBuf;

    /// An `App` with the given terminal sessions opened, for layout/tab tests.
    fn app_with_terms(sessions: Vec<TermSession>) -> App {
        let mut app = App::new(PathBuf::from("/tmp"));
        for s in sessions {
            app.terms.open(s);
        }
        app
    }

    #[test]
    fn term_pane_size_none_matches_inner_geometry() {
        // 80x40 frame, prompt closed. draw() reserves 1 (tabs) + 1 (bottom) → 38
        // content rows. Bottom section = 50% of 38 = 19 rows; panel width = 70%
        // of 80 = 56 cols. Inner screen = minus 1-cell border each side.
        let frame = Rect::new(0, 0, 80, 40);
        assert_eq!(term_pane_size(frame, false), Some((19 - 2, 56 - 2)));
    }

    #[test]
    fn term_pane_size_prompt_open_shrinks_height() {
        // Prompt open reserves a 2-line bottom bar → 37 content rows; 50% = 18.
        let frame = Rect::new(0, 0, 80, 40);
        assert_eq!(term_pane_size(frame, true), Some((18 - 2, 56 - 2)));
    }

    #[test]
    fn term_pane_size_tiny_frame_is_none() {
        // Too small to carve a usable inner screen.
        assert_eq!(term_pane_size(Rect::new(0, 0, 4, 4), false), None);
    }

    #[test]
    fn inbox_areas_split_the_width_at_split_pct() {
        let area = Rect::new(2, 3, 100, 20);
        let (list, thread) = inbox_areas(area, 40);
        assert_eq!((list.x, list.width), (2, 40));
        assert_eq!((thread.x, thread.width), (42, 60));
        assert_eq!((list.y, list.height, thread.y, thread.height), (3, 20, 3, 20));
        // The default split, on an odd width: the thread pane takes the rest.
        let (list, thread) = inbox_areas(Rect::new(0, 0, 81, 10), crate::tui::app::InboxView::default().split_pct);
        assert_eq!((list.width, thread.width), (32, 49));
    }

    #[test]
    fn inbox_split_rect_matches_draw_inbox() {
        let frame = Rect::new(0, 0, 100, 40);
        for prompt_open in [false, true] {
            // Content = frame minus the tab line and the 1-2 row bottom bar.
            let bottom = if prompt_open { 2 } else { 1 };
            let content = Rect::new(0, 1, 100, 39 - bottom);
            // No terminals: the whole content area, as draw_inbox lays it out.
            let closed = App::new(PathBuf::from("/tmp"));
            let (top, detail, terms) = content_areas(&closed, content);
            assert!(terms.is_none());
            let rect = inbox_split_rect(frame, prompt_open, false);
            assert_eq!(rect, top.union(detail));
            assert_eq!(rect, content);
            // Terminals open: the top only, ending where the panel starts.
            let open = app_with_terms(vec![TermSession::test_session("web-1", "devsandbox-web-1", 24, 80)]);
            let (top, _detail, terms) = content_areas(&open, content);
            let rect = inbox_split_rect(frame, prompt_open, true);
            assert_eq!(rect, top);
            assert_eq!(rect.bottom(), terminal_panel_rect(frame, prompt_open).y);
            assert_eq!(terms, Some(terminal_panel_rect(frame, prompt_open)));
            // The divider is the thread pane's left edge.
            let (_list, thread) = inbox_areas(rect, 40);
            assert_eq!(inbox_divider_col(rect, 40), thread.x);
            assert_eq!(thread.x, 40);
        }
    }

    #[test]
    fn tab_specs_number_and_flag_active() {
        let app = app_with_terms(vec![
            TermSession::test_session("web-1", "devsandbox-web-1", 24, 80),
            TermSession::test_session("api-2", "devsandbox-api-2", 24, 80),
        ]);
        // `open` makes the last session active.
        let specs = terminal_tab_specs(&app);
        assert_eq!(
            specs,
            vec![
                ("1:web-1".to_string(), false, false),
                ("2:api-2".to_string(), true, false),
            ]
        );
    }

    #[test]
    fn tab_specs_exited_gets_suffix() {
        let dead = TermSession::test_session("web-1", "devsandbox-web-1", 24, 80);
        dead.set_exited();
        let app = app_with_terms(vec![dead]);
        let specs = terminal_tab_specs(&app);
        assert_eq!(specs, vec![("1:web-1 (exited)".to_string(), true, true)]);
    }

    #[test]
    fn highlight_toml_styles_by_kind() {
        // Section header: cyan bold.
        let header = highlight_toml_line("[sandbox.repo]");
        assert_eq!(header.spans.len(), 1);
        let s = header.spans[0].style;
        assert_eq!(s.fg, Some(ACCENT));
        assert!(s.add_modifier.contains(Modifier::BOLD));

        // Comment: dim.
        let comment = highlight_toml_line("  # a note");
        assert!(comment.spans[0].style.add_modifier.contains(Modifier::DIM));

        // Assignment: key half green, value split off.
        let kv = highlight_toml_line("image = \"node:22\"");
        assert_eq!(kv.spans.len(), 2);
        assert_eq!(kv.spans[0].style.fg, Some(Color::Green));
        assert_eq!(kv.spans[0].content, "image =");
        assert_eq!(kv.spans[1].content, " \"node:22\"");

        // Plain line: single default span, no panic.
        let plain = highlight_toml_line("just text");
        assert_eq!(plain.spans.len(), 1);
    }

    #[test]
    fn highlight_splits_a_full_document() {
        let doc = "[sandbox.s]\nimage = \"a\"\n# c\n\nx";
        let lines: Vec<Line> = doc.lines().map(highlight_toml_line).collect();
        assert_eq!(lines.len(), 5);
    }

    #[test]
    fn highlight_json_styles_by_kind() {
        // Key/value: green key half through the colon, plain value.
        let kv = highlight_json_line("    \"Id\": \"abc\",");
        assert_eq!(kv.spans.len(), 2);
        assert_eq!(kv.spans[0].style.fg, Some(Color::Green));
        assert_eq!(kv.spans[0].content, "    \"Id\":");
        assert_eq!(kv.spans[1].content, " \"abc\",");

        // Structural punctuation line: dim.
        let brace = highlight_json_line("  {");
        assert_eq!(brace.spans.len(), 1);
        assert!(brace.spans[0].style.add_modifier.contains(Modifier::DIM));

        // Plain value line: single default span, no panic.
        let plain = highlight_json_line("    \"abc\"");
        assert_eq!(plain.spans.len(), 1);
        assert_eq!(plain.spans[0].style.fg, None);
    }

    use crate::devsbd::notify::Record;
    use crate::inbox::{Inbox, Note};
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    fn text(line: &Line) -> String {
        line.spans.iter().map(|s| s.content.as_ref()).collect()
    }

    fn dthread(title: &str, state: State, status: Option<&str>) -> Thread {
        Thread {
            kind: Kind::Thread,
            title: title.into(),
            owner_name: "bab-disp".into(),
            state: Some(state),
            status: status.map(str::to_string),
            ..Thread::default()
        }
    }

    fn note(msg: &str, level: Level, at: u64) -> Thread {
        Thread {
            kind: Kind::Notify,
            owner_name: "builder".into(),
            notes: vec![Note { id: 1, record: Record { level, key: None, link: None, msg: msg.into(), at } }],
            ..Thread::default()
        }
    }

    #[test]
    fn fit_keeps_both_with_a_gap_and_truncates_left_first() {
        assert_eq!(fit("title", "2m", 20), ("title".into(), "2m".into()));
        // Exactly fits with one space.
        assert_eq!(fit("title", "2m", 8), ("title".into(), "2m".into()));
        // Left cut with `…` to keep the gap.
        assert_eq!(fit("a long title here", "2m", 14), ("a long tit…".into(), "2m".into()));
        // Too narrow to keep FIT_MIN_LEFT columns of title: the right goes.
        assert_eq!(fit("a long title here", "12 min ago", 15), ("a long title h…".into(), String::new()));
        // A short left needs only its own width.
        assert_eq!(fit("ok", "12 min ago", 13), ("ok".into(), "12 min ago".into()));
        assert_eq!(fit("anything", "", 4), ("any…".into(), String::new()));
        assert_eq!(fit("x", "y", 0), (String::new(), String::new()));
    }

    #[test]
    fn fit_counts_display_width() {
        // `界` is two columns: 4 glyphs = 8 columns.
        assert_eq!(fit("世界世界", "1h", 11), ("世界世界".into(), "1h".into()));
        // 8 columns for the left: three wide glyphs (6) + `…`, as a fourth
        // wouldn't leave room for it.
        let (l, r) = fit("世界世界世界", "1h", 11);
        assert_eq!((l.as_str(), r.as_str()), ("世界世…", "1h"));
        assert!(cols(&l) <= 8);
        // A wide glyph that would straddle the limit is dropped whole.
        assert_eq!(truncate("a世界", 3), "a…");
    }

    #[test]
    fn chip_per_kind_state_and_level() {
        let c = |t: &Thread| card_chip(t).into_iter().map(|(s, _)| s).collect::<String>();
        // The status shows next to every state, not just active.
        assert_eq!(c(&dthread("t", State::NeedsYou, Some("x"))), "● x");
        assert_eq!(c(&dthread("t", State::NeedsYou, None)), "● needs you");
        assert_eq!(c(&dthread("t", State::Active, Some("running ci"))), "○ running ci");
        assert_eq!(c(&dthread("t", State::Active, None)), "○ active");
        assert_eq!(c(&dthread("t", State::Active, Some("  "))), "○ active");
        assert_eq!(c(&dthread("t", State::Done, None)), "✓ done");
        assert_eq!(c(&dthread("t", State::Done, Some("merged"))), "✓ merged");
        assert_eq!(c(&note("m", Level::Warn, 0)), "▲ warn");
        assert_eq!(c(&note("m", Level::Error, 0)), "✖ error");
        assert_eq!(c(&note("m", Level::Info, 0)), "· info");
        assert_eq!(card_chip(&dthread("t", State::NeedsYou, None))[0].1.fg, Some(Color::Yellow));
        assert_eq!(card_chip(&dthread("t", State::NeedsYou, Some("x")))[0].1.fg, Some(Color::Yellow));
        assert_eq!(card_chip(&note("m", Level::Error, 0))[0].1.fg, Some(Color::Red));
        // A status is inline markdown.
        let parts = card_chip(&dthread("t", State::Active, Some("run `ci`\nnext")));
        assert_eq!(parts.iter().map(|(s, _)| s.as_str()).collect::<String>(), "○ run ci next");
        assert_eq!(parts.iter().find(|(s, _)| s == "ci").unwrap().1.bg, markdown::CODE.bg);
    }

    #[test]
    fn card_chip_and_pane_head_agree() {
        let row_text = |l: &Line| l.spans.iter().map(|s| s.content.as_ref()).collect::<String>();
        for t in [
            dthread("t", State::NeedsYou, Some("review `drafts`")),
            dthread("t", State::Active, None),
            dthread("t", State::Done, None),
            note("m", Level::Warn, 0),
        ] {
            let card: String = card_chip(&t).into_iter().map(|(s, _)| s).collect();
            let pane = &header_lines(&pane_header(&t, None, false, 0), 200, false)[1];
            assert!(row_text(pane).starts_with(&format!("{card}  ·  ")), "{card:?} vs {:?}", row_text(pane));
        }
    }

    #[test]
    fn card_lines_layout_and_selection() {
        let mut t = dthread("#6900 feat/agent-run-cost", State::NeedsYou, None);
        t.unread = true;
        t.updated_at = 1000 - 120;
        let [l1, l2] = card_lines(&t, 30, false, true, 1000, 0);
        assert_eq!(text(&l1), " #6900 feat/agent-run-cost 2m ");
        assert_eq!(text(&l2), " ● needs you         bab-disp ");
        assert_eq!((l1.width(), l2.width()), (30, 30));
        assert!(l1.spans[1].style.add_modifier.contains(Modifier::BOLD), "unread title is bold");
        assert_eq!(l1.style.bg, None);

        let [s1, s2] = card_lines(&t, 30, true, true, 1000, 0);
        for (line, bar) in [(&s1, ACCENT), (&s2, ACCENT)] {
            assert_eq!(line.spans[0].content, "▌");
            assert_eq!(line.spans[0].style.fg, Some(bar));
            assert_eq!(line.style.bg, Some(CARD_TINT));
        }
        let [u1, _] = card_lines(&t, 30, true, false, 1000, 0);
        assert_eq!(u1.spans[0].style.fg, Some(ACCENT_DIM));

        // Link + archived suffixes; archived dims the title.
        t.link = Some("https://x".into());
        t.archived = true;
        t.title = "fix".into();
        let [a1, _] = card_lines(&t, 40, false, true, 1000, 0);
        assert!(text(&a1).starts_with(" fix ↗ · archived "));
        assert!(a1.spans[1].style.add_modifier.contains(Modifier::DIM));
    }

    #[test]
    fn card_offset_scrolls_minimally() {
        // 11 rows hold 4 cards (the last spacer dropped).
        assert_eq!(card_offset(0, 3, 10, 11), 0);
        assert_eq!(card_offset(0, 4, 10, 11), 1);
        // Moving up inside the window keeps it still.
        assert_eq!(card_offset(3, 4, 10, 11), 3);
        assert_eq!(card_offset(3, 2, 10, 11), 2);
        // A shrunk list pulls the window back.
        assert_eq!(card_offset(8, 5, 6, 11), 2);
        // Too short for even one card: the selected one leads.
        assert_eq!(card_offset(0, 5, 10, 1), 5);
    }

    #[test]
    fn view_strip_shortens_to_fit() {
        let counts = [3, 5, 0, 9];
        let full = view_strip(View::NeedsYou, counts, 80);
        assert_eq!(text(&full), " ‹ Needs you 3 │ Active 5 │ Done │ All 9 ›");
        let current = full.spans.iter().find(|s| s.content == "Needs you").unwrap();
        assert_eq!(current.style.fg, Some(ACCENT));
        assert!(full.spans[1].style.add_modifier.contains(Modifier::DIM), "‹ dim at the left end");
        assert_eq!(text(&view_strip(View::Active, counts, 36)), " ‹ Needs you │ Active │ Done │ All ›");
        assert_eq!(text(&view_strip(View::All, counts, 20)), " ‹ Needs │ Active │ Done │ All ›");
    }

    fn render(app: &App, w: u16, h: u16) -> String {
        let mut term = Terminal::new(TestBackend::new(w, h)).unwrap();
        term.draw(|f| draw(f, app)).unwrap();
        let buf = term.backend().buffer().clone();
        (0..h)
            .map(|y| (0..w).map(|x| buf[(x, y)].symbol().to_string()).collect::<String>())
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Sandbox `s` with one instance per `(name, status, phase)`.
    fn phase_app(rows: Vec<(&str, ContainerStatus, Option<PhaseRow>)>) -> App {
        let instances = rows
            .into_iter()
            .map(|(name, status, phase)| InstanceRow {
                name: name.into(),
                sandbox: "s".into(),
                container: format!("devsandbox-{name}"),
                status,
                uptime_secs: 0,
                cpu: None,
                mem: None,
                folder: "/f".into(),
                worktree: false,
                services: Vec::new(),
                workspace: "/w".into(),
                remote_user: None,
                remote_env_len: 0,
                base_folder: "/f".into(),
                drift: false,
                instance_id: name.into(),
                dispatcher: None,
                done: false,
                phase,
                root: None,
                machine: None,
            })
            .collect();
        let sandbox = SandboxRow {
            name: "s".into(),
            source: "image x".into(),
            folder: None,
            services: Vec::new(),
            extends: Vec::new(),
            config_hash: "hash".into(),
            build_hash: String::new(),
            issues: Vec::new(),
            identity: Vec::new(),
            dispatcher: false,
            worktree_branch: None,
            root: None,
            machine: None,
        };
        let mut app = App::new(PathBuf::from("/tmp"));
        app.set_snapshot(Snapshot {
            instances,
            sandboxes: vec![sandbox],
            services: Vec::new(),
            sandbox_count: 1,
            runtime_name: "docker".into(),
            runtime_version: None,
            collected_at: std::time::Instant::now(),
            stats: true,
            error: None,
        });
        app
    }

    /// STATUS shows the phase (widening for a lifecycle step's name) in its
    /// own colors, and a failed row's Detail says where and why.
    #[test]
    fn instance_rows_show_their_phase() {
        let failed = PhaseRow::Failed { step: "postCreateCommand".into(), error: "exit status 1".into() };
        let mut app = phase_app(vec![
            ("bad", running(), Some(failed)),
            ("busy", ContainerStatus::Missing, Some(PhaseRow::InFlight { step: "postCreateCommand".into() })),
            ("ok", running(), None),
        ]);
        app.on_key(KeyEvent::from(KeyCode::Down)); // onto `bad`
        let screen = render(&app, 140, 30);
        let line = |name: &str| screen.lines().find(|l| l.contains(&format!("  {name} "))).unwrap().to_string();
        assert!(line("bad").contains(" failed "), "{screen}");
        assert!(line("busy").contains(" postCreateCommand "), "unclipped: {screen}");
        assert!(line("ok").contains(" running "), "{screen}");
        assert!(screen.contains("failed at postCreateCommand: exit status 1"), "{screen}");
        assert!(screen.contains("s rebuild"), "help bar offers the retry: {screen}");

        let style = |i: usize| instance_status_style(&app.snapshot.as_ref().unwrap().instances[i]);
        assert_eq!(style(0), Style::default().fg(Color::Red).add_modifier(Modifier::BOLD));
        assert_eq!(style(1), Style::default().fg(Color::Yellow));
        assert_eq!(style(2), Style::default().fg(Color::Green));
    }

    /// A cached session count puts a badge on the tree row (none at zero or
    /// unknown) and a `sessions:` line in the selected instance's Detail.
    #[test]
    fn session_counts_show_in_the_tree_and_detail() {
        use crate::runtime::procs::SessionCount;
        let mut app = phase_app(vec![("web", running(), None), ("idle", running(), None), ("old", running(), None)]);
        let rows = |sessions| ProcState::Rows { rows: Vec::new(), signalable: true, sessions };
        app.procs.insert("web".into(), rows(Some(SessionCount { running: 2, detached: 1 })));
        app.procs.insert("idle".into(), rows(Some(SessionCount::default())));
        app.procs.insert("old".into(), rows(None));
        app.on_key(KeyEvent::from(KeyCode::Down)); // onto `web`
        let screen = render(&app, 140, 30);
        let line = |name: &str| screen.lines().find(|l| l.contains(&format!("  {name} "))).unwrap().to_string();
        assert!(line("web").contains(&format!("  web {SESSION_BADGE}2 ")), "{screen}");
        assert!(!line("idle").contains(SESSION_BADGE), "{screen}");
        assert!(!line("old").contains(SESSION_BADGE), "{screen}");
        assert!(screen.contains("sessions: 2 (1 detached)"), "{screen}");

        let r = &app.snapshot.as_ref().unwrap().instances[0];
        let text = |l: Line| l.spans.iter().map(|s| s.content.to_string()).collect::<String>();
        assert_eq!(sessions_line(r, Some(SessionCount { running: 1, detached: 0 })).map(text).as_deref(), Some("sessions: 1"));
        assert!(sessions_line(r, None).is_none(), "an old helper: no line");
        let mut stopped = r.clone();
        stopped.status = ContainerStatus::Missing;
        assert!(sessions_line(&stopped, Some(SessionCount::default())).is_none());
    }

    /// Un-acked identity notes put a yellow line above the table, in both
    /// views; Detail lists every note, yellow, the acked ones dimmed.
    #[test]
    fn identity_notes_show_in_the_header_and_detail() {
        use crate::snapshot::IdentityNote;
        let mut app = phase_app(vec![("web", running(), None)]);
        let mut s = app.snapshot.clone().unwrap();
        s.sandboxes[0].identity = vec![
            IdentityNote { id: "a".into(), text: "sandbox.s: remove remoteUser = \"root\"".into(), acked: true },
            IdentityNote { id: "b".into(), text: "sandbox.s: mounts entry \"x\" -> \"y\"".into(), acked: false },
        ];
        app.set_snapshot(s.clone());
        let screen = render(&app, 140, 30);
        assert!(screen.contains("1 sandbox uses /root (U to update)"), "{screen}");
        // A start of it asks first: the un-acked notes, then the choices.
        let mut asked = phase_app(vec![("web", running(), None)]);
        asked.set_snapshot(s.clone());
        asked.pending_action = Some(crate::tui::prompt::PromptAction::Start { instance: "web".into() });
        assert_eq!(asked.take_pending_action(), None);
        let modal = render(&asked, 140, 30);
        assert!(modal.contains("sandbox s assumes root in the container"), "{modal}");
        assert!(modal.contains("  sandbox.s: mounts entry \"x\" -> \"y\""), "{modal}");
        assert!(!modal.contains("│  sandbox.s: remove remoteUser"), "acked: not listed: {modal}");
        assert!(modal.contains("[u] update  [c] continue as is (don't ask again)  [s] skip this time"), "{modal}");
        assert!(modal.contains("u update · c continue as is · s/esc skip"), "help bar: {modal}");
        assert!(screen.contains("⚠ sandbox.s: remove remoteUser = \"root\""), "{screen}");

        // Detail's fixed height clips the rest on screen; the lines are all there.
        let lines = sandbox_detail(&s, 0, &s.sandboxes[0]);
        assert_eq!(text(lines.last().unwrap()), "⚠ sandbox.s: mounts entry \"x\" -> \"y\"");
        let style = |needle: &str| lines.iter().find(|l| text(l).contains(needle)).unwrap().spans[0].style;
        assert_eq!(style("remoteUser"), Style::default().fg(Color::Yellow).add_modifier(Modifier::DIM));
        assert_eq!(style("mounts entry"), Style::default().fg(Color::Yellow));

        app.on_key(KeyEvent::from(KeyCode::Char('2')));
        let services = render(&app, 140, 30);
        assert!(services.contains("1 sandbox uses /root"), "services view too: {services}");

        // Everything acked: no line.
        s.sandboxes[0].identity[1].acked = true;
        app.set_snapshot(s);
        assert!(!render(&app, 140, 30).contains("uses /root"));
    }

    /// The MACHINE column only with a machine registered; a machine that
    /// isn't connected shows its rows `unreachable` (Detail: why), and one
    /// with no rows yet a note before the totals.
    #[test]
    fn machine_rows_get_a_column_and_unreachable_status() {
        use crate::serve::snapshots::LinkState;
        use crate::tui::remote::tests::sm;
        let mut app = phase_app(vec![("web", running(), None)]);
        let alone = render(&app, 200, 30);
        assert!(!alone.contains("MACHINE"), "{alone}");

        let mut s = app.snapshot.clone().unwrap();
        let mut remote = s.instances[0].clone();
        remote.machine = Some("box".into());
        let mut sandbox = s.sandboxes[0].clone();
        sandbox.machine = Some("box".into());
        s.instances.push(remote);
        s.sandboxes.push(sandbox);
        let mut boxed = sm("box", LinkState::Unreachable);
        boxed.error = Some("Connection refused".into());
        app.machines = vec![boxed, sm("new", LinkState::Connecting)];
        app.set_snapshot(s);
        for _ in 0..3 {
            app.on_key(KeyEvent::from(KeyCode::Down)); // onto box's web
        }
        let screen = render(&app, 200, 30);
        let header = screen.lines().find(|l| l.contains("TREE")).unwrap();
        assert!(header.contains("TREE") && header.contains(" MACHINE ") && header.contains("STATUS"), "{screen}");
        let rows: Vec<&str> = screen.lines().filter(|l| l.contains("  web ")).collect();
        assert_eq!(rows.len(), 2, "{screen}");
        assert!(rows[0].contains(" running ") && !rows[0].contains("box"), "local first: {screen}");
        assert!(rows[1].contains(" box ") && rows[1].contains(" unreachable "), "{screen}");
        assert!(screen.contains("box unreachable: Connection refused (last known)"), "{screen}");
        assert!(screen.contains("new: connecting · 1 sandbox"), "{screen}");

        // Connected again: its own status.
        app.machines[0].state = LinkState::Connected;
        let screen = render(&app, 200, 30);
        let rows: Vec<&str> = screen.lines().filter(|l| l.contains("  web ")).collect();
        assert!(rows[1].contains(" running "), "{screen}");
    }

    /// The Machines tab: a row per registered machine, in order, with its
    /// target, link state (and why), `agent` on/off and version (`-`).
    #[test]
    fn machines_tab_rows() {
        use crate::serve::snapshots::LinkState;
        use crate::tui::remote::tests::sm;
        let mut app = phase_app(vec![("web", running(), None)]);
        let mut down = sm("down", LinkState::Unreachable);
        down.error = Some("Connection refused".into());
        let mut up = sm("box", LinkState::Connected);
        up.agent = true;
        up.version = Some("0.9.1".into());
        down.exposed_by = Some(vec!["hub".into(), "box".into(), "down".into()]);
        let g = 1u64 << 30;
        up.capacity = Some(crate::serve::capacity::Capacity {
            cpus: Some(8),
            mem_total: Some(32 * g),
            mem_available: Some(14 * g),
            disk_free: Some(120 * g),
            disk_total: Some(500 * g),
            running: 3,
            caps: Some(crate::serve::capacity::Caps { mem: Some(16 * g), ..Default::default() }),
        });
        app.set_machines(vec![up, down]);
        app.on_key(KeyEvent::from(KeyCode::Char('5')));
        let screen = render(&app, 180, 30);
        let header = screen.lines().find(|l| l.contains("NAME")).unwrap();
        for col in ["TARGET", "STATE", "AGENT", "VERSION", "CAPACITY"] {
            assert!(header.contains(col), "{screen}");
        }
        assert!(!header.contains("LEND"), "{screen}");
        let line = |name: &str| screen.lines().find(|l| l.contains(&format!("│{name} "))).unwrap().to_string();
        let (up, down) = (line("box"), line("down"));
        assert!(up.contains("me@box") && up.contains(" connected ") && up.contains(" on ") && up.contains("0.9.1"), "{screen}");
        assert!(up.contains("8 cpu · 18/32G · 120G free · 3 run  over cap: mem 18G/16G"), "{screen}");
        assert!(down.contains(" unreachable: Connection refused ") && down.contains(" off ") && down.contains(" - "), "{screen}");
        // Exposed while `worker`: the machine that dials it named.
        assert!(down.contains("│down  exposed via box ") && !up.contains("exposed"), "{screen}");
        // No report yet: VERSION and CAPACITY `-`.
        assert!(down.trim_end_matches('│').trim_end().ends_with("-            -"), "{down}");
        assert!(screen.find("│box ").unwrap() < screen.find("│down ").unwrap(), "{screen}");
        assert!(screen.contains("Machines"), "{screen}");
    }

    /// The Ports tab's MACHINE column: absent with only this host's
    /// forwards, the machine (and its target without the prefix) on a
    /// remote one's row, blank on a local one's.
    #[test]
    fn remote_forwards_get_a_machine_column() {
        let row = |id: u64, target: &str, machine: Option<&str>| PortRow {
            id,
            local: format!("127.0.0.1:{}", 8080 + id),
            target: target.into(),
            process: None,
            state: "active".into(),
            conns: 0,
            configured: false,
            machine: machine.map(String::from),
        };
        let mut app = phase_app(vec![("web", running(), None)]);
        app.tab = Tab::Ports;
        app.set_ports(vec![row(0, "web:3000", None)]);
        let alone = render(&app, 160, 20);
        assert!(alone.contains("LOCAL") && !alone.contains("MACHINE"), "{alone}");

        app.set_ports(vec![row(0, "web:3000", None), row(1, "box/api:3000", Some("box"))]);
        let screen = render(&app, 160, 20);
        let header = screen.lines().find(|l| l.contains("LOCAL")).unwrap();
        assert!(header.contains(" MACHINE ") && header.contains("TARGET"), "{screen}");
        let local = screen.lines().find(|l| l.contains("127.0.0.1:8080")).unwrap();
        assert!(local.contains(" web:3000") && !local.contains("box"), "{screen}");
        let remote = screen.lines().find(|l| l.contains("127.0.0.1:8081")).unwrap();
        assert!(remote.contains(" box ") && remote.contains(" api:3000") && !remote.contains("box/"), "{screen}");
    }

    fn running() -> ContainerStatus {
        ContainerStatus::Running("Up".into())
    }

    fn inbox_app() -> App {
        let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
        let mut a = dthread("#6900 feat/agent-run-cost", State::NeedsYou, Some("review draft replies"));
        a.updated_at = now - 120;
        a.unread = true;
        a.link = Some("https://example.com/pr/6900".into());
        let mut b = dthread("#7414 fix/login", State::Active, Some("running ci"));
        b.updated_at = now - 3600;
        let c = note("ci failed on main", Level::Warn, now - 3 * 86_400);
        let mut d = dthread("#7001 docs/config", State::Done, None);
        d.updated_at = now - 5 * 86_400;
        let e = note("image rebuilt", Level::Info, now - 6 * 86_400);
        let mut threads = vec![a, b, c, d, e];
        for (i, t) in threads.iter_mut().enumerate() {
            t.id = i as u64 + 1;
            t.owner = format!("{}-id", t.owner_name);
        }
        let mut inbox = Inbox::default();
        inbox.threads = threads;
        let mut app = App::new(PathBuf::from("/tmp"));
        app.set_inbox(inbox);
        app.on_key(KeyEvent::from(KeyCode::Char('4')));
        for _ in 0..3 {
            app.on_key(KeyEvent::from(KeyCode::Right));
        }
        app
    }

    #[test]
    fn inbox_renders_cards() {
        let app = inbox_app();
        let screen = render(&app, 120, 30);
        if std::env::var_os("SHOW_INBOX").is_some() {
            println!("{screen}");
        }
        assert!(screen.contains("‹ Needs you 1 │ Active 1 │ Done 1 │ All 5 ›"), "{screen}");
        assert!(screen.contains("╭ Inbox "), "{screen}");
        // Needs you → Active → Done → All: each view without the selected
        // thread starts at its top, and All keeps Done's `#7001` by id.
        assert!(screen.contains("▌#7001 docs/config"), "{screen}");
        assert!(screen.contains(" #6900 feat/agent-run-cost ↗"), "{screen}");
        assert!(screen.contains("▲ warn"), "{screen}");
    }

    #[test]
    fn tab_spans_match_the_rendered_tab_line() {
        let app = inbox_app();
        assert_eq!(app.tab_title(Tab::Inbox), "Inbox (1)");
        let screen = render(&app, 120, 30);
        let first: Vec<char> = screen.lines().next().unwrap().chars().collect();
        let frame = Rect::new(0, 0, 120, 30);
        let spans = tab_spans(&app);
        for (tab, title, r) in &spans {
            let drawn: String = first[r.start as usize..r.end as usize].iter().collect();
            assert_eq!(drawn, format!(" {title} "));
            assert_eq!(tab_hit(&app, frame, r.start, 0), Some(*tab));
            assert_eq!(tab_hit(&app, frame, r.end - 1, 0), Some(*tab));
            // Not on the content row below.
            assert_eq!(tab_hit(&app, frame, r.start, 1), None);
        }
        // The dividers between tabs and the rest of the row hit nothing.
        for w in spans.windows(2) {
            assert_eq!(w[0].2.end + 1, w[1].2.start);
            assert_eq!(tab_hit(&app, frame, w[0].2.end, 0), None);
        }
        assert_eq!(tab_hit(&app, frame, spans.last().unwrap().2.end + 5, 0), None);
    }

    #[test]
    fn view_strip_hits_follow_the_drawn_spans() {
        let counts = [3, 5, 0, 9];
        let line = text(&view_strip(View::NeedsYou, counts, 80));
        let col = |needle: &str| line[..line.find(needle).unwrap()].chars().count() as u16;
        let hit = |x| view_strip_hit(View::NeedsYou, counts, 80, x);
        assert_eq!(hit(0), None, "leading space");
        assert_eq!(hit(col("‹")), Some(StripHit::Prev));
        assert_eq!(hit(col("Needs you")), Some(StripHit::View(View::NeedsYou)));
        assert_eq!(hit(col("Active 5") + 7), Some(StripHit::View(View::Active)), "the count is the view's too");
        assert_eq!(hit(col("Active") - 2), None, "separator");
        assert_eq!(hit(col("Done")), Some(StripHit::View(View::Done)));
        assert_eq!(hit(col("All")), Some(StripHit::View(View::All)));
        assert_eq!(hit(col("›")), Some(StripHit::Next));
        assert_eq!(hit(col("›") + 1), None, "past the end");
        // Narrow: the short names move everything left.
        let narrow = text(&view_strip(View::All, counts, 20));
        let at = narrow.find("Active").map(|b| narrow[..b].chars().count() as u16).unwrap();
        assert_eq!(view_strip_hit(View::All, counts, 20, at), Some(StripHit::View(View::Active)));
    }

    #[test]
    fn card_at_maps_rows_to_cards_past_the_offset() {
        let inner = Rect::new(1, 3, 30, 10);
        assert_eq!(card_at(inner, 0, 5, 2), None, "above");
        assert_eq!(card_at(inner, 0, 5, 3), Some(0));
        assert_eq!(card_at(inner, 0, 5, 4), Some(0));
        assert_eq!(card_at(inner, 0, 5, 5), None, "spacer");
        assert_eq!(card_at(inner, 0, 5, 6), Some(1));
        assert_eq!(card_at(inner, 2, 5, 3), Some(2), "offset");
        assert_eq!(card_at(inner, 2, 5, 9), Some(4));
        assert_eq!(card_at(inner, 2, 5, 12), None, "past the last card");
        assert_eq!(card_at(inner, 0, 5, 13), None, "below");
    }

    #[test]
    fn inbox_hit_lands_on_what_is_drawn() {
        let mut app = inbox_app();
        let frame = Rect::new(0, 0, 120, 30);
        let screen: Vec<String> = render(&app, 120, 30).lines().map(str::to_string).collect();
        // Every card's title row hits that card.
        let threads = app.inbox.threads().to_vec();
        for (pos, &i) in app.inbox.rows().iter().enumerate() {
            let title = title_of(&threads[i]);
            // Within the list's 48 columns (40% of 120): the pane repeats the
            // selected title.
            let in_list = |l: &String| l.chars().take(48).collect::<String>().contains(title.as_str());
            let row = screen.iter().position(in_list).unwrap() as u16;
            assert_eq!(inbox_hit(&app, frame, 5, row), Some(InboxHit::Card(pos)), "{title}");
            assert_eq!(inbox_hit(&app, frame, 5, row + 2), Some(InboxHit::ListBlank), "spacer under {title}");
        }
        // The strip's row: `All` is current; `‹` steps back.
        let strip = &screen[1];
        let col = strip[..strip.find('‹').unwrap()].chars().count() as u16;
        assert_eq!(inbox_hit(&app, frame, col, 1), Some(InboxHit::Strip(StripHit::Prev)));
        // Thread pane (list 40% of 120 = 48 cols): content, then the
        // selected `#7001` takes no replies, so its last inner row is the hint.
        let hint = screen.iter().position(|l| l.contains("this thread takes no replies")).unwrap() as u16;
        assert_eq!(inbox_hit(&app, frame, 60, hint), Some(InboxHit::Hint));
        assert_eq!(inbox_hit(&app, frame, 60, hint - 1), Some(InboxHit::Thread));
        assert_eq!(inbox_hit(&app, frame, 60, 1), Some(InboxHit::Thread), "border");
        assert_eq!(inbox_hit(&app, frame, 60, 0), None, "tab line");
        assert_eq!(inbox_hit(&app, frame, 60, 29), None, "help bar");
        // A thread taking replies: the input box's three rows.
        let sel = app.inbox.rows()[app.selected()];
        let mut inbox = Inbox::default();
        inbox.threads = threads;
        inbox.threads[sel].compose = Some(Default::default());
        app.set_inbox(inbox);
        let screen: Vec<String> = render(&app, 120, 30).lines().map(str::to_string).collect();
        let top = screen.iter().position(|l| l.contains("╭ r reply")).unwrap() as u16;
        for row in top..top + 3 {
            assert_eq!(inbox_hit(&app, frame, 60, row), Some(InboxHit::Input), "row {row}");
        }
        assert_eq!(inbox_hit(&app, frame, 60, top - 1), Some(InboxHit::Thread));
    }

    /// The reply box wraps what's typed, grows with it up to
    /// `textarea::MAX_ROWS` rows then scrolls to the cursor, and hit-testing
    /// sees the same box.
    #[test]
    fn reply_box_wraps_grows_and_follows_the_cursor() {
        let mut app = inbox_app();
        let sel = app.inbox.rows()[app.selected()];
        let mut inbox = Inbox::default();
        inbox.threads = app.inbox.threads().to_vec();
        inbox.threads[sel].compose = Some(Default::default());
        app.set_inbox(inbox);
        app.on_key(KeyEvent::from(KeyCode::Char('r')));
        assert_eq!(app.inbox.focus, InboxFocus::Input);
        let frame = Rect::new(0, 0, 120, 30);
        // The box's rows (borders included), its inner columns, the caret.
        let draw = |app: &App| {
            let mut term = Terminal::new(TestBackend::new(120, 30)).unwrap();
            term.draw(|f| draw(f, app)).unwrap();
            let buf = term.backend().buffer().clone();
            let screen: Vec<String> =
                (0..30).map(|y| (0..120).map(|x| buf[(x, y)].symbol().to_string()).collect()).collect();
            let top = screen.iter().position(|l| l.contains("╭ enter sends")).unwrap();
            let bottom = top + screen[top..].iter().position(|l| l.contains('╰')).unwrap();
            let border = &screen[top];
            let left = border.chars().position(|c| c == '╭').unwrap();
            let right = border.chars().position(|c| c == '╮').unwrap();
            let rows: Vec<String> =
                screen[top + 1..bottom].iter().map(|l| l.chars().skip(left + 1).take(right - left - 1).collect()).collect();
            let caret = term.get_cursor_position().unwrap();
            (top as u16, bottom as u16, left as u16 + 1, rows, (caret.x, caret.y))
        };
        let typed = |app: &mut App, s: &str| s.chars().for_each(|c| app.on_key(KeyEvent::from(KeyCode::Char(c))));

        // Empty: one row, the placeholder.
        let (_, _, _, rows, _) = draw(&app);
        assert_eq!(rows.len(), 1);
        assert!(rows[0].starts_with("reply to the owner"), "{rows:?}");

        // Longer than a row: wrapped, nothing lost, caret after the last char.
        let (_, _, x0, rows, _) = draw(&app);
        let width = rows[0].chars().count();
        let text = format!("start{}END", "x".repeat(width * 2));
        typed(&mut app, &text);
        let (top, bottom, _, rows, caret) = draw(&app);
        assert_eq!(rows.len(), 3, "{rows:?}");
        assert!(rows[0].starts_with("start"));
        assert_eq!(rows.concat().trim_end(), text);
        let end = rows[2].trim_end().chars().count() as u16;
        assert_eq!(caret, (x0 + end, top + 3));
        for row in top..=bottom {
            assert_eq!(inbox_hit(&app, frame, x0 + 1, row), Some(InboxHit::Input), "row {row}");
        }
        assert_eq!(inbox_hit(&app, frame, x0 + 1, top - 1), Some(InboxHit::Thread));

        // A newline (alt-enter) starts a row; plain enter would send.
        app.on_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::ALT));
        typed(&mut app, "next");
        let (_, _, _, rows, _) = draw(&app);
        assert_eq!(rows.len(), 4);
        assert_eq!(rows[3].trim_end(), "next");

        // Past the cap: six rows, scrolled so the caret's row is the last.
        for _ in 0..5 {
            app.on_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::SHIFT));
        }
        typed(&mut app, "tail");
        let (top, bottom, _, rows, caret) = draw(&app);
        assert_eq!(rows.len(), textarea::MAX_ROWS as usize);
        assert_eq!(rows[5].trim_end(), "tail");
        assert!(!rows.iter().any(|r| r.starts_with("start")), "scrolled past the top");
        assert_eq!(caret, (x0 + 4, top + 6));
        assert_eq!(inbox_hit(&app, frame, x0 + 1, bottom), Some(InboxHit::Input));
        assert_eq!(inbox_hit(&app, frame, x0 + 1, top), Some(InboxHit::Input));

        // Enter sends and the box shrinks back to one row.
        app.on_key(KeyEvent::from(KeyCode::Enter));
        let (_, _, _, rows, _) = draw(&app);
        assert_eq!(rows.len(), 1);
    }

    /// The `:` prompt scrolls sideways so the caret stays on screen.
    #[test]
    fn prompt_scrolls_to_the_caret() {
        let mut app = App::new(PathBuf::from("/tmp"));
        app.on_key(KeyEvent::from(KeyCode::Char(':')));
        let text = format!("exec {}Z", "a".repeat(60));
        text.chars().for_each(|c| app.on_key(KeyEvent::from(KeyCode::Char(c))));
        let mut term = Terminal::new(TestBackend::new(40, 10)).unwrap();
        term.draw(|f| draw(f, &app)).unwrap();
        let buf = term.backend().buffer().clone();
        let line: String = (0..40).map(|x| buf[(x, 8)].symbol().to_string()).collect();
        assert!(line.starts_with(": "), "{line:?}");
        assert!(line.trim_end().ends_with('Z'), "{line:?}");
        let caret = term.get_cursor_position().unwrap();
        assert_eq!((caret.x, caret.y), (39, 8));
    }

    const LLM_MESSAGE: &str = "## Review summary

I checked **4 comments** from Greptile:

- `parse_port` overflows on `0`
- the retry loop never backs off
  - nested: also in `connect`

```rust
fn parse(s: &str) -> u16 {
\ts.parse().unwrap()
}
```

> CI is green on the branch.

See [PR 6900](https://github.com/o/r/pull/6900).";

    /// The Inbox showing one thread with `message`, its pane focused.
    fn message_app(message: &str) -> App {
        let mut t = dthread("#6900 fix `parse_port`", State::NeedsYou, Some("review **drafts**"));
        t.id = 1;
        t.owner = "bab-disp-id".into();
        t.feed = vec![crate::inbox::FeedItem::markdown(1, 0, "m", message)];
        let mut inbox = Inbox::default();
        inbox.threads = vec![t];
        let mut app = App::new(PathBuf::from("/tmp"));
        app.set_inbox(inbox);
        app.on_key(KeyEvent::from(KeyCode::Char('4')));
        app.on_key(KeyEvent::from(KeyCode::Enter));
        app
    }

    fn draw_buffer(app: &App, w: u16, h: u16) -> ratatui::buffer::Buffer {
        let mut term = Terminal::new(TestBackend::new(w, h)).unwrap();
        term.draw(|f| draw(f, app)).unwrap();
        term.backend().buffer().clone()
    }

    fn rows_of(buf: &ratatui::buffer::Buffer) -> Vec<String> {
        let a = buf.area;
        (0..a.height).map(|y| (0..a.width).map(|x| buf[(x, y)].symbol().to_string()).collect()).collect()
    }

    /// Where `needle` starts on screen, as a cell position (wide-glyph-free
    /// rows, so a char index is a column).
    fn find_cell(rows: &[String], needle: &str) -> (u16, u16) {
        let y = rows.iter().position(|r| r.contains(needle)).unwrap_or_else(|| panic!("{needle}:\n{}", rows.join("\n")));
        let x = rows[y][..rows[y].find(needle).unwrap()].chars().count();
        (x as u16, y as u16)
    }

    #[test]
    fn thread_pane_renders_a_typical_llm_message() {
        let app = message_app(LLM_MESSAGE);
        let buf = draw_buffer(&app, 100, 34);
        let rows = rows_of(&buf);
        if std::env::var_os("SHOW_INBOX").is_some() {
            println!("{}", rows.join("\n"));
        }
        let screen = rows.join("\n");
        for gone in ["##", "**", "```", "`parse_port`", "](https"] {
            assert!(!screen.contains(gone), "{gone} in\n{screen}");
        }
        let style = |needle: &str| buf[find_cell(&rows, needle)].style();
        let heading = style("Review summary");
        assert_eq!((heading.fg, heading.add_modifier.contains(Modifier::BOLD)), (Some(ACCENT), true));
        assert!(style("4 comments").add_modifier.contains(Modifier::BOLD));
        assert_eq!(style("parse_port overflows").bg, markdown::CODE.bg);
        assert!(screen.contains("• parse_port overflows on 0"), "{screen}");
        assert!(screen.contains("  • nested: also in connect"), "{screen}");
        // The code block: tinted, its tab expanded, padded across the pane.
        let (x, y) = find_cell(&rows, "fn parse(s: &str)");
        assert_eq!(buf[(x, y)].style().bg, markdown::CODE.bg);
        assert!(rows[y as usize + 1].contains("    s.parse().unwrap()"), "{screen}");
        assert_eq!(buf[(98 - 1, y)].style().bg, markdown::CODE.bg, "padded to the pane's inner edge");
        assert!(screen.contains("│ CI is green on the branch."), "{screen}");
        assert!(style("PR 6900").add_modifier.contains(Modifier::UNDERLINED));
        assert!(screen.contains("See PR 6900 (https://github.com/o/r/pull/6900)."), "{screen}");
        // Title and status are inline markdown too (the status only shows in
        // the pane; the title also on the card, left of column 40).
        assert!(style("drafts").add_modifier.contains(Modifier::BOLD));
        let y = rows.iter().position(|r| r.chars().skip(40).collect::<String>().contains("#6900 fix parse_port")).unwrap();
        let x = 40 + rows[y].chars().skip(40).collect::<String>().find("parse_port").unwrap() as u16;
        assert_eq!(buf[(x, y as u16)].style().bg, markdown::CODE.bg);
    }

    #[test]
    fn thread_pane_lays_out_a_table() {
        let mut app = message_app("Checks:\n\n| check | took | result |\n|:--|--:|:-:|\n| `cargo test` | 41s | ok |\n| e2e | 3m | failing |");
        let buf = draw_buffer(&app, 100, 20);
        let rows = rows_of(&buf);
        if std::env::var_os("SHOW_INBOX").is_some() {
            println!("{}", rows.join("\n"));
        }
        let screen = rows.join("\n");
        let (x, y) = find_cell(&rows, "check       took  result");
        assert!(buf[(x, y)].style().add_modifier.contains(Modifier::BOLD), "bold header");
        let rule = &rows[y as usize + 1];
        assert_eq!(rule.chars().skip(x as usize).take_while(|c| *c == '─').count(), 25, "{screen}");
        assert!(buf[(x, y + 1)].style().add_modifier.contains(Modifier::DIM), "dim rule");
        let (cx, cy) = find_cell(&rows, "cargo test   41s    ok");
        assert_eq!((cx, cy), (x, y + 2), "{screen}");
        assert_eq!(buf[(cx, cy)].style().bg, markdown::CODE.bg, "inline code keeps its tint");
        assert_eq!(find_cell(&rows, "e2e           3m  failing"), (x, y + 3), "{screen}");
        // Raw: the source.
        app.on_key(KeyEvent::from(KeyCode::Char('m')));
        assert!(render(&app, 100, 20).contains("| `cargo test` | 41s | ok |"));
    }

    #[test]
    fn m_toggles_the_raw_source() {
        let mut app = message_app(LLM_MESSAGE);
        app.on_key(KeyEvent::from(KeyCode::Char('m')));
        assert!(app.inbox.raw);
        let screen = render(&app, 100, 34);
        assert!(screen.contains("╭ Thread · raw "), "{screen}");
        assert!(screen.contains("## Review summary"), "{screen}");
        assert!(screen.contains("I checked **4 comments** from Greptile:"), "{screen}");
        assert!(screen.contains("```rust"), "{screen}");
        assert!(screen.contains("review **drafts**"), "{screen}");
        app.on_key(KeyEvent::from(KeyCode::Char('m')));
        assert!(!render(&app, 100, 34).contains("```rust"));
    }

    /// The scroll bound is the rows drawn: scrolled to the bottom, the last
    /// line sits on the pane's last content row, right above the hint.
    #[test]
    fn the_pane_scroll_bound_is_exact() {
        let long: String = (1..=40).map(|i| format!("- item {i} with a few words to wrap\n")).collect();
        let table = "| a | b |\n|---|--:|\n| 1 | 2 |\n| `x` | 3 |\n";
        let mut app = message_app(&format!("{table}\n{long}\n{table}\nTHE END"));
        // Draw once so the bound is known, then jump to the bottom.
        render(&app, 80, 24);
        app.on_key(KeyEvent::from(KeyCode::Char('G')));
        let rows: Vec<String> = render(&app, 80, 24).lines().map(str::to_string).collect();
        let (_, end) = find_cell(&rows, "THE END");
        let (_, hint) = find_cell(&rows, "this thread takes no replies");
        assert_eq!(end + 1, hint, "{}", rows.join("\n"));
        // One more line down is not possible.
        let scroll = app.inbox.scroll;
        app.on_key(KeyEvent::from(KeyCode::Down));
        assert_eq!(app.inbox.scroll, scroll);
    }

    /// One thread of `n` messages (`message 1` oldest), a link, a key, two
    /// actions and `compose`, its pane focused.
    fn feed_app(n: u64, compose: Option<crate::inbox::Compose>) -> App {
        let mut t = dthread("#6900 feat/agent-run-cost-event", State::NeedsYou, Some("review drafts"));
        t.id = 1;
        t.owner = "bab-disp-id".into();
        t.key = Some("pr-6900".into());
        t.link = Some("https://x/pr/6900".into());
        t.actions = vec![
            crate::inbox::Action { id: "retry".into(), label: "Retry".into(), ..Default::default() },
            crate::inbox::Action { id: "done".into(), label: "Done".into(), done: true, ..Default::default() },
        ];
        t.feed = (1..=n)
            .map(|i| crate::inbox::FeedItem::markdown(i, i * 60, &format!("m{i}"), &format!("message {i}")))
            .collect();
        t.compose = compose;
        let mut inbox = Inbox::default();
        inbox.threads = vec![t];
        let mut app = App::new(PathBuf::from("/tmp"));
        app.set_inbox(inbox);
        app.on_key(KeyEvent::from(KeyCode::Char('4')));
        app.on_key(KeyEvent::from(KeyCode::Enter));
        app
    }

    /// The thread pane's columns of a 100-wide frame's row (list 40%).
    fn pane_part(row: &str) -> String {
        row.chars().skip(40).collect()
    }

    // At 100x24: the pane's inner area is columns 41-98, rows 2-21.
    #[test]
    fn the_header_stays_put_while_the_feed_scrolls_newest_first() {
        let mut app = feed_app(20, None);
        let rows = rows_of(&draw_buffer(&app, 100, 24));
        if std::env::var_os("SHOW_INBOX").is_some() {
            println!("{}", rows.join("\n"));
        }
        let pane: Vec<String> = rows.iter().map(|r| pane_part(r)).collect();
        assert!(pane[2].starts_with("│#6900 feat/agent-run-cost-event ↗ "), "{}", pane.join("\n"));
        assert!(pane[3].starts_with("│● review drafts  ·  ") && pane[3].ends_with(" bab-disp · pr-6900│"), "{:?}", pane[3]);
        // The action row wraps between buttons: 58 columns hold five.
        assert_eq!(pane[4], format!("│{:58}│", "[1] Retry  [2] Done ✓  [o] VS Code  [t] Terminal  [l] Logs"));
        assert_eq!(pane[5], format!("│{:58}│", "[p] Port"));
        assert_eq!(pane[6], format!("├{}┤", "─".repeat(58)), "separator joined to the border");
        // Newest first: scroll 0 shows the latest message right under it.
        assert!(pane[7].trim_end_matches('│').trim_end().ends_with("  bab-disp"), "{:?}", pane[7]);
        assert!(pane[8].contains("message 20"), "{:?}", pane[8]);
        let header: Vec<String> = pane[1..=6].to_vec();

        // Scrolled to the end: the oldest message is in view, the header the same.
        app.on_key(KeyEvent::from(KeyCode::Char('G')));
        assert!(app.inbox.scroll > 0);
        let pane: Vec<String> = rows_of(&draw_buffer(&app, 100, 24)).iter().map(|r| pane_part(r)).collect();
        assert_eq!(pane[1..=6], header[..], "pinned");
        assert!(!pane.iter().any(|r| r.contains("message 20")));
        // The last feed row sits right above the no-replies hint.
        assert!(pane[20].contains("message 1 "), "{}", pane.join("\n"));
        assert!(pane[21].contains("this thread takes no replies"));

        // Header rows and the separator hit the thread, not the input.
        let frame = Rect::new(0, 0, 100, 24);
        for row in 2..=7 {
            assert_eq!(inbox_hit(&app, frame, 60, row), Some(InboxHit::Thread), "row {row}");
        }
        assert_eq!(inbox_hit(&app, frame, 60, 21), Some(InboxHit::Hint));
        // The wheel over the header scrolls the feed like over the feed.
        let max = app.inbox.scroll;
        let wheel = crossterm::event::MouseEvent {
            kind: crossterm::event::MouseEventKind::ScrollUp,
            column: 60,
            row: 3,
            modifiers: KeyModifiers::NONE,
        };
        app.on_mouse(&wheel, frame);
        assert_eq!(app.inbox.scroll, max - 3);
    }

    #[test]
    fn the_composer_draws_its_hint_under_the_box_and_hits_agree() {
        let hint = "Starts an agent with your message, then waits for it to finish and posts the result";
        let compose = crate::inbox::Compose {
            placeholder: Some("Instructions for this PR…".into()),
            hint: Some(hint.into()),
        };
        let mut app = feed_app(3, Some(compose));
        let frame = Rect::new(0, 0, 100, 24);
        let check = |app: &App, box_rows: u16| {
            let pane: Vec<String> = rows_of(&draw_buffer(app, 100, 24)).iter().map(|r| pane_part(r)).collect();
            // The hint is the last inner row, cut to the width with `…`.
            assert_eq!(pane[21], format!("│{}│", truncate(hint, 58)), "{}", pane.join("\n"));
            assert!(pane[21].contains('…'));
            // The box right above it: border + rows + border.
            let top = 21 - box_rows - 2;
            assert!(pane[top as usize].starts_with("│╭"), "{}", pane.join("\n"));
            assert!(pane[20].starts_with("│╰"), "{}", pane.join("\n"));
            for row in top..=21 {
                assert_eq!(inbox_hit(app, frame, 60, row), Some(InboxHit::Input), "row {row}");
            }
            assert_eq!(inbox_hit(app, frame, 60, top - 1), Some(InboxHit::Thread));
            assert_eq!(inbox_hit(app, frame, 60, 3), Some(InboxHit::Thread), "header");
            pane
        };
        let pane = check(&app, 1);
        assert!(pane[19].contains("Instructions for this PR…"), "{}", pane.join("\n"));

        // Typing grows the box; the hint stays under it, hits follow.
        app.on_key(KeyEvent::from(KeyCode::Char('r')));
        let typed = "y".repeat(56 * 2 + 5);
        typed.chars().for_each(|c| app.on_key(KeyEvent::from(KeyCode::Char(c))));
        check(&app, 3);
        // A click on the hint row keeps the typed line (it's the composer).
        app.on_mouse(
            &crossterm::event::MouseEvent {
                kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
                column: 60,
                row: 21,
                modifiers: KeyModifiers::NONE,
            },
            frame,
        );
        assert_eq!(app.inbox.focus, InboxFocus::Input);
        assert_eq!(app.inbox.reply.as_ref().unwrap().line.input(), typed);
    }

    /// [`feed_app`] whose newest message carries an open form of `n`
    /// questions: the first a choice with context, the rest confirms.
    fn form_feed_app(n: usize) -> App {
        use crate::inbox::form::{ChoiceOption, Form, Question, QuestionKind};
        let mut app = feed_app(3, None);
        let mut questions = vec![Question {
            id: "c-1".into(),
            label: "greptile on `src/cost.ts:42`".into(),
            context: Some("> Consider batching these writes.".into()),
            required: true,
            under: None,
            when: None,
            kind: QuestionKind::Choice {
                options: vec![
                    ChoiceOption { id: "post".into(), label: "Post the reply".into(), description: None },
                    ChoiceOption { id: "skip".into(), label: "Don't reply".into(), description: None },
                ],
                multiple: false,
                default: Some(crate::inbox::form::ChoiceDefault::One("post".into())),
            },
        }];
        questions.extend((2..=n).map(|i| Question {
            id: format!("q-{i}"),
            label: format!("Question {i}?"),
            context: None,
            required: false,
            under: None,
            when: None,
            kind: QuestionKind::Confirm { yes: None, no: None, default: None },
        }));
        let form = Form { id: "drafts".into(), title: Some("Replies to post".into()), submit: "Post".into(), questions };
        let mut t = app.selected_inbox_thread().unwrap().clone();
        let blocks = vec![crate::inbox::Block::Form(form)];
        let record = crate::inbox::FormRecord::open("drafts");
        let kind = crate::inbox::ItemKind::Message { id: "m4".into(), blocks, edited: false, withdrawn: false, form: Some(record) };
        t.feed.push(crate::inbox::FeedItem { seq: 4, at: 240, kind });
        let mut inbox = Inbox::default();
        inbox.threads = vec![t];
        app.set_inbox(inbox);
        app
    }

    fn press(app: &mut App, frame: Rect, kind: crossterm::event::MouseEventKind, row: u16) {
        app.on_mouse(&crossterm::event::MouseEvent { kind, column: 60, row, modifiers: KeyModifiers::NONE }, frame);
    }

    // At 100x24: the pane's inner area is columns 41-98, rows 2-21; the
    // header takes rows 2-5, the separator row 6.
    #[test]
    fn open_forms_are_pinned_between_the_header_and_the_feed_and_hits_agree() {
        let mut app = form_feed_app(2);
        let frame = Rect::new(0, 0, 100, 24);
        let pane: Vec<String> = rows_of(&draw_buffer(&app, 100, 24)).iter().map(|r| pane_part(r)).collect();
        if std::env::var_os("SHOW_INBOX").is_some() {
            println!("{}", pane.join("\n"));
        }
        assert_eq!(pane[6], format!("├{}┤", "─".repeat(58)));
        assert!(pane[7].starts_with("│╭ Replies to post ─") && pane[7].ends_with("─ open form ╮│"), "{:?}", pane[7]);
        assert_eq!(pane[8], format!("││ {:54} ││", "  1/2 greptile on src/cost.ts:42"));
        assert_eq!(pane[9], format!("││ {:54} ││", "    (•) Post the reply   ( ) Don't reply"));
        assert_eq!(pane[10], format!("││ {:54} ││", "  2/2 Question 2?"));
        assert_eq!(pane[12], format!("││ {:54} ││", "[Tab] next  [Space] pick  [e] edit  [Enter] Confirm"));
        assert_eq!(pane[13], format!("│╰{}╯│", "─".repeat(56)));
        // The feed right under it, newest first: the form's message.
        assert!(pane[14].trim_end_matches('│').trim_end().ends_with("  bab-disp"), "{}", pane.join("\n"));
        assert!(pane[15].contains("form: Replies to post · open, pinned above"), "{}", pane.join("\n"));

        // Hits: the box is the form zone, by question; around it the thread.
        let spot = |question| Some(InboxHit::Form(Some(FormSpot { form: 0, question })));
        assert_eq!(inbox_hit(&app, frame, 60, 6), Some(InboxHit::Thread));
        assert_eq!(inbox_hit(&app, frame, 60, 7), spot(None));
        assert_eq!(inbox_hit(&app, frame, 60, 8), spot(Some(0)));
        assert_eq!(inbox_hit(&app, frame, 60, 11), spot(Some(1)));
        assert_eq!(inbox_hit(&app, frame, 60, 12), spot(None));
        assert_eq!(inbox_hit(&app, frame, 60, 14), Some(InboxHit::Thread));

        // A click on question 2 focuses it; the box is accented, the focused
        // question marked; question 1's context stays folded.
        press(&mut app, frame, crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left), 11);
        assert_eq!(app.inbox.focus, InboxFocus::Form);
        assert_eq!(app.inbox.form.as_ref().map(|e| e.question), Some(1));
        let pane: Vec<String> = rows_of(&draw_buffer(&app, 100, 24)).iter().map(|r| pane_part(r)).collect();
        assert_eq!(pane[10], format!("││ {:54} ││", "› 2/2 Question 2?"));
        // Back to question 1: its context shows, the box grows a row.
        app.on_key(KeyEvent::from(KeyCode::Tab));
        let pane: Vec<String> = rows_of(&draw_buffer(&app, 100, 24)).iter().map(|r| pane_part(r)).collect();
        assert!(pane[9].contains("Consider batching these writes."), "{}", pane.join("\n"));
        assert!(pane[14].starts_with("│╰"), "{}", pane.join("\n"));
    }

    #[test]
    fn a_tall_form_takes_half_the_pane_and_scrolls_to_the_cursor() {
        let mut app = form_feed_app(12);
        let frame = Rect::new(0, 0, 100, 24);
        let pane: Vec<String> = rows_of(&draw_buffer(&app, 100, 24)).iter().map(|r| pane_part(r)).collect();
        // Half of the 20 inner rows: 7-16, then the feed.
        assert!(pane[7].starts_with("│╭ Replies to post"), "{}", pane.join("\n"));
        assert!(pane[17].trim_end_matches('│').trim_end().ends_with("  bab-disp"), "{}", pane.join("\n"));
        assert_eq!(inbox_hit(&app, frame, 60, 16), Some(InboxHit::Form(Some(FormSpot { form: 0, question: Some(4) }))));
        assert_eq!(inbox_hit(&app, frame, 60, 17), Some(InboxHit::Thread));
        // Focus the last question: the box scrolls to it.
        app.on_key(KeyEvent::from(KeyCode::Tab));
        app.on_key(KeyEvent::from(KeyCode::BackTab));
        let pane: Vec<String> = rows_of(&draw_buffer(&app, 100, 24)).iter().map(|r| pane_part(r)).collect();
        assert!(pane[7..=16].iter().any(|r| r.contains("› 12/12 Question 12?")), "{}", pane.join("\n"));
        assert!(!pane[7..=16].iter().any(|r| r.contains("Replies to post")), "scrolled past the top border");
        let scrolled = app.inbox.forms_scroll();
        assert!(scrolled > 0);
        // The wheel over the box scrolls it, and the cursor doesn't pull it back.
        press(&mut app, frame, crossterm::event::MouseEventKind::ScrollUp, 10);
        assert_eq!(app.inbox.forms_scroll(), scrolled - 3);
        draw_buffer(&app, 100, 24);
        assert_eq!(app.inbox.forms_scroll(), scrolled - 3);
        // A text-free form: `e` does nothing to the composer.
        app.on_key(KeyEvent::from(KeyCode::Char('e')));
        assert_eq!(inbox_hit(&app, frame, 60, 21), Some(InboxHit::Hint));
    }

    #[test]
    fn header_lines_cut_align_and_wrap() {
        let line = |left: &str, right: Option<&str>| HeaderRow::Line {
            left: vec![(Tone::Title, left.to_string())],
            right: right.map(str::to_string),
        };
        let texts = |rows: &[HeaderRow], w: u16| header_lines(rows, w, false).iter().map(text).collect::<Vec<_>>();
        // Right-aligned when both fit; the left cut first, then the right dropped.
        assert_eq!(texts(&[line("chip", Some("owner · key"))], 20), ["chip     owner · key"]);
        assert_eq!(texts(&[line("a long chip line", Some("owner"))], 20), ["a long chip l… owner"]);
        assert_eq!(texts(&[line("a long chip line", Some("owner"))], 10), ["a long ch…"]);
        // Titles are one row, inline markdown rendered before cutting.
        assert_eq!(texts(&[line("fix `parse_port` everywhere", None)], 16), ["fix parse_port …"]);
        let b = |s: &str| vec![(Tone::Plain, s.to_string())];
        let buttons = HeaderRow::Buttons(vec![b("[1] Retry"), b("[2] Done"), b("[o] VS Code")]);
        assert_eq!(texts(std::slice::from_ref(&buttons), 40), ["[1] Retry  [2] Done  [o] VS Code"]);
        assert_eq!(texts(std::slice::from_ref(&buttons), 20), ["[1] Retry  [2] Done", "[o] VS Code"]);
        // A button wider than the pane: cut on its own row.
        assert_eq!(texts(std::slice::from_ref(&buttons), 6), ["[1] R…", "[2] D…", "[o] V…"]);
    }

    #[test]
    fn a_card_title_renders_inline_code_without_backticks() {
        let mut t = dthread("fix `parse_port` *now*", State::NeedsYou, None);
        t.updated_at = 1000;
        let [l1, _] = card_lines(&t, 40, false, true, 1000, 0);
        assert!(text(&l1).starts_with(" fix parse_port now  ") && text(&l1).ends_with(" now "), "{l1:?}");
        assert_eq!(l1.width(), 40);
        let code = l1.spans.iter().find(|s| s.content == "parse_port").unwrap();
        assert_eq!(code.style.bg, markdown::CODE.bg);
        assert!(l1.spans.iter().find(|s| s.content == "now").unwrap().style.add_modifier.contains(Modifier::ITALIC));
        // Truncated, the code keeps its tint up to the `…`.
        let [cut, _] = card_lines(&t, 12, false, true, 1000, 0);
        assert_eq!(text(&cut), " fix parse… ");
        assert_eq!(cut.spans.iter().find(|s| s.content == "parse…").unwrap().style.bg, markdown::CODE.bg);
    }

    #[test]
    fn tiny_inbox_keeps_the_selected_card_visible() {
        let mut app = inbox_app();
        for _ in 0..4 {
            app.on_key(KeyEvent::from(KeyCode::Down));
        }
        let screen = render(&app, 30, 8);
        assert!(screen.contains("▌image"), "{screen}");
        // Back up to the top: the window follows.
        for _ in 0..4 {
            app.on_key(KeyEvent::from(KeyCode::Up));
        }
        let screen = render(&app, 30, 8);
        assert!(screen.contains("▌#6"), "{screen}");
    }
}