codewhale-tui 0.9.8

Terminal UI for open-source and open-weight coding models
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
//! Ocean Work Graph surface ownership — **this module is the top bar.**
//!
//! Naming warning, because it has confused readers repeatedly: this is called
//! the "rail" or the "work surface", but [`WorkSurfacePlacement`] defaults to
//! `Top`, so by default it renders as a horizontal strip under the header and
//! above the transcript. "The rail", "the work surface" and "the top bar" all
//! name this module. It is not the header ([`crate::tui::underwater`]) and not
//! the footer.
//!
//! Two settings are orthogonal and are routinely mixed up:
//!
//! - **placement** — where it renders. `Top` (default) | `Left` | `Right` |
//!   `Off`. Drag-resizing the divider persists `work_surface_top_height`
//!   (2..=16) or `work_surface_side_width` (26..=80) to `settings.toml`.
//! - **panel** — what it shows. [`RailPanel`]: `Tasks` (default) | `Agents` |
//!   `Context` | `Pinned`, from the `rail_panel` setting. The legacy
//!   `sidebar_focus` key migrates into it.
//!
//! So the word "Pinned" on screen is a PANEL name, not a state.
//!
//! ## Auto-fit by placement
//!
//! Placement changes *which axis is the ceiling*, not the content rule:
//!
//! | Placement | Ceiling | Auto-fit | Empty |
//! |---|---|---|---|
//! | `Top` | `top_height` (rows) | content rows + divider, clamped to ceiling | `height() == 0` |
//! | `Left`/`Right` | `side_width` (cols) | full chat height at that width | no column reserved |
//! | `Off` | — | — | nothing |
//!
//! Shared rules: content drives size; the setting is a ceiling, never padding;
//! empty work is not a rail. Top never paints a chrome panel title (a checklist
//! reads as a checklist); side rails are named by their content's own heading
//! row (`Work · …`, `▾ Subagents N`, `Goal: …`) except Context, which keeps a
//! muted panel title over its fact list. Narrow hosts that cannot fit a side
//! column fall back to Top, where height auto-fit takes over.
//!
//! ## Row lifetime
//!
//! The strip is a standing register of this session's work, not a live-only
//! view. A to-do or sub-agent row appears when the work exists and stays for
//! the rest of the session after it settles — completion is quiet (glyph,
//! tone, frozen receipt), never an eviction, and the active goal title
//! outlives the work under it. Only transient receipts (aggregated file
//! activity, settled operations) expire on the #4688/#4690 lifetimes.
//! Auto-fit and the row budget decide how many rows are *visible* at once;
//! they never decide membership.
//!
//! ## Rows are objects — in every panel
//!
//! Tasks, Agents, and Pinned all render through one row/hitbox pipeline:
//! every visible work row is selectable, hoverable, and clickable, and its
//! primary action opens the row's world (agent transcript / work inspector).
//! Keyboard Enter and mouse click dispatch identically. Context is the one
//! line-list panel; it holds facts, not rows.
//!
//! Height is decided once per frame by [`render::height`]; the row budget it is
//! given comes from `crate::tui::ui::rail_row_budget`, which is its only
//! production caller.
//!
//! Placement, scrolling, selection, and pager ownership remain local to this
//! component. Every visible work row derives from the active-session graph.

mod input;
mod interaction;
mod model;
mod panels;
mod render;

pub use input::{enter_agents, handle_key, handle_mouse};
pub(crate) use interaction::{agent_details_closed, release_focus};
pub use model::{RailPanel, WorkSurfacePlacement, WorkSurfaceState};
pub(crate) use render::collapse_strip;
pub use render::{height, render, split_chat};

#[cfg(test)]
mod tests {
    use super::WorkSurfacePlacement;
    use std::path::PathBuf;

    use crossterm::event::{
        KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
    };
    use ratatui::{Terminal, backend::TestBackend};

    use crate::config::{ApiProvider, Config};
    use crate::tools::subagent::{
        AgentWorkerStatus, FleetRole, MailboxMessage, SubAgentAssignment, SubAgentResult,
        SubAgentStatus,
    };
    use crate::tools::todo::TodoStatus;
    use crate::tui::app::{
        AgentCurrentActivity, AgentCurrentActivityStatus, App, SidebarRowAction, ToolDetailRecord,
        TuiOptions,
    };
    use crate::tui::history::{
        FileMutationReceipt, GenericToolCell, HistoryCell, PatchSummaryCell, ToolCell, ToolStatus,
    };
    use crate::work_graph::{
        AcceptanceRequirement, ChangeCtx, EdgeKind, EvidenceKindTag, NodeKind, NodeState,
        OperationBinding, OperationOwnerSnapshot, OwnerState, Provenance, WorkEdge, WorkEdgeId,
        WorkGraph, WorkGraphChange, WorkNode, WorkNodeId,
    };

    const SESSION: &str = "work-surface-test";

    fn app() -> App {
        let options = TuiOptions {
            use_mouse_capture: true,
            max_subagents: 4,
            ..crate::test_support::test_tui_options(PathBuf::from("."))
        };
        let mut app = App::new(options, &Config::default());
        app.ui_locale = crate::localization::Locale::En;
        // Dogfood guard: App::new reads the developer's real settings.toml,
        // and the 0.9.4 migration maps a legacy sidebar_focus onto the rail
        // panel. These tests exercise the Tasks panel's row machinery, so
        // pin it rather than depend on the host file.
        app.work_surface.panel = super::RailPanel::Tasks;
        app
    }

    /// The row budget `ui::render` would hand the rail on a terminal of this
    /// height with real work on screen. Calls the production formula rather
    /// than restating it, so a change to the chrome accounting shows up here
    /// instead of silently diverging. The idle-empty budget (where the
    /// ambient floor bites) is covered end-to-end in `ui::tests`.
    fn working_budget(app: &App, terminal_height: u16) -> u16 {
        crate::tui::ui::rail_row_budget(app, 80, terminal_height, false)
    }

    /// A budget wide enough never to bind, for tests about something else.
    const AMPLE_BUDGET: u16 = u16::MAX;

    fn add_todos(app: &mut App, count: usize) {
        let mut todos = app.todos.try_lock().expect("todos");
        for index in 0..count {
            todos.add(
                format!("work item {index}"),
                if index == 0 {
                    TodoStatus::InProgress
                } else {
                    TodoStatus::Pending
                },
            );
        }
    }

    fn operation_graph(state: NodeState) -> crate::work_graph::WorkGraphSnapshot {
        let objective = WorkNodeId::derive(SESSION, "objective");
        let operation = WorkNodeId::derive(SESSION, "operation");
        let ctx = |now| ChangeCtx {
            session_id: SESSION.to_string(),
            now,
            idempotency_key: None,
        };
        let node = |id: WorkNodeId, kind, title: &str, now| WorkNode {
            id,
            kind,
            title: title.to_string(),
            state: NodeState::Ready,
            acceptance: Vec::new(),
            binding: None,
            evidence: None,
            provenance: Provenance::RuntimeReconcile {
                source: "test-owner".to_string(),
                observed_at: now,
            },
            created_at: now,
            updated_at: now,
        };
        let mut graph = WorkGraph::new();
        graph
            .apply(
                WorkGraphChange::AddNode {
                    node: node(objective.clone(), NodeKind::Objective, "Ship v0.9.1", 1),
                },
                ctx(1),
            )
            .expect("objective");
        graph
            .apply(
                WorkGraphChange::AddNode {
                    node: node(
                        operation.clone(),
                        NodeKind::Operation,
                        "Verify installed build",
                        2,
                    ),
                },
                ctx(2),
            )
            .expect("operation");
        graph
            .apply(
                WorkGraphChange::AddEdge {
                    edge: WorkEdge {
                        id: WorkEdgeId::derive(SESSION, "contains"),
                        kind: EdgeKind::Contains,
                        from: objective,
                        to: operation.clone(),
                    },
                },
                ctx(3),
            )
            .expect("contains");
        graph
            .apply(
                WorkGraphChange::BindOperation {
                    node: operation.clone(),
                    binding: OperationBinding {
                        external: "shell:shell_1234abcd".to_string(),
                        durable: false,
                        last_observation: None,
                    },
                },
                ctx(4),
            )
            .expect("binding");
        if state != NodeState::Ready {
            graph
                .apply(
                    WorkGraphChange::UpdateNode {
                        id: operation,
                        patch: crate::work_graph::WorkNodePatch {
                            state: Some(state),
                            ..crate::work_graph::WorkNodePatch::default()
                        },
                    },
                    ctx(5),
                )
                .expect("state");
        }
        graph.into_snapshot()
    }

    fn restore_graph(app: &mut App, graph: &crate::work_graph::WorkGraphSnapshot) {
        app.current_session_id = Some(SESSION.to_string());
        app.runtime_services
            .work
            .as_ref()
            .expect("Work Graph runtime")
            .restore(
                SESSION,
                Some(graph),
                &crate::work_graph::project_todos(graph),
                &crate::work_graph::project_plan(graph),
            )
            .expect("restore graph");
    }

    fn restore_saved_graph(app: &mut App, graph: &crate::work_graph::WorkGraphSnapshot) {
        app.current_session_id = Some(SESSION.to_string());
        let state = crate::session_manager::SessionWorkState {
            graph: Some(graph.clone()),
            todos: crate::work_graph::project_todos(graph),
            plan: crate::work_graph::project_plan(graph),
        };
        app.restore_work_state(SESSION, std::path::Path::new("."), Some(&state))
            .expect("restore saved graph");
    }

