teamctl-ui 0.8.3

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

use std::time::{Duration, Instant};

use anyhow::Result;
use crossterm::event::{self, Event, KeyCode, KeyEventKind};
use ratatui::backend::Backend;
use ratatui::buffer::Buffer;
use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::widgets::{Block, Borders, Clear, Paragraph, Widget};
use ratatui::{Frame, Terminal};

use crate::approvals::{
    Approval, ApprovalDecider, ApprovalSource, BrokerApprovalSource, CliApprovalDecider, Decision,
};
use crate::compose::{CliMessageSender, ComposeTarget, Editor, EditorAction, MessageSender};
use crate::data::TeamSnapshot;
use crate::keysender::{encode_key, KeySender, ScrollDirection, TmuxKeySender};
use crate::layouts;
use crate::mailbox::{BrokerMailboxSource, MailboxBuffers, MailboxSource, MailboxTab};
use crate::pane::{PaneSource, TmuxPaneSource};
use crate::splash;
use crate::status_bar;
use crate::statusline;
use crate::theme::{detect_capabilities, Capabilities};
use crate::triptych::{self, MainLayout, Pane};
use crate::tutorial;
use crate::watch::Watch;

const SPLASH_AUTO_DISMISS: Duration = Duration::from_secs(3);
const POLL_INTERVAL: Duration = Duration::from_millis(50);
/// How often the team snapshot + detail-pane capture get refreshed.
/// PR-UI-2 polls; PR-UI-3 may upgrade to event subscriptions.
const REFRESH_INTERVAL: Duration = Duration::from_secs(1);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Stage {
    Splash,
    Triptych,
    QuitConfirm,
    /// Approvals modal — opens on `a` (only when there's a
    /// pending approval), routes Approve/Deny via the existing
    /// `teamctl approve|deny` CLI so T-031's `delivered_at`
    /// contract stays honored.
    ApprovalsModal,
    /// Compose modal — opens on `@` (DM-to-focused-agent) or `!`
    /// (broadcast-to-current-channel). Routes through `teamctl
    /// send|broadcast` so the channel-ACL + ratelimit + delivery
    /// hooks the CLI already runs through ride for free.
    ComposeModal,
    /// `?` help overlay — modal listing every chord registered in
    /// `help::ALL_GROUPS`. Read-only; closes on Esc / `?`.
    HelpOverlay,
    /// Onboarding tutorial walkthrough. Auto-opens on first
    /// launch (per-team sentinel at
    /// `.team/state/ui-tutorial-completed`); reopenable via `t`
    /// from any non-modal state.
    Tutorial,
    /// Stream-keys mode (T-108). Activated by `Ctrl+E` while the
    /// detail pane is focused; every subsequent keystroke (except
    /// `Esc`, the exit chord) is forwarded to the focused agent's
    /// tmux pane via `tmux send-keys`. The Triptych keeps rendering
    /// underneath — the 1s refresh tick still captures whatever the
    /// agent prints in response — so the operator interacts with
    /// the agent in real time without leaving the UI.
    StreamKeys,
}

/// Splitscreen orientation per detail-pane split (PR-UI-7 lift
/// of PR-UI-6's deferred Q1). `Vertical` subdivides side-by-side
/// (Ctrl+|); `Horizontal` stacks top-to-bottom (Ctrl+-).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SplitOrientation {
    Vertical,
    Horizontal,
}

pub struct App {
    pub stage: Stage,
    /// Tracked so QuitConfirm can return to whichever stage opened it.
    pub previous_stage: Stage,
    pub focused_pane: Pane,
    pub team: TeamSnapshot,
    /// Index into `team.agents` of the agent the detail pane is
    /// streaming. `None` when the team is empty or roster
    /// navigation hasn't picked one yet.
    pub selected_agent: Option<usize>,
    /// Lines from the most recent pane capture. Bounded to the last
    /// `MAX_DETAIL_LINES` so the buffer doesn't grow unboundedly
    /// over a long-running session.
    pub detail_buffer: Vec<String>,
    pub version: &'static str,
    pub capabilities: Capabilities,
    pub splash_started: Instant,
    /// Last time the snapshot + pane capture were refreshed. Used by
    /// `tick()` to gate the next refresh.
    pub last_refresh: Instant,
    pub running: bool,
    /// First-launch detection — when the marker file exists, future
    /// stacked-PRs (PR-UI-7) skip the tutorial after splash. PR-UI-1
    /// only reads the flag; nothing routes off it yet.
    pub tutorial_completed: bool,
    /// Active tab inside the mailbox pane (PR-UI-3). Walked with
    /// `←` / `→` when `focused_pane == Mailbox` (T-124 hard-swapped
    /// the prior `[` / `]` chord for arrow keys; T-074 bug 6 is
    /// the gating-on-focus invariant). `Tab` always cycles pane
    /// focus, never mailbox tabs — the previous "Tab cycles tabs
    /// when mailbox is focused" shape stranded operators inside
    /// the mailbox.
    pub mailbox_tab: MailboxTab,
    /// Per-tab buffers + cursors for the focused agent's mailbox
    /// view. Reset whenever the focused agent changes — switching
    /// agents starts the operator at the head of fresh traffic.
    pub mailbox: MailboxBuffers,
    /// Pending approvals snapshot (PR-UI-4). Drives the conditional
    /// stripe at the top of Triptych and the modal opened by `a`.
    pub pending_approvals: Vec<Approval>,
    /// Index into `pending_approvals` of the row the modal is
    /// currently showing. Reset to 0 each time the modal opens;
    /// `j` / `k` (or `↑` / `↓`) cycle.
    pub selected_approval: usize,
    /// Last error from a CLI-routed Approve/Deny call — surfaced
    /// inline in the modal so the operator sees why a decision
    /// didn't take.
    pub approval_error: Option<String>,
    /// Open compose target — `Some` while `Stage::ComposeModal`
    /// is the active stage, `None` otherwise. Stored on App so
    /// the editor's contents survive rerenders.
    pub compose_target: Option<ComposeTarget>,
    /// Editor backing the compose modal. Reset to `default()` each
    /// time the modal opens so an old draft from a prior
    /// invocation can't leak into a new send.
    pub compose_editor: Editor,
    /// Last error from a CLI-routed send call — surfaced inline
    /// in the modal so the operator sees rate-limit / ACL-block
    /// errors without leaving the UI.
    pub compose_error: Option<String>,
    /// Active main-view layout (PR-UI-6). Triptych is the default;
    /// `Ctrl+W` toggles Wall, `Ctrl+M` toggles MailboxFirst.
    pub layout: MainLayout,
    /// Top-of-window agent index for the Wall view's vertical
    /// scroll. SPEC §3 caps visible tiles at 4; this offsets which
    /// 4-agent window is shown when the team has more.
    pub wall_scroll: usize,
    /// Selected channel index (into `team.channels`) for the
    /// MailboxFirst layout's channel list and for the broadcast
    /// picker. `None` until the operator picks one.
    pub selected_channel: Option<usize>,
    /// Splits within Triptych's detail pane (PR-UI-6). When
    /// non-empty, the detail pane subdivides; each entry pairs an
    /// agent id with the per-split orientation (PR-UI-7 lift of
    /// the Q1 deferral). `selected_split` is the vim-window-motion
    /// focus.
    pub detail_splits: Vec<(String, SplitOrientation)>,
    pub selected_split: usize,
    /// Chord-prefix machine for `Ctrl+W` follow-ups (PR-UI-7 lift
    /// of PR-UI-6's `Ctrl+Q` alias). When `Some(KeyCode::Char('w'))`,
    /// the next key is interpreted as a `Ctrl+W` follow: `q` =
    /// close split, `o` = close others. Cleared on any unrelated
    /// keypress so a typo doesn't leave the editor stuck.
    pub pending_chord: Option<KeyCode>,
    /// `true` when the operator's first launch on this team has
    /// not yet completed the tutorial — drives the auto-open after
    /// splash. Reset to `false` on tutorial completion.
    pub tutorial_pending_for_team: bool,
    /// Brand-spinner frame counter (PR-UI-7). Bumped each refresh
    /// tick so the statusline indicator shows the app is alive.
    pub spinner_frame: usize,
    /// Tutorial step cursor (PR-UI-7). Index into
    /// `onboarding::STEPS`; reset to 0 when the tutorial reopens.
    pub tutorial_step: usize,
    /// Modal substage for the broadcast channel picker (PR-UI-6).
    /// When `true` the compose modal renders a picker over the
    /// editor; selecting a channel populates `compose_target` and
    /// drops back to the editor.
    pub compose_picker_open: bool,
    /// Picker selection cursor — index into `team.channels`.
    pub compose_picker_index: usize,
    /// T-32: when `true`, the compose modal renders a single-line
    /// path-input overlay instead of the editor; Enter appends a
    /// `📎 attachment: <path>` line to the editor body and closes the
    /// overlay. Tab inside the editor opens it; Esc inside the
    /// overlay cancels back to the editor (matches the picker
    /// overlay's modal-vs-modal symmetry from PR-UI-6).
    pub compose_attach_input_open: bool,
    /// Single-line buffer for the path-input overlay. Reset on close
    /// so a cancelled draft can't leak into the next attach attempt.
    pub compose_attach_buffer: String,
    /// T-199: per-session cache of the last Detail-pane size we
    /// pushed to `tmux resize-pane`. The run loop diffs the current
    /// Detail rect against this on every frame and only spawns the
    /// tmux command when the size actually changed — common case
    /// (no resize, no focus switch) is a HashMap lookup. Keyed by
    /// `tmux_session` (e.g. `t-hello-manager`). See
    /// `crate::pane_resize`.
    pub last_synced_pane_sizes: std::collections::HashMap<String, (u16, u16)>,
    /// T-209: live system handle for the bottom status bar's
    /// CPU% + RAM% indicator. Refreshed in-place on the existing
    /// 1-second App tick (see `refresh_with_default_sources` and the
    /// run-loop tick at the top of `run()`); no background thread.
    /// `default-features = false` + only the `system` feature is
    /// enabled in the dep to keep the compile surface narrow. See
    /// `crate::status_bar`.
    pub sysinfo: sysinfo::System,
    /// T-212 preview gate. `true` when `TEAMCTL_UI_RATE_LIMIT_INDICATOR`
    /// was set at App::new(), `false` otherwise. The bottom status
    /// bar's center slot only renders when this is true — opt-in
    /// while the indicator's data shape (currently reset-time only)
    /// stabilizes against the eventual usage-% data path. Tests can
    /// flip the field directly to exercise both branches without
    /// process-wide env-var racing.
    pub rate_limit_indicator_enabled: bool,
}

const MAX_DETAIL_LINES: usize = 2000;

impl App {
    /// Construct an empty App — no team snapshot loaded. Used by
    /// tests and as the splash-stage default. Production launch
    /// goes through `App::launch()` which immediately runs an
    /// initial `refresh()` so the splash screen already shows the
    /// real team name + agent count.
    pub fn new() -> Self {
        Self {
            stage: Stage::Splash,
            previous_stage: Stage::Splash,
            focused_pane: Pane::Roster,
            team: TeamSnapshot::empty(std::path::PathBuf::new()),
            selected_agent: None,
            detail_buffer: Vec::new(),
            version: env!("CARGO_PKG_VERSION"),
            capabilities: detect_capabilities(),
            splash_started: Instant::now(),
            last_refresh: Instant::now() - REFRESH_INTERVAL,
            running: true,
            tutorial_completed: tutorial::is_completed(),
            mailbox_tab: MailboxTab::Inbox,
            mailbox: MailboxBuffers::default(),
            pending_approvals: Vec::new(),
            selected_approval: 0,
            approval_error: None,
            compose_target: None,
            compose_editor: Editor::default(),
            compose_error: None,
            layout: MainLayout::Triptych,
            wall_scroll: 0,
            selected_channel: None,
            detail_splits: Vec::new(),
            selected_split: 0,
            compose_picker_open: false,
            compose_picker_index: 0,
            compose_attach_input_open: false,
            compose_attach_buffer: String::new(),
            pending_chord: None,
            tutorial_pending_for_team: false,
            spinner_frame: 0,
            tutorial_step: 0,
            last_synced_pane_sizes: std::collections::HashMap::new(),
            // sysinfo's `new()` allocates but doesn't read any metrics;
            // the first values are populated by the first refresh tick
            // in `refresh_with_default_sources`. Until then the status
            // bar reads zeros — operator sees the bar shape but the
            // numbers stabilize after ~1 second.
            sysinfo: sysinfo::System::new(),
            // T-212: per-agent rate-limit indicator is gated behind a
            // preview env var so we can ship the indicator surface
            // (reset-time only) without committing the operator-facing
            // shape until the usage-% data path lands. Operators
            // opt in by setting `TEAMCTL_UI_RATE_LIMIT_INDICATOR=1`
            // (any non-empty value enables). Read once at App::new()
            // — flipping the flag mid-session requires a TUI restart.
            rate_limit_indicator_enabled: std::env::var_os("TEAMCTL_UI_RATE_LIMIT_INDICATOR")
                .is_some(),
        }
    }

    /// Per-tutorial-step cursor (used by Stage::Tutorial). Wraps
    /// at the end so `t`-then-keys walks the full tour.
    pub fn enter_help_overlay(&mut self) {
        self.previous_stage = self.stage;
        self.stage = Stage::HelpOverlay;
    }
    pub fn close_help_overlay(&mut self) {
        self.stage = self.previous_stage;
    }
    pub fn enter_tutorial(&mut self) {
        self.previous_stage = self.stage;
        self.stage = Stage::Tutorial;
        self.tutorial_step = 0;
    }
    pub fn close_tutorial(&mut self) {
        self.stage = self.previous_stage;
        self.tutorial_pending_for_team = false;
        if !self.team.root.as_os_str().is_empty() {
            let _ = crate::onboarding::mark_completed(&self.team.root);
        }
    }
    pub fn tutorial_advance(&mut self) {
        let len = crate::onboarding::STEPS.len();
        if len == 0 {
            self.close_tutorial();
            return;
        }
        if self.tutorial_step + 1 >= len {
            self.close_tutorial();
        } else {
            self.tutorial_step += 1;
        }
    }
    pub fn tutorial_back(&mut self) {
        self.tutorial_step = self.tutorial_step.saturating_sub(1);
    }

    pub fn toggle_wall_layout(&mut self) {
        self.layout = self.layout.toggle_wall();
    }
    pub fn toggle_mailbox_first_layout(&mut self) {
        self.layout = self.layout.toggle_mailbox_first();
        // First entry into MailboxFirst seeds the channel cursor
        // so the feed pane has something to render.
        if matches!(self.layout, MainLayout::MailboxFirst) && self.selected_channel.is_none() {
            self.selected_channel = if self.team.channels.is_empty() {
                None
            } else {
                Some(0)
            };
        }
    }
    pub fn wall_scroll_up(&mut self) {
        self.wall_scroll = self
            .wall_scroll
            .saturating_sub(crate::layouts::WALL_TILE_CAP);
    }
    pub fn wall_scroll_down(&mut self) {
        let next = self.wall_scroll + crate::layouts::WALL_TILE_CAP;
        if next < self.team.agents.len() {
            self.wall_scroll = next;
        }
    }
    pub fn select_next_channel(&mut self) {
        if self.team.channels.is_empty() {
            return;
        }
        self.selected_channel = Some(match self.selected_channel {
            None => 0,
            Some(i) => (i + 1) % self.team.channels.len(),
        });
    }
    pub fn select_prev_channel(&mut self) {
        if self.team.channels.is_empty() {
            return;
        }
        self.selected_channel = Some(match self.selected_channel {
            None | Some(0) => self.team.channels.len() - 1,
            Some(i) => i - 1,
        });
    }

    /// Add a split for the focused agent (or current selection)
    /// to the detail pane. Cap at 4 splits per the SPEC §3 cap.
    /// Add a vertical split (PR-UI-7). `Ctrl+|` calls this.
    pub fn add_detail_split_vertical(&mut self) {
        self.add_detail_split_with_orientation(SplitOrientation::Vertical);
    }
    /// Add a horizontal split (PR-UI-7). `Ctrl+-` calls this.
    pub fn add_detail_split_horizontal(&mut self) {
        self.add_detail_split_with_orientation(SplitOrientation::Horizontal);
    }
    fn add_detail_split_with_orientation(&mut self, orientation: SplitOrientation) {
        let Some(id) = self.selected_agent_id() else {
            return;
        };
        if self.detail_splits.len() >= 4 {
            return;
        }
        self.detail_splits.push((id, orientation));
        self.selected_split = self.detail_splits.len() - 1;
    }
    /// Back-compat shim — earlier PRs called the unsuffixed name.
    /// Defaults to vertical (matching the most-common chord
    /// `Ctrl+|`). Kept so the test surface PR-UI-6 pinned doesn't
    /// drift.
    pub fn add_detail_split(&mut self) {
        self.add_detail_split_vertical();
    }
    pub fn close_focused_split(&mut self) {
        if self.detail_splits.is_empty() {
            return;
        }
        let i = self.selected_split.min(self.detail_splits.len() - 1);
        self.detail_splits.remove(i);
        self.selected_split = i.saturating_sub(1);
    }
    pub fn cycle_split_next(&mut self) {
        if self.detail_splits.is_empty() {
            return;
        }
        self.selected_split = (self.selected_split + 1) % self.detail_splits.len();
    }
    pub fn cycle_split_prev(&mut self) {
        if self.detail_splits.is_empty() {
            return;
        }
        self.selected_split = if self.selected_split == 0 {
            self.detail_splits.len() - 1
        } else {
            self.selected_split - 1
        };
    }

    /// Open the broadcast compose flow — picker first when at
    /// least one channel is declared, else fall back to the
    /// project's `all` channel (PR-UI-5 behaviour) on the
    /// assumption that `all` always exists in production composes.
    pub fn enter_compose_broadcast_with_picker(&mut self) {
        if self.team.channels.is_empty() {
            // Fall back to the PR-UI-5 default if no channels
            // are declared yet — should only happen with a
            // half-loaded snapshot.
            self.enter_compose_broadcast();
            return;
        }
        let project_id = self
            .team
            .channels
            .first()
            .map(|c| c.project_id.clone())
            .unwrap_or_default();
        self.previous_stage = self.stage;
        self.stage = Stage::ComposeModal;
        self.compose_target = Some(ComposeTarget::Broadcast {
            channel_id: format!("{project_id}:all"),
            project_id,
        });
        self.compose_editor = Editor::default();
        self.compose_error = None;
        self.compose_picker_open = true;
        self.compose_picker_index = 0;
    }
    pub fn picker_next(&mut self) {
        if self.team.channels.is_empty() {
            return;
        }
        self.compose_picker_index = (self.compose_picker_index + 1) % self.team.channels.len();
    }
    pub fn picker_prev(&mut self) {
        if self.team.channels.is_empty() {
            return;
        }
        self.compose_picker_index = if self.compose_picker_index == 0 {
            self.team.channels.len() - 1
        } else {
            self.compose_picker_index - 1
        };
    }
    pub fn picker_confirm(&mut self) {
        if let Some(ch) = self.team.channels.get(self.compose_picker_index) {
            self.compose_target = Some(ComposeTarget::Broadcast {
                channel_id: ch.id.clone(),
                project_id: ch.project_id.clone(),
            });
        }
        self.compose_picker_open = false;
    }

    /// T-32: open the path-input overlay. Resets the buffer so a
    /// previously-cancelled draft can't carry over.
    pub fn open_compose_attach_input(&mut self) {
        self.compose_attach_input_open = true;
        self.compose_attach_buffer.clear();
    }

    /// T-32: append a `📎 attachment: <path>` line to the compose
    /// editor and close the overlay. The line lands as a fresh row
    /// at the end of the body so the operator can edit it (or delete
    /// it) before sending. Whitespace-only buffers are ignored — Tab
    /// followed by Enter shouldn't insert an empty marker.
    pub fn confirm_compose_attach_input(&mut self) {
        let path = self.compose_attach_buffer.trim().to_string();
        if !path.is_empty() {
            let marker = format!("📎 attachment: {path}");
            // The body's final-trailing-blank rule (Editor::body)
            // strips empty trailing lines, so an empty last line
            // doesn't matter — we always push the marker as a new
            // line after current contents.
            if let Some(last) = self.compose_editor.lines.last_mut() {
                if !last.is_empty() {
                    self.compose_editor.lines.push(marker);
                } else {
                    *last = marker;
                }
            } else {
                self.compose_editor.lines.push(marker);
            }
            // Park the cursor at end of the new line so subsequent
            // typing in Insert mode picks up after the marker.
            self.compose_editor.cursor_row = self.compose_editor.lines.len() - 1;
            self.compose_editor.cursor_col = self
                .compose_editor
                .lines
                .last()
                .map(|l| l.len())
                .unwrap_or(0);
        }
        self.close_compose_attach_input();
    }

    pub fn close_compose_attach_input(&mut self) {
        self.compose_attach_input_open = false;
        self.compose_attach_buffer.clear();
    }

    pub fn cycle_mailbox_tab(&mut self) {
        self.mailbox_tab = self.mailbox_tab.next();
    }

    pub fn cycle_mailbox_tab_back(&mut self) {
        self.mailbox_tab = self.mailbox_tab.prev();
    }

    pub fn cycle_focus_back(&mut self) {
        self.focused_pane = self.focused_pane.prev();
    }

    pub fn has_pending_approvals(&self) -> bool {
        !self.pending_approvals.is_empty()
    }

    pub fn enter_approvals_modal(&mut self) {
        if self.pending_approvals.is_empty() {
            return;
        }
        self.previous_stage = self.stage;
        self.stage = Stage::ApprovalsModal;
        self.selected_approval = 0;
        self.approval_error = None;
    }

    pub fn close_approvals_modal(&mut self) {
        self.stage = self.previous_stage;
        self.approval_error = None;
    }

    pub fn cycle_approval_next(&mut self) {
        if self.pending_approvals.is_empty() {
            return;
        }
        self.selected_approval = (self.selected_approval + 1) % self.pending_approvals.len();
    }

    pub fn cycle_approval_prev(&mut self) {
        if self.pending_approvals.is_empty() {
            return;
        }
        self.selected_approval = if self.selected_approval == 0 {
            self.pending_approvals.len() - 1
        } else {
            self.selected_approval - 1
        };
    }

    pub fn focused_approval(&self) -> Option<&Approval> {
        self.pending_approvals.get(self.selected_approval)
    }

    /// Replace the pending-approvals list. Closes the modal when
    /// the queue empties (no row to act on); preserves the modal
    /// otherwise but clamps `selected_approval` into range so an
    /// approval resolved out-of-band doesn't leave us pointing at
    /// a stale index.
    pub fn replace_approvals(&mut self, approvals: Vec<Approval>) {
        self.pending_approvals = approvals;
        if self.pending_approvals.is_empty() {
            if matches!(self.stage, Stage::ApprovalsModal) {
                self.close_approvals_modal();
            }
            self.selected_approval = 0;
        } else if self.selected_approval >= self.pending_approvals.len() {
            self.selected_approval = self.pending_approvals.len() - 1;
        }
    }

    /// Apply a decision to the focused approval via the injected
    /// decider. The decider routes through `teamctl approve|deny`
    /// in production; tests inject a recorder. On success the row
    /// gets removed from the local `pending_approvals` snapshot
    /// optimistically — the next `refresh_approvals` will reconcile
    /// against the broker.
    pub fn apply_decision<D: ApprovalDecider>(&mut self, decider: &D, kind: Decision, note: &str) {
        let Some(approval) = self.focused_approval().cloned() else {
            return;
        };
        match decider.decide(&self.team.root, approval.id, kind, note) {
            Ok(()) => {
                self.pending_approvals.retain(|a| a.id != approval.id);
                self.approval_error = None;
                if self.pending_approvals.is_empty() {
                    self.close_approvals_modal();
                } else if self.selected_approval >= self.pending_approvals.len() {
                    self.selected_approval = self.pending_approvals.len() - 1;
                }
            }
            Err(err) => {
                self.approval_error = Some(err.to_string());
            }
        }
    }

    /// Open the compose modal for the focused agent (if any). The
    /// `@` chord. No-op when no agent is focused.
    pub fn enter_compose_dm_for_focused(&mut self) {
        let Some(info) = self
            .selected_agent
            .and_then(|i| self.team.agents.get(i))
            .cloned()
        else {
            return;
        };
        self.previous_stage = self.stage;
        self.stage = Stage::ComposeModal;
        self.compose_target = Some(ComposeTarget::Dm {
            agent_id: info.id.clone(),
            project_id: info.project.clone(),
        });
        self.compose_editor = Editor::default();
        self.compose_error = None;
    }

    /// Open the compose modal targeting the project's `all`
    /// channel — the broadcast wire. The `!` chord. PR-UI-5 ships
    /// with channel scoping limited to `all` (the Wire tab is the
    /// only channel context the mailbox pane currently surfaces);
    /// PR-UI-6's mailbox UI work will widen the scope to per-channel
    /// targets when individual channels become first-class in the
    /// pane.
    pub fn enter_compose_broadcast(&mut self) {
        let project_id = self
            .selected_agent
            .and_then(|i| self.team.agents.get(i))
            .map(|a| a.project.clone())
            .or_else(|| self.team.agents.first().map(|a| a.project.clone()));
        let Some(project_id) = project_id else {
            return;
        };
        let channel_id = format!("{project_id}:all");
        self.previous_stage = self.stage;
        self.stage = Stage::ComposeModal;
        self.compose_target = Some(ComposeTarget::Broadcast {
            channel_id,
            project_id,
        });
        self.compose_editor = Editor::default();
        self.compose_error = None;
    }

    pub fn close_compose_modal(&mut self) {
        self.stage = self.previous_stage;
        self.compose_target = None;
        self.compose_editor = Editor::default();
        self.compose_error = None;
        // T-32: ensure the attach overlay state can't survive a
        // close-and-reopen of the modal.
        self.compose_attach_input_open = false;
        self.compose_attach_buffer.clear();
    }

    /// Send the current compose body via the injected message
    /// sender. Routes through `teamctl send|broadcast` in
    /// production; tests inject a recorder. Closes the modal +
    /// triggers a mailbox refresh on success; surfaces error
    /// inline on failure.
    pub fn apply_send<S: MessageSender, M: MailboxSource>(
        &mut self,
        sender: &S,
        mailbox_source: &M,
    ) {
        let Some(target) = self.compose_target.clone() else {
            return;
        };
        let body = self.compose_editor.body();
        if body.is_empty() {
            self.compose_error = Some("body is empty".into());
            return;
        }
        let result = match &target {
            ComposeTarget::Dm { agent_id, .. } => sender.send_dm(&self.team.root, agent_id, &body),
            ComposeTarget::Broadcast { channel_id, .. } => {
                sender.broadcast(&self.team.root, channel_id, &body)
            }
        };
        match result {
            Ok(()) => {
                self.close_compose_modal();
                // Refresh the mailbox so the just-sent row appears
                // in the relevant tab on the next paint.
                refresh_mailbox(self, mailbox_source);
            }
            Err(err) => {
                self.compose_error = Some(err.to_string());
            }
        }
    }

    pub fn dismiss_splash(&mut self) {
        if matches!(self.stage, Stage::Splash) {
            self.stage = Stage::Triptych;
            self.previous_stage = Stage::Triptych;
        }
    }

    pub fn cycle_focus(&mut self) {
        self.focused_pane = self.focused_pane.next();
    }

    /// Move roster selection up by one — wraps at the top. No-op
    /// when the team is empty. Does not change `focused_pane`.
    /// Resets mailbox buffers when the resulting agent id differs
    /// from the prior selection — switching agents should start the
    /// operator at the head of fresh traffic.
    pub fn select_prev(&mut self) {
        if self.team.agents.is_empty() {
            self.selected_agent = None;
            return;
        }
        let prior = self.selected_agent_id();
        self.selected_agent = Some(match self.selected_agent {
            None | Some(0) => self.team.agents.len() - 1,
            Some(i) => i - 1,
        });
        if prior != self.selected_agent_id() {
            self.mailbox.reset();
        }
    }

    /// Move roster selection down by one — wraps at the bottom.
    /// No-op when the team is empty.
    pub fn select_next(&mut self) {
        if self.team.agents.is_empty() {
            self.selected_agent = None;
            return;
        }
        let prior = self.selected_agent_id();
        self.selected_agent = Some(match self.selected_agent {
            None => 0,
            Some(i) => (i + 1) % self.team.agents.len(),
        });
        if prior != self.selected_agent_id() {
            self.mailbox.reset();
        }
    }

    /// `<project>:<agent>` of the currently selected agent, if any.
    pub fn selected_agent_id(&self) -> Option<String> {
        self.selected_agent
            .and_then(|i| self.team.agents.get(i))
            .map(|a| a.id.clone())
    }

    pub fn enter_quit_confirm(&mut self) {
        self.previous_stage = self.stage;
        self.stage = Stage::QuitConfirm;
    }

    pub fn cancel_quit(&mut self) {
        self.stage = self.previous_stage;
    }

    pub fn confirm_quit(&mut self) {
        self.running = false;
    }

    /// Replace the team snapshot. Preserves the current selection
    /// when the agent at that index still exists; otherwise resets
    /// to the first agent (or `None` for an empty team). Resets the
    /// mailbox buffers when the resulting agent id differs from the
    /// prior selection — same agent-changed contract as
    /// `select_next` / `select_prev`.
    pub fn replace_team(&mut self, team: TeamSnapshot) {
        let prior_id = self.selected_agent_id();
        self.team = team;
        self.selected_agent = match (prior_id.clone(), self.team.agents.is_empty()) {
            (_, true) => None,
            (Some(id), false) => self.team.agents.iter().position(|a| a.id == id).or(Some(0)),
            (None, false) => Some(0),
        };
        if prior_id != self.selected_agent_id() {
            self.mailbox.reset();
        }
    }

    /// Return the focused agent's tmux session name, if any. Used
    /// by the run loop to know which session to capture.
    pub fn focused_session(&self) -> Option<&str> {
        self.selected_agent
            .and_then(|i| self.team.agents.get(i))
            .map(|a| a.tmux_session.as_str())
    }

    /// Tmux session that stream-keys mode should target. Cell 0 of
    /// the detail-pane split layout is always the focused agent;
    /// cells 1..N are the entries in `detail_splits`. When the
    /// operator has focused a non-zero split, route stream-keys to
    /// that split's agent — that's the cell visually showing as the
    /// focus ring, so it's the one the operator expects to type into.
    pub fn stream_target_session(&self) -> Option<String> {
        if self.detail_splits.is_empty() || self.selected_split == 0 {
            return self.focused_session().map(|s| s.to_string());
        }
        let split_idx = self.selected_split - 1;
        let agent_id = self.detail_splits.get(split_idx).map(|(id, _)| id)?;
        self.team
            .agents
            .iter()
            .find(|a| &a.id == agent_id)
            .map(|a| a.tmux_session.clone())
    }

    /// Enter stream-keys mode. No-op unless an agent is selected —
    /// without a target session there's nothing to forward to.
    /// Caller is responsible for the focused-pane gate (entry chord
    /// only fires from `focused_pane == Pane::Detail`).
    pub fn enter_stream_keys(&mut self) {
        if self.stream_target_session().is_none() {
            return;
        }
        self.previous_stage = self.stage;
        self.stage = Stage::StreamKeys;
    }

    /// Exit stream-keys mode and return to whichever stage opened it.
    /// `Esc` is the only exit chord per the issue's recommendation —
    /// every other key (including `Ctrl+C`) forwards to the agent.
    pub fn exit_stream_keys(&mut self) {
        self.stage = self.previous_stage;
    }

    /// Replace the detail buffer, clipped at the recent-line cap.
    pub fn set_detail_buffer(&mut self, lines: Vec<String>) {
        let len = lines.len();
        let start = len.saturating_sub(MAX_DETAIL_LINES);
        self.detail_buffer = lines[start..].to_vec();
    }
}

impl Default for App {
    fn default() -> Self {
        Self::new()
    }
}