    fn render_text(app: &mut App, width: u16, height: u16) -> String {
        let backend = TestBackend::new(width, height);
        let mut terminal = Terminal::new(backend).expect("terminal");
        terminal
            .draw(|frame| super::render(frame, frame.area(), app))
            .expect("draw");
        terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|cell| cell.symbol())
            .collect()
    }

    #[test]
    fn projection_keeps_every_legacy_todo_as_a_graph_row() {
        let mut app = app();
        add_todos(&mut app, 4);

        let rows = super::model::project(&mut app);

        assert!(
            rows[0].label.starts_with("Work · Running:")
                || rows[0]
                    .label
                    .starts_with("Work · 1 active · 0 needs input · 3 ready"),
            "unexpected heading {}",
            rows[0].label
        );
        for index in 0..4 {
            assert!(
                rows.iter()
                    .any(|row| row.label == format!("work item {index}"))
            );
        }
        assert!(rows.iter().all(|row| !row.id.0.starts_with("todo:")));
    }

    #[test]
    fn coordination_projection_is_one_selectable_work_row_with_shared_details() {
        use crate::tools::subagent::CoordinationDetailProjection;
        use crate::tools::subagent::coord::{
            CoordinationDetailMetrics, DecisionRecord, DecisionStatus,
        };

        let mut app = app();
        app.coordination_detail = Some(CoordinationDetailProjection {
            schema_version: 1,
            sequence: 7,
            decisions: vec![DecisionRecord {
                decision_id: "decision-work".to_string(),
                subject: "coordination row".to_string(),
                status: DecisionStatus::Accepted,
                owner: "release-owner".to_string(),
                scope: Vec::new(),
                constraints: vec!["PRIVATE-TRANSCRIPT-MARKER".to_string()],
                evidence_handles: Vec::new(),
                version: 2,
                sequence: 7,
            }],
            write_claims: Vec::new(),
            reconciliations: Vec::new(),
            context_projections: Vec::new(),
            contentions: Vec::new(),
            metrics: CoordinationDetailMetrics {
                hottest_paths: Vec::new(),
                package_or_module_growth: None,
                route_or_cost: None,
                note: "No active claims".to_string(),
            },
            bounded: true,
            limit: 24,
            process_lock_held: true,
            process_lock_note: None,
        });

        let rows = super::model::project(&mut app);
        assert_eq!(
            rows[0].label,
            "Work · 0 active · 0 needs input · 0 ready · 1 recent"
        );
        let row = rows
            .iter()
            .find(|row| row.id.0 == "coordination")
            .expect("coordination Work row");
        assert_eq!(row.label, "Coordination Work");
        assert_eq!(row.detail, "1 decisions · 0 contentions · 0 reconciled");
        let Some(SidebarRowAction::InspectWork { title, body, .. }) = row.primary_action.as_ref()
        else {
            panic!("coordination row must open the shared Work inspector");
        };
        assert_eq!(title, "Coordination Work");
        assert!(body.contains("decision-work · coordination row"), "{body}");
        assert!(
            body.contains("status accepted · owner release-owner · version 2"),
            "{body}"
        );
        assert!(!body.contains("PRIVATE-TRANSCRIPT-MARKER"), "{body}");

        app.work_surface.placement = WorkSurfacePlacement::Right;
        app.work_surface.effective_placement = WorkSurfacePlacement::Right;
        let narrow = render_text(&mut app, 32, 4);
        assert!(narrow.contains("Coordination Work"), "{narrow}");
        let _ = super::handle_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('w'), KeyModifiers::ALT),
        );
        let action = super::handle_key(&mut app, KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE))
            .expect("Work surface handled Enter")
            .expect("coordination inspector action");
        assert!(matches!(action, SidebarRowAction::InspectWork { .. }));
    }

    #[test]
    fn empty_coordination_projection_does_not_create_work_chrome() {
        use crate::tools::subagent::CoordinationDetailProjection;
        use crate::tools::subagent::coord::{ContextProjectionReceipt, CoordinationDetailMetrics};

        let mut app = app();
        app.coordination_detail = Some(CoordinationDetailProjection {
            schema_version: 1,
            sequence: 3,
            decisions: Vec::new(),
            write_claims: Vec::new(),
            reconciliations: Vec::new(),
            context_projections: ["agent-a", "agent-b", "agent-c"]
                .into_iter()
                .enumerate()
                .map(|(index, child_id)| ContextProjectionReceipt {
                    child_id: child_id.to_string(),
                    decision_ids: Vec::new(),
                    projected_bytes: 0,
                    deduplicated: 0,
                    omitted: 0,
                    sequence: u64::try_from(index + 1).expect("small fixture sequence"),
                })
                .collect(),
            contentions: Vec::new(),
            metrics: CoordinationDetailMetrics {
                hottest_paths: Vec::new(),
                package_or_module_growth: None,
                route_or_cost: None,
                note: "growth and route/cost stay null when the coordination ledger has no authoritative source".to_string(),
            },
            bounded: true,
            limit: 24,
            process_lock_held: true,
            process_lock_note: None,
        });

        let rows = super::model::project(&mut app);
        assert!(
            rows.is_empty(),
            "zero-byte, no-decision coordination receipts must not create Work chrome: {rows:?}"
        );
    }

    #[test]
    fn nonempty_context_projection_remains_inspectable_work() {
        use crate::tools::subagent::CoordinationDetailProjection;
        use crate::tools::subagent::coord::{ContextProjectionReceipt, CoordinationDetailMetrics};

        let mut app = app();
        app.coordination_detail = Some(CoordinationDetailProjection {
            schema_version: 1,
            sequence: 1,
            decisions: Vec::new(),
            write_claims: Vec::new(),
            reconciliations: Vec::new(),
            context_projections: vec![ContextProjectionReceipt {
                child_id: "agent-a".to_string(),
                decision_ids: vec!["decision-a".to_string()],
                projected_bytes: 32,
                deduplicated: 0,
                omitted: 0,
                sequence: 1,
            }],
            contentions: Vec::new(),
            metrics: CoordinationDetailMetrics {
                hottest_paths: Vec::new(),
                package_or_module_growth: None,
                route_or_cost: None,
                note: String::new(),
            },
            bounded: true,
            limit: 24,
            process_lock_held: true,
            process_lock_note: None,
        });

        let rows = super::model::project(&mut app);
        assert!(
            rows.iter().any(|row| row.id.0 == "coordination"),
            "non-empty context projection must remain inspectable: {rows:?}"
        );
    }

    #[test]
    fn current_blocked_contention_uses_attention_bucket_mark_and_tone() {
        use crate::tools::subagent::CoordinationDetailProjection;
        use crate::tools::subagent::coord::{
            CoordinationDetailMetrics, PersistedWriteClaim, WriteContentionDisposition,
            WriteContentionReceipt, WriteScopeClaim,
        };

        let mut app = app();
        app.coordination_detail = Some(CoordinationDetailProjection {
            schema_version: 1,
            sequence: 2,
            decisions: Vec::new(),
            write_claims: vec![PersistedWriteClaim {
                claim: WriteScopeClaim {
                    owner: "worker-a".to_string(),
                    roots: vec!["crates/tui".to_string()],
                    exact_files: Vec::new(),
                    contracts: vec!["ui-contract".to_string()],
                },
                sequence: 1,
                isolated_worktree: false,
            }],
            reconciliations: Vec::new(),
            context_projections: Vec::new(),
            contentions: vec![WriteContentionReceipt {
                claimant: "worker-b".to_string(),
                conflicting_owner: "worker-a".to_string(),
                roots: vec!["crates/tui".to_string()],
                exact_files: Vec::new(),
                contracts: vec!["ui-contract".to_string()],
                disposition: WriteContentionDisposition::BlockedPendingIsolationOrSerialization,
                resolution_sequence: None,
                sequence: 2,
            }],
            metrics: CoordinationDetailMetrics {
                hottest_paths: Vec::new(),
                package_or_module_growth: None,
                route_or_cost: None,
                note: "No authoritative metric source".to_string(),
            },
            bounded: true,
            limit: 24,
            process_lock_held: true,
            process_lock_note: None,
        });

        let rows = super::model::project(&mut app);
        assert_eq!(
            rows[0].label,
            "Work · Needs input: Coordination Work · 1 blocked"
        );
        let row = rows
            .iter()
            .find(|row| row.id.0 == "coordination")
            .expect("blocked coordination Work row");
        assert_eq!(row.mark, crate::tui::glyphs::ATTENTION);
        assert_eq!(row.tone, super::model::WorkTone::Attention);
        assert_eq!(row.detail, "0 decisions · 1 contentions · 0 reconciled");
    }

    #[test]
    fn todos_share_one_canonical_work_projection_without_a_second_heading() {
        let mut app = app();
        {
            let mut todos = app.todos.try_lock().expect("todos");
            todos.add("finished".to_string(), TodoStatus::Completed);
            todos.add("current".to_string(), TodoStatus::InProgress);
            todos.add("next".to_string(), TodoStatus::Pending);
        }

        let rows = super::model::project(&mut app);

        assert!(
            rows[0].label.starts_with("Work · Running:")
                || rows[0].label.starts_with("Work · Ready:"),
            "expected actionable title heading, got {}",
            rows[0].label
        );
        assert_eq!(
            rows.iter()
                .skip(1)
                .map(|row| row.label.as_str())
                .collect::<Vec<_>>(),
            ["finished", "current", "next"]
        );
    }

    #[test]
    fn top_surface_pins_one_progress_receipt_and_numbers_canonical_rows() {
        let mut app = app();
        {
            let mut todos = app.todos.try_lock().expect("todos");
            todos.add("finished".to_string(), TodoStatus::Completed);
            todos.add("current".to_string(), TodoStatus::InProgress);
            todos.add("next".to_string(), TodoStatus::Pending);
        }

        let text = render_text(&mut app, 80, 6);
        let done = format!("1 · {} finished", crate::tui::glyphs::DONE);
        let current = format!("2 · {} current", crate::tui::glyphs::SELECTION);
        let next = format!("3 · {} next", crate::tui::glyphs::READY);

        assert!(text.contains("To-do · 1/3 · 2 left"), "{text:?}");
        assert_eq!(text.matches("To-do ·").count(), 1, "{text:?}");
        assert!(text.contains(&done), "{text:?}");
        assert!(text.contains(&current), "{text:?}");
        assert!(text.contains(&next), "{text:?}");
        assert!(
            text.find(&done) < text.find(&current) && text.find(&current) < text.find(&next),
            "canonical order drifted: {text:?}"
        );
        assert_eq!(app.work_surface.hitboxes.len(), 3);
        assert_eq!(app.work_surface.hitboxes[0].row_y, 1);
    }

    #[test]
    fn top_strip_auto_fits_step_count_up_to_caps() {
        // Two steps: divider + progress receipt + 2 rows = 4 lines, not a
        // fixed-height band of blank water.
        let mut two_steps = app();
        two_steps.work_surface.top_height = 8;
        add_todos(&mut two_steps, 2);
        let budget = working_budget(&two_steps, 40);
        assert_eq!(super::height(&mut two_steps, 100, 40, budget), 4);

        // Ten steps: content wants 12 lines, the default 8-line cap wins.
        let mut ten_steps = app();
        ten_steps.work_surface.top_height = 8;
        add_todos(&mut ten_steps, 10);
        let budget = working_budget(&ten_steps, 40);
        assert_eq!(super::height(&mut ten_steps, 100, 40, budget), 8);

        // Short terminal: the transcript's spare rows beat both content and
        // the configured cap. A 12-row terminal spends 1 on the header, 1 on
        // the phase strip and 3 on the bordered composer, and owes the
        // transcript its 3-row floor — so 4 rows are actually spare. (This
        // used to be 6, half the terminal, which left the transcript 2 rows.)
        let mut short_terminal = app();
        short_terminal.work_surface.top_height = 8;
        add_todos(&mut short_terminal, 10);
        let budget = working_budget(&short_terminal, 12);
        assert_eq!(super::height(&mut short_terminal, 100, 12, budget), 4);

        // Nothing to show: no strip at all.
        let mut empty = app();
        empty.work_surface.top_height = 8;
        assert_eq!(super::height(&mut empty, 100, 40, AMPLE_BUDGET), 0);
    }

    /// A strip that reports zero rows is not on screen, so the interaction
    /// state describing it must go with it. Stale hitboxes outlive the rows
    /// they described: the transcript rows that replaced the strip would keep
    /// routing clicks into a panel that is not there.
    #[test]
    fn a_yielded_strip_drops_its_interaction_state() {
        // Each case is a distinct zero-return inside `height`, and every one
        // of them has to tear down. `starve` turns a rendered strip into a
        // yielded one; the assertions are identical either way. The first two
        // are the returns this yield rule introduced — the ones that had no
        // teardown at all.
        type Starve = fn(&mut App) -> (u16, u16, u16);
        let cases: [(&str, Starve); 3] = [
            ("budget starves the Tasks strip", |_app| (100, 40, 0)),
            ("budget starves a switched-to panel", |app| {
                app.work_surface.panel = super::RailPanel::Pinned;
                (100, 40, 0)
            }),
            ("placement off", |app| {
                app.work_surface.placement = WorkSurfacePlacement::Off;
                (100, 40, AMPLE_BUDGET)
            }),
        ];

        for (label, starve) in cases {
            let mut app = app();
            app.work_surface.placement = WorkSurfacePlacement::Top;
            // `app()` reads the developer's real settings.toml. Pin the height
            // too, or the strip this test renders to earn its hitboxes depends
            // on whoever runs the suite.
            app.work_surface.top_height = 8;
            add_todos(&mut app, 4);

            // Earn a real strip, so the hitboxes under test are the ones the
            // renderer actually produces rather than a fixture's guess.
            render_text(&mut app, 100, 12);
            assert!(
                !app.work_surface.hitboxes.is_empty(),
                "{label}: setup never rendered a strip to tear down"
            );
            app.work_surface.focused = true;
            app.work_surface.resizing = true;
            app.work_surface.divider_hovered = true;

            let (width, height, budget) = starve(&mut app);
            assert_eq!(
                super::height(&mut app, width, height, budget),
                0,
                "{label}: expected the strip to yield"
            );
            assert!(
                app.work_surface.hitboxes.is_empty(),
                "{label}: left {} stale hitboxes behind",
                app.work_surface.hitboxes.len()
            );
            assert!(
                app.work_surface.last_area.is_none(),
                "{label}: stale last_area"
            );
            assert!(!app.work_surface.focused, "{label}: focus survived");
            assert!(!app.work_surface.resizing, "{label}: resize drag survived");
            assert!(
                !app.work_surface.divider_hovered,
                "{label}: divider hover survived"
            );
        }
    }

    /// `top_height` is a ceiling, not a fixed size. A short ceiling must still
    /// render (not collapse), and content longer than the ceiling is clamped
    /// to it rather than padded with blank water.
    #[test]
    fn a_short_top_height_caps_content_rather_than_collapsing() {
        let mut capped = app();
        capped.work_surface.placement = WorkSurfacePlacement::Top;
        capped.work_surface.panel = super::RailPanel::Pinned;
        capped.work_surface.top_height = 2;
        capped.composer_border = true;
        // Goal + several checklist rows: content wants more than 2, the cap wins.
        capped.hunt.quarry = Some("ship the release".to_string());
        add_todos(&mut capped, 6);
        let budget = working_budget(&capped, 40);
        assert_eq!(
            super::height(&mut capped, 100, 40, budget),
            2,
            "short top_height is a cap the strip must fit under, not a cliff"
        );

        // Content shorter than the cap shrinks: a single goal line + divider
        // is 2 rows, not a padded 8-row band.
        let mut short = app();
        short.work_surface.placement = WorkSurfacePlacement::Top;
        short.work_surface.panel = super::RailPanel::Pinned;
        short.work_surface.top_height = 8;
        short.hunt.quarry = Some("one goal only".to_string());
        let budget = working_budget(&short, 40);
        let h = super::height(&mut short, 100, 40, budget);
        assert!(
            (2..=4).contains(&h),
            "short content auto-fits under the cap, got {h}"
        );
    }

    /// Non-Tasks Top panels auto-fit the same way Tasks always did: content
    /// rows + divider, never a fixed four-row chrome band. An active goal
    /// adds exactly one title row (not a panel name).
    #[test]
    fn top_panel_auto_fits_content_like_tasks() {
        let mut pinned = app();
        pinned.work_surface.placement = WorkSurfacePlacement::Top;
        pinned.work_surface.panel = super::RailPanel::Pinned;
        pinned.work_surface.top_height = 12;
        pinned.hunt.quarry = Some("goal".to_string());
        add_todos(&mut pinned, 3);
        let budget = working_budget(&pinned, 40);
        let h = super::height(&mut pinned, 100, 40, budget);
        // goal title + 3 checklist + divider ≈ 5; must not be the old fixed 4,
        // and must not pad out to the 12-row cap.
        assert!(
            (4..=8).contains(&h),
            "Pinned should auto-fit checklist content, got {h}"
        );

        // Empty Pinned collapses entirely.
        let mut empty = app();
        empty.work_surface.placement = WorkSurfacePlacement::Top;
        empty.work_surface.panel = super::RailPanel::Pinned;
        empty.work_surface.top_height = 12;
        assert_eq!(
            super::height(&mut empty, 100, 40, AMPLE_BUDGET),
            0,
            "empty Pinned is not a panel"
        );

        // Empty Agents collapses too (no "No agents" chrome strip).
        let mut agents = app();
        agents.work_surface.placement = WorkSurfacePlacement::Top;
        agents.work_surface.panel = super::RailPanel::Agents;
        agents.work_surface.top_height = 12;
        assert_eq!(
            super::height(&mut agents, 100, 40, AMPLE_BUDGET),
            0,
            "empty Agents is not a panel"
        );
    }

    /// Top titles only when a live goal is set — never the panel name.
    #[test]
    fn top_title_is_goal_only_never_panel_chrome() {
        // With a goal: title is "Goal: …".
        let mut with_goal = app();
        with_goal.work_surface.placement = WorkSurfacePlacement::Top;
        with_goal.work_surface.panel = super::RailPanel::Pinned;
        with_goal.work_surface.top_height = 8;
        with_goal.hunt.quarry = Some("ship 0.9.4".to_string());
        let text = render_text(&mut with_goal, 80, 8);
        assert!(
            text.contains("Goal: ship 0.9.4"),
            "active goal must be the Top title: {text:?}"
        );
        assert!(
            !text.contains("Pinned"),
            "panel name is not a Top title: {text:?}"
        );

        // Without a goal, only checklist: no Goal title, no Pinned chrome.
        let mut no_goal = app();
        no_goal.work_surface.placement = WorkSurfacePlacement::Top;
        no_goal.work_surface.panel = super::RailPanel::Pinned;
        no_goal.work_surface.top_height = 8;
        add_todos(&mut no_goal, 2);
        let text = render_text(&mut no_goal, 80, 6);
        assert!(
            !text.contains("Goal:"),
            "no live goal → no Goal title: {text:?}"
        );
        assert!(
            !text.contains("Pinned"),
            "panel name is never a Top title: {text:?}"
        );
    }

    /// Tasks with only a goal (no todos/agents) still shows a strip.
    #[test]
    fn top_tasks_goal_alone_still_renders_a_strip() {
        let mut app = app();
        app.work_surface.placement = WorkSurfacePlacement::Top;
        app.work_surface.panel = super::RailPanel::Tasks;
        app.work_surface.top_height = 8;
        app.hunt.quarry = Some("only a goal".to_string());
        let budget = working_budget(&app, 40);
        let h = super::height(&mut app, 100, 40, budget);
        assert!(h >= 2, "goal alone must reserve title + divider, got {h}");
        let text = render_text(&mut app, 80, h);
        assert!(
            text.contains("Goal: only a goal"),
            "goal-alone strip must paint the title: {text:?}"
        );
    }

    /// Side rails share the empty-collapse rule: no content → no column.
    /// Width stays the configured ceiling when content exists.
    #[test]
    fn side_rail_collapses_when_empty_and_reserves_when_contentful() {
        let area = ratatui::layout::Rect::new(0, 0, 120, 32);

        // Empty Pinned: no side column.
        let mut empty = app();
        empty.work_surface.placement = WorkSurfacePlacement::Right;
        empty.work_surface.panel = super::RailPanel::Pinned;
        empty.work_surface.side_width = 30;
        assert_eq!(
            super::split_chat(&mut empty, area, 0),
            (area, None),
            "empty Pinned must not reserve a side column"
        );

        // Contentful Pinned: full-height column at configured width.
        let mut full = app();
        full.work_surface.placement = WorkSurfacePlacement::Right;
        full.work_surface.panel = super::RailPanel::Pinned;
        full.work_surface.side_width = 30;
        full.hunt.quarry = Some("ship it".to_string());
        let (chat, rail) = super::split_chat(&mut full, area, 0);
        let rail = rail.expect("contentful Pinned reserves a side rail");
        assert_eq!(rail.width, 30);
        assert_eq!(chat.width, area.width - 30);
        assert_eq!(rail.height, area.height);
    }

    #[test]
    fn minimum_top_surface_keeps_a_numbered_todo_selectable() {
        let mut app = app();
        add_todos(&mut app, 2);

        let text = render_text(&mut app, 40, 2);

        assert!(text.contains("1 ·"), "{text:?}");
        assert!(!text.contains("To-do · 0/"), "{text:?}");
        assert_eq!(app.work_surface.hitboxes.len(), 1);
        assert_eq!(app.work_surface.hitboxes[0].row_y, 0);
    }

    #[test]
    fn compact_progress_window_reveals_current_without_reordering() {
        let mut app = app();
        {
            let mut todos = app.todos.try_lock().expect("todos");
            todos.add("finished".to_string(), TodoStatus::Completed);
            todos.add("current".to_string(), TodoStatus::InProgress);
            todos.add("next".to_string(), TodoStatus::Pending);
        }

        // Three rows means one pinned progress receipt, one selectable row,
        // and the divider. The current item must win that compact window while
        // retaining its canonical ordinal.
        let text = render_text(&mut app, 80, 3);

        assert!(text.contains("To-do · 1/3 · 2 left"), "{text:?}");
        assert!(
            text.contains(&format!("2 · {} current", crate::tui::glyphs::SELECTION)),
            "{text:?}"
        );
        assert_eq!(app.work_surface.scroll_offset, 1);
        assert_eq!(app.work_surface.hitboxes[0].row_y, 1);
    }

    #[test]
    fn settled_file_tools_aggregate_once_and_keep_only_safe_targets() {
        let mut app = app();
        app.current_session_id = Some(SESSION.to_string());
        app.workspace = PathBuf::from("/workspace/project");
        for (id, name, input, status) in [
            (
                "read-1",
                "read_file",
                serde_json::json!({"path": "/workspace/project/src/lib.rs"}),
                ToolStatus::Success,
            ),
            (
                "search-1",
                "grep_files",
                serde_json::json!({"pattern": "WorkSurfaceState"}),
                ToolStatus::Success,
            ),
            (
                "write-1",
                "edit_file",
                serde_json::json!({"path": "src/lib.rs"}),
                ToolStatus::Success,
            ),
            (
                "read-external",
                "read_file",
                serde_json::json!({"path": "/Users/alice/private.txt"}),
                ToolStatus::Failed,
            ),
        ] {
            app.add_message(HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
                name: name.to_string(),
                status,
                input_summary: None,
                output: Some("done".to_string()),
                prompts: None,
                spillover_path: None,
                output_summary: None,
                is_diff: false,
            })));
            let index = app.history.len() - 1;
            app.tool_details_by_cell.insert(
                index,
                ToolDetailRecord {
                    tool_id: id.to_string(),
                    tool_name: name.to_string(),
                    input,
                    output: Some("done".to_string()),
                },
            );
        }

        let rows = super::model::project(&mut app);
        let activity = rows
            .iter()
            .find(|row| row.id.0 == "activity:aggregate")
            .expect("aggregated activity row");
        assert!(
            activity.label.contains("Read 1 files")
                && activity.label.contains("Searched 1 patterns")
                && activity.label.contains("Wrote 1 files"),
            "aggregated label: {}",
            activity.label
        );
        assert!(!activity.detail.contains("/Users/alice"));
        assert!(!activity.label.contains("WorkSurfaceState"));
    }

    #[test]
    fn agent_rows_show_role_assignment_and_open_the_agent_transcript() {
        let mut app = app();
        app.current_session_id = Some(SESSION.to_string());
        app.subagent_cache.push(SubAgentResult {
            name: "agent_worker".to_string(),
            agent_id: "agent_worker".to_string(),
            context_mode: "fresh".to_string(),
            fork_context: false,
            workspace: None,
            git_branch: None,
            agent_type: FleetRole::Builder,
            assignment: SubAgentAssignment {
                objective: "Wire settled file activity".to_string(),
                role: Some("worker".to_string()),
            },
            model: "test-model".to_string(),
            nickname: Some("Blue Whale".to_string()),
            status: SubAgentStatus::Running,
            worker_status: Some(AgentWorkerStatus::RunningTool),
            runtime_permissions: None,
            parent_run_id: None,
            spawn_depth: 1,
            child_route: None,
            result: None,
            steps_taken: 2,
            checkpoint: None,
            needs_input: None,
            duration_ms: 50,
            started_at: None,
            from_prior_session: false,
        });
        app.agent_progress_meta.insert(
            "agent_worker".to_string(),
            crate::tui::app::AgentProgressMeta {
                current_activity: Some(AgentCurrentActivity::bounded(
                    AgentCurrentActivityStatus::RunningTool,
                    None,
                    Some("File.apply_patch".to_string()),
                    Some(2),
                )),
                current_tool: Some("apply_patch".to_string()),
                files_touched: 2,
                ..crate::tui::app::AgentProgressMeta::default()
            },
        );

        let rows = super::model::project(&mut app);
        let row = rows
            .iter()
            .find(|row| row.id.0 == "worker:agent_worker")
            .expect("agent work row");
        // The identity column leads with the agent's nickname and keeps the
        // fleet role as the fallback spelling. It is never the raw agent id
        // (#36), and carries no `(+N)` while the agent is childless.
        assert_eq!(row.label, "Blue Whale");
        let facts = row.agent.as_ref().expect("agent row facts");
        assert_eq!(facts.role_label, "worker");
        assert_eq!(facts.objective, "Wire settled file activity");
        assert_eq!(facts.elapsed_secs, Some(0));
        // No usage envelope has been seen, so there is no token figure at all.
        assert_eq!(facts.tokens, None);
        assert!(row.detail.contains("Wire settled file activity"));
        assert!(row.detail.contains("using File.apply_patch"));
        assert!(row.detail.contains("step 2"));
        assert!(row.detail.contains("2 files changed"));
        // One agent, one destination (v0.9.7): activation opens the agent's
        // transcript directly; Agent Details is the secondary action.
        assert_eq!(
            row.primary_action,
            Some(SidebarRowAction::OpenAgentTranscript {
                agent_id: "agent_worker".to_string(),
            })
        );
    }

    fn cached_worker(
        id: &str,
        role: &str,
        nickname: Option<&str>,
        parent_run_id: Option<&str>,
        status: SubAgentStatus,
    ) -> SubAgentResult {
        SubAgentResult {
            // `name` is the raw session id in production snapshots — the
            // strip must never render it (#36).
            name: id.to_string(),
            agent_id: id.to_string(),
            context_mode: "fresh".to_string(),
            fork_context: false,
            workspace: None,
            git_branch: None,
            agent_type: FleetRole::Builder,
            assignment: SubAgentAssignment {
                objective: format!("objective for {id}"),
                role: Some(role.to_string()),
            },
            model: "test-model".to_string(),
            nickname: nickname.map(str::to_string),
            status,
            worker_status: None,
            runtime_permissions: None,
            parent_run_id: parent_run_id.map(str::to_string),
            spawn_depth: u32::from(parent_run_id.is_some()) + 1,
            child_route: None,
            result: None,
            steps_taken: 1,
            checkpoint: None,
            needs_input: None,
            duration_ms: 50,
            started_at: None,
            from_prior_session: false,
        }
    }

    #[test]
    fn agent_rows_identify_by_fleet_role_and_never_leak_raw_ids() {
        // #36: the strip identifies an agent by its fleet role; the raw agent
        // id hash is noise and must never render as the "name". Flat fan-outs
        // carry no nesting chrome.
        let mut app = app();
        app.current_session_id = Some(SESSION.to_string());
        app.subagent_cache.push(cached_worker(
            "agent_e0b2dcf1",
            "builder",
            None,
            None,
            SubAgentStatus::Running,
        ));
        app.subagent_cache.push(cached_worker(
            "agent_99aa77bb",
            "scout",
            None,
            None,
            SubAgentStatus::Running,
        ));

        let rows = super::model::project(&mut app);
        let first = rows
            .iter()
            .find(|row| row.id.0 == "worker:agent_e0b2dcf1")
            .expect("first agent row");
        let second = rows
            .iter()
            .find(|row| row.id.0 == "worker:agent_99aa77bb")
            .expect("second agent row");
        assert_eq!(first.label, "builder");
        assert_eq!(second.label, "scout");
        assert!(first.detail.starts_with("running"), "{}", first.detail);
        for row in rows.iter().filter(|row| row.id.0.starts_with("worker:")) {
            assert!(!row.label.contains("agent_e0b2dcf1"), "{}", row.label);
            assert!(!row.label.contains("agent_99aa77bb"), "{}", row.label);
            assert!(
                !row.label.contains(''),
                "flat fan-out must not show nesting chrome: {}",
                row.label
            );
        }
    }

    #[test]
    fn agent_rows_order_and_indent_nested_spawns_under_their_parent() {
        // #36: nesting is visible only when actually present — the child
        // renders directly under its parent with a `↳` indent, and the parent
        // advertises the child it spawned as `(+1)`.
        let mut app = app();
        app.current_session_id = Some(SESSION.to_string());
        app.subagent_cache.push(cached_worker(
            "agent_child",
            "scout",
            None,
            Some("agent_parent"),
            SubAgentStatus::Running,
        ));
        app.subagent_cache.push(cached_worker(
            "agent_parent",
            "builder",
            None,
            None,
            SubAgentStatus::Running,
        ));

        let rows = super::model::project(&mut app);
        let worker_labels = rows
            .iter()
            .filter(|row| row.id.0.starts_with("worker:"))
            .map(|row| row.label.as_str())
            .collect::<Vec<_>>();
        let parent_pos = worker_labels
            .iter()
            .position(|label| *label == "builder (+1)")
            .expect("parent row label with child count");
        let child_pos = worker_labels
            .iter()
            .position(|label| *label == "↳ scout")
            .expect("indented child row label");
        assert!(
            child_pos == parent_pos + 1,
            "child must render directly under its parent: {worker_labels:?}"
        );
    }

    #[test]
    fn agent_rows_completed_agents_render_quietly_without_spawn_metadata() {
        // #36: quiet completion — a finished agent keeps status + objective;
        // in-flight metadata (tool, step counters, file tallies) must not
        // linger as a receipt dump.
        let mut app = app();
        app.current_session_id = Some(SESSION.to_string());
        app.subagent_cache.push(cached_worker(
            "agent_done",
            "builder",
            None,
            None,
            SubAgentStatus::Completed,
        ));
        app.agent_progress_meta.insert(
            "agent_done".to_string(),
            crate::tui::app::AgentProgressMeta {
                current_activity: Some(AgentCurrentActivity::bounded(
                    AgentCurrentActivityStatus::Done,
                    Some("apply_patch finished".to_string()),
                    Some("File.apply_patch".to_string()),
                    Some(7),
                )),
                current_tool: Some("apply_patch".to_string()),
                files_touched: 4,
                ..crate::tui::app::AgentProgressMeta::default()
            },
        );

        let rows = super::model::project(&mut app);
        let row = rows
            .iter()
            .find(|row| row.id.0 == "worker:agent_done")
            .expect("completed agent row");
        assert!(row.detail.contains("completed"), "{}", row.detail);
        assert!(
            row.detail.contains("objective for agent_done"),
            "{}",
            row.detail
        );
        assert!(!row.detail.contains("using "), "{}", row.detail);
        assert!(!row.detail.contains("step 7"), "{}", row.detail);
        assert!(!row.detail.contains("files changed"), "{}", row.detail);
    }

    // ---- Fleet row layout -------------------------------------------------

    /// Painted lines, one per terminal row, trailing padding removed.
    fn render_rows(app: &mut App, width: u16, height: u16) -> Vec<String> {
        let backend = TestBackend::new(width, height);
        let mut terminal = Terminal::new(backend).expect("terminal");
        terminal
            .draw(|frame| super::render(frame, frame.area(), app))
            .expect("draw");
        let buffer = terminal.backend().buffer().clone();
        (0..height)
            .map(|y| {
                (0..width)
                    .map(|x| buffer[(x, y)].symbol())
                    .collect::<String>()
                    .trim_end()
                    .to_string()
            })
            .collect()
    }

    fn fleet_row(rows: &[String]) -> String {
        rows.iter()
            .find(|line| line.contains("Streaming"))
            .cloned()
            .unwrap_or_else(|| panic!("no fleet row in {rows:?}"))
    }

    fn fleet_worker(
        id: &str,
        role: &str,
        objective: &str,
        duration_ms: u64,
        status: SubAgentStatus,
    ) -> SubAgentResult {
        let mut agent = cached_worker(id, role, None, None, status);
        agent.assignment.objective = objective.to_string();
        agent.duration_ms = duration_ms;
        agent
    }

    /// Seed a live fleet of one, with a reported token spend.
    fn fleet_app(tokens: Option<u64>) -> App {
        let mut app = app();
        app.current_session_id = Some(SESSION.to_string());
        app.subagent_cache.push(fleet_worker(
            "agent_stream",
            "general-purpose",
            "Streaming dead-code removal",
            753_000,
            SubAgentStatus::Running,
        ));
        app.agent_progress_meta.insert(
            "agent_stream".to_string(),
            crate::tui::app::AgentProgressMeta {
                received_tokens: tokens,
                ..crate::tui::app::AgentProgressMeta::default()
            },
        );
        app
    }

    #[test]
    fn fleet_row_lays_out_type_objective_and_a_right_aligned_receipt() {
        let mut app = fleet_app(Some(111_900));
        let rows = render_rows(&mut app, 100, 4);

        assert_eq!(
            fleet_row(&rows),
            " ▸ general-purpose  running  Streaming dead-code removal                  \
12m 33s · ↓ 111.9k tokens"
        );
        // The group header the strip already had stays put.
        assert!(
            rows.iter().any(|line| line.contains("Subagents 1")),
            "{rows:?}"
        );
    }

    #[test]
    fn focused_worker_row_carries_the_left_marker_and_queued_follow_ups() {
        let mut app = fleet_app(Some(111_900));
        // No focus, nothing queued: the row is exactly as before.
        let plain = fleet_row(&render_rows(&mut app, 100, 4));
        assert!(!plain.starts_with(""), "{plain}");
        assert!(!plain.contains("queued"), "{plain}");

        crate::tui::agent_focus::focus_agent(&mut app, "agent_stream");
        app.agent_queued_follow_ups
            .insert("agent_stream".to_string(), 1);
        let focused = fleet_row(&render_rows(&mut app, 110, 4));
        assert!(
            focused.trim_start().starts_with("❯ ▸ general-purpose"),
            "left-edge marker names the addressed fork: {focused}"
        );
        assert!(focused.ends_with("· 1 queued"), "{focused}");

        // The counter is the runtime's truth: once the child takes the input
        // the next AgentList refresh clears it and the suffix disappears.
        app.agent_queued_follow_ups.clear();
        let drained = fleet_row(&render_rows(&mut app, 110, 4));
        assert!(!drained.contains("queued"), "{drained}");
        // Leaving focus removes the gutter again.
        crate::tui::agent_focus::exit_focus(&mut app);
        let back = fleet_row(&render_rows(&mut app, 100, 4));
        assert_eq!(back, plain);
    }

    #[test]
    fn fleet_row_repaints_resolved_model_and_each_distinct_usage_total() {
        let mut app = fleet_app(None);
        crate::tui::ui::record_agent_spawned_route(&mut app, "agent_stream", "deepseek-v4-pro");
        let launched = fleet_row(&render_rows(&mut app, 120, 4));
        assert!(launched.contains("deepseek-v4-pro"), "{launched}");
        assert!(!launched.contains("tokens"), "{launched}");

        let route = crate::cost_status::EffectiveRouteEnvelope::capture(
            None,
            ApiProvider::Deepseek,
            ApiProvider::Deepseek.as_str(),
            "deepseek-v4-pro",
            Some(ApiProvider::Deepseek.default_base_url()),
            chrono::Utc::now(),
        );
        let usage = |source_id: &str, input_tokens, output_tokens| MailboxMessage::TokenUsage {
            agent_id: "agent_stream".to_string(),
            source_id: source_id.to_string(),
            route: route.clone(),
            usage: crate::models::Usage {
                input_tokens,
                output_tokens,
                ..Default::default()
            },
        };

        crate::tui::subagent_routing::handle_subagent_mailbox(
            &mut app,
            99,
            &usage("response-1", 10_000, 1_000),
        );
        let first = fleet_row(&render_rows(&mut app, 120, 4));
        assert!(first.contains("deepseek-v4-pro"), "{first}");
        assert!(first.contains("11.0k tokens"), "{first}");

        // Replaying the same mailbox envelope must not inflate the receipt.
        crate::tui::subagent_routing::handle_subagent_mailbox(
            &mut app,
            1,
            &usage("response-1", 10_000, 1_000),
        );
        let replay = fleet_row(&render_rows(&mut app, 120, 4));
        assert!(replay.contains("11.0k tokens"), "{replay}");

        crate::tui::subagent_routing::handle_subagent_mailbox(
            &mut app,
            2,
            &usage("response-2", 20_000, 2_000),
        );
        let second = fleet_row(&render_rows(&mut app, 120, 4));
        assert!(second.contains("deepseek-v4-pro"), "{second}");
        assert!(second.contains("33.0k tokens"), "{second}");
    }

    #[test]
    fn fleet_row_shows_remaining_todos_only_when_the_ledger_has_unsettled_work() {
        let mut app = fleet_app(Some(1_200));
        app.agent_progress_meta
            .get_mut("agent_stream")
            .expect("meta")
            .todos_remaining = Some(3);

        let with_left = fleet_row(&render_rows(&mut app, 100, 4));
        assert!(
            with_left.contains("3 left"),
            "unsettled ledger must surface on the receipt: {with_left}"
        );
        assert!(
            with_left.contains("") && with_left.contains("tokens"),
            "tokens stay alongside the remaining chip: {with_left}"
        );

        // Fully settled list → quiet (no fabricated zero chip).
        app.agent_progress_meta
            .get_mut("agent_stream")
            .expect("meta")
            .todos_remaining = Some(0);
        let settled = fleet_row(&render_rows(&mut app, 100, 4));
        assert!(
            !settled.contains("left"),
            "zero remaining must not paint a chip: {settled}"
        );

        // No ledger published → quiet.
        app.agent_progress_meta
            .get_mut("agent_stream")
            .expect("meta")
            .todos_remaining = None;
        let absent = fleet_row(&render_rows(&mut app, 100, 4));
        assert!(
            !absent.contains("left"),
            "missing ledger must not invent a chip: {absent}"
        );
    }

    #[test]
    fn fleet_identity_prefers_the_nickname_and_falls_back_to_the_role() {
        // Nicknames are CodeWhale identity, so they lead. An agent that has
        // none falls back to its fleet role rather than showing a blank or a
        // fabricated name.
        let mut app = app();
        app.current_session_id = Some(SESSION.to_string());
        let mut named = fleet_worker(
            "agent_named",
            "general-purpose",
            "Streaming dead-code removal",
            753_000,
            SubAgentStatus::Running,
        );
        named.nickname = Some("Fluke".to_string());
        app.subagent_cache.push(named);
        app.subagent_cache.push(fleet_worker(
            "agent_plain",
            "general-purpose",
            "Ambient visual calm-down",
            741_000,
            SubAgentStatus::Running,
        ));

        let rows = super::model::project(&mut app);
        let row = |id: &str| {
            rows.iter()
                .find(|row| row.id.0 == format!("worker:{id}"))
                .unwrap_or_else(|| panic!("row for {id}"))
        };
        assert_eq!(row("agent_named").label, "Fluke");
        assert_eq!(
            row("agent_named").agent.as_ref().expect("facts").role_label,
            "general-purpose"
        );
        // No nickname: the identity and its fallback are the same string.
        assert_eq!(row("agent_plain").label, "general-purpose");

        // Both spellings share one column, so the objectives stay aligned.
        let painted = render_rows(&mut app, 100, 5);
        let named_line = painted
            .iter()
            .find(|line| line.contains("Fluke"))
            .expect("nicknamed row");
        let plain_line = painted
            .iter()
            .find(|line| line.contains("general-purpose"))
            .expect("un-nicknamed row");
        assert_eq!(
            named_line.find("Streaming"),
            plain_line.find("Ambient"),
            "objectives must share a column:\n{named_line}\n{plain_line}"
        );
    }

    #[test]
    fn an_identity_too_wide_for_the_column_falls_back_without_widening_it() {
        // The identity column is shared, so one outlier must not starve every
        // other objective — and a name is shown whole or not at all.
        let mut app = app();
        app.current_session_id = Some(SESSION.to_string());
        let mut long = fleet_worker(
            "agent_long",
            "general-purpose",
            "Streaming dead-code removal",
            753_000,
            SubAgentStatus::Running,
        );
        long.nickname = Some("Bartholomew the Extremely Long-Winded Humpback".to_string());
        app.subagent_cache.push(long);
        app.subagent_cache.push(fleet_worker(
            "agent_plain",
            "scout",
            "Ambient visual calm-down",
            741_000,
            SubAgentStatus::Running,
        ));

        let painted = render_rows(&mut app, 100, 5);
        let joined = painted.join("\n");
        // The oversized nickname never renders, whole or truncated.
        assert!(!joined.contains("Bartholomew"), "{joined}");
        assert!(!joined.contains("Bartholom"), "{joined}");
        // It falls back to its role, and the other row is untouched.
        assert!(joined.contains("general-purpose"), "{joined}");
        assert!(joined.contains("scout"), "{joined}");
        // Neither objective was starved by the outlier.
        assert!(joined.contains("Streaming dead-code removal"), "{joined}");
        assert!(joined.contains("Ambient visual calm-down"), "{joined}");
    }

    #[test]
    fn fleet_row_drops_tokens_then_elapsed_then_type_as_the_surface_narrows() {
        // Settled degradation order: tokens first, then elapsed, then the
        // type and status columns together. The objective is the last thing
        // to go and every column truncates rather than wrapping. The status
        // word outlives the whole receipt — a fleet row that cannot say its
        // state in words has lost the fact the strip exists to show.
        let mut app = fleet_app(Some(111_900));
        let medium = fleet_row(&render_rows(&mut app, 72, 4));
        assert!(medium.contains("12m 33s"), "{medium}");
        assert!(!medium.contains("tokens"), "{medium}");
        assert!(medium.contains("general-purpose"), "{medium}");
        assert!(medium.contains("running"), "{medium}");

        let narrow = fleet_row(&render_rows(&mut app, 56, 4));
        assert!(!narrow.contains("tokens"), "{narrow}");
        assert!(!narrow.contains("12m 33s"), "{narrow}");
        assert!(narrow.contains("general-purpose"), "{narrow}");
        assert!(narrow.contains("running"), "{narrow}");

        let tight = fleet_row(&render_rows(&mut app, 28, 4));
        assert!(!tight.contains("general-purpose"), "{tight}");
        assert!(!tight.contains("running"), "{tight}");
        assert!(tight.contains("Streaming"), "{tight}");

        for line in [&medium, &narrow, &tight] {
            assert!(line.chars().all(|ch| ch != '\n'), "{line}");
        }
    }

    #[test]
    fn fleet_row_elapsed_freezes_once_the_agent_is_finished() {
        // The manager recomputes `duration_ms` as `started_at.elapsed()` on
        // every snapshot, so a finished agent's raw duration keeps growing.
        // The row must latch the first terminal reading instead.
        let mut app = fleet_app(None);
        app.subagent_cache[0].status = SubAgentStatus::Completed;
        app.subagent_cache[0].duration_ms = 753_000;

        let first = super::model::project(&mut app);
        let finished = first
            .iter()
            .find(|row| row.id.0 == "worker:agent_stream")
            .and_then(|row| row.agent.as_ref())
            .expect("finished agent facts");
        assert_eq!(finished.elapsed_secs, Some(753));

        // A later snapshot reports a larger duration for the same dead agent.
        app.subagent_cache[0].duration_ms = 999_000;
        let second = super::model::project(&mut app);
        let still = second
            .iter()
            .find(|row| row.id.0 == "worker:agent_stream")
            .and_then(|row| row.agent.as_ref())
            .expect("finished agent facts");
        assert_eq!(
            still.elapsed_secs,
            Some(753),
            "finished elapsed must freeze"
        );
    }

    #[test]
    fn fleet_row_elapsed_still_advances_while_the_agent_runs() {
        let mut app = fleet_app(None);
        app.subagent_cache[0].duration_ms = 10_000;
        let early = super::model::project(&mut app);
        assert_eq!(
            early
                .iter()
                .find(|row| row.id.0 == "worker:agent_stream")
                .and_then(|row| row.agent.as_ref())
                .expect("running agent facts")
                .elapsed_secs,
            Some(10)
        );

        app.subagent_cache[0].duration_ms = 40_000;
        let later = super::model::project(&mut app);
        assert_eq!(
            later
                .iter()
                .find(|row| row.id.0 == "worker:agent_stream")
                .and_then(|row| row.agent.as_ref())
                .expect("running agent facts")
                .elapsed_secs,
            Some(40)
        );
    }

    #[test]
    fn fleet_row_with_no_reported_usage_shows_no_token_figure_at_all() {
        // An unknown number is rendered as nothing. Never `0`, which would
        // claim the agent spent nothing.
        let mut app = fleet_app(None);
        let row = fleet_row(&render_rows(&mut app, 100, 4));
        assert!(!row.contains("tokens"), "{row}");
        assert!(!row.contains(''), "{row}");
        assert!(row.contains("12m 33s"), "{row}");

        let mut spent = fleet_app(Some(0));
        let zero = fleet_row(&render_rows(&mut spent, 100, 4));
        // A *reported* zero is a fact and does render.
        assert!(zero.contains("↓ 0 tokens"), "{zero}");
    }

    #[test]
    fn fleet_row_child_badge_counts_children_that_are_on_the_surface() {
        let mut app = app();
        app.current_session_id = Some(SESSION.to_string());
        app.subagent_cache.push(cached_worker(
            "agent_lead",
            "general-purpose",
            None,
            None,
            SubAgentStatus::Running,
        ));
        for child in ["agent_c1", "agent_c2", "agent_c3"] {
            app.subagent_cache.push(cached_worker(
                child,
                "scout",
                None,
                Some("agent_lead"),
                SubAgentStatus::Running,
            ));
        }
        // A child whose parent is not on the surface must not be counted for
        // anyone, and must not inflate the lead's badge.
        app.subagent_cache.push(cached_worker(
            "agent_orphan",
            "scout",
            None,
            Some("agent_missing"),
            SubAgentStatus::Running,
        ));

        let rows = super::model::project(&mut app);
        let label = |id: &str| {
            rows.iter()
                .find(|row| row.id.0 == format!("worker:{id}"))
                .map(|row| row.label.clone())
                .unwrap_or_else(|| panic!("row for {id}"))
        };
        assert_eq!(label("agent_lead"), "general-purpose (+3)");
        assert_eq!(label("agent_c1"), "↳ scout");
        assert_eq!(label("agent_orphan"), "scout");
    }

    #[test]
    fn a_capped_fleet_list_announces_how_many_rows_it_is_hiding() {
        let mut app = app();
        app.current_session_id = Some(SESSION.to_string());
        for index in 0..8 {
            app.subagent_cache.push(cached_worker(
                &format!("agent_{index}"),
                "general-purpose",
                None,
                None,
                SubAgentStatus::Running,
            ));
        }

        // Four content rows for nine projected rows (header + eight workers).
        let rows = render_rows(&mut app, 100, 5);
        let more = rows
            .iter()
            .find(|line| line.contains("more"))
            .unwrap_or_else(|| panic!("no overflow line in {rows:?}"));
        // Nine projected rows (header + eight workers); three fit, six do not.
        assert!(more.contains("↓ 6 more"), "{more}");
        // Right-aligned against the content column, not the left margin.
        assert!(more.starts_with("        "), "{more}");
    }

    #[test]
    fn fleet_rows_render_in_top_left_and_right_placements() {
        for placement in [
            super::WorkSurfacePlacement::Top,
            super::WorkSurfacePlacement::Left,
            super::WorkSurfacePlacement::Right,
        ] {
            let mut app = fleet_app(Some(111_900));
            app.work_surface.placement = placement;
            app.work_surface.effective_placement = placement;
            let rows = render_rows(&mut app, 40, 8);
            let row = fleet_row(&rows);
            assert!(
                row.contains("Streaming"),
                "{placement:?} lost the objective: {rows:?}"
            );
        }
    }

    #[test]
    fn progress_only_work_rows_use_typed_activity_not_display_substrings() {
        let mut app = app();
        app.current_session_id = Some(SESSION.to_string());
        app.agent_progress.insert(
            "agent_progress_only".to_string(),
            "queued waiting failed completed".to_string(),
        );

        let rows = super::model::project(&mut app);
        let row = rows
            .iter()
            .find(|row| row.id.0 == "worker:agent_progress_only")
            .expect("progress-only work row");
        assert_eq!(row.detail, "running");

        app.agent_progress_meta.insert(
            "agent_progress_only".to_string(),
            crate::tui::app::AgentProgressMeta {
                current_activity: Some(AgentCurrentActivity::bounded(
                    AgentCurrentActivityStatus::Waiting,
                    Some("approval required".to_string()),
                    None,
                    Some(5),
                )),
                ..crate::tui::app::AgentProgressMeta::default()
            },
        );

        let rows = super::model::project(&mut app);
        let row = rows
            .iter()
            .find(|row| row.id.0 == "worker:agent_progress_only")
            .expect("typed progress-only work row");
        assert!(row.detail.contains("waiting for input"), "{}", row.detail);
        assert!(row.detail.contains("approval required"), "{}", row.detail);
        assert!(row.detail.contains("step 5"), "{}", row.detail);
    }

    #[test]
    fn agent_transcript_keyboard_mouse_and_return_selection_converge() {
        fn add_worker(app: &mut App) {
            app.current_session_id = Some(SESSION.to_string());
            app.subagent_cache.push(SubAgentResult {
                name: "agent_converge".to_string(),
                agent_id: "agent_converge".to_string(),
                context_mode: "fresh".to_string(),
                fork_context: false,
                workspace: None,
                git_branch: Some("codex/details".to_string()),
                agent_type: FleetRole::Builder,
                assignment: SubAgentAssignment {
                    objective: "Verify keyboard and mouse convergence".to_string(),
                    role: Some("worker".to_string()),
                },
                model: "test-model".to_string(),
                nickname: Some("Blue Whale".to_string()),
                status: SubAgentStatus::Running,
                worker_status: Some(AgentWorkerStatus::Running),
                runtime_permissions: None,
                parent_run_id: None,
                spawn_depth: 1,
                child_route: None,
                result: None,
                steps_taken: 1,
                checkpoint: None,
                needs_input: None,
                duration_ms: 100,
                started_at: None,
                from_prior_session: false,
            });
        }

        let mut keyboard = app();
        add_worker(&mut keyboard);
        let _ = render_text(&mut keyboard, 100, 6);
        let _ = super::handle_key(
            &mut keyboard,
            KeyEvent::new(KeyCode::Char('w'), KeyModifiers::ALT),
        );
        let keyboard_action = super::handle_key(
            &mut keyboard,
            KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE),
        )
        .expect("Work key handled")
        .expect("agent transcript action");
        let keyboard_selection = keyboard.work_surface.selected.clone();

        let mut mouse = app();
        add_worker(&mut mouse);
        let _ = render_text(&mut mouse, 100, 6);
        let row_y = mouse
            .work_surface
            .hitboxes
            .iter()
            .find(|hit| hit.id.0 == "worker:agent_converge")
            .expect("agent hitbox")
            .row_y;
        let mouse_action = super::handle_mouse(
            &mut mouse,
            MouseEvent {
                kind: MouseEventKind::Down(MouseButton::Left),
                column: 2,
                row: row_y,
                modifiers: KeyModifiers::NONE,
            },
        )
        .action
        .expect("mouse agent transcript action");
        assert_eq!(mouse_action, keyboard_action);
        assert_eq!(mouse.work_surface.selected, keyboard_selection);

        crate::tui::mouse_ui::apply_sidebar_row_action(&mut mouse, mouse_action);
        // One agent, one destination: activation focuses the worker in place
        // (its full transcript owns the conversation area) instead of opening
        // a modal, and leaving focus keeps the rail selection where it was.
        assert!(
            mouse
                .agent_focus
                .as_ref()
                .is_some_and(|focus| focus.is("agent_converge")),
            "activation must focus the worker"
        );
        let selected_before_close = mouse.work_surface.selected.clone();
        assert!(crate::tui::agent_focus::exit_focus(&mut mouse));
        assert_eq!(mouse.work_surface.selected, selected_before_close);
        assert!(mouse.work_surface.opened.is_none());
    }

    #[test]
    fn active_session_without_work_keeps_surface_invisible() {
        let mut app = app();
        app.current_session_id = Some(SESSION.to_string());

        let rows = super::model::project(&mut app);

        assert!(rows.is_empty());
        assert_eq!(super::height(&mut app, 120, 32, AMPLE_BUDGET), 0);
    }

    #[test]
    fn empty_work_stays_hidden_after_cached_session_state_is_cleared() {
        let mut app = app();
        app.current_session_id = Some(SESSION.to_string());
        app.work_surface.cached_graph = Some(operation_graph(NodeState::Active));

        let rows = super::model::project(&mut app);

        assert!(rows.is_empty());
        assert!(app.work_surface.cached_graph.is_none());
    }

    #[test]
    fn empty_work_reserves_no_side_rail() {
        for placement in [
            super::WorkSurfacePlacement::Left,
            super::WorkSurfacePlacement::Right,
        ] {
            let mut app = app();
            app.current_session_id = Some(SESSION.to_string());
            app.work_surface.placement = placement;
            let area = ratatui::layout::Rect::new(0, 0, 120, 32);

            assert_eq!(
                super::height(&mut app, area.width, area.height, AMPLE_BUDGET),
                0
            );
            assert_eq!(super::split_chat(&mut app, area, 0), (area, None));
        }
    }

    fn terminal_text(terminal: &Terminal<TestBackend>) -> String {
        let buf = terminal.backend().buffer();
        let mut text = String::new();
        for y in 0..buf.area.height {
            for x in 0..buf.area.width {
                text.push_str(buf[(x, y)].symbol());
            }
        }
        text
    }

    /// Render-level smoke coverage for the ported rail panels — reinstates
    /// the sidebar render smoke tests removed with the classic shell
    /// (739616787). Top never spends a row on panel chrome (content is
    /// self-evident). Side rails are named by their content's own heading
    /// row (`▾ Subagents N`, `Goal: …`); Context is the one line-list panel
    /// and keeps its muted panel title.
    #[test]
    fn rail_panels_render_in_all_placements() {
        for panel in [
            super::RailPanel::Agents,
            super::RailPanel::Context,
            super::RailPanel::Pinned,
        ] {
            for placement in [
                super::WorkSurfacePlacement::Top,
                super::WorkSurfacePlacement::Left,
                super::WorkSurfacePlacement::Right,
            ] {
                let mut app = app();
                app.work_surface.placement = placement;
                app.work_surface.panel = panel;
                // Content so empty-collapse does not hide the panel. Agents
                // needs a cached worker; Pinned needs a goal; Context always
                // has session facts.
                app.hunt.quarry = Some("ship the release".to_string());
                if panel == super::RailPanel::Agents {
                    app.subagent_cache.push(cached_worker(
                        "agent-a",
                        "explore",
                        Some("scout"),
                        None,
                        SubAgentStatus::Running,
                    ));
                }
                let area = ratatui::layout::Rect::new(0, 0, 100, 24);

                // Render coverage, not yield coverage: a 24-row terminal with
                // work on screen has rows to spare, so the panel is expected
                // to draw. The idle-empty budget is exercised end-to-end in
                // `ui::tests::rail_strip_yields_the_ambient_floor_*`.
                let budget = working_budget(&app, area.height);
                let strip = super::height(&mut app, area.width, area.height, budget);
                let (_chat, rail) = super::split_chat(&mut app, area, 0);
                let backend = TestBackend::new(area.width, area.height);
                let mut terminal = Terminal::new(backend).expect("terminal");
                terminal
                    .draw(|frame| {
                        if strip > 0 {
                            super::render(
                                frame,
                                ratatui::layout::Rect::new(0, 0, area.width, strip),
                                &mut app,
                            );
                        } else if let Some(rail) = rail {
                            super::render(frame, rail, &mut app);
                        }
                    })
                    .expect("draw");
                let text = terminal_text(&terminal);
                match placement {
                    super::WorkSurfacePlacement::Top => {
                        assert!(
                            strip > 0,
                            "{panel:?} on Top should auto-fit a content strip; got height 0"
                        );
                        // Panel chrome ("Pinned"/"Agents") never on Top.
                        // An active goal *is* a title — and this fixture sets one.
                        assert!(
                            !text.contains(panel.title())
                                || panel.title() == "Context" && text.contains("Context"),
                            "{panel:?} on Top must not spend a row on panel chrome; got: {text}"
                        );
                        if panel != super::RailPanel::Context {
                            assert!(
                                !text.split_whitespace().any(|tok| tok == panel.title()),
                                "{panel:?} on Top must not print the panel name as chrome; got: {text}"
                            );
                        }
                        // Goal title when a live goal is set.
                        assert!(
                            text.contains("Goal:") && text.contains("ship the release"),
                            "Top with an active goal must title with Goal: …; got: {text}"
                        );
                    }
                    super::WorkSurfacePlacement::Left | super::WorkSurfacePlacement::Right => {
                        assert!(
                            rail.is_some() || strip > 0,
                            "{panel:?} in {placement:?} should reserve a rail"
                        );
                        // Work-row panels are named by their content heading;
                        // only the Context fact list keeps a panel title.
                        match panel {
                            super::RailPanel::Agents => {
                                assert!(
                                    text.contains("Subagents 1"),
                                    "{panel:?} in {placement:?} should render its \
                                     Subagents heading; got: {text}"
                                );
                                assert!(
                                    !app.work_surface.hitboxes.is_empty(),
                                    "{panel:?} in {placement:?} must record hitboxes — \
                                     every work row is a door"
                                );
                            }
                            super::RailPanel::Pinned => {
                                assert!(
                                    text.contains("Goal: ship the release"),
                                    "{panel:?} in {placement:?} should render the goal \
                                     heading; got: {text}"
                                );
                            }
                            _ => {
                                assert!(
                                    text.contains(panel.title()),
                                    "{panel:?} in {placement:?} should render its muted \
                                     title; got: {text}"
                                );
                            }
                        }
                    }
                    super::WorkSurfacePlacement::Off => {}
                }
            }
        }
    }

    #[test]
    fn off_placement_reserves_no_rail_in_any_panel() {
        for panel in [
            super::RailPanel::Tasks,
            super::RailPanel::Agents,
            super::RailPanel::Context,
            super::RailPanel::Pinned,
        ] {
            let mut app = app();
            add_todos(&mut app, 2);
            app.work_surface.placement = super::WorkSurfacePlacement::Off;
            app.work_surface.panel = panel;
            let area = ratatui::layout::Rect::new(0, 0, 120, 32);

            assert_eq!(
                super::height(&mut app, area.width, area.height, AMPLE_BUDGET),
                0
            );
            assert_eq!(super::split_chat(&mut app, area, 0), (area, None));
            assert_eq!(app.work_surface.last_area, None);
        }
    }

    #[test]
    fn context_panel_renders_session_facts_in_side_rail() {
        let mut app = app();
        app.work_surface.placement = super::WorkSurfacePlacement::Right;
        app.work_surface.panel = super::RailPanel::Context;
        let area = ratatui::layout::Rect::new(0, 0, 100, 24);

        let budget = working_budget(&app, area.height);
        let strip = super::height(&mut app, area.width, area.height, budget);
        assert_eq!(strip, 0, "side placements take no top strip");
        let (_chat, rail) = super::split_chat(&mut app, area, 0);
        let rail = rail.expect("context panel reserves a side rail");

        let backend = TestBackend::new(area.width, area.height);
        let mut terminal = Terminal::new(backend).expect("terminal");
        terminal
            .draw(|frame| super::render(frame, rail, &mut app))
            .expect("draw");
        let text = terminal_text(&terminal);
        assert!(text.contains("Context"), "panel title; got: {text}");
        assert!(text.contains("lsp:"), "session facts; got: {text}");
    }

    #[test]
    fn missing_runtime_renders_disconnected_state() {
        let mut app = app();
        app.current_session_id = Some(SESSION.to_string());
        app.runtime_services.work = None;

        let rows = super::model::project(&mut app);

        assert_eq!(rows[0].label, "Work · disconnected");
    }

    #[test]
    fn busy_graph_authority_renders_truthful_error_without_leaking_it_into_header() {
        let mut app = app();
        app.current_session_id = Some(SESSION.to_string());
        let todos = app.todos.clone();
        let _guard = todos.try_lock().expect("hold To-do authority lock");

        let rows = super::model::project(&mut app);

        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].label, "Work · error");
        assert!(rows[0].detail.contains("To-do state is busy"));
        assert!(!rows[0].label.contains("busy"));
    }

    #[test]
    fn graph_error_without_an_active_session_stays_suppressed() {
        let mut app = app();
        let todos = app.todos.clone();
        let _guard = todos.try_lock().expect("hold To-do authority lock");

        let rows = super::model::project(&mut app);

        assert!(rows.is_empty());
    }

    #[test]
    fn waiting_operation_is_not_counted_as_running() {
        let mut app = app();
        let graph = operation_graph(NodeState::Waiting);
        restore_graph(&mut app, &graph);
        app.runtime_services
            .work
            .as_ref()
            .expect("Work Graph runtime")
            .reconcile_operation(
                SESSION,
                OperationOwnerSnapshot::new("shell:shell_1234abcd", OwnerState::Waiting, 1, 6),
            )
            .expect("waiting shell owner");

        let rows = super::model::project(&mut app);

        assert!(
            rows[0].label.starts_with("Work · Needs input:")
                || rows[0]
                    .label
                    .starts_with("Work · 0 active · 1 needs input · 0 ready · 0 recent"),
            "{}",
            rows[0].label
        );
        assert!(
            rows[0].label.contains("blocked") || rows[0].label.contains("needs input"),
            "{}",
            rows[0].label
        );
    }

    #[test]
    fn stale_operation_is_blocked_attention_with_bounded_output_section() {
        let mut app = app();
        let graph = operation_graph(NodeState::Stale);
        restore_graph(&mut app, &graph);

        let rows = super::model::project(&mut app);
        assert!(
            rows[0].label.contains("Needs input") || rows[0].label.contains("1 needs input"),
            "{}",
            rows[0].label
        );
        let row = rows.iter().find(|row| row.selectable).expect("stale row");
        assert_eq!(row.mark, "?");
        assert!(row.detail.starts_with("stale · operation"));
        let Some(SidebarRowAction::InspectWork {
            body, stop_action, ..
        }) = row.primary_action.as_ref()
        else {
            panic!("stale row must open inspector");
        };
        assert!(
            stop_action.is_none(),
            "a stale owner cannot truthfully expose a stop action"
        );
        assert!(
            body.contains("Last bounded output\nNo output receipt"),
            "{body}"
        );
        assert!(body.contains("Owner cannot confirm liveness"), "{body}");
    }

    /// A durable failed operation, as a fleet agent task from a crashed or
    /// sibling instance leaves behind in the persisted graph (#4416).
    fn durable_failed_operation_graph() -> crate::work_graph::WorkGraphSnapshot {
        let mut graph = WorkGraph::from_snapshot(operation_graph(NodeState::Failed));
        let operation = WorkNodeId::derive(SESSION, "operation");
        graph
            .apply(
                WorkGraphChange::BindOperation {
                    node: operation,
                    binding: OperationBinding {
                        external: "fleet:run_1/task_1".to_string(),
                        durable: true,
                        last_observation: None,
                    },
                },
                ChangeCtx {
                    session_id: SESSION.to_string(),
                    now: 6,
                    idempotency_key: None,
                },
            )
            .expect("durable binding");
        graph.into_snapshot()
    }

    // Regression for #4416: a persisted failed-agent record stamped by
    // another session instance (boot id) must not appear in the default
    // work listing of a fresh session in the same workspace.
    #[test]
    fn prior_instance_failed_rows_stay_out_of_the_default_listing() {
        let dir = tempfile::tempdir().expect("tempdir");
        let manager =
            crate::session_manager::SessionManager::new(dir.path().to_path_buf()).expect("manager");
        manager
            .record_session_boot_owner(SESSION, "boot_other_instance")
            .expect("stamp other instance");

        let mut app = app();
        app.work_surface.session_owner_probe_dir = Some(dir.path().to_path_buf());
        let graph = durable_failed_operation_graph();
        restore_saved_graph(&mut app, &graph);

        let rows = super::model::project(&mut app);
        assert!(
            rows.iter()
                .all(|row| !row.label.contains("Verify installed build")),
            "prior-instance failed row leaked into the default listing: {rows:#?}"
        );
        assert!(
            rows.iter()
                .all(|row| !row.label.contains("needs input") && !row.label.contains("1 active")),
            "prior-instance residue must not count as live work: {rows:#?}"
        );
        // The record stays reachable through the explicit catalog, clearly
        // marked historical.
        let historical = app
            .work_surface
            .catalog_rows
            .iter()
            .find(|row| row.label.contains("Verify installed build"))
            .expect("historical row remains in the catalog");
        assert!(
            historical.detail.starts_with("prior session · "),
            "historical row must be labeled: {}",
            historical.detail
        );
    }

    // Ownership control for #4416: the same failed record owned by this
    // session instance still renders as actionable work.
    #[test]
    fn current_instance_failed_rows_still_render_in_the_default_listing() {
        let dir = tempfile::tempdir().expect("tempdir");
        let manager =
            crate::session_manager::SessionManager::new(dir.path().to_path_buf()).expect("manager");
        manager
            .record_session_boot_owner(SESSION, crate::session_manager::current_session_boot_id())
            .expect("stamp current instance");

        let mut app = app();
        app.work_surface.session_owner_probe_dir = Some(dir.path().to_path_buf());
        let graph = durable_failed_operation_graph();
        restore_graph(&mut app, &graph);

        let rows = super::model::project(&mut app);
        assert!(
            rows.iter()
                .any(|row| row.label.contains("Verify installed build")),
            "this instance's own failed work must stay visible: {rows:#?}"
        );
    }

    // Regression for review of #5063: if a prior session persisted no graph,
    // the first graph captured later belongs to this process and must not be
    // mistaken for restored residue.
    #[test]
    fn first_live_graph_after_empty_prior_restore_stays_visible() {
        let dir = tempfile::tempdir().expect("tempdir");
        let manager =
            crate::session_manager::SessionManager::new(dir.path().to_path_buf()).expect("manager");
        manager
            .record_session_boot_owner(SESSION, "boot_other_instance")
            .expect("stamp other instance");

        let mut app = app();
        app.work_surface.session_owner_probe_dir = Some(dir.path().to_path_buf());
        app.current_session_id = Some(SESSION.to_string());
        app.restore_work_state(SESSION, std::path::Path::new("."), None)
            .expect("restore empty prior session");

        let graph = durable_failed_operation_graph();
        restore_graph(&mut app, &graph);
        let rows = super::model::project(&mut app);
        assert!(
            rows.iter()
                .any(|row| row.label.contains("Verify installed build")),
            "this instance's first live graph must stay visible: {rows:#?}"
        );
    }

    #[test]
    fn completed_operation_with_acceptance_is_not_rendered_done() {
        let mut graph = WorkGraph::from_snapshot(operation_graph(NodeState::Ready));
        let operation = WorkNodeId::derive(SESSION, "operation");
        graph
            .apply(
                WorkGraphChange::UpdateNode {
                    id: operation,
                    patch: crate::work_graph::WorkNodePatch {
                        state: Some(NodeState::Completed),
                        acceptance: Some(vec![AcceptanceRequirement::EvidenceOfKind {
                            kind: EvidenceKindTag::ToolRun,
                        }]),
                        ..crate::work_graph::WorkNodePatch::default()
                    },
                },
                ChangeCtx {
                    session_id: SESSION.to_string(),
                    now: 6,
                    idempotency_key: None,
                },
            )
            .expect("completed pending evidence");
        let graph = graph.into_snapshot();
        let mut app = app();
        restore_graph(&mut app, &graph);

        let rows = super::model::project(&mut app);
        assert!(
            rows[0].label.contains("Needs input") || rows[0].label.contains("1 needs input"),
            "{}",
            rows[0].label
        );
        let row = rows
            .iter()
            .find(|row| row.selectable)
            .expect("operation row");
        assert_eq!(row.mark, crate::tui::glyphs::ATTENTION);
        assert!(row.detail.contains("completed · evidence pending"));
        assert_ne!(row.mark, "");
        let Some(SidebarRowAction::InspectWork { body, .. }) = row.primary_action.as_ref() else {
            panic!("completed operation must remain inspectable");
        };
        assert!(body.contains("evidence of kind tool run"), "{body}");
        assert!(
            body.contains("acceptance evidence is still missing"),
            "{body}"
        );
    }

    #[test]
    fn work_rows_open_graph_inspector_without_inline_controls() {
        let mut app = app();
        app.work_surface.placement = WorkSurfacePlacement::Right;
        app.work_surface.effective_placement = WorkSurfacePlacement::Right;
        let graph = operation_graph(NodeState::Active);
        restore_graph(&mut app, &graph);
        app.runtime_services
            .work
            .as_ref()
            .expect("Work Graph runtime")
            .reconcile_operation(
                SESSION,
                OperationOwnerSnapshot::new("shell:shell_1234abcd", OwnerState::Running, 1, 6),
            )
            .expect("live shell owner");

        let text = render_text(&mut app, 100, 6);
        assert!(!text.contains("[open]"), "{text}");
        assert!(!text.contains("[stop]"), "{text}");
        let row_y = app
            .work_surface
            .hitboxes
            .iter()
            .find(|hit| hit.id.0.starts_with("graph:"))
            .expect("graph hitbox")
            .row_y;
        let outcome = super::handle_mouse(
            &mut app,
            MouseEvent {
                kind: MouseEventKind::Down(MouseButton::Left),
                column: 2,
                row: row_y,
                modifiers: KeyModifiers::NONE,
            },
        );
        let action = outcome.action.expect("inspector action");
        let SidebarRowAction::InspectWork {
            body, stop_action, ..
        } = &action
        else {
            panic!("expected Work inspector");
        };
        for section in [
            "Objective",
            "Prerequisites",
            "Downstream impact",
            "Binding + lifecycle owner",
            "Evidence vs acceptance",
            "Blockers / approvals",
            "Why next",
            "Provenance + last reconcile",
        ] {
            assert!(body.contains(section), "missing {section}: {body}");
        }
        assert!(matches!(
            stop_action.as_deref(),
            Some(SidebarRowAction::Command(command)) if command == "/jobs cancel shell_1234abcd"
        ));
        crate::tui::mouse_ui::apply_sidebar_row_action(&mut app, action);
        assert_eq!(
            app.view_stack.top_kind(),
            Some(crate::tui::views::ModalKind::Pager)
        );
    }

    #[test]
    fn narrow_render_hover_keeps_full_untruncated_row() {
        let mut app = app();
        app.todos.try_lock().expect("todos").add(
            "A deliberately long graph-owned work row".to_string(),
            TodoStatus::InProgress,
        );

        let _ = render_text(&mut app, 24, 4);
        let hover = app
            .sidebar_hover
            .sections
            .last()
            .and_then(|section| section.rows.first())
            .expect("hover row");
        assert!(hover.is_truncated);
        assert!(hover.full_text.contains("deliberately long graph-owned"));
        assert!(hover.stop_action.is_none());
    }

    #[test]
    fn narrow_file_activity_prioritizes_the_canonical_aggregate_label() {
        let mut app = app();
        app.workspace = PathBuf::from("/workspace/project");
        let result = crate::tools::spec::ToolResult::success("ok").with_metadata(
            serde_json::json!({
                "mutation": {
                    "diff": "--- a/update.rs\n+++ b/update.rs\n@@ -1 +1 @@\n-old\n+new\n--- /dev/null\n+++ b/create.rs\n@@ -0,0 +1 @@\n+created\n--- a/delete.rs\n+++ /dev/null\n@@ -1 +0,0 @@\n-deleted\n",
                    "files": [
                        { "path": "update.rs", "outcome": "updated" },
                        { "path": "create.rs", "outcome": "created" },
                        { "path": "delete.rs", "outcome": "deleted" }
                    ],
                    "renames": [{ "from": "old.rs", "to": "new.rs" }]
                }
            }),
        );
        let receipt = FileMutationReceipt::from_success(&app.workspace, &result).expect("receipt");
        app.add_message(HistoryCell::Tool(ToolCell::PatchSummary(
            PatchSummaryCell {
                path: "4 files".to_string(),
                summary: "ok".to_string(),
                status: ToolStatus::Success,
                error: None,
                receipt: Some(receipt),
            },
        )));
        app.tool_details_by_cell.insert(
            0,
            ToolDetailRecord {
                tool_id: "file-multi".to_string(),
                tool_name: "File".to_string(),
                input: serde_json::json!({"action": "patch"}),
                output: Some("ok".to_string()),
            },
        );

        app.work_surface.placement = WorkSurfacePlacement::Right;
        app.work_surface.effective_placement = WorkSurfacePlacement::Right;
        let text = render_text(&mut app, 80, 6);
        assert!(text.contains("Wrote 4 files"), "{text}");
    }

    #[test]
    fn overflow_scroll_and_selection_remain_panel_owned() {
        let mut app = app();
        add_todos(&mut app, 8);
        let _ = render_text(&mut app, 80, 5);
        assert!(app.work_surface.total_rows > app.work_surface.visible_rows);

        let transcript_delta = app.viewport.pending_scroll_delta;
        let outcome = super::handle_mouse(
            &mut app,
            MouseEvent {
                kind: MouseEventKind::ScrollDown,
                column: 10,
                row: 2,
                modifiers: KeyModifiers::NONE,
            },
        );
        assert!(outcome.consumed);
        assert_eq!(app.viewport.pending_scroll_delta, transcript_delta);
        assert!(app.work_surface.scroll_offset > 0);
    }

    #[test]
    fn mouse_wheel_reaches_last_todo_across_top_surface_heights() {
        for height in [3, 5, 6, 8] {
            let mut app = app();
            add_todos(&mut app, 10);
            let _ = render_text(&mut app, 80, height);
            assert!(app.work_surface.total_rows > app.work_surface.visible_rows);
            let transcript_delta = app.viewport.pending_scroll_delta;

            let mut text = String::new();
            for _ in 0..16 {
                let outcome = super::handle_mouse(
                    &mut app,
                    MouseEvent {
                        kind: MouseEventKind::ScrollDown,
                        column: 10,
                        row: 1,
                        modifiers: KeyModifiers::NONE,
                    },
                );
                assert!(outcome.consumed, "height {height}");
                text = render_text(&mut app, 80, height);
            }

            assert!(
                text.contains("work item 9"),
                "last To-do was unreachable at surface height {height}: {text:?}"
            );
            assert_eq!(
                app.work_surface.scroll_offset,
                app.work_surface
                    .total_rows
                    .saturating_sub(app.work_surface.visible_rows.max(1)),
                "wheel did not reach the legal tail at surface height {height}"
            );
            assert_eq!(app.viewport.pending_scroll_delta, transcript_delta);
        }
    }

    #[test]
    fn mouse_wheel_reaches_last_todo_in_side_rail_placements() {
        for placement in [
            super::WorkSurfacePlacement::Left,
            super::WorkSurfacePlacement::Right,
        ] {
            let mut app = app();
            add_todos(&mut app, 10);
            app.work_surface.placement = placement;
            app.work_surface.effective_placement = placement;
            let _ = render_text(&mut app, 30, 6);

            let mut text = String::new();
            for _ in 0..16 {
                let outcome = super::handle_mouse(
                    &mut app,
                    MouseEvent {
                        kind: MouseEventKind::ScrollDown,
                        column: 10,
                        row: 1,
                        modifiers: KeyModifiers::NONE,
                    },
                );
                assert!(outcome.consumed, "placement {placement:?}");
                text = render_text(&mut app, 30, 6);
            }

            assert!(
                text.contains("work item 9"),
                "last To-do was unreachable in {placement:?}: {text:?}"
            );
        }
    }

    #[test]
    fn keyboard_end_reveals_last_todo_after_redraw() {
        let mut app = app();
        add_todos(&mut app, 10);
        let _ = render_text(&mut app, 80, 5);
        let _ = super::handle_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('w'), KeyModifiers::ALT),
        );
        let _ = super::handle_key(&mut app, KeyEvent::new(KeyCode::End, KeyModifiers::NONE));

        let text = render_text(&mut app, 80, 5);

        assert!(text.contains("work item 9"), "{text:?}");
        assert_eq!(
            app.work_surface.scroll_offset,
            app.work_surface
                .total_rows
                .saturating_sub(app.work_surface.visible_rows.max(1))
        );
    }

    #[test]
    fn keyboard_navigation_is_panel_local_when_focused() {
        let mut app = app();
        add_todos(&mut app, 3);
        app.work_surface.visible_rows = 2;
        assert!(
            super::handle_key(
                &mut app,
                KeyEvent::new(KeyCode::Char('w'), KeyModifiers::ALT)
            )
            .is_some()
        );
        let first = app.work_surface.selected.clone();
        let _ = super::handle_key(&mut app, KeyEvent::new(KeyCode::End, KeyModifiers::NONE));
        assert_ne!(app.work_surface.selected, first);
        assert!(app.work_surface.focused);
    }

    #[test]
    fn printable_keys_release_panel_focus_for_composer() {
        let mut app = app();
        add_todos(&mut app, 1);
        let _ = super::handle_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('w'), KeyModifiers::ALT),
        );

        let outcome = super::handle_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('j'), KeyModifiers::NONE),
        );

        assert!(outcome.is_none());
        assert!(!app.work_surface.focused);
    }

    #[test]
    fn side_placements_reuse_the_same_graph_rows() {
        for (placement, expected_chat_x, expected_rail_x) in [
            (super::WorkSurfacePlacement::Left, 30, 0),
            (super::WorkSurfacePlacement::Right, 0, 70),
        ] {
            let mut app = app();
            add_todos(&mut app, 2);
            app.work_surface.placement = placement;
            assert_eq!(super::height(&mut app, 100, 24, AMPLE_BUDGET), 0);
            let area = ratatui::layout::Rect::new(0, 0, 100, 12);
            let (chat, rail) = super::split_chat(&mut app, area, 0);
            let rail = rail.expect("side rail");
            assert_eq!(chat.x, expected_chat_x);
            assert_eq!(rail.x, expected_rail_x);
            assert_eq!(rail.width, 30);
            assert!(
                app.work_surface
                    .latest_rows
                    .iter()
                    .any(|row| row.label == "work item 1")
            );
        }
    }

    #[test]
    fn divider_drag_resizes_top_left_and_right_surfaces() {
        let mut top = app();
        add_todos(&mut top, 3);
        let _ = render_text(&mut top, 80, 3);
        let down = super::handle_mouse(
            &mut top,
            MouseEvent {
                kind: MouseEventKind::Down(MouseButton::Left),
                column: 20,
                row: 2,
                modifiers: KeyModifiers::NONE,
            },
        );
        assert!(down.consumed);
        let _ = super::handle_mouse(
            &mut top,
            MouseEvent {
                kind: MouseEventKind::Drag(MouseButton::Left),
                column: 20,
                row: 7,
                modifiers: KeyModifiers::NONE,
            },
        );
        assert_eq!(top.work_surface.top_height, 8);

        for (placement, drag_column, expected_width) in [
            (WorkSurfacePlacement::Left, 39, 40),
            (WorkSurfacePlacement::Right, 10, 26),
        ] {
            let mut side = app();
            add_todos(&mut side, 2);
            side.work_surface.placement = placement;
            side.work_surface.effective_placement = placement;
            let _ = render_text(&mut side, 30, 8);
            let divider_column = if placement == WorkSurfacePlacement::Left {
                29
            } else {
                0
            };
            let _ = super::handle_mouse(
                &mut side,
                MouseEvent {
                    kind: MouseEventKind::Down(MouseButton::Left),
                    column: divider_column,
                    row: 2,
                    modifiers: KeyModifiers::NONE,
                },
            );
            let _ = super::handle_mouse(
                &mut side,
                MouseEvent {
                    kind: MouseEventKind::Drag(MouseButton::Left),
                    column: drag_column,
                    row: 2,
                    modifiers: KeyModifiers::NONE,
                },
            );
            assert_eq!(
                side.work_surface.side_width, expected_width,
                "{placement:?}"
            );
        }
    }

    #[test]
    fn divider_hover_and_drag_render_a_discoverable_handle() {
        let mut app = app();
        add_todos(&mut app, 3);
        let resting = render_text(&mut app, 80, 3);
        assert!(resting.contains(''), "{resting}");

        let hover = super::handle_mouse(
            &mut app,
            MouseEvent {
                kind: MouseEventKind::Moved,
                column: 20,
                row: 2,
                modifiers: KeyModifiers::NONE,
            },
        );
        assert!(hover.consumed);
        assert!(app.work_surface.divider_hovered);
        let hovered = render_text(&mut app, 80, 3);
        assert!(hovered.contains(''), "{hovered}");

        let _ = super::handle_mouse(
            &mut app,
            MouseEvent {
                kind: MouseEventKind::Down(MouseButton::Left),
                column: 20,
                row: 2,
                modifiers: KeyModifiers::NONE,
            },
        );
        let dragging = render_text(&mut app, 80, 3);
        assert!(dragging.contains(''), "{dragging}");
    }

    #[test]
    fn top_bar_excludes_generic_operations() {
        let mut operation_app = app();
        let graph = operation_graph(NodeState::Failed);
        restore_graph(&mut operation_app, &graph);

        assert_eq!(super::height(&mut operation_app, 100, 24, AMPLE_BUDGET), 0);
        assert!(operation_app.work_surface.latest_rows.is_empty());

        let mut todo_app = app();
        add_todos(&mut todo_app, 2);
        assert!(super::height(&mut todo_app, 100, 24, AMPLE_BUDGET) > 0);
        assert!(
            todo_app
                .work_surface
                .latest_rows
                .iter()
                .all(|row| row.id.0.starts_with("graph:") || row.id.0.starts_with("worker:"))
        );
        assert!(
            todo_app
                .work_surface
                .latest_rows
                .iter()
                .all(|row| !row.label.starts_with("Work ·"))
        );
    }

    #[test]
    fn opened_row_toggles_closed_without_losing_selection() {
        let mut app = app();
        add_todos(&mut app, 1);
        let row = super::model::project(&mut app)
            .into_iter()
            .find(|row| row.selectable)
            .expect("work row");
        let open = row.primary_action.clone();

        assert!(super::interaction::activate_primary(&mut app, &row.id, open.clone()).is_some());
        // The action's pager is on screen, so the second activation is a
        // toggle-close.
        app.view_stack.push(crate::tui::pager::PagerView::from_text(
            "Work · test".to_string(),
            "body",
            40,
        ));
        assert!(super::interaction::activate_primary(&mut app, &row.id, open).is_none());
        assert!(app.work_surface.opened.is_none());
        assert_eq!(app.work_surface.selected.as_ref(), Some(&row.id));
    }

    #[test]
    fn a_click_after_the_pager_closed_itself_reopens_instead_of_going_dead() {
        // q/Esc inside the pager pops it without clearing `opened`. The next
        // click on that row must reopen its world, not be swallowed by a
        // stale toggle (owner regression report, 2026-08-04).
        let mut app = app();
        add_todos(&mut app, 1);
        let row = super::model::project(&mut app)
            .into_iter()
            .find(|row| row.selectable)
            .expect("work row");
        let open = row.primary_action.clone();

        assert!(super::interaction::activate_primary(&mut app, &row.id, open.clone()).is_some());
        // The pager was closed from inside itself; `opened` is now stale.
        assert_eq!(app.work_surface.opened.as_ref(), Some(&row.id));
        assert!(app.view_stack.is_empty());

        let reopened = super::interaction::activate_primary(&mut app, &row.id, open);
        assert!(
            reopened.is_some(),
            "a stale opened owner must not swallow the next activation"
        );
        assert_eq!(app.work_surface.opened.as_ref(), Some(&row.id));
    }

    /// Settled to-dos keep their rows across the recent-only TTL and new user
    /// turns. Finished sub-agents collapse into the Subagents Archived count
    /// (still reachable via the Agents panel) so fan-outs do not permanently
    /// eat the transcript.
    #[test]
    fn settled_todos_stay_and_finished_workers_collapse_after_ttl() {
        let mut app = app();
        app.current_session_id = Some(SESSION.to_string());
        {
            let mut todos = app.todos.try_lock().expect("todos");
            todos.add("ship the fix".to_string(), TodoStatus::Completed);
            todos.add("verify the fix".to_string(), TodoStatus::Completed);
        }
        app.subagent_cache.push(cached_worker(
            "agent-settled",
            "builder",
            None,
            None,
            SubAgentStatus::Completed,
        ));

        app.work_surface.set_presentation_now_ms(0);
        let first = super::model::project_visible(&mut app);
        assert!(
            first.iter().any(|row| row.id.0.starts_with("graph:")),
            "settled to-dos must be listed: {first:?}"
        );
        assert!(
            first
                .iter()
                .any(|row| { row.id.0 == "section:agents" && row.label.contains("Archived 1") }),
            "finished workers collapse into the header count: {first:?}"
        );
        assert!(
            !first.iter().any(|row| row.id.0.starts_with("worker:")),
            "finished workers must leave strip rows: {first:?}"
        );

        app.work_surface
            .set_presentation_now_ms(super::model::RECENT_ONLY_TTL_MS + 1);
        app.work_surface.note_user_turn_or_new_operation();
        let later = super::model::project_visible(&mut app);
        assert!(
            later.iter().any(|row| row.id.0.starts_with("graph:")),
            "a settled to-do must survive the TTL and the next user turn: {later:?}"
        );
        assert!(
            later
                .iter()
                .any(|row| { row.id.0 == "section:agents" && row.label.contains("Archived 1") }),
            "header still accounts for settled workers after TTL: {later:?}"
        );
        assert!(
            super::height(&mut app, 100, 40, AMPLE_BUDGET) > 0,
            "the strip must keep its height while it holds settled work"
        );
    }

    /// A to-do row says its state in words, in the `/task digest` vocabulary.
    /// Dropping the words (2011b9b11 conflated them with the redundant kind
    /// label) was half of owner regression A1.
    #[test]
    fn todo_rows_carry_their_status_words() {
        let mut app = app();
        add_todos(&mut app, 3);
        let rows = super::model::project(&mut app);
        let todo_details: Vec<&str> = rows
            .iter()
            .filter(|row| row.id.0.starts_with("graph:"))
            .map(|row| row.detail.as_str())
            .collect();
        assert!(
            todo_details.contains(&"in progress"),
            "the active step says so in words: {todo_details:?}"
        );
        assert!(
            todo_details.contains(&"pending"),
            "a pending step is labeled, not blank: {todo_details:?}"
        );

        // And the words are painted, not just projected.
        let text = render_text(&mut app, 100, 6);
        assert!(text.contains("in progress"), "{text}");
        assert!(text.contains("pending"), "{text}");
    }

    /// Top strip collapses completed/cancelled workers into an Archived count
    /// while keeping live (and failed) workers as rows. Agents panel still
    /// lists every worker — see the click test below.
    #[test]
    fn top_strip_collapses_settled_subagents_into_header() {
        let mut app = app();
        app.work_surface.placement = super::WorkSurfacePlacement::Top;
        app.work_surface.effective_placement = super::WorkSurfacePlacement::Top;
        app.current_session_id = Some(SESSION.to_string());
        app.subagent_cache.push(cached_worker(
            "agent-live",
            "scout",
            None,
            None,
            SubAgentStatus::Running,
        ));
        app.subagent_cache.push(cached_worker(
            "agent-done",
            "builder",
            None,
            None,
            SubAgentStatus::Completed,
        ));
        app.subagent_cache.push(cached_worker(
            "agent-failed",
            "verifier",
            None,
            None,
            SubAgentStatus::Failed("boom".to_string()),
        ));

        let rows = super::model::project_visible(&mut app);
        let labels: Vec<&str> = rows.iter().map(|row| row.label.as_str()).collect();
        let ids: Vec<&str> = rows.iter().map(|row| row.id.0.as_str()).collect();

        assert!(
            labels.iter().any(|label| {
                label.contains("1 running")
                    && label.contains("1 needs input")
                    && label.contains("Archived 1")
            }),
            "header splits running / needs-input / settled: {labels:?}"
        );
        assert!(
            ids.contains(&"worker:agent-live"),
            "running worker stays in the strip: {ids:?}"
        );
        assert!(
            ids.contains(&"worker:agent-failed"),
            "failed worker stays (needs attention): {ids:?}"
        );
        assert!(
            !ids.contains(&"worker:agent-done"),
            "completed worker must leave the strip: {ids:?}"
        );
    }

    #[test]
    fn subagent_header_opens_the_full_agents_register() {
        let mut app = app();
        app.work_surface.placement = super::WorkSurfacePlacement::Top;
        app.work_surface.effective_placement = super::WorkSurfacePlacement::Top;
        app.current_session_id = Some(SESSION.to_string());
        app.subagent_cache.push(cached_worker(
            "agent-archived",
            "builder",
            None,
            None,
            SubAgentStatus::Completed,
        ));

        let top = render_text(&mut app, 100, 4);
        assert!(top.contains("Archived 1"), "{top}");
        let header_y = app
            .work_surface
            .hitboxes
            .iter()
            .find(|hit| hit.id.0 == "section:agents")
            .expect("subagent header must be a real hit target")
            .row_y;
        let action = super::handle_mouse(
            &mut app,
            MouseEvent {
                kind: MouseEventKind::Down(MouseButton::Left),
                column: 2,
                row: header_y,
                modifiers: KeyModifiers::NONE,
            },
        )
        .action
        .expect("subagent header must dispatch its primary action");
        assert_eq!(action, SidebarRowAction::ShowSubagentsPanel);
        assert!(crate::tui::mouse_ui::apply_sidebar_row_action(&mut app, action).is_empty());
        assert_eq!(app.work_surface.panel, super::RailPanel::Agents);

        let agents = render_text(&mut app, 100, 6);
        assert!(
            agents.contains("agent-archived") || agents.contains("builder"),
            "the full Agents register keeps the archived worker reachable: {agents}"
        );
    }

    /// Acceptance for owner regression A2: an agent row is a door in the
    /// Agents panel too, and a FINISHED agent's world still opens — the
    /// panel is a standing register, not a live-only view. Since v0.9.7 the
    /// door leads to the agent's transcript (which explains itself when no
    /// capture exists yet), not to the details projection.
    #[test]
    fn agents_panel_click_opens_the_transcript_even_for_finished_agents() {
        let mut app = app();
        app.work_surface.panel = super::RailPanel::Agents;
        app.current_session_id = Some(SESSION.to_string());
        app.subagent_cache.push(cached_worker(
            "agent-finished",
            "builder",
            None,
            None,
            SubAgentStatus::Completed,
        ));

        let _ = render_text(&mut app, 100, 6);
        let row_y = app
            .work_surface
            .hitboxes
            .iter()
            .find(|hit| hit.id.0 == "worker:agent-finished")
            .expect("finished agent row must keep a hitbox in the Agents panel")
            .row_y;
        let action = super::handle_mouse(
            &mut app,
            MouseEvent {
                kind: MouseEventKind::Down(MouseButton::Left),
                column: 2,
                row: row_y,
                modifiers: KeyModifiers::NONE,
            },
        )
        .action
        .expect("click on a finished agent row must dispatch its primary action");
        assert_eq!(
            action,
            SidebarRowAction::OpenAgentTranscript {
                agent_id: "agent-finished".to_string()
            }
        );
        crate::tui::mouse_ui::apply_sidebar_row_action(&mut app, action);
        assert!(
            app.agent_focus
                .as_ref()
                .is_some_and(|focus| focus.is("agent-finished")),
            "the finished agent's transcript must actually take focus"
        );
    }

    /// Acceptance for owner regression A1: to-do rows are doors in the
    /// Pinned panel too — clicking one opens the work inspector.
    #[test]
    fn pinned_panel_todo_rows_stay_clickable() {
        let mut app = app();
        app.work_surface.panel = super::RailPanel::Pinned;
        add_todos(&mut app, 2);

        let _ = render_text(&mut app, 100, 6);
        let hit = app
            .work_surface
            .hitboxes
            .iter()
            .find(|hit| hit.id.0.starts_with("graph:"))
            .expect("Pinned panel to-do rows must keep hitboxes")
            .clone();
        let action = super::handle_mouse(
            &mut app,
            MouseEvent {
                kind: MouseEventKind::Down(MouseButton::Left),
                column: 2,
                row: hit.row_y,
                modifiers: KeyModifiers::NONE,
            },
        )
        .action
        .expect("click on a Pinned to-do row must dispatch its primary action");
        assert!(
            matches!(action, SidebarRowAction::InspectWork { .. }),
            "a to-do row opens the work inspector: {action:?}"
        );
    }

    /// Opening the sub-agent register must not hide the to-do list — both
    /// durable surfaces stay visible together (owner report, 0.9.6).
    #[test]
    fn agents_panel_keeps_todos_visible_alongside_subagents() {
        let mut app = app();
        app.current_session_id = Some(SESSION.to_string());
        app.work_surface.panel = super::RailPanel::Agents;
        app.subagent_cache.push(cached_worker(
            "agent-live",
            "scout",
            None,
            None,
            SubAgentStatus::Running,
        ));
        add_todos(&mut app, 2);

        let rows = super::model::visible_rows_for_panel(&mut app);
        let ids: Vec<String> = rows.iter().map(|row| row.id.0.clone()).collect();

        assert!(
            ids.iter().any(|id| id.starts_with("worker:")),
            "the sub-agent register stays in the Agents panel: {ids:?}"
        );
        assert!(
            ids.iter().any(|id| id.starts_with("graph:")),
            "opening the register must not hide the to-do list: {ids:?}"
        );
    }

    /// The register header is a two-way door: open the Agents panel, then the
    /// same click returns to Tasks, so the to-do list is never stranded.
    #[test]
    fn subagent_header_is_a_two_way_door() {
        let mut app = app();
        app.work_surface.placement = super::WorkSurfacePlacement::Top;
        app.work_surface.effective_placement = super::WorkSurfacePlacement::Top;
        app.current_session_id = Some(SESSION.to_string());
        app.subagent_cache.push(cached_worker(
            "agent-archived",
            "builder",
            None,
            None,
            SubAgentStatus::Completed,
        ));

        let click_header = |app: &mut App| -> SidebarRowAction {
            let header_y = app
                .work_surface
                .hitboxes
                .iter()
                .find(|hit| hit.id.0 == "section:agents")
                .expect("subagent header is a real hit target")
                .row_y;
            super::handle_mouse(
                app,
                MouseEvent {
                    kind: MouseEventKind::Down(MouseButton::Left),
                    column: 2,
                    row: header_y,
                    modifiers: KeyModifiers::NONE,
                },
            )
            .action
            .expect("subagent header dispatches its primary action")
        };

        let _ = render_text(&mut app, 100, 4);
        let action = click_header(&mut app);
        assert_eq!(action, SidebarRowAction::ShowSubagentsPanel);
        crate::tui::mouse_ui::apply_sidebar_row_action(&mut app, action);
        assert_eq!(app.work_surface.panel, super::RailPanel::Agents);

        let _ = render_text(&mut app, 100, 6);
        let action = click_header(&mut app);
        crate::tui::mouse_ui::apply_sidebar_row_action(&mut app, action);
        assert_eq!(
            app.work_surface.panel,
            super::RailPanel::Tasks,
            "clicking the header inside the register returns to Tasks"
        );
    }

    /// ⌥V opens the selected work row's own details; the transcript pager is
    /// only the fallback when no row is selected (owner report, 0.9.6).
    #[test]
    fn details_chord_opens_the_selected_work_row() {
        let mut app = app();
        app.current_session_id = Some(SESSION.to_string());
        app.work_surface.panel = super::RailPanel::Agents;
        add_todos(&mut app, 2);

        let rows = super::model::visible_rows_for_panel(&mut app);
        let todo_row = rows
            .iter()
            .find(|row| row.id.0.starts_with("graph:"))
            .expect("a to-do row projects")
            .clone();
        app.work_surface.focused = true;
        app.work_surface.selected = Some(todo_row.id.clone());

        let handled = super::handle_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('v'), KeyModifiers::ALT),
        );
        assert!(
            matches!(handled, Some(Some(SidebarRowAction::InspectWork { .. }))),
            "⌥V opens the selected row's own details: {handled:?}"
        );
    }
}