/// Refresh the team snapshot + the focused agent's pane capture +
/// the mailbox tabs (PR-UI-3). Pulled out so tests can drive a
/// single tick deterministically against `MockPaneSource` and
/// `MockMailboxSource` without going through the event loop.
pub fn refresh<P: PaneSource, M: MailboxSource, A: ApprovalSource>(
    app: &mut App,
    pane_source: &P,
    mailbox_source: &M,
    approval_source: &A,
) {
    if let Ok(Some(snapshot)) = TeamSnapshot::discover_and_load() {
        app.replace_team(snapshot);
    }
    if let Some(session) = app.focused_session().map(|s| s.to_string()) {
        if let Ok(lines) = pane_source.capture(&session) {
            app.set_detail_buffer(lines);
        }
    } else {
        app.detail_buffer.clear();
    }
    refresh_mailbox(app, mailbox_source);
    refresh_approvals(app, approval_source);
    app.last_refresh = Instant::now();
}

/// Approvals-only refresh. Extracted on the same shape as
/// `refresh_mailbox` — PR-UI-5+ can call it on its own cadence
/// (e.g. in response to a `notify` signal) without re-running the
/// heavier paths. Errors degrade to "no pending" so the stripe
/// just hides on a transient broker read failure.
pub fn refresh_approvals<A: ApprovalSource>(app: &mut App, approval_source: &A) {
    let approvals = approval_source.pending().unwrap_or_default();
    app.replace_approvals(approvals);
}

/// Mailbox-only refresh — extracted so PR-UI-4+ can call it on its
/// own cadence (e.g. in response to a broker INSERT signal) without
/// re-running the heavier compose + tmux capture path. PR-UI-3
/// just calls it from the main `refresh` once per tick.
pub fn refresh_mailbox<M: MailboxSource>(app: &mut App, mailbox_source: &M) {
    let Some(agent_id) = app.selected_agent_id() else {
        // No agent focused → nothing to fetch. Buffers were already
        // reset on selection change so the empty-state hint shows.
        return;
    };
    let project_id = app
        .selected_agent
        .and_then(|i| app.team.agents.get(i))
        .map(|a| a.project.clone())
        .unwrap_or_default();
    if let Ok(batch) = mailbox_source.inbox(&agent_id, app.mailbox.inbox_after) {
        app.mailbox.extend(MailboxTab::Inbox, batch);
    }
    if let Ok(batch) = mailbox_source.sent(&agent_id, app.mailbox.sent_after) {
        app.mailbox.extend(MailboxTab::Sent, batch);
    }
    if let Ok(batch) = mailbox_source.channel_feed(&agent_id, app.mailbox.channel_after) {
        app.mailbox.extend(MailboxTab::Channel, batch);
    }
    if let Ok(batch) = mailbox_source.wire(&project_id, app.mailbox.wire_after) {
        app.mailbox.extend(MailboxTab::Wire, batch);
    }
}

pub fn run<B: Backend>(terminal: &mut Terminal<B>) -> Result<()> {
    let mut app = App::new();
    let pane_source = TmuxPaneSource;
    let decider = CliApprovalDecider;
    let sender = CliMessageSender;
    let key_sender = TmuxKeySender;
    let pane_resizer = crate::pane_resize::TmuxPaneResizer;
    // First refresh resolves the team root; only then can we
    // bring up the file-watcher, which keys on `<root>/state/`.
    refresh_with_default_sources(&mut app, &pane_source);
    let mut watch = Watch::try_new(&app.team.root.join("state"));
    while app.running {
        terminal.draw(|f| draw(f, &app))?;
        // T-199: after every frame, push the focused agent's inner
        // tmux pane to match teamctl-ui's Detail rect so claude
        // reflows when the operator resizes the host terminal (or
        // when focus switches to a different agent whose pane was
        // last sized for a different layout). The cache inside
        // `sync_focused_pane_size_to` keeps this to one HashMap
        // lookup per frame in the no-op case.
        let term_sz = terminal.size()?;
        let term_area = ratatui::layout::Rect::new(0, 0, term_sz.width, term_sz.height);
        sync_focused_pane_size_to(&mut app, term_area, &pane_resizer);
        if event::poll(POLL_INTERVAL)? {
            // The mailbox source for handle_event mirrors the
            // refresh path; the same db_path key avoids divergence
            // between read + write fanout.
            let db_path = app.team.root.join("state/mailbox.db");
            let mailbox_source = BrokerMailboxSource::new(db_path);
            handle_event(
                &mut app,
                event::read()?,
                &decider,
                &sender,
                &mailbox_source,
                &key_sender,
            );
        }
        if matches!(app.stage, Stage::Splash) && app.splash_started.elapsed() >= SPLASH_AUTO_DISMISS
        {
            app.dismiss_splash();
        }
        // Refresh on either (a) deadline elapsed or (b) the
        // notify-watcher said the broker DB changed. The watcher
        // shaves the typical refresh latency from ~1s to ~50ms when
        // the platform supports it; on platforms without notify
        // support `take_dirty` always returns false and the
        // deadline path is the only trigger (PR-UI-3 behaviour).
        let dirty = watch.take_dirty();
        if dirty || app.last_refresh.elapsed() >= REFRESH_INTERVAL {
            let prior_root = app.team.root.clone();
            refresh_with_default_sources(&mut app, &pane_source);
            // Team root drifted (operator launched in a different
            // tree) → swap the watcher to the new state dir.
            if app.team.root != prior_root {
                watch = Watch::try_new(&app.team.root.join("state"));
            }
        }
    }
    Ok(())
}

/// T-199: push the focused agent's inner tmux pane to match the
/// Detail rect teamctl-ui will draw into. No-op when:
///
/// - no agent is focused (nothing to size);
/// - the active main layout isn't Triptych (Wall / MailboxFirst
///   render differently and aren't in scope for this fix; flagged
///   as follow-up surfaces in #199);
/// - the Detail rect is degenerate (zero width or height — the
///   helper returns `None` and we leave the pane alone);
/// - the cached size for this session already matches.
///
/// The cache lives on `App` (`last_synced_pane_sizes`) so the
/// common case (no resize, focused on same agent) is a HashMap
/// lookup, not a subprocess spawn.
pub fn sync_focused_pane_size_to<R: crate::pane_resize::PaneResizer>(
    app: &mut App,
    total_area: ratatui::layout::Rect,
    resizer: &R,
) {
    if !matches!(app.layout, MainLayout::Triptych) {
        return;
    }
    let Some(detail) =
        crate::pane_resize::triptych_detail_area(total_area, app.has_pending_approvals())
    else {
        return;
    };
    let Some(session) = app.focused_session().map(|s| s.to_string()) else {
        return;
    };
    let target = (detail.width, detail.height);
    if !crate::pane_resize::should_sync(&app.last_synced_pane_sizes, &session, target) {
        return;
    }
    resizer.resize(&session, target.0, target.1);
    app.last_synced_pane_sizes.insert(session, target);
}

/// Build the production `BrokerMailboxSource` + `BrokerApprovalSource`
/// from the current team root and run a refresh with all three
/// default sources. Lives here (rather than inline in `run`) so
/// the team-root → DB-path derivation has one home.
fn refresh_with_default_sources<P: PaneSource>(app: &mut App, pane_source: &P) {
    if let Ok(Some(snapshot)) = TeamSnapshot::discover_and_load() {
        app.replace_team(snapshot);
    }
    let db_path = app.team.root.join("state/mailbox.db");
    let mailbox_source = BrokerMailboxSource::new(db_path.clone());
    let approval_source = BrokerApprovalSource::new(db_path);
    if let Some(session) = app.focused_session().map(|s| s.to_string()) {
        if let Ok(lines) = pane_source.capture(&session) {
            app.set_detail_buffer(lines);
        }
    } else {
        app.detail_buffer.clear();
    }
    refresh_mailbox(app, &mailbox_source);
    refresh_approvals(app, &approval_source);
    // T-209: refresh the live CPU/RAM numbers on the same 1-second
    // cadence as the rest of App. `refresh_cpu_usage` + `refresh_memory`
    // are the minimal pair — `refresh_all` would also probe disks,
    // networks, processes, and components, none of which the status
    // bar shows. Sub-millisecond cost on modern hardware.
    app.sysinfo.refresh_cpu_usage();
    app.sysinfo.refresh_memory();
    app.last_refresh = Instant::now();
}

pub fn draw(f: &mut Frame<'_>, app: &App) {
    let area = f.area();
    match app.stage {
        Stage::Splash => splash::draw(f, app),
        Stage::Triptych => draw_main(f, area, app),
        // T-108: stream-keys reuses the Triptych render path — the
        // detail pane carries the visual indicator (border + title +
        // statusline shift) via the `app.stage == StreamKeys` branch
        // in those widgets. No separate modal draw.
        Stage::StreamKeys => draw_main(f, area, app),
        Stage::QuitConfirm => {
            draw_main(f, area, app);
            draw_quit_confirm(f, area);
        }
        Stage::ApprovalsModal => {
            draw_main(f, area, app);
            draw_approvals_modal(f, area, app);
        }
        Stage::ComposeModal => {
            draw_main(f, area, app);
            draw_compose_modal(f, area, app);
        }
        Stage::HelpOverlay => {
            draw_main(f, area, app);
            let buf = f.buffer_mut();
            render_help_overlay(area, buf, app);
        }
        Stage::Tutorial => {
            draw_main(f, area, app);
            let buf = f.buffer_mut();
            render_tutorial(area, buf, app);
        }
    }
}

fn render_help_overlay(area: Rect, buf: &mut Buffer, app: &App) {
    let popup_w = 70u16.min(area.width.saturating_sub(4));
    let popup_h = 24u16.min(area.height.saturating_sub(2));
    let popup = centered_rect(popup_w, popup_h, area);
    Clear.render(popup, buf);
    let block = Block::default()
        .title("help · ? to close")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(app.capabilities.accent()));
    let inner = block.inner(popup);
    block.render(popup, buf);
    let muted = Style::default().fg(app.capabilities.muted());
    let bold = Style::default().add_modifier(Modifier::BOLD);
    let mut lines: Vec<ratatui::text::Line<'_>> = Vec::new();
    for group in crate::help::ALL_GROUPS {
        lines.push(ratatui::text::Line::styled(group.title, bold));
        for b in group.bindings {
            lines.push(ratatui::text::Line::raw(format!(
                "  {:<22}  {}",
                b.chord, b.description
            )));
        }
        lines.push(ratatui::text::Line::styled("", muted));
    }
    Paragraph::new(lines).render(inner, buf);
}

fn render_tutorial(area: Rect, buf: &mut Buffer, app: &App) {
    let popup_w = 64u16.min(area.width.saturating_sub(4));
    let popup_h = 14u16.min(area.height.saturating_sub(2));
    let popup = centered_rect(popup_w, popup_h, area);
    Clear.render(popup, buf);
    let total = crate::onboarding::STEPS.len();
    let i = app.tutorial_step.min(total.saturating_sub(1));
    let step = &crate::onboarding::STEPS[i];
    let block = Block::default()
        .title(format!("tutorial · {}/{total}", i + 1))
        .borders(Borders::ALL)
        .border_style(Style::default().fg(app.capabilities.accent()));
    let inner = block.inner(popup);
    block.render(popup, buf);
    let muted = Style::default().fg(app.capabilities.muted());
    let lines = vec![
        ratatui::text::Line::styled(step.heading, Style::default().add_modifier(Modifier::BOLD)),
        ratatui::text::Line::raw(""),
        ratatui::text::Line::raw(step.body),
        ratatui::text::Line::raw(""),
        ratatui::text::Line::styled("any key next  ·  k / ↑ / p back  ·  Esc skip", muted),
    ];
    // T-074 bug 5: tutorial bodies are prose paragraphs, not pre-
    // formatted lines — clip-on-overflow leaves them looking truncated
    // on common (≤80 col) terminals. Soft-wrap with `trim: true` so
    // long step descriptions reflow into the modal width instead of
    // dropping off the right edge.
    Paragraph::new(lines)
        .wrap(ratatui::widgets::Wrap { trim: true })
        .render(inner, buf);
}

fn draw_main(f: &mut Frame<'_>, area: Rect, app: &App) {
    // T-209: bottom of the screen is now a two-row footer —
    // existing keybindings statusline on top, new status bar
    // (cwd-left + CPU/RAM-right; T-212 will fill the center slot
    // per coordination with kian) below. Both 1 row tall.
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Min(3),
            Constraint::Length(1), // existing keybindings statusline
            Constraint::Length(1), // T-209 bottom status bar
        ])
        .split(area);
    let buf = f.buffer_mut();
    match app.layout {
        crate::triptych::MainLayout::Triptych => {
            triptych::Triptych { app }.render(chunks[0], buf);
        }
        crate::triptych::MainLayout::Wall => {
            layouts::Wall { app }.render(chunks[0], buf);
        }
        crate::triptych::MainLayout::MailboxFirst => {
            layouts::MailboxFirst { app }.render(chunks[0], buf);
        }
    }
    statusline::Statusline { app }.render(chunks[1], buf);
    status_bar::StatusBar { app }.render(chunks[2], buf);
}

fn draw_approvals_modal(f: &mut Frame<'_>, area: Rect, app: &App) {
    let buf = f.buffer_mut();
    render_approvals_modal(area, buf, app);
}

fn draw_compose_modal(f: &mut Frame<'_>, area: Rect, app: &App) {
    let buf = f.buffer_mut();
    render_compose_modal(area, buf, app);
}

fn render_compose_picker_body(inner: Rect, buf: &mut Buffer, app: &App) {
    let muted = Style::default().fg(app.capabilities.muted());
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Min(1),
            Constraint::Length(1),
            Constraint::Length(1),
        ])
        .split(inner);
    let lines: Vec<ratatui::text::Line<'_>> = if app.team.channels.is_empty() {
        vec![ratatui::text::Line::styled(
            "(no channels declared in team-compose)",
            muted,
        )]
    } else {
        app.team
            .channels
            .iter()
            .enumerate()
            .map(|(i, ch)| {
                let label = format!("  #{}  ({})", ch.name, ch.project_id);
                let style = if i == app.compose_picker_index {
                    Style::default()
                        .fg(app.capabilities.accent())
                        .add_modifier(Modifier::REVERSED)
                } else {
                    Style::default()
                };
                ratatui::text::Line::styled(label, style)
            })
            .collect()
    };
    Paragraph::new(lines).render(chunks[0], buf);
    Paragraph::new("pick a channel to broadcast to")
        .style(muted)
        .render(chunks[1], buf);
    Paragraph::new("Enter pick · j/k navigate · Esc cancel")
        .style(muted)
        .render(chunks[2], buf);
}

fn render_compose_modal(area: Rect, buf: &mut Buffer, app: &App) {
    let popup_w = 80u16.min(area.width.saturating_sub(4));
    let popup_h = 16u16.min(area.height.saturating_sub(2));
    let popup = centered_rect(popup_w, popup_h, area);
    Clear.render(popup, buf);
    let title = app
        .compose_target
        .as_ref()
        .map(|t| t.title(&app.team))
        .unwrap_or_else(|| "→ ?".into());
    let block = Block::default()
        .title(title)
        .borders(Borders::ALL)
        .border_style(Style::default().fg(app.capabilities.accent()));
    let inner = block.inner(popup);
    block.render(popup, buf);

    if inner.height < 3 {
        return;
    }
    // PR-UI-6: when the broadcast picker is open we render a
    // channel-list inside the modal instead of the editor; the
    // editor footer stays so operators see the same layout.
    if app.compose_picker_open {
        render_compose_picker_body(inner, buf, app);
        return;
    }
    if app.compose_attach_input_open {
        render_compose_attach_input(inner, buf, app);
        return;
    }
    // Reserve the bottom two rows: an error line (rendered when
    // present, blank otherwise) and the footer with key hints.
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Min(1),    // editor body
            Constraint::Length(1), // error / status
            Constraint::Length(1), // footer
        ])
        .split(inner);

    // Body — render lines with a `▏` cursor marker on the active
    // row when in Insert. Skip cursor cell in Normal/Ex modes so
    // the operator's eye finds the row by row context, not a
    // blinking caret.
    let muted = Style::default().fg(app.capabilities.muted());
    let body_lines: Vec<ratatui::text::Line<'_>> = app
        .compose_editor
        .lines
        .iter()
        .enumerate()
        .map(|(row, line)| {
            if row == app.compose_editor.cursor_row
                && app.compose_editor.mode == crate::compose::VimMode::Insert
            {
                let col = app.compose_editor.cursor_col.min(line.len());
                let (head, tail) = line.split_at(col);
                ratatui::text::Line::from(vec![
                    ratatui::text::Span::raw(head.to_string()),
                    ratatui::text::Span::styled(
                        "",
                        Style::default().fg(app.capabilities.accent()),
                    ),
                    ratatui::text::Span::raw(tail.to_string()),
                ])
            } else {
                ratatui::text::Line::raw(line.clone())
            }
        })
        .collect();
    Paragraph::new(body_lines).render(chunks[0], buf);

    let error_line = match (&app.compose_error, app.compose_editor.mode) {
        (Some(e), _) => format!("error: {e}"),
        (None, crate::compose::VimMode::Ex) => format!(":{}", app.compose_editor.ex_buffer),
        (None, crate::compose::VimMode::Normal) => "-- NORMAL --".into(),
        (None, crate::compose::VimMode::Insert) => "-- INSERT --".into(),
    };
    let style = if app.compose_error.is_some() {
        Style::default().fg(app.capabilities.accent())
    } else {
        muted
    };
    Paragraph::new(error_line)
        .style(style)
        .render(chunks[1], buf);

    Paragraph::new("Alt+Enter send · Esc Esc cancel · Tab attach")
        .style(muted)
        .render(chunks[2], buf);
}

/// T-32: render the path-input overlay. Single-line buffer + a
/// caret marker, with hints for confirm/cancel. Mirrors the picker
/// overlay's layout (body / status line / footer) so the modal's
/// vertical rhythm doesn't shift between the two overlays.
fn render_compose_attach_input(inner: Rect, buf: &mut Buffer, app: &App) {
    let muted = Style::default().fg(app.capabilities.muted());
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Min(1),
            Constraint::Length(1),
            Constraint::Length(1),
        ])
        .split(inner);
    let line = ratatui::text::Line::from(vec![
        ratatui::text::Span::raw(format!("path: {}", app.compose_attach_buffer)),
        ratatui::text::Span::styled("", Style::default().fg(app.capabilities.accent())),
    ]);
    Paragraph::new(line).render(chunks[0], buf);
    Paragraph::new("type or paste an absolute path; the agent reads it via the broker")
        .style(muted)
        .render(chunks[1], buf);
    Paragraph::new("Enter confirm · Esc cancel")
        .style(muted)
        .render(chunks[2], buf);
}

fn render_approvals_modal(area: Rect, buf: &mut Buffer, app: &App) {
    let popup_w = 80u16.min(area.width.saturating_sub(4));
    let popup_h = 18u16.min(area.height.saturating_sub(2));
    let popup = centered_rect(popup_w, popup_h, area);
    Clear.render(popup, buf);
    let n = app.pending_approvals.len();
    let i = app.selected_approval.min(n.saturating_sub(1));
    let title = format!("approvals · {}/{n}", i + 1);
    let block = Block::default()
        .title(title)
        .borders(Borders::ALL)
        .border_style(Style::default().fg(app.capabilities.accent()));
    let inner = block.inner(popup);
    block.render(popup, buf);

    let muted = Style::default().fg(app.capabilities.muted());
    let bold = Style::default().add_modifier(Modifier::BOLD);

    let Some(a) = app.focused_approval() else {
        Paragraph::new("(no pending approvals)")
            .style(muted)
            .alignment(Alignment::Center)
            .render(inner, buf);
        return;
    };

    let mut lines: Vec<ratatui::text::Line<'_>> = vec![
        ratatui::text::Line::styled(format!("#{}  {}", a.id, a.action), bold),
        ratatui::text::Line::styled(
            format!("from: {}", crate::data::agent_label(&app.team, &a.agent_id)),
            muted,
        ),
        ratatui::text::Line::raw(""),
        ratatui::text::Line::raw(a.summary.clone()),
    ];
    if !a.payload_json.is_empty() && a.payload_json != "{}" {
        lines.push(ratatui::text::Line::raw(""));
        lines.push(ratatui::text::Line::styled("payload:", muted));
        for chunk in a.payload_json.lines().take(4) {
            lines.push(ratatui::text::Line::raw(chunk.to_string()));
        }
    }
    if let Some(err) = &app.approval_error {
        lines.push(ratatui::text::Line::raw(""));
        lines.push(ratatui::text::Line::styled(
            format!("error: {err}"),
            Style::default().fg(app.capabilities.accent()),
        ));
    }
    lines.push(ratatui::text::Line::raw(""));
    lines.push(ratatui::text::Line::styled(
        "[y] approve  ·  [Shift-N] deny  ·  [j/k] cycle  ·  [Esc] close",
        muted,
    ));
    Paragraph::new(lines).render(inner, buf);
}

fn draw_quit_confirm(f: &mut Frame<'_>, area: Rect) {
    let popup_w = 36u16.min(area.width.saturating_sub(2));
    let popup_h = 5u16.min(area.height.saturating_sub(2));
    let popup = centered_rect(popup_w, popup_h, area);
    let buf = f.buffer_mut();
    Clear.render(popup, buf);
    Paragraph::new("Quit teamctl-ui?  [y / n]")
        .alignment(Alignment::Center)
        .block(Block::default().borders(Borders::ALL).title("confirm"))
        .render(popup, buf);
}

fn centered_rect(w: u16, h: u16, area: Rect) -> Rect {
    let x = area.x + area.width.saturating_sub(w) / 2;
    let y = area.y + area.height.saturating_sub(h) / 2;
    Rect {
        x,
        y,
        width: w,
        height: h,
    }
}

pub fn handle_event<D: ApprovalDecider, S: MessageSender, M: MailboxSource, K: KeySender>(
    app: &mut App,
    ev: Event,
    decider: &D,
    sender: &S,
    mailbox_source: &M,
    key_sender: &K,
) {
    use crossterm::event::KeyModifiers;
    match ev {
        Event::Key(k) if k.kind == KeyEventKind::Press => match app.stage {
            Stage::Splash => app.dismiss_splash(),
            Stage::Triptych => match k.code {
                // PR-UI-7 chord-prefix follow-ups MUST be tested
                // before unguarded `Char('q')` / `Char('o')` arms,
                // otherwise the no-modifier `q` quit would shadow
                // the `Ctrl+W q` close-split.
                KeyCode::Char('q') if app.pending_chord == Some(KeyCode::Char('w')) => {
                    app.pending_chord = None;
                    app.close_focused_split();
                }
                KeyCode::Char('o') if app.pending_chord == Some(KeyCode::Char('w')) => {
                    app.pending_chord = None;
                    if !app.detail_splits.is_empty() {
                        let keep = app.selected_split.min(app.detail_splits.len() - 1);
                        let kept = app.detail_splits.remove(keep);
                        app.detail_splits.clear();
                        app.detail_splits.push(kept);
                        app.selected_split = 0;
                    }
                }
                KeyCode::Char('q') if k.modifiers.is_empty() => app.enter_quit_confirm(),
                // PR-UI-4: `a` opens the approvals modal when there's
                // at least one pending row. No-op otherwise so the
                // chord doesn't surprise anyone hammering keys.
                KeyCode::Char('a') => app.enter_approvals_modal(),
                // PR-UI-5: `@` opens DM compose to focused agent.
                // PR-UI-6: `!` now opens the broadcast picker so
                // operators choose which channel to broadcast to,
                // not just the project's `all` wire.
                KeyCode::Char('@') => app.enter_compose_dm_for_focused(),
                KeyCode::Char('!') => app.enter_compose_broadcast_with_picker(),
                // PR-UI-7 chord-prefix: when there's at least one
                // detail split, `Ctrl+W` arms the chord-prefix
                // (the next key dispatches `q` close-split, `o`
                // close-others). Tested BEFORE the wall-layout
                // toggle below so the chord-prefix wins when
                // relevant. Both casings accepted because CapsLock
                // / Shift+Ctrl produce `Char('W')`; armed value is
                // normalised to lowercase so the follow-up arms
                // above can match a single literal.
                KeyCode::Char('w') | KeyCode::Char('W')
                    if k.modifiers.contains(KeyModifiers::CONTROL)
                        && !app.detail_splits.is_empty() =>
                {
                    app.pending_chord = Some(KeyCode::Char('w'))
                }
                // PR-UI-6: layout toggles. `Ctrl+W` for Wall when
                // there are no splits to chord on; `Ctrl+M` for
                // MailboxFirst (always). Both casings accepted —
                // see the chord-arm comment above.
                KeyCode::Char('w') | KeyCode::Char('W')
                    if k.modifiers.contains(KeyModifiers::CONTROL) =>
                {
                    app.toggle_wall_layout()
                }
                KeyCode::Char('m') | KeyCode::Char('M')
                    if k.modifiers.contains(KeyModifiers::CONTROL) =>
                {
                    app.toggle_mailbox_first_layout()
                }
                // PR-UI-7 splitscreen lift: `Ctrl+|` subdivides
                // vertically, `Ctrl+-` horizontally — vim/tmux
                // operators' muscle memory matches the visual.
                KeyCode::Char('|') if k.modifiers.contains(KeyModifiers::CONTROL) => {
                    app.add_detail_split_vertical()
                }
                KeyCode::Char('-') if k.modifiers.contains(KeyModifiers::CONTROL) => {
                    app.add_detail_split_horizontal()
                }
                // Vim window-motion `Ctrl+H/J/K/L` cycles between
                // splits when there's more than one. Both casings
                // accepted — see the Ctrl+W chord-arm comment above
                // for the CapsLock + Shift+Ctrl rationale.
                KeyCode::Char('h')
                | KeyCode::Char('H')
                | KeyCode::Char('k')
                | KeyCode::Char('K')
                    if k.modifiers.contains(KeyModifiers::CONTROL) =>
                {
                    app.cycle_split_prev()
                }
                KeyCode::Char('l')
                | KeyCode::Char('L')
                | KeyCode::Char('j')
                | KeyCode::Char('J')
                    if k.modifiers.contains(KeyModifiers::CONTROL) =>
                {
                    app.cycle_split_next()
                }
                // PR-UI-6 alias preserved for back-compat: `Ctrl+Q`
                // closes the focused split. PR-UI-7 also wires the
                // proper `Ctrl+W q` chord; both work. Both casings
                // accepted for the same reason as Ctrl+W/M.
                KeyCode::Char('q') | KeyCode::Char('Q')
                    if k.modifiers.contains(KeyModifiers::CONTROL) =>
                {
                    app.close_focused_split()
                }
                // T-108: `Ctrl+E` activates stream-keys mode when the
                // detail pane is focused — every subsequent keystroke
                // forwards to the agent's tmux pane. Gated on detail
                // focus so operators in the roster / mailbox don't
                // get pulled into stream-mode by a stray chord. Both
                // casings accepted for the CapsLock/Shift+Ctrl case
                // (same rationale as Ctrl+W/M arms above).
                KeyCode::Char('e') | KeyCode::Char('E')
                    if k.modifiers.contains(KeyModifiers::CONTROL)
                        && app.focused_pane == Pane::Detail =>
                {
                    app.enter_stream_keys()
                }
                // (chord-prefix follow-ups handled at top of arm
                // before unguarded letter-arms — see top of
                // `Stage::Triptych` match.)
                // PR-UI-7 help + tutorial chords. `?` opens help
                // overlay; `t` reopens tutorial. Both no-op if a
                // modifier is in flight (so `Shift+?` and `Ctrl+T`
                // don't double-bind).
                KeyCode::Char('?')
                    if k.modifiers.is_empty() || k.modifiers == KeyModifiers::SHIFT =>
                {
                    app.enter_help_overlay()
                }
                KeyCode::Char('t') if k.modifiers.is_empty() => app.enter_tutorial(),
                // PR-UI-4: Shift+Tab cycles panes backward. Some
                // terminals send `BackTab`, others send `Tab` with
                // SHIFT — handle both.
                KeyCode::BackTab => app.cycle_focus_back(),
                KeyCode::Tab if k.modifiers.contains(KeyModifiers::SHIFT) => app.cycle_focus_back(),
                // T-074 bug 6: Tab always cycles pane focus, never
                // mailbox tabs. Previously Tab routed into mailbox
                // tab-cycling when the mailbox pane was focused —
                // this stranded operators inside the mailbox with no
                // discoverable way out (Alireza's exact report). The
                // vim/tmux convention is "Tab moves between panes";
                // honour it across every pane uniformly.
                KeyCode::Tab => app.cycle_focus(),
                // T-124: mailbox sub-navigation uses Left/Right
                // arrows (more discoverable than the prior `[`/`]`
                // chord). Gated on the mailbox pane being focused
                // so the keys stay unsurprising elsewhere — Up/Down
                // remain free to scroll layout-specific lists, and
                // Left/Right have no other binding today.
                KeyCode::Right if app.focused_pane == Pane::Mailbox => app.cycle_mailbox_tab(),
                KeyCode::Left if app.focused_pane == Pane::Mailbox => app.cycle_mailbox_tab_back(),
                // PR-UI-6: in Wall layout, `j`/`k` (and arrows)
                // scroll the tile grid — same vim shape, different
                // surface. In Triptych roster focus they still
                // navigate the roster.
                KeyCode::Up | KeyCode::Char('k') if matches!(app.layout, MainLayout::Wall) => {
                    app.wall_scroll_up()
                }
                KeyCode::Down | KeyCode::Char('j') if matches!(app.layout, MainLayout::Wall) => {
                    app.wall_scroll_down()
                }
                // PR-UI-6: in MailboxFirst, `j`/`k` walk the
                // channel list.
                KeyCode::Up | KeyCode::Char('k')
                    if matches!(app.layout, MainLayout::MailboxFirst) =>
                {
                    app.select_prev_channel()
                }
                KeyCode::Down | KeyCode::Char('j')
                    if matches!(app.layout, MainLayout::MailboxFirst) =>
                {
                    app.select_next_channel()
                }
                // Roster navigation — only when roster is the
                // focused pane. j/k mirror Vim; arrows mirror
                // every-day navigation.
                KeyCode::Up | KeyCode::Char('k') if app.focused_pane == Pane::Roster => {
                    app.select_prev()
                }
                KeyCode::Down | KeyCode::Char('j') if app.focused_pane == Pane::Roster => {
                    app.select_next()
                }
                _ => {}
            },
            Stage::QuitConfirm => match k.code {
                KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => app.confirm_quit(),
                KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => app.cancel_quit(),
                _ => {}
            },
            Stage::ApprovalsModal => match k.code {
                // Asymmetric chord shape (T-074 bug 4 fix): approve is
                // the common path so it accepts both `y` and `Y` —
                // matches QuitConfirm's loose convention and the
                // muscle-memory most TUI prompts build. Deny is the
                // destructive side, so it requires deliberate Shift
                // (`N` only); a stray lowercase `n` does nothing.
                // Trades cosmetic chord-symmetry for discoverability
                // on the load-bearing approve flow.
                KeyCode::Char('y') | KeyCode::Char('Y') => {
                    app.apply_decision(decider, Decision::Approve, "")
                }
                KeyCode::Char('N') => app.apply_decision(decider, Decision::Deny, ""),
                KeyCode::Char('j') | KeyCode::Down => app.cycle_approval_next(),
                KeyCode::Char('k') | KeyCode::Up => app.cycle_approval_prev(),
                KeyCode::Esc | KeyCode::Char('q') => app.close_approvals_modal(),
                _ => {}
            },
            Stage::ComposeModal => {
                // PR-UI-6: when the broadcast picker is open the
                // editor doesn't see keys yet — operator first
                // chooses a channel.
                if app.compose_picker_open {
                    match k.code {
                        KeyCode::Down | KeyCode::Char('j') => app.picker_next(),
                        KeyCode::Up | KeyCode::Char('k') => app.picker_prev(),
                        KeyCode::Enter => app.picker_confirm(),
                        // PR-UI-6 fixup (Q6, dev2 review): Esc
                        // dismisses the picker overlay only and
                        // returns to the editor with whatever the
                        // operator already typed; the editor's own
                        // Esc-Esc cancel-the-modal flow handles
                        // bailing out of the whole compose. Mirrors
                        // the overlay-vs-modal symmetry vim users
                        // expect.
                        KeyCode::Esc => {
                            app.compose_picker_open = false;
                            app.compose_picker_index = 0;
                        }
                        _ => {}
                    }
                } else if app.compose_attach_input_open {
                    // T-32: path-input overlay. Keys edit the buffer
                    // directly; Enter confirms (appends marker line
                    // to the editor body); Esc cancels back to the
                    // editor. Same overlay-vs-modal symmetry as the
                    // picker — Esc dismisses *the overlay*, not the
                    // whole compose.
                    match k.code {
                        KeyCode::Char(c) => app.compose_attach_buffer.push(c),
                        KeyCode::Backspace => {
                            app.compose_attach_buffer.pop();
                        }
                        KeyCode::Enter => app.confirm_compose_attach_input(),
                        KeyCode::Esc => app.close_compose_attach_input(),
                        _ => {}
                    }
                } else if k.code == KeyCode::Tab {
                    // T-32: Tab opens the path-input overlay. The
                    // editor never sees Tab today (apply_insert
                    // ignores it), so intercepting here doesn't
                    // change the editor's surface.
                    app.open_compose_attach_input();
                } else {
                    // Route every keypress through the editor; the
                    // editor returns Send / Cancel / Continue.
                    match app.compose_editor.apply_key(k) {
                        EditorAction::Continue => {}
                        EditorAction::Send => app.apply_send(sender, mailbox_source),
                        EditorAction::Cancel => app.close_compose_modal(),
                    }
                }
            }
            Stage::HelpOverlay => match k.code {
                KeyCode::Esc | KeyCode::Char('?') | KeyCode::Char('q') => app.close_help_overlay(),
                _ => {}
            },
            Stage::Tutorial => match k.code {
                KeyCode::Esc => app.close_tutorial(),
                KeyCode::Char('k') | KeyCode::Up | KeyCode::Char('p') => app.tutorial_back(),
                _ => app.tutorial_advance(),
            },
            // T-108 stream-keys mode. Esc is the only chord we
            // intercept — every other key (including `Ctrl+C`,
            // `Ctrl+E`, arrow keys, `Enter`) forwards to the agent's
            // tmux pane. The pass-through behaviour is intentional:
            // the operator is "effectively attached," and a shell-
            // user's Ctrl+C should send SIGINT to the agent, not
            // bail them out of the mode they just entered.
            Stage::StreamKeys => {
                if matches!(k.code, KeyCode::Esc) {
                    app.exit_stream_keys();
                } else if let Some(session) = app.stream_target_session() {
                    if let Some(encoded) = encode_key(k) {
                        // Best-effort: a tmux failure (session
                        // vanished, target pane gone) is silent in
                        // v1; the next refresh tick reflects whatever
                        // the agent's pane actually shows.
                        let _ = key_sender.send(&session, &encoded);
                    }
                } else {
                    // Target session disappeared mid-stream (agent
                    // restarted, team reloaded). Drop back to
                    // Triptych so the operator isn't typing into the
                    // void with no feedback.
                    app.exit_stream_keys();
                }
            }
        },
        Event::Resize(_, _) => {
            // ratatui redraws on the next loop iteration; nothing to do.
        }
        // T-158: mouse-wheel routes by focused pane. Detail forwards
        // each tick to the agent's tmux pane as a copy-mode scroll —
        // wheel-up enters copy-mode and walks history, wheel-down
        // walks back toward live. Roster steps the agent selection
        // (same step as `j`/`k`). Mailbox is a no-op until T-131
        // lands the row-cursor state for the rows to scroll; the
        // routing scaffold is in place so that fill-in is local.
        // Stages other than Triptych ignore mouse input — modal
        // overlays (compose, approvals, picker, help) own the screen
        // and shouldn't get a surprise scroll routed past them.
        Event::Mouse(m) if matches!(app.stage, Stage::Triptych) => {
            use crossterm::event::MouseEventKind;
            let direction = match m.kind {
                MouseEventKind::ScrollUp => Some(ScrollDirection::Up),
                MouseEventKind::ScrollDown => Some(ScrollDirection::Down),
                _ => None,
            };
            if let Some(dir) = direction {
                match app.focused_pane {
                    Pane::Detail => {
                        if let Some(session) = app.focused_session().map(|s| s.to_string()) {
                            // Best-effort, same convention as
                            // stream-keys: tmux failure (session
                            // vanished) is silent; the next refresh
                            // reflects reality.
                            let _ = key_sender.scroll(&session, dir);
                        }
                    }
                    Pane::Roster => match dir {
                        ScrollDirection::Up => app.select_prev(),
                        ScrollDirection::Down => app.select_next(),
                    },
                    Pane::Mailbox => {
                        // T-131 will wire row-level scroll state
                        // here. v1 ships the routing only.
                    }
                }
            }
        }
        _ => {}
    }
}

/// Render the entire UI into a `Buffer` at fixed size — used by the
/// snapshot tests. Mirrors `draw` exactly but doesn't require a
/// `Terminal`. Update both in lockstep when adding new stages.
pub fn render_to_buffer(app: &App, width: u16, height: u16) -> Buffer {
    let area = Rect::new(0, 0, width, height);
    let mut buf = Buffer::empty(area);
    match app.stage {
        Stage::Splash => splash::Splash { app }.render(area, &mut buf),
        Stage::Triptych => render_main(app, area, &mut buf),
        Stage::StreamKeys => render_main(app, area, &mut buf),
        Stage::QuitConfirm => {
            render_main(app, area, &mut buf);
            render_quit_confirm(area, &mut buf);
        }
        Stage::ApprovalsModal => {
            render_main(app, area, &mut buf);
            render_approvals_modal(area, &mut buf, app);
        }
        Stage::ComposeModal => {
            render_main(app, area, &mut buf);
            render_compose_modal(area, &mut buf, app);
        }
        Stage::HelpOverlay => {
            render_main(app, area, &mut buf);
            render_help_overlay(area, &mut buf, app);
        }
        Stage::Tutorial => {
            render_main(app, area, &mut buf);
            render_tutorial(area, &mut buf, app);
        }
    }
    buf
}

fn render_main(app: &App, area: Rect, buf: &mut Buffer) {
    // T-209: two-row footer — keep this in lockstep with `draw_main`
    // (snapshot tests render via this fn, the runtime via the other).
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Min(3),
            Constraint::Length(1), // existing keybindings statusline
            Constraint::Length(1), // T-209 bottom status bar
        ])
        .split(area);
    match app.layout {
        crate::triptych::MainLayout::Triptych => {
            triptych::Triptych { app }.render(chunks[0], buf);
        }
        crate::triptych::MainLayout::Wall => {
            layouts::Wall { app }.render(chunks[0], buf);
        }
        crate::triptych::MainLayout::MailboxFirst => {
            layouts::MailboxFirst { app }.render(chunks[0], buf);
        }
    }
    statusline::Statusline { app }.render(chunks[1], buf);
    status_bar::StatusBar { app }.render(chunks[2], buf);
}

fn render_quit_confirm(area: Rect, buf: &mut Buffer) {
    let popup_w = 36u16.min(area.width.saturating_sub(2));
    let popup_h = 5u16.min(area.height.saturating_sub(2));
    let popup = centered_rect(popup_w, popup_h, area);
    Clear.render(popup, buf);
    Paragraph::new("Quit teamctl-ui?  [y / n]")
        .alignment(Alignment::Center)
        .block(Block::default().borders(Borders::ALL).title("confirm"))
        .render(popup, buf);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data::AgentInfo;
    use crossterm::event::{KeyEvent, KeyEventState, KeyModifiers};
    use team_core::supervisor::AgentState;

    fn key(code: KeyCode) -> Event {
        Event::Key(KeyEvent {
            code,
            modifiers: KeyModifiers::NONE,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        })
    }

    fn key_with(code: KeyCode, modifiers: KeyModifiers) -> Event {
        Event::Key(KeyEvent {
            code,
            modifiers,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        })
    }

    /// Noop decider for tests that don't exercise approve/deny.
    struct NoopDecider;
    impl crate::approvals::ApprovalDecider for NoopDecider {
        fn decide(
            &self,
            _root: &std::path::Path,
            _id: i64,
            _kind: crate::approvals::Decision,
            _note: &str,
        ) -> anyhow::Result<()> {
            Ok(())
        }
    }

    /// Noop sender for tests that don't exercise compose-send.
    struct NoopSender;
    impl crate::compose::MessageSender for NoopSender {
        fn send_dm(
            &self,
            _root: &std::path::Path,
            _agent: &str,
            _body: &str,
        ) -> anyhow::Result<()> {
            Ok(())
        }
        fn broadcast(
            &self,
            _root: &std::path::Path,
            _channel: &str,
            _body: &str,
        ) -> anyhow::Result<()> {
            Ok(())
        }
    }

    /// Mailbox source that returns nothing — refresh_mailbox after
    /// a successful send becomes a no-op.
    struct EmptyMailbox;
    impl crate::mailbox::MailboxSource for EmptyMailbox {
        fn inbox(&self, _id: &str, _after: i64) -> anyhow::Result<Vec<crate::mailbox::MessageRow>> {
            Ok(Vec::new())
        }
        fn sent(&self, _id: &str, _after: i64) -> anyhow::Result<Vec<crate::mailbox::MessageRow>> {
            Ok(Vec::new())
        }
        fn channel_feed(
            &self,
            _id: &str,
            _after: i64,
        ) -> anyhow::Result<Vec<crate::mailbox::MessageRow>> {
            Ok(Vec::new())
        }
        fn wire(&self, _id: &str, _after: i64) -> anyhow::Result<Vec<crate::mailbox::MessageRow>> {
            Ok(Vec::new())
        }
    }

    /// Boilerplate-free dispatcher for tests not exercising the
    /// decision / send paths.
    fn dispatch(app: &mut App, ev: Event) {
        super::handle_event(
            app,
            ev,
            &NoopDecider,
            &NoopSender,
            &EmptyMailbox,
            &crate::keysender::test_support::MockKeySender::default(),
        );
    }

    fn agent(id: &str, state: AgentState) -> AgentInfo {
        AgentInfo {
            id: id.into(),
            agent: id
                .split_once(':')
                .map(|(_, a)| a.to_string())
                .unwrap_or_default(),
            project: id
                .split_once(':')
                .map(|(p, _)| p.to_string())
                .unwrap_or_default(),
            tmux_session: format!("t-{}", id.replace(':', "-")),
            state,
            unread_mail: 0,
            pending_approvals: 0,
            is_manager: false,
            display_name: None,
            rate_limit_resets_at: None,
            reports_to: None,
        }
    }

    pub fn fixture_team(agents: Vec<AgentInfo>) -> TeamSnapshot {
        TeamSnapshot {
            root: std::path::PathBuf::from("/fixture"),
            team_name: "fixture".into(),
            agents,
            channels: Vec::new(),
        }
    }

    #[test]
    fn splash_dismissed_by_any_key() {
        let mut app = App::new();
        assert_eq!(app.stage, Stage::Splash);
        dispatch(&mut app, key(KeyCode::Char(' ')));
        assert_eq!(app.stage, Stage::Triptych);
    }

    #[test]
    fn tab_cycles_panes_uniformly_and_wraps_through_mailbox() {
        // T-074 bug 6: Tab cycles pane focus only — Roster → Detail
        // → Mailbox → Roster — at every step. The previous "Tab
        // cycles tabs once focused on mailbox" shape stranded
        // operators inside the mailbox; this test pins the corrected
        // uniform cycle so a future refactor can't reintroduce the
        // dead-end.
        let mut app = App::new();
        app.dismiss_splash();
        assert_eq!(app.focused_pane, Pane::Roster);
        dispatch(&mut app, key(KeyCode::Tab));
        assert_eq!(app.focused_pane, Pane::Detail);
        dispatch(&mut app, key(KeyCode::Tab));
        assert_eq!(app.focused_pane, Pane::Mailbox);
        assert_eq!(
            app.mailbox_tab,
            MailboxTab::Inbox,
            "Tab into mailbox does NOT touch the active mailbox tab"
        );
        dispatch(&mut app, key(KeyCode::Tab));
        assert_eq!(
            app.focused_pane,
            Pane::Roster,
            "Tab from mailbox wraps to roster, not into mailbox subtabs"
        );
        assert_eq!(
            app.mailbox_tab,
            MailboxTab::Inbox,
            "mailbox tab still untouched"
        );
    }

    #[test]
    fn arrow_keys_walk_mailbox_tabs_when_mailbox_focused() {
        // T-124: Right/Left arrows are the mailbox-tab walker
        // (more discoverable than the prior `[`/`]` chord). Gated
        // on mailbox being the focused pane so the arrows stay
        // unsurprising in every other context.
        let mut app = App::new();
        app.dismiss_splash();
        // Walk into mailbox via Tab.
        dispatch(&mut app, key(KeyCode::Tab));
        dispatch(&mut app, key(KeyCode::Tab));
        assert_eq!(app.focused_pane, Pane::Mailbox);
        assert_eq!(app.mailbox_tab, MailboxTab::Inbox);

        dispatch(&mut app, key(KeyCode::Right));
        assert_eq!(app.mailbox_tab, MailboxTab::Sent);
        dispatch(&mut app, key(KeyCode::Right));
        assert_eq!(app.mailbox_tab, MailboxTab::Channel);
        dispatch(&mut app, key(KeyCode::Right));
        assert_eq!(app.mailbox_tab, MailboxTab::Wire);
        dispatch(&mut app, key(KeyCode::Right));
        assert_eq!(app.mailbox_tab, MailboxTab::Inbox, "→ wraps");

        dispatch(&mut app, key(KeyCode::Left));
        assert_eq!(app.mailbox_tab, MailboxTab::Wire, "← walks back");
    }

    #[test]
    fn arrow_keys_no_op_when_mailbox_not_focused() {
        // The arrows must not surprise an operator scrolling the
        // roster — gate is load-bearing.
        let mut app = App::new();
        app.dismiss_splash();
        assert_eq!(app.focused_pane, Pane::Roster);
        let initial = app.mailbox_tab;
        dispatch(&mut app, key(KeyCode::Right));
        dispatch(&mut app, key(KeyCode::Left));
        assert_eq!(
            app.mailbox_tab, initial,
            "←/→ from non-mailbox panes must not flip the active tab"
        );
    }

    #[test]
    fn brackets_no_longer_cycle_mailbox_tabs() {
        // T-124 regression: `[` / `]` were the previous binding;
        // hard-swap means they are now fully inert in the mailbox
        // pane. Pin the no-op so a future binding can't quietly
        // re-introduce the old chord.
        let mut app = App::new();
        app.dismiss_splash();
        dispatch(&mut app, key(KeyCode::Tab));
        dispatch(&mut app, key(KeyCode::Tab));
        assert_eq!(app.focused_pane, Pane::Mailbox);
        let initial = app.mailbox_tab;

        dispatch(&mut app, key(KeyCode::Char(']')));
        dispatch(&mut app, key(KeyCode::Char('[')));
        assert_eq!(
            app.mailbox_tab, initial,
            "`[` / `]` must no longer cycle mailbox tabs (T-124 hard-swap)",
        );
    }

    #[test]
    fn q_opens_confirm_then_n_cancels() {
        let mut app = App::new();
        app.dismiss_splash();
        dispatch(&mut app, key(KeyCode::Char('q')));
        assert_eq!(app.stage, Stage::QuitConfirm);
        dispatch(&mut app, key(KeyCode::Char('n')));
        assert_eq!(app.stage, Stage::Triptych);
        assert!(app.running, "n must not exit");
    }

    #[test]
    fn q_then_y_exits() {
        let mut app = App::new();
        app.dismiss_splash();
        dispatch(&mut app, key(KeyCode::Char('q')));
        dispatch(&mut app, key(KeyCode::Char('y')));
        assert!(!app.running);
    }

    #[test]
    fn esc_cancels_quit_confirm() {
        let mut app = App::new();
        app.dismiss_splash();
        app.enter_quit_confirm();
        dispatch(&mut app, key(KeyCode::Esc));
        assert_eq!(app.stage, Stage::Triptych);
    }

    #[test]
    fn render_does_not_panic_at_minimal_size() {
        let app = App::new();
        let _ = render_to_buffer(&app, 20, 8);
    }

    #[test]
    fn render_does_not_panic_at_huge_size() {
        let app = App::new();
        let _ = render_to_buffer(&app, 240, 80);
    }

    #[test]
    fn select_next_wraps_through_team() {
        let mut app = App::new();
        app.replace_team(fixture_team(vec![
            agent("p:a", AgentState::Running),
            agent("p:b", AgentState::Running),
            agent("p:c", AgentState::Running),
        ]));
        assert_eq!(app.selected_agent, Some(0));
        app.select_next();
        assert_eq!(app.selected_agent, Some(1));
        app.select_next();
        assert_eq!(app.selected_agent, Some(2));
        app.select_next();
        assert_eq!(app.selected_agent, Some(0)); // wraps
    }

    #[test]
    fn select_prev_wraps_at_top() {
        let mut app = App::new();
        app.replace_team(fixture_team(vec![
            agent("p:a", AgentState::Running),
            agent("p:b", AgentState::Running),
        ]));
        app.selected_agent = Some(0);
        app.select_prev();
        assert_eq!(app.selected_agent, Some(1));
    }

    #[test]
    fn select_no_op_on_empty_team() {
        let mut app = App::new();
        app.select_next();
        assert_eq!(app.selected_agent, None);
        app.select_prev();
        assert_eq!(app.selected_agent, None);
    }

    #[test]
    fn replace_team_preserves_selection_when_agent_still_present() {
        let mut app = App::new();
        app.replace_team(fixture_team(vec![
            agent("p:a", AgentState::Running),
            agent("p:b", AgentState::Running),
        ]));
        app.selected_agent = Some(1);
        app.replace_team(fixture_team(vec![
            agent("p:a", AgentState::Running),
            agent("p:b", AgentState::Stopped), // same id, new state
        ]));
        assert_eq!(app.selected_agent, Some(1), "selection follows the id");
    }

    #[test]
    fn replace_team_resets_selection_when_agent_disappears() {
        let mut app = App::new();
        app.replace_team(fixture_team(vec![
            agent("p:a", AgentState::Running),
            agent("p:gone", AgentState::Running),
        ]));
        app.selected_agent = Some(1);
        app.replace_team(fixture_team(vec![agent("p:a", AgentState::Running)]));
        assert_eq!(app.selected_agent, Some(0), "falls back to first agent");
    }

    #[test]
    fn switching_agent_resets_mailbox_buffers() {
        // The mailbox cursors are per-agent context; switching to a
        // new agent must clear them so we don't skip historical
        // rows that landed before the new agent's first refresh.
        let mut app = App::new();
        app.replace_team(fixture_team(vec![
            agent("p:a", AgentState::Running),
            agent("p:b", AgentState::Running),
        ]));
        app.mailbox.extend(
            crate::mailbox::MailboxTab::Inbox,
            vec![crate::mailbox::MessageRow {
                id: 7,
                sender: "p:b".into(),
                recipient: "p:a".into(),
                text: "hi".into(),
                sent_at: 0.0,
            }],
        );
        assert_eq!(app.mailbox.inbox.len(), 1);
        assert_eq!(app.mailbox.inbox_after, 7);
        // Move selection to p:b — different agent id, mailbox resets.
        app.select_next();
        assert_eq!(app.selected_agent_id().as_deref(), Some("p:b"));
        assert!(app.mailbox.inbox.is_empty());
        assert_eq!(app.mailbox.inbox_after, 0);
    }

    /// Tiny single-call mailbox stub for the refresh-fanout test —
    /// keeps the assertion local without depending on
    /// `mailbox::tests::MockMailboxSource` (which lives behind a
    /// private `tests` module).
    struct TripleFilterMock {
        inbox: Vec<crate::mailbox::MessageRow>,
        sent: Vec<crate::mailbox::MessageRow>,
        channel: Vec<crate::mailbox::MessageRow>,
        wire: Vec<crate::mailbox::MessageRow>,
        calls: std::sync::Mutex<Vec<(&'static str, String, i64)>>,
    }
    impl crate::mailbox::MailboxSource for TripleFilterMock {
        fn inbox(&self, id: &str, after: i64) -> anyhow::Result<Vec<crate::mailbox::MessageRow>> {
            self.calls.lock().unwrap().push(("inbox", id.into(), after));
            Ok(self.inbox.clone())
        }
        fn sent(&self, id: &str, after: i64) -> anyhow::Result<Vec<crate::mailbox::MessageRow>> {
            self.calls.lock().unwrap().push(("sent", id.into(), after));
            Ok(self.sent.clone())
        }
        fn channel_feed(
            &self,
            id: &str,
            after: i64,
        ) -> anyhow::Result<Vec<crate::mailbox::MessageRow>> {
            self.calls
                .lock()
                .unwrap()
                .push(("channel", id.into(), after));
            Ok(self.channel.clone())
        }
        fn wire(&self, id: &str, after: i64) -> anyhow::Result<Vec<crate::mailbox::MessageRow>> {
            self.calls.lock().unwrap().push(("wire", id.into(), after));
            Ok(self.wire.clone())
        }
    }

    #[test]
    fn refresh_mailbox_fans_out_to_four_filters() {
        use crate::mailbox::MessageRow;
        let mut app = App::new();
        app.replace_team(fixture_team(vec![agent("p:a", AgentState::Running)]));
        let mock = TripleFilterMock {
            inbox: vec![MessageRow {
                id: 1,
                sender: "p:b".into(),
                recipient: "p:a".into(),
                text: "dm".into(),
                sent_at: 0.0,
            }],
            sent: vec![MessageRow {
                id: 4,
                sender: "p:a".into(),
                recipient: "p:b".into(),
                text: "outgoing dm".into(),
                sent_at: 0.0,
            }],
            channel: vec![MessageRow {
                id: 2,
                sender: "p:b".into(),
                recipient: "channel:p:editorial".into(),
                text: "ch".into(),
                sent_at: 0.0,
            }],
            wire: vec![MessageRow {
                id: 3,
                sender: "p:b".into(),
                recipient: "channel:p:all".into(),
                text: "wire".into(),
                sent_at: 0.0,
            }],
            calls: std::sync::Mutex::new(Vec::new()),
        };
        super::refresh_mailbox(&mut app, &mock);
        assert_eq!(app.mailbox.inbox.len(), 1);
        assert_eq!(app.mailbox.sent.len(), 1);
        assert_eq!(app.mailbox.channel.len(), 1);
        assert_eq!(app.mailbox.wire.len(), 1);
        let calls = mock.calls.lock().unwrap();
        // The selected agent is p:a (auto-set by replace_team to
        // index 0); the wire filter takes the project id `p`.
        assert!(calls.contains(&("inbox", "p:a".into(), 0)));
        assert!(calls.contains(&("sent", "p:a".into(), 0)));
        assert!(calls.contains(&("channel", "p:a".into(), 0)));
        assert!(calls.contains(&("wire", "p".into(), 0)));
    }

    fn ap(id: i64) -> crate::approvals::Approval {
        crate::approvals::Approval {
            id,
            project_id: "p".into(),
            agent_id: "p:m".into(),
            action: "publish".into(),
            summary: format!("approval #{id}"),
            payload_json: String::new(),
        }
    }

    #[test]
    fn has_pending_approvals_tracks_replace_calls() {
        let mut app = App::new();
        assert!(!app.has_pending_approvals());
        app.replace_approvals(vec![ap(1), ap(2)]);
        assert!(app.has_pending_approvals());
        app.replace_approvals(vec![]);
        assert!(!app.has_pending_approvals());
    }

    #[test]
    fn enter_approvals_modal_no_op_when_queue_empty() {
        let mut app = App::new();
        app.dismiss_splash();
        app.enter_approvals_modal();
        assert_eq!(app.stage, Stage::Triptych, "no pending → no modal");
    }

    #[test]
    fn a_chord_opens_modal_when_pending() {
        let mut app = App::new();
        app.dismiss_splash();
        app.replace_approvals(vec![ap(1), ap(2)]);
        dispatch(&mut app, key(KeyCode::Char('a')));
        assert_eq!(app.stage, Stage::ApprovalsModal);
        assert_eq!(app.selected_approval, 0);
    }

    #[test]
    fn modal_cycle_jk_walks_approvals() {
        let mut app = App::new();
        app.dismiss_splash();
        app.replace_approvals(vec![ap(1), ap(2), ap(3)]);
        app.enter_approvals_modal();
        dispatch(&mut app, key(KeyCode::Char('j')));
        assert_eq!(app.selected_approval, 1);
        dispatch(&mut app, key(KeyCode::Char('j')));
        assert_eq!(app.selected_approval, 2);
        dispatch(&mut app, key(KeyCode::Char('j')));
        assert_eq!(app.selected_approval, 0, "wraps");
        dispatch(&mut app, key(KeyCode::Char('k')));
        assert_eq!(app.selected_approval, 2, "k wraps too");
    }

    #[test]
    fn capital_y_routes_approve_through_decider() {
        use crate::approvals::test_support::MockApprovalDecider;
        let dec = MockApprovalDecider::default();
        let mut app = App::new();
        app.dismiss_splash();
        app.replace_approvals(vec![ap(7), ap(8)]);
        app.enter_approvals_modal();
        super::handle_event(
            &mut app,
            key(KeyCode::Char('Y')),
            &dec,
            &NoopSender,
            &EmptyMailbox,
            &crate::keysender::test_support::MockKeySender::default(),
        );
        let calls = dec.calls.lock().unwrap().clone();
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].0, 7);
        assert_eq!(calls[0].1, crate::approvals::Decision::Approve);
        // Optimistic local removal — approval id 7 dropped.
        assert_eq!(app.pending_approvals.len(), 1);
        assert_eq!(app.pending_approvals[0].id, 8);
    }

    #[test]
    fn capital_n_routes_deny_through_decider() {
        use crate::approvals::test_support::MockApprovalDecider;
        let dec = MockApprovalDecider::default();
        let mut app = App::new();
        app.dismiss_splash();
        app.replace_approvals(vec![ap(7)]);
        app.enter_approvals_modal();
        super::handle_event(
            &mut app,
            key(KeyCode::Char('N')),
            &dec,
            &NoopSender,
            &EmptyMailbox,
            &crate::keysender::test_support::MockKeySender::default(),
        );
        let calls = dec.calls.lock().unwrap().clone();
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].1, crate::approvals::Decision::Deny);
        // Queue empty after the only approval resolves → modal closes.
        assert_eq!(app.stage, Stage::Triptych);
    }

    #[test]
    fn esc_closes_approvals_modal() {
        let mut app = App::new();
        app.dismiss_splash();
        app.replace_approvals(vec![ap(1)]);
        app.enter_approvals_modal();
        dispatch(&mut app, key(KeyCode::Esc));
        assert_eq!(app.stage, Stage::Triptych);
    }

    #[test]
    fn lowercase_y_routes_approve_through_decider() {
        // T-074 bug 4: discoverable approve. Most operators try
        // lowercase first; the modal must accept it on the
        // approve (low-risk) side. Deny stays Shift-gated.
        use crate::approvals::test_support::MockApprovalDecider;
        let dec = MockApprovalDecider::default();
        let mut app = App::new();
        app.dismiss_splash();
        app.replace_approvals(vec![ap(7)]);
        app.enter_approvals_modal();
        super::handle_event(
            &mut app,
            key(KeyCode::Char('y')),
            &dec,
            &NoopSender,
            &EmptyMailbox,
            &crate::keysender::test_support::MockKeySender::default(),
        );
        let calls = dec.calls.lock().unwrap().clone();
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].1, crate::approvals::Decision::Approve);
    }

    #[test]
    fn lowercase_n_does_not_deny() {
        // Asymmetry guard: deny is destructive — `n` lowercase must
        // NOT fire the decider. A future "symmetric loose" refactor
        // would silently regress the destructive-deny Shift-gate;
        // this test pins it.
        use crate::approvals::test_support::MockApprovalDecider;
        let dec = MockApprovalDecider::default();
        let mut app = App::new();
        app.dismiss_splash();
        app.replace_approvals(vec![ap(7)]);
        app.enter_approvals_modal();
        super::handle_event(
            &mut app,
            key(KeyCode::Char('n')),
            &dec,
            &NoopSender,
            &EmptyMailbox,
            &crate::keysender::test_support::MockKeySender::default(),
        );
        assert!(
            dec.calls.lock().unwrap().is_empty(),
            "lowercase n must not route through the decider"
        );
        assert_eq!(
            app.stage,
            Stage::ApprovalsModal,
            "stale lowercase n leaves the modal open"
        );
    }

    #[test]
    fn shift_tab_cycles_panes_backward() {
        use crossterm::event::KeyModifiers;
        let mut app = App::new();
        app.dismiss_splash();
        assert_eq!(app.focused_pane, Pane::Roster);
        // Shift+Tab from Roster → Mailbox (the "back out of mailbox"
        // direction's mirror).
        dispatch(&mut app, key(KeyCode::BackTab));
        assert_eq!(app.focused_pane, Pane::Mailbox);
        // Some terminals send Tab + SHIFT instead of BackTab.
        dispatch(&mut app, key_with(KeyCode::Tab, KeyModifiers::SHIFT));
        assert_eq!(app.focused_pane, Pane::Detail);
    }

    #[test]
    fn at_chord_opens_compose_dm_to_focused_agent() {
        let mut app = App::new();
        app.replace_team(fixture_team(vec![
            agent("writing:manager", AgentState::Running),
            agent("writing:dev1", AgentState::Running),
        ]));
        app.dismiss_splash();
        app.select_next();
        dispatch(&mut app, key(KeyCode::Char('@')));
        assert_eq!(app.stage, Stage::ComposeModal);
        match app.compose_target.as_ref() {
            Some(crate::compose::ComposeTarget::Dm { agent_id, .. }) => {
                assert_eq!(agent_id, "writing:dev1");
            }
            other => panic!("expected DM target, got {other:?}"),
        }
    }

    #[test]
    fn bang_chord_opens_compose_broadcast_to_all_channel() {
        let mut app = App::new();
        app.replace_team(fixture_team(vec![agent(
            "writing:manager",
            AgentState::Running,
        )]));
        app.dismiss_splash();
        dispatch(&mut app, key(KeyCode::Char('!')));
        assert_eq!(app.stage, Stage::ComposeModal);
        match app.compose_target.as_ref() {
            Some(crate::compose::ComposeTarget::Broadcast { channel_id, .. }) => {
                assert_eq!(channel_id, "writing:all");
            }
            other => panic!("expected Broadcast target, got {other:?}"),
        }
    }

    #[test]
    fn send_routes_dm_through_mock_sender() {
        use crate::compose::test_support::MockMessageSender;
        let sender = MockMessageSender::default();
        let mailbox = EmptyMailbox;
        let mut app = App::new();
        app.replace_team(fixture_team(vec![agent(
            "writing:dev1",
            AgentState::Running,
        )]));
        app.dismiss_splash();
        app.enter_compose_dm_for_focused();
        for c in "ship it".chars() {
            super::handle_event(
                &mut app,
                key(KeyCode::Char(c)),
                &NoopDecider,
                &sender,
                &mailbox,
                &crate::keysender::test_support::MockKeySender::default(),
            );
        }
        super::handle_event(
            &mut app,
            key_with(KeyCode::Enter, crossterm::event::KeyModifiers::CONTROL),
            &NoopDecider,
            &sender,
            &mailbox,
            &crate::keysender::test_support::MockKeySender::default(),
        );
        let calls = sender.dm_calls.lock().unwrap().clone();
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].0, "writing:dev1");
        assert_eq!(calls[0].1, "ship it");
        assert_eq!(app.stage, Stage::Triptych, "modal closes on send");
    }

    #[test]
    fn esc_esc_cancels_compose_without_send() {
        use crate::compose::test_support::MockMessageSender;
        let sender = MockMessageSender::default();
        let mailbox = EmptyMailbox;
        let mut app = App::new();
        app.replace_team(fixture_team(vec![agent(
            "writing:dev1",
            AgentState::Running,
        )]));
        app.dismiss_splash();
        app.enter_compose_dm_for_focused();
        for c in "draft".chars() {
            super::handle_event(
                &mut app,
                key(KeyCode::Char(c)),
                &NoopDecider,
                &sender,
                &mailbox,
                &crate::keysender::test_support::MockKeySender::default(),
            );
        }
        super::handle_event(
            &mut app,
            key(KeyCode::Esc),
            &NoopDecider,
            &sender,
            &mailbox,
            &crate::keysender::test_support::MockKeySender::default(),
        );
        super::handle_event(
            &mut app,
            key(KeyCode::Esc),
            &NoopDecider,
            &sender,
            &mailbox,
            &crate::keysender::test_support::MockKeySender::default(),
        );
        assert_eq!(app.stage, Stage::Triptych);
        assert!(sender.dm_calls.lock().unwrap().is_empty());
    }

    #[test]
    fn send_failure_surfaces_error_inline_keeps_modal_open() {
        use crate::compose::test_support::MockMessageSender;
        let sender = MockMessageSender::default();
        *sender.fail_next.lock().unwrap() = Some("rate limit".into());
        let mailbox = EmptyMailbox;
        let mut app = App::new();
        app.replace_team(fixture_team(vec![agent(
            "writing:dev1",
            AgentState::Running,
        )]));
        app.dismiss_splash();
        app.enter_compose_dm_for_focused();
        super::handle_event(
            &mut app,
            key(KeyCode::Char('x')),
            &NoopDecider,
            &sender,
            &mailbox,
            &crate::keysender::test_support::MockKeySender::default(),
        );
        super::handle_event(
            &mut app,
            key_with(KeyCode::Enter, crossterm::event::KeyModifiers::CONTROL),
            &NoopDecider,
            &sender,
            &mailbox,
            &crate::keysender::test_support::MockKeySender::default(),
        );
        assert_eq!(app.stage, Stage::ComposeModal, "modal stays open on err");
        assert!(app
            .compose_error
            .as_deref()
            .unwrap_or_default()
            .contains("rate limit"));
    }

    fn channel(id: &str, project: &str) -> crate::data::ChannelInfo {
        crate::data::ChannelInfo {
            id: id.into(),
            name: id
                .rsplit_once(':')
                .map(|(_, n)| n.to_string())
                .unwrap_or_default(),
            project_id: project.into(),
        }
    }

    fn fixture_team_with_channels(
        agents: Vec<AgentInfo>,
        channels: Vec<crate::data::ChannelInfo>,
    ) -> TeamSnapshot {
        TeamSnapshot {
            root: std::path::PathBuf::from("/fixture"),
            team_name: "fixture".into(),
            agents,
            channels,
        }
    }

    #[test]
    fn ctrl_w_toggles_wall_layout() {
        use crossterm::event::KeyModifiers;
        let mut app = App::new();
        app.dismiss_splash();
        assert_eq!(app.layout, MainLayout::Triptych);
        dispatch(
            &mut app,
            key_with(KeyCode::Char('w'), KeyModifiers::CONTROL),
        );
        assert_eq!(app.layout, MainLayout::Wall);
        dispatch(
            &mut app,
            key_with(KeyCode::Char('w'), KeyModifiers::CONTROL),
        );
        assert_eq!(app.layout, MainLayout::Triptych);
    }

    #[test]
    fn ctrl_m_toggles_mailbox_first_layout() {
        use crossterm::event::KeyModifiers;
        let mut app = App::new();
        app.dismiss_splash();
        dispatch(
            &mut app,
            key_with(KeyCode::Char('m'), KeyModifiers::CONTROL),
        );
        assert_eq!(app.layout, MainLayout::MailboxFirst);
        dispatch(
            &mut app,
            key_with(KeyCode::Char('m'), KeyModifiers::CONTROL),
        );
        assert_eq!(app.layout, MainLayout::Triptych);
    }

    #[test]
    fn wall_scroll_pages_through_overflow_agents() {
        let mut app = App::new();
        let mut agents: Vec<_> = (1..=10)
            .map(|i| agent(&format!("p:agent-{i:02}"), AgentState::Running))
            .collect();
        // managers-first sort would otherwise reorder; mark all as workers.
        for a in agents.iter_mut() {
            a.is_manager = false;
        }
        app.replace_team(fixture_team(agents));
        app.dismiss_splash();
        app.toggle_wall_layout();
        assert_eq!(app.wall_scroll, 0);
        app.wall_scroll_down();
        assert_eq!(app.wall_scroll, 4);
        app.wall_scroll_down();
        assert_eq!(app.wall_scroll, 8);
        // Past 10-1 = 9; cap blocks 12.
        app.wall_scroll_down();
        assert_eq!(app.wall_scroll, 8, "scroll capped at last full window");
        app.wall_scroll_up();
        assert_eq!(app.wall_scroll, 4);
    }

    #[test]
    fn ctrl_pipe_adds_detail_split_capped_at_four() {
        use crossterm::event::KeyModifiers;
        let mut app = App::new();
        app.replace_team(fixture_team(vec![
            agent("p:a", AgentState::Running),
            agent("p:b", AgentState::Running),
        ]));
        app.dismiss_splash();
        for _ in 0..6 {
            dispatch(
                &mut app,
                key_with(KeyCode::Char('|'), KeyModifiers::CONTROL),
            );
        }
        assert_eq!(app.detail_splits.len(), 4, "split count capped at 4");
    }

    #[test]
    fn ctrl_q_closes_focused_split() {
        use crossterm::event::KeyModifiers;
        let mut app = App::new();
        app.replace_team(fixture_team(vec![agent("p:a", AgentState::Running)]));
        app.dismiss_splash();
        dispatch(
            &mut app,
            key_with(KeyCode::Char('|'), KeyModifiers::CONTROL),
        );
        dispatch(
            &mut app,
            key_with(KeyCode::Char('|'), KeyModifiers::CONTROL),
        );
        assert_eq!(app.detail_splits.len(), 2);
        dispatch(
            &mut app,
            key_with(KeyCode::Char('Q'), KeyModifiers::CONTROL),
        );
        assert_eq!(app.detail_splits.len(), 1);
    }

    #[test]
    fn ctrl_hjkl_cycles_splits() {
        use crossterm::event::KeyModifiers;
        let mut app = App::new();
        app.replace_team(fixture_team(vec![agent("p:a", AgentState::Running)]));
        app.dismiss_splash();
        for _ in 0..3 {
            dispatch(
                &mut app,
                key_with(KeyCode::Char('|'), KeyModifiers::CONTROL),
            );
        }
        assert_eq!(app.selected_split, 2);
        dispatch(
            &mut app,
            key_with(KeyCode::Char('l'), KeyModifiers::CONTROL),
        );
        assert_eq!(app.selected_split, 0, "wraps");
        dispatch(
            &mut app,
            key_with(KeyCode::Char('h'), KeyModifiers::CONTROL),
        );
        assert_eq!(app.selected_split, 2);
    }

    #[test]
    fn wall_scroll_at_exactly_cap_agents_does_not_scroll() {
        // PR-UI-6 fixup (qa Gap 1a): with exactly WALL_TILE_CAP=4
        // agents the entire team fits in one window — scrolling
        // is a no-op in both directions. Pinning this catches a
        // future `<` → `<=` slip in `wall_scroll_down`.
        let mut app = App::new();
        let agents: Vec<_> = (1..=4)
            .map(|i| agent(&format!("p:agent-{i}"), AgentState::Running))
            .collect();
        app.replace_team(fixture_team(agents));
        app.dismiss_splash();
        app.toggle_wall_layout();
        assert_eq!(app.wall_scroll, 0);
        app.wall_scroll_down();
        assert_eq!(app.wall_scroll, 0, "exactly-cap should not advance");
        app.wall_scroll_up();
        assert_eq!(app.wall_scroll, 0);
    }

    #[test]
    fn wall_scroll_at_cap_plus_one_advances_then_stops() {
        // PR-UI-6 fixup (qa Gap 1b): exactly 5 agents → 4 fit in
        // window-0, the 5th lives at window-4. One scroll
        // advances; the next caps. Pins the off-by-one between 4
        // and 5 agents.
        let mut app = App::new();
        let agents: Vec<_> = (1..=5)
            .map(|i| agent(&format!("p:agent-{i}"), AgentState::Running))
            .collect();
        app.replace_team(fixture_team(agents));
        app.dismiss_splash();
        app.toggle_wall_layout();
        app.wall_scroll_down();
        assert_eq!(app.wall_scroll, 4, "first scroll exposes agent 5");
        app.wall_scroll_down();
        assert_eq!(app.wall_scroll, 4, "second scroll caps; nothing past");
    }

    #[test]
    fn esc_in_picker_dismisses_overlay_only_keeps_modal_open() {
        // PR-UI-6 fixup (Q6 dev2 review + qa Gap 3): Esc inside
        // the broadcast picker should close the picker overlay
        // and return to the editor in its current state — NOT
        // close the whole compose modal. Editor's Esc-Esc
        // already handles cancel-the-modal.
        let mut app = App::new();
        app.replace_team(fixture_team_with_channels(
            vec![agent("writing:manager", AgentState::Running)],
            vec![
                channel("writing:all", "writing"),
                channel("writing:editorial", "writing"),
            ],
        ));
        app.dismiss_splash();
        dispatch(&mut app, key(KeyCode::Char('!')));
        assert!(app.compose_picker_open);
        assert_eq!(app.stage, Stage::ComposeModal);
        dispatch(&mut app, key(KeyCode::Esc));
        assert!(!app.compose_picker_open, "picker dismissed");
        assert_eq!(app.stage, Stage::ComposeModal, "compose modal stays open");
    }

    #[test]
    fn send_routes_broadcast_through_mock_sender_via_picker() {
        // PR-UI-6 fixup (qa Gap 4): the broadcast path needs the
        // same MockMessageSender pin the DM path got in PR-UI-5.
        // Pins both per-channel-correct-id (picker selection
        // flows through to the send call) AND routes-through-
        // `broadcast()`-not-`send()` (no DM call recorded).
        use crate::compose::test_support::MockMessageSender;
        let sender = MockMessageSender::default();
        let mailbox = EmptyMailbox;
        let mut app = App::new();
        app.replace_team(fixture_team_with_channels(
            vec![agent("writing:manager", AgentState::Running)],
            vec![
                channel("writing:all", "writing"),
                channel("writing:editorial", "writing"),
                channel("writing:critique", "writing"),
            ],
        ));
        app.dismiss_splash();
        // Open picker, walk to channel index 1 (`editorial`),
        // confirm, type a body, Ctrl+Enter to send.
        super::handle_event(
            &mut app,
            key(KeyCode::Char('!')),
            &NoopDecider,
            &sender,
            &mailbox,
            &crate::keysender::test_support::MockKeySender::default(),
        );
        super::handle_event(
            &mut app,
            key(KeyCode::Char('j')),
            &NoopDecider,
            &sender,
            &mailbox,
            &crate::keysender::test_support::MockKeySender::default(),
        );
        super::handle_event(
            &mut app,
            key(KeyCode::Enter),
            &NoopDecider,
            &sender,
            &mailbox,
            &crate::keysender::test_support::MockKeySender::default(),
        );
        for c in "ship docs".chars() {
            super::handle_event(
                &mut app,
                key(KeyCode::Char(c)),
                &NoopDecider,
                &sender,
                &mailbox,
                &crate::keysender::test_support::MockKeySender::default(),
            );
        }
        super::handle_event(
            &mut app,
            key_with(KeyCode::Enter, crossterm::event::KeyModifiers::CONTROL),
            &NoopDecider,
            &sender,
            &mailbox,
            &crate::keysender::test_support::MockKeySender::default(),
        );
        let dm_calls = sender.dm_calls.lock().unwrap().clone();
        let bcast_calls = sender.broadcast_calls.lock().unwrap().clone();
        assert!(dm_calls.is_empty(), "broadcast must not route via send_dm");
        assert_eq!(bcast_calls.len(), 1);
        assert_eq!(
            bcast_calls[0].0, "writing:editorial",
            "channel id from picker selection"
        );
        assert_eq!(bcast_calls[0].1, "ship docs");
        assert_eq!(app.stage, Stage::Triptych, "modal closes on send");
    }

    #[test]
    fn bang_chord_opens_picker_when_channels_available() {
        let mut app = App::new();
        app.replace_team(fixture_team_with_channels(
            vec![agent("writing:manager", AgentState::Running)],
            vec![
                channel("writing:all", "writing"),
                channel("writing:editorial", "writing"),
                channel("writing:critique", "writing"),
            ],
        ));
        app.dismiss_splash();
        dispatch(&mut app, key(KeyCode::Char('!')));
        assert_eq!(app.stage, Stage::ComposeModal);
        assert!(app.compose_picker_open);
        // Walk the picker.
        dispatch(&mut app, key(KeyCode::Char('j')));
        assert_eq!(app.compose_picker_index, 1);
        // Confirm pulls into compose target.
        dispatch(&mut app, key(KeyCode::Enter));
        assert!(!app.compose_picker_open, "picker closes on confirm");
        match app.compose_target.as_ref() {
            Some(crate::compose::ComposeTarget::Broadcast { channel_id, .. }) => {
                assert_eq!(channel_id, "writing:editorial");
            }
            other => panic!("expected Broadcast target, got {other:?}"),
        }
    }

    #[test]
    fn mailbox_first_layout_seeds_channel_selection_on_entry() {
        let mut app = App::new();
        app.replace_team(fixture_team_with_channels(
            vec![agent("writing:manager", AgentState::Running)],
            vec![
                channel("writing:all", "writing"),
                channel("writing:editorial", "writing"),
            ],
        ));
        app.dismiss_splash();
        assert!(app.selected_channel.is_none());
        app.toggle_mailbox_first_layout();
        assert_eq!(app.selected_channel, Some(0));
    }

    #[test]
    fn help_overlay_opens_on_question_mark_closes_on_esc() {
        let mut app = App::new();
        app.dismiss_splash();
        dispatch(&mut app, key(KeyCode::Char('?')));
        assert_eq!(app.stage, Stage::HelpOverlay);
        dispatch(&mut app, key(KeyCode::Esc));
        assert_eq!(app.stage, Stage::Triptych);
    }

    #[test]
    fn tutorial_opens_on_t_advances_and_closes() {
        let mut app = App::new();
        app.dismiss_splash();
        dispatch(&mut app, key(KeyCode::Char('t')));
        assert_eq!(app.stage, Stage::Tutorial);
        assert_eq!(app.tutorial_step, 0);
        // Any non-Esc/back key advances.
        dispatch(&mut app, key(KeyCode::Char(' ')));
        assert_eq!(app.tutorial_step, 1);
        // `k` walks back.
        dispatch(&mut app, key(KeyCode::Char('k')));
        assert_eq!(app.tutorial_step, 0);
        // Esc closes from any step.
        dispatch(&mut app, key(KeyCode::Esc));
        assert_eq!(app.stage, Stage::Triptych);
    }

    #[test]
    fn tutorial_walk_back_at_step_zero_is_no_op() {
        // qa Gap C fold: pin the chosen behaviour for `k`/`Up`/`p`
        // at step 0 — saturating decrement keeps `tutorial_step`
        // at 0 rather than wrapping. Any future shift to
        // wrap-to-end would break this test, which is the point.
        let mut app = App::new();
        app.dismiss_splash();
        app.enter_tutorial();
        assert_eq!(app.tutorial_step, 0);
        dispatch(&mut app, key(KeyCode::Char('k')));
        assert_eq!(app.tutorial_step, 0, "step-0 walk-back is no-op");
        // The walk-back keypress must NOT close the tutorial
        // either — the Stage stays.
        assert_eq!(app.stage, Stage::Tutorial);
    }

    #[test]
    fn ctrl_pipe_adds_vertical_split_ctrl_minus_adds_horizontal() {
        use crossterm::event::KeyModifiers;
        let mut app = App::new();
        app.replace_team(fixture_team(vec![agent("p:a", AgentState::Running)]));
        app.dismiss_splash();
        dispatch(
            &mut app,
            key_with(KeyCode::Char('|'), KeyModifiers::CONTROL),
        );
        dispatch(
            &mut app,
            key_with(KeyCode::Char('-'), KeyModifiers::CONTROL),
        );
        assert_eq!(app.detail_splits.len(), 2);
        assert_eq!(app.detail_splits[0].1, SplitOrientation::Vertical);
        assert_eq!(app.detail_splits[1].1, SplitOrientation::Horizontal);
    }

    #[test]
    fn ctrl_w_q_chord_prefix_closes_focused_split() {
        use crossterm::event::KeyModifiers;
        let mut app = App::new();
        app.replace_team(fixture_team(vec![agent("p:a", AgentState::Running)]));
        app.dismiss_splash();
        // Two splits — `Ctrl+W` arms only when there's something
        // to close.
        dispatch(
            &mut app,
            key_with(KeyCode::Char('|'), KeyModifiers::CONTROL),
        );
        dispatch(
            &mut app,
            key_with(KeyCode::Char('|'), KeyModifiers::CONTROL),
        );
        dispatch(
            &mut app,
            key_with(KeyCode::Char('w'), KeyModifiers::CONTROL),
        );
        assert_eq!(app.pending_chord, Some(KeyCode::Char('w')));
        // Plain `q` (no modifier) is now interpreted as the
        // chord-prefix follow-up — close split, NOT quit.
        dispatch(&mut app, key(KeyCode::Char('q')));
        assert_eq!(app.detail_splits.len(), 1);
        assert_eq!(app.stage, Stage::Triptych, "must not enter quit confirm");
        assert_eq!(app.pending_chord, None, "chord cleared");
    }

    #[test]
    fn ctrl_w_o_chord_keeps_only_focused_split() {
        use crossterm::event::KeyModifiers;
        let mut app = App::new();
        app.replace_team(fixture_team(vec![agent("p:a", AgentState::Running)]));
        app.dismiss_splash();
        for _ in 0..3 {
            dispatch(
                &mut app,
                key_with(KeyCode::Char('|'), KeyModifiers::CONTROL),
            );
        }
        // Focus the middle split.
        app.selected_split = 1;
        let kept_id = app.detail_splits[1].0.clone();
        dispatch(
            &mut app,
            key_with(KeyCode::Char('w'), KeyModifiers::CONTROL),
        );
        dispatch(&mut app, key(KeyCode::Char('o')));
        assert_eq!(app.detail_splits.len(), 1);
        assert_eq!(app.detail_splits[0].0, kept_id);
        assert_eq!(app.selected_split, 0);
    }

    #[test]
    fn add_detail_split_saturates_at_four_with_explicit_4_and_5_calls() {
        // qa Gap 2 fold: pin the cap explicitly. Reaching exactly
        // 4 must stick; the 5th call must be a no-op (not panic,
        // not silently grow). If `add_detail_split` ever returns
        // a Result, this test catches the silent-success regression.
        let mut app = App::new();
        app.replace_team(fixture_team(vec![agent("p:a", AgentState::Running)]));
        for _ in 0..4 {
            app.add_detail_split();
        }
        assert_eq!(app.detail_splits.len(), 4);
        let snapshot_len = app.detail_splits.len();
        app.add_detail_split();
        assert_eq!(app.detail_splits.len(), snapshot_len, "5th call rejected");
    }

    #[test]
    fn replace_approvals_clamps_selection_in_range() {
        let mut app = App::new();
        app.replace_approvals(vec![ap(1), ap(2), ap(3)]);
        app.selected_approval = 2;
        // Approval id 3 resolved out-of-band; new snapshot has 2 rows.
        app.replace_approvals(vec![ap(1), ap(2)]);
        assert_eq!(app.selected_approval, 1, "clamps to last index");
    }

    #[test]
    fn arrow_keys_navigate_only_when_roster_focused() {
        let mut app = App::new();
        app.replace_team(fixture_team(vec![
            agent("p:a", AgentState::Running),
            agent("p:b", AgentState::Running),
        ]));
        app.dismiss_splash();
        // Focused pane is Roster → arrow cycles selection.
        app.selected_agent = Some(0);
        dispatch(&mut app, key(KeyCode::Down));
        assert_eq!(app.selected_agent, Some(1));
        // Cycle to Detail → arrow no longer touches selection.
        app.cycle_focus();
        dispatch(&mut app, key(KeyCode::Down));
        assert_eq!(
            app.selected_agent,
            Some(1),
            "non-roster focus ignores arrows"
        );
    }

    // ---- T-108 stream-keys mode -------------------------------------------

    /// Spin up a Triptych-stage app with one agent selected and the
    /// detail pane focused — the standard precondition for entering
    /// stream-keys mode.
    fn stream_keys_fixture() -> App {
        let mut app = App::new();
        app.replace_team(fixture_team(vec![agent("p:a", AgentState::Running)]));
        app.dismiss_splash();
        app.cycle_focus(); // Roster → Detail
        assert_eq!(app.focused_pane, Pane::Detail);
        assert_eq!(app.selected_agent, Some(0));
        app
    }

    fn stream_dispatch(
        app: &mut App,
        ev: Event,
        key_sender: &crate::keysender::test_support::MockKeySender,
    ) {
        super::handle_event(
            app,
            ev,
            &NoopDecider,
            &NoopSender,
            &EmptyMailbox,
            key_sender,
        );
    }

    #[test]
    fn ctrl_e_enters_stream_keys_when_detail_focused() {
        use crate::keysender::test_support::MockKeySender;
        use crossterm::event::KeyModifiers;
        let mut app = stream_keys_fixture();
        let ks = MockKeySender::default();
        stream_dispatch(
            &mut app,
            key_with(KeyCode::Char('e'), KeyModifiers::CONTROL),
            &ks,
        );
        assert_eq!(app.stage, Stage::StreamKeys);
        assert!(
            ks.calls.lock().unwrap().is_empty(),
            "the activation chord itself never forwards a keystroke"
        );
    }

    #[test]
    fn ctrl_e_no_op_when_detail_not_focused() {
        // Activation gate: stream-mode never triggers from Roster /
        // Mailbox focus, so a stray `Ctrl+E` while scrolling the
        // roster doesn't yank the operator into a modal they didn't
        // ask for.
        use crate::keysender::test_support::MockKeySender;
        use crossterm::event::KeyModifiers;
        let mut app = App::new();
        app.replace_team(fixture_team(vec![agent("p:a", AgentState::Running)]));
        app.dismiss_splash();
        assert_eq!(app.focused_pane, Pane::Roster);
        let ks = MockKeySender::default();
        stream_dispatch(
            &mut app,
            key_with(KeyCode::Char('e'), KeyModifiers::CONTROL),
            &ks,
        );
        assert_eq!(app.stage, Stage::Triptych);
    }

    #[test]
    fn ctrl_e_no_op_when_no_agent_selected() {
        // No target session → entering stream-mode would type into
        // the void. The guard short-circuits.
        use crate::keysender::test_support::MockKeySender;
        use crossterm::event::KeyModifiers;
        let mut app = App::new();
        app.dismiss_splash();
        app.cycle_focus(); // Detail
        assert_eq!(app.selected_agent, None);
        let ks = MockKeySender::default();
        stream_dispatch(
            &mut app,
            key_with(KeyCode::Char('e'), KeyModifiers::CONTROL),
            &ks,
        );
        assert_eq!(app.stage, Stage::Triptych);
    }

    #[test]
    fn esc_exits_stream_keys() {
        use crate::keysender::test_support::MockKeySender;
        let mut app = stream_keys_fixture();
        app.enter_stream_keys();
        assert_eq!(app.stage, Stage::StreamKeys);
        let ks = MockKeySender::default();
        stream_dispatch(&mut app, key(KeyCode::Esc), &ks);
        assert_eq!(app.stage, Stage::Triptych);
        assert!(
            ks.calls.lock().unwrap().is_empty(),
            "Esc is the exit chord — it must not forward as a keystroke"
        );
    }

    #[test]
    fn stream_mode_forwards_printable_chars_to_target_session() {
        use crate::keysender::test_support::MockKeySender;
        let mut app = stream_keys_fixture();
        app.enter_stream_keys();
        let ks = MockKeySender::default();
        for c in "hi".chars() {
            stream_dispatch(&mut app, key(KeyCode::Char(c)), &ks);
        }
        let calls = ks.calls.lock().unwrap();
        assert_eq!(calls.len(), 2, "one tmux send-keys per keystroke");
        // Target session = the focused agent's tmux_session (set by
        // the fixture to `t-p-a`).
        assert_eq!(calls[0].0, "t-p-a");
        assert_eq!(calls[0].1.args, vec!["-l".to_string(), "h".to_string()]);
        assert_eq!(calls[1].1.args, vec!["-l".to_string(), "i".to_string()]);
    }

    #[test]
    fn stream_mode_passes_ctrl_c_through_to_agent() {
        // Issue #108 design point: Ctrl+C is shell-SIGINT semantics,
        // not a stream-mode escape. Pin the contract so a future
        // "intercept Ctrl+C as bail" refactor doesn't regress it.
        use crate::keysender::test_support::MockKeySender;
        use crossterm::event::KeyModifiers;
        let mut app = stream_keys_fixture();
        app.enter_stream_keys();
        let ks = MockKeySender::default();
        stream_dispatch(
            &mut app,
            key_with(KeyCode::Char('c'), KeyModifiers::CONTROL),
            &ks,
        );
        assert_eq!(app.stage, Stage::StreamKeys, "Ctrl+C does NOT exit");
        let calls = ks.calls.lock().unwrap();
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].1.args, vec!["C-c".to_string()]);
    }

    #[test]
    fn stream_mode_forwards_enter_and_arrows() {
        use crate::keysender::test_support::MockKeySender;
        let mut app = stream_keys_fixture();
        app.enter_stream_keys();
        let ks = MockKeySender::default();
        stream_dispatch(&mut app, key(KeyCode::Enter), &ks);
        stream_dispatch(&mut app, key(KeyCode::Up), &ks);
        let calls = ks.calls.lock().unwrap();
        assert_eq!(calls[0].1.args, vec!["Enter".to_string()]);
        assert_eq!(calls[1].1.args, vec!["Up".to_string()]);
    }

    #[test]
    fn stream_target_session_uses_focused_split_when_present() {
        // Splits change which agent the operator is "looking at."
        // The selected_split index drives the focus ring in
        // render_detail_splits; stream_target_session must mirror
        // that so typing lands in the right pane.
        let mut app = App::new();
        app.replace_team(fixture_team(vec![
            agent("p:a", AgentState::Running),
            agent("p:b", AgentState::Running),
        ]));
        app.dismiss_splash();
        app.cycle_focus(); // Detail
        app.selected_agent = Some(0);
        // Manually push a split for `p:b` and focus it.
        app.detail_splits
            .push(("p:b".into(), crate::app::SplitOrientation::Vertical));
        app.selected_split = 1; // cell index 0 = focused agent, 1 = first split
        let target = app.stream_target_session();
        assert_eq!(
            target.as_deref(),
            Some("t-p-b"),
            "selected split's agent drives the target"
        );
    }

    #[test]
    fn stream_mode_drops_back_when_target_session_disappears() {
        // If the team gets reloaded mid-stream and the focused
        // agent's index points off the end, the next keystroke
        // can't resolve a session. Drop back to Triptych so the
        // operator isn't silently typing into the void.
        use crate::keysender::test_support::MockKeySender;
        let mut app = stream_keys_fixture();
        app.enter_stream_keys();
        // Simulate the agent disappearing.
        app.selected_agent = None;
        app.team.agents.clear();
        let ks = MockKeySender::default();
        stream_dispatch(&mut app, key(KeyCode::Char('a')), &ks);
        assert_eq!(app.stage, Stage::Triptych);
        assert!(ks.calls.lock().unwrap().is_empty());
    }

    // ── T-199: detail-pane → inner-tmux size sync ───────────────────

    fn pane_sync_fixture() -> App {
        let mut app = App::new();
        app.team = fixture_team(vec![
            agent("hello:mgr", AgentState::Running),
            agent("hello:dev", AgentState::Running),
        ]);
        app.selected_agent = Some(0);
        app.stage = Stage::Triptych;
        app.layout = MainLayout::Triptych;
        app
    }

    #[test]
    fn sync_fires_resize_on_first_frame() {
        let mut app = pane_sync_fixture();
        let resizer = crate::pane_resize::test_support::MockPaneResizer::default();
        sync_focused_pane_size_to(
            &mut app,
            ratatui::layout::Rect::new(0, 0, 120, 40),
            &resizer,
        );
        let calls = resizer.calls.lock().unwrap();
        // First frame: cache empty, expect one call for the focused
        // session (mgr) at the typical 120×40 Triptych Detail rect.
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].0, "t-hello-mgr");
        assert_eq!(calls[0].1, 92); // Detail width = 120 - 28 sidebar
        assert_eq!(calls[0].2, 24); // Detail height = 3/5 of 40
    }

    #[test]
    fn sync_skips_when_size_unchanged() {
        let mut app = pane_sync_fixture();
        let resizer = crate::pane_resize::test_support::MockPaneResizer::default();
        // Two frames at identical size → only the first should fire.
        sync_focused_pane_size_to(
            &mut app,
            ratatui::layout::Rect::new(0, 0, 120, 40),
            &resizer,
        );
        sync_focused_pane_size_to(
            &mut app,
            ratatui::layout::Rect::new(0, 0, 120, 40),
            &resizer,
        );
        assert_eq!(resizer.calls.lock().unwrap().len(), 1);
    }

    #[test]
    fn sync_fires_again_when_terminal_resizes() {
        let mut app = pane_sync_fixture();
        let resizer = crate::pane_resize::test_support::MockPaneResizer::default();
        sync_focused_pane_size_to(
            &mut app,
            ratatui::layout::Rect::new(0, 0, 120, 40),
            &resizer,
        );
        // Operator resized the host terminal.
        sync_focused_pane_size_to(
            &mut app,
            ratatui::layout::Rect::new(0, 0, 200, 60),
            &resizer,
        );
        let calls = resizer.calls.lock().unwrap();
        assert_eq!(calls.len(), 2);
        assert_eq!(calls[0].1, 92);
        assert_eq!(calls[0].2, 24);
        assert_eq!(calls[1].1, 172); // 200 - 28
                                     // Height = 3/5 of 60 = 36.
        assert_eq!(calls[1].2, 36);
    }

    #[test]
    fn sync_fires_on_focus_switch_to_unsynced_session() {
        let mut app = pane_sync_fixture();
        let resizer = crate::pane_resize::test_support::MockPaneResizer::default();
        sync_focused_pane_size_to(
            &mut app,
            ratatui::layout::Rect::new(0, 0, 120, 40),
            &resizer,
        );
        // Operator switched focus to the dev agent.
        app.selected_agent = Some(1);
        sync_focused_pane_size_to(
            &mut app,
            ratatui::layout::Rect::new(0, 0, 120, 40),
            &resizer,
        );
        let calls = resizer.calls.lock().unwrap();
        assert_eq!(calls.len(), 2);
        assert_eq!(calls[0].0, "t-hello-mgr");
        assert_eq!(calls[1].0, "t-hello-dev");
    }

    #[test]
    fn sync_is_noop_when_no_agent_focused() {
        let mut app = pane_sync_fixture();
        app.selected_agent = None;
        let resizer = crate::pane_resize::test_support::MockPaneResizer::default();
        sync_focused_pane_size_to(
            &mut app,
            ratatui::layout::Rect::new(0, 0, 120, 40),
            &resizer,
        );
        assert!(resizer.calls.lock().unwrap().is_empty());
    }

    #[test]
    fn sync_is_noop_when_layout_is_not_triptych() {
        let mut app = pane_sync_fixture();
        app.layout = MainLayout::Wall;
        let resizer = crate::pane_resize::test_support::MockPaneResizer::default();
        sync_focused_pane_size_to(
            &mut app,
            ratatui::layout::Rect::new(0, 0, 120, 40),
            &resizer,
        );
        // Wall / MailboxFirst use different geometry; out of scope for
        // T-199. No tmux resize-pane should fire from this path.
        assert!(resizer.calls.lock().unwrap().is_empty());
    }

    #[test]
    fn sync_is_noop_on_degenerate_terminal_area() {
        let mut app = pane_sync_fixture();
        let resizer = crate::pane_resize::test_support::MockPaneResizer::default();
        // Width is exactly the sidebar (28) → Detail rect is zero.
        sync_focused_pane_size_to(&mut app, ratatui::layout::Rect::new(0, 0, 28, 40), &resizer);
        assert!(resizer.calls.lock().unwrap().is_empty());
    }

    #[test]
    fn sync_accounts_for_approvals_stripe_when_present() {
        let mut app = pane_sync_fixture();
        // Force the approvals-stripe path: one pending approval.
        app.pending_approvals = vec![crate::approvals::Approval {
            id: 1,
            project_id: "hello".into(),
            agent_id: "hello:dev".into(),
            action: "test".into(),
            summary: "test approval".into(),
            payload_json: String::new(),
        }];
        assert!(app.has_pending_approvals());
        let resizer = crate::pane_resize::test_support::MockPaneResizer::default();
        sync_focused_pane_size_to(
            &mut app,
            ratatui::layout::Rect::new(0, 0, 120, 40),
            &resizer,
        );
        let calls = resizer.calls.lock().unwrap();
        // Stripe consumes one row → Detail height is 3/5 of 39 = 23.
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].2, 23);
    }
}