omni-dev 0.46.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, Datadog, Gmail, and Drive.
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
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
//! The worktrees UI's event loop and mutable state (issue #1585 Phases 2–3):
//! the tree pane's cursor/marks and action popups, one embedded terminal
//! tab, and the single `tokio::select!` that merges crossterm input, PTY
//! events, and hub redraw signals.
//!
//! Extracted from `mod.rs` in Phase 3 — the point where PTY state gave the
//! type enough weight to justify its own file. Phase 4 adds the mouse
//! contract (`handle_mouse`, applying what `mouse.rs` decides); tabs/splits
//! extend `App` further.

use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use alacritty_terminal::event::Event as TermEvent;
use alacritty_terminal::grid::Scroll;
use alacritty_terminal::selection::SelectionType;
use alacritty_terminal::term::TermMode;
use anyhow::Result;
use crossterm::event::{
    Event, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent,
    MouseEventKind,
};
use futures::StreamExt;
use ratatui::backend::CrosstermBackend;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::widgets::{Block, Borders};
use ratatui::{Frame, Terminal};
use tokio::sync::mpsc;

use super::actions::{self, ActionFlow, ActionKind, CheckReport, Dispatcher, Target};
use super::glyph::GlyphMode;
use super::hub::{HubCommand, ViewModelHandle};
use super::keys::{self, ChromeKey, KeyRoute};
use super::menu;
use super::mouse::{self, DragOrigin, Hit, RegionMap, TreeClick, WheelRoute};
use super::panes;
use super::session_layout;
use super::terminal::{GridSize, TabEffect, TabId, TabKind, TerminalTab};
use super::tree::TreeState;
use super::view_model::WorktreesViewModel;
use super::{clipboard, popup, render};
use crate::sessions::relocate::{self, RelocationMode};

/// Which pane receives keys.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
enum Focus {
    #[default]
    Tree,
    Terminal,
}

/// Minimum interval between redraws while PTY output is streaming: a burst
/// of `Wakeup` events produces one frame, not one frame per event.
const FRAME_INTERVAL: Duration = Duration::from_millis(16);

/// The render layer's mutable state: cursor/marks, the current action-flow
/// popup, the Move/Copy-Claude-Session-Here picker wizard when active, and
/// the terminal tab. Everything here is local UI state, not daemon truth —
/// see `tree::TreeState`'s own doc comment.
struct App {
    tree: TreeState,
    flow: ActionFlow,
    menu: Option<popup::ActionMenu>,
    relocate: Option<RelocateStep>,
    focus: Focus,
    /// The terminal side: a vertical stack of tab groups (Phase 4b).
    panes: panes::PaneLayout,
    /// `q` with a live child asks first; the answer lands here.
    quit_confirm: bool,
    /// Set by a menu-invoked *Quit*. A key can quit by returning `true` from
    /// `handle_key`; a menu is dispatched from the mouse path, which has no
    /// such channel, so the loop checks this instead.
    quit_requested: bool,
    /// A one-line message for the status bar, cleared on the next key.
    notice: Option<String>,
    pty_tx: mpsc::UnboundedSender<(TabId, TermEvent)>,
    commands: mpsc::UnboundedSender<HubCommand>,
    /// Unicode or ASCII row cues, resolved once at startup.
    glyphs: GlyphMode,
    /// The scrollback-find or command-palette prompt, when one is open.
    prompt: Option<Prompt>,
    /// The worktree paths the tree pane last rendered, so the hub only
    /// fetches ahead/behind for rows that are actually on screen.
    reported_visible: Vec<PathBuf>,
    /// The hit-testable regions of the last drawn frame.
    regions: RegionMap,
    /// The terminal side's rect as of the last frame — what a splitter drag
    /// recomputes weights against.
    terminal_area: Option<Rect>,
    /// The tab a tab-strip context menu was opened on — that menu's subject,
    /// the strip's analogue of `ActionMenu::origin_row`. A strip menu's
    /// entries act on the tab that was right-clicked, which is not
    /// necessarily the active one.
    menu_tab: Option<panes::TabAddr>,
    /// The splitter a layout context menu was opened on — that menu's
    /// subject, the boundary's analogue of `menu_tab`.
    menu_splitter: Option<usize>,
    /// The drag in progress, if any, and the region it is clamped to.
    drag: DragOrigin,
    clicks: mouse::ClickTracker,
}

/// A one-line text prompt: either the scrollback find (`alt-f`) or the
/// command palette (`:`). Both are a typed string plus a status line, so
/// they share one state and one renderer rather than two near-copies.
struct Prompt {
    kind: PromptKind,
    input: String,
    status: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PromptKind {
    /// Search the focused tab's scrollback.
    Find,
    /// Run a command by name.
    Palette,
}

impl PromptKind {
    fn title(self) -> &'static str {
        match self {
            Self::Find => " find in scrollback ",
            Self::Palette => " command ",
        }
    }
}

/// One entry in the command palette: the name typed to match it, and the
/// action it runs. Built from the same [`ActionKind`] set the action menu
/// uses, so the palette can never drift from the menu.
fn palette_entries(targets: &[Target]) -> Vec<popup::MenuItem> {
    actions::applicable_actions(targets)
        .into_iter()
        .map(|(action, label)| popup::MenuItem::action(action, label))
        .collect()
}

/// Filters palette entries by a case-insensitive substring of their label.
fn filter_palette(entries: Vec<popup::MenuItem>, query: &str) -> Vec<popup::MenuItem> {
    if query.is_empty() {
        return entries;
    }
    let needle = query.to_lowercase();
    entries
        .into_iter()
        .filter(|item| item.label.to_lowercase().contains(&needle))
        .collect()
}

/// The Move/Copy-Claude-Session-Here wizard's steps (issue #1585 Phase 2
/// §5): pick which session (skipped when the source row has exactly one),
/// then pick a destination worktree, then confirm. Kept out of the generic
/// [`ActionFlow`] since a relocation's parameters (a resolved session id
/// plus a source/destination pair) don't fit the uniform `targets: &[Target]`
/// fan-out shape every other action uses.
enum RelocateStep {
    PickSession {
        mode: RelocationMode,
        source_worktree: PathBuf,
        source_dir: PathBuf,
        sessions: Vec<actions::relocate_types::SessionInfo>,
        selected: usize,
    },
    PickDestination {
        mode: RelocationMode,
        source_dir: PathBuf,
        session: actions::relocate_types::SessionInfo,
        candidates: Vec<PathBuf>,
        selected: usize,
    },
    Confirm {
        mode: RelocationMode,
        source_dir: PathBuf,
        session: actions::relocate_types::SessionInfo,
        dest_worktree: PathBuf,
        prompt: actions::ConfirmPrompt,
    },
}

/// The event loop: one `select!` over crossterm input, the shared PTY event
/// channel, and the hub's view updates, redrawing at most every
/// [`FRAME_INTERVAL`] while anything is dirty. Quits on `q` from the tree
/// (after a confirm when a child is live).
pub async fn run(
    terminal: &mut Terminal<CrosstermBackend<std::io::Stdout>>,
    mut handle: ViewModelHandle,
    dispatcher: Dispatcher,
    commands: mpsc::UnboundedSender<HubCommand>,
    glyphs: GlyphMode,
) -> Result<()> {
    let mut events = EventStream::new();
    let (pty_tx, mut pty_rx) = mpsc::unbounded_channel();
    let mut app = App {
        tree: TreeState::default(),
        flow: ActionFlow::Idle,
        menu: None,
        relocate: None,
        focus: Focus::Tree,
        panes: panes::PaneLayout::default(),
        quit_confirm: false,
        quit_requested: false,
        notice: None,
        pty_tx,
        commands,
        glyphs,
        prompt: None,
        reported_visible: Vec::new(),
        regions: RegionMap::default(),
        terminal_area: None,
        menu_tab: None,
        menu_splitter: None,
        drag: DragOrigin::None,
        clicks: mouse::ClickTracker::default(),
    };
    // Restore the previous run's pane shape (Phase 5). Tabs are respawned,
    // never resumed — the children died with the last process — and a tab
    // that will not spawn is dropped rather than failing the start.
    let saved = session_layout::load(None);
    if !saved.is_empty() {
        let tx = app.pty_tx.clone();
        let size = GridSize {
            cols: 80,
            lines: 24,
        };
        let failed = app.panes.restore(&saved, |id, kind, path| {
            TerminalTab::spawn(id, kind, path.to_path_buf(), size, tx.clone())
        });
        for worktree in app.panes.open_worktrees() {
            let _ = app.commands.send(HubCommand::SetOpenTab(worktree));
        }
        if !app.panes.is_empty() {
            app.focus = Focus::Terminal;
        }
        if failed > 0 {
            app.notice = Some(format!("{failed} saved tab(s) could not be reopened"));
        }
    }

    let mut last_drawn_generation: Option<u64> = None;
    let mut dirty = true;
    let mut last_draw = tokio::time::Instant::now() - FRAME_INTERVAL;

    loop {
        let view = handle.view.borrow_and_update().clone();
        let generation_moved = last_drawn_generation != Some(view.generation);
        if (dirty || generation_moved) && last_draw.elapsed() >= FRAME_INTERVAL {
            terminal.draw(|frame| draw(frame, &view, &mut app))?;
            last_drawn_generation = Some(view.generation);
            dirty = false;
            last_draw = tokio::time::Instant::now();
        }
        // Coalesce: while dirty, wait out the rest of the frame interval;
        // otherwise a slow fallback tick keeps the status bar's
        // reconnecting/polling state fresh between real events.
        let wait = if dirty || generation_moved {
            FRAME_INTERVAL.saturating_sub(last_draw.elapsed())
        } else {
            Duration::from_millis(500)
        };

        tokio::select! {
            biased;
            ev = events.next() => {
                match ev {
                    Some(Ok(Event::Key(key))) if key.kind == KeyEventKind::Press => {
                        app.notice = None;
                        if handle_key(&mut app, &view, &dispatcher, key).await {
                            break;
                        }
                        dirty = true;
                    }
                    Some(Ok(Event::Mouse(mouse))) => {
                        if handle_mouse(&mut app, &view, &dispatcher, mouse).await {
                            dirty = true;
                        }
                        if app.quit_requested {
                            break;
                        }
                    }
                    Some(Ok(Event::Paste(text))) => {
                        if app.focus == Focus::Terminal {
                            if let Some(tab) = app.panes.active_tab().filter(|t| t.is_alive()) {
                                tab.write_input(keys::paste_bytes(&text, tab.mode()));
                            }
                        }
                    }
                    Some(Ok(Event::FocusGained)) => app.forward_focus(true),
                    Some(Ok(Event::FocusLost)) => app.forward_focus(false),
                    Some(Ok(Event::Resize(..))) => dirty = true,
                    Some(Ok(_)) => {}
                    Some(Err(_)) | None => break,
                }
            }
            pty = pty_rx.recv() => {
                match pty {
                    Some((tab_id, event)) => {
                        if app.handle_pty_event(tab_id, event) {
                            dirty = true;
                        }
                    }
                    None => break,
                }
            }
            changed = handle.view.changed() => {
                if changed.is_err() {
                    break; // the hub actor is gone
                }
            }
            () = tokio::time::sleep(wait) => {}
        }
    }

    // Persist the pane shape before tearing the children down, so the next
    // run opens the same workspace. Best-effort: failing to write a
    // convenience file must not fail the command.
    if let Err(e) = session_layout::save(&app.panes.to_saved(), None) {
        tracing::debug!("worktrees ui: could not save the layout: {e:#}");
    }
    for group in &mut app.panes.groups {
        for tab in &mut group.tabs {
            tab.shutdown();
        }
    }
    Ok(())
}

impl App {
    /// Absorbs one emulator event; returns whether a redraw is needed.
    fn handle_pty_event(&mut self, tab_id: TabId, event: TermEvent) -> bool {
        let Some(effect) = self.panes.handle_event(tab_id, event) else {
            return false; // an event from a tab that has already been closed
        };
        match effect {
            TabEffect::None => false,
            TabEffect::Redraw => true,
            TabEffect::CopyToClipboard(text) => {
                if clipboard::copy_text(&text).is_err() {
                    self.notice = Some("clipboard unavailable".to_string());
                }
                false
            }
            TabEffect::Exited => {
                self.notice = Some("terminal exited — alt-w to close the tab".to_string());
                true
            }
        }
    }

    /// Forwards host focus in/out to a child that asked for it
    /// (`TermMode::FOCUS_IN_OUT`), the way a real terminal would. Only the
    /// focused tab hears about it — a background tab never had focus to
    /// gain or lose.
    fn forward_focus(&self, gained: bool) {
        if let Some(tab) = self.panes.active_tab().filter(|t| t.is_alive()) {
            if tab.mode().contains(TermMode::FOCUS_IN_OUT) {
                tab.write_input(if gained {
                    b"\x1b[I".to_vec()
                } else {
                    b"\x1b[O".to_vec()
                });
            }
        }
    }

    /// Opens a tab of `kind` in `worktree`, focusing an existing live one
    /// for the same worktree and kind rather than opening a duplicate. With
    /// `split`, the tab lands in a new group below the focused one.
    fn open_tab(&mut self, kind: TabKind, worktree: PathBuf, size: GridSize, split: bool) {
        // Reusing an existing tab is the *open* gesture's convenience. A
        // split is an explicit "give me another pane", so it always makes
        // one — including on a worktree that already has a tab.
        if !split {
            if let Some(addr) = self.panes.find_in_worktree(&worktree, kind) {
                self.panes.focus(addr);
                self.focus = Focus::Terminal;
                return;
            }
        }
        let tx = self.pty_tx.clone();
        let target = worktree.clone();
        let spawn = move |id| TerminalTab::spawn(id, kind, target, size, tx);
        let opened = if split {
            self.panes.split(spawn)
        } else {
            self.panes.open_tab(spawn)
        };
        match opened {
            Ok(_) => {
                self.focus = Focus::Terminal;
                let _ = self.commands.send(HubCommand::SetOpenTab(worktree));
            }
            Err(e) => self.notice = Some(format!("{e:#}")),
        }
    }

    /// Closes the focused tab. The `here` cue is only cleared once the
    /// *last* tab on that worktree has gone, since several tabs may share
    /// one worktree.
    fn close_tab(&mut self) {
        let Some(worktree) = self.panes.close_active() else {
            return;
        };
        if !self.panes.open_worktrees().contains(&worktree) {
            let _ = self.commands.send(HubCommand::ClearOpenTab(worktree));
        }
        if self.panes.is_empty() {
            self.focus = Focus::Tree;
        }
    }

    fn cursor_worktree(&self, view: &WorktreesViewModel) -> Option<PathBuf> {
        match self.tree.targets_for_cursor_only(view).into_iter().next()? {
            Target::Worktree { path, .. } => Some(path),
            Target::Repo { root, .. } => Some(root),
        }
    }
}

// --- Layout and drawing ---------------------------------------------------

struct Areas {
    tree: Rect,
    terminal: Option<Rect>,
    status: Rect,
}

/// The tree on the left, the terminal pane on the right when a tab exists
/// (full width otherwise), and a one-line status bar.
fn layout(area: Rect, has_terminal: bool) -> Areas {
    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Min(1), Constraint::Length(1)])
        .split(area);
    if !has_terminal {
        return Areas {
            tree: rows[0],
            terminal: None,
            status: rows[1],
        };
    }
    let cols = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(38), Constraint::Min(20)])
        .split(rows[0]);
    Areas {
        tree: cols[0],
        terminal: Some(cols[1]),
        status: rows[1],
    }
}

fn draw(frame: &mut Frame<'_>, view: &WorktreesViewModel, app: &mut App) {
    dismiss_menu_if_origin_gone(app, view);
    let areas = layout(frame.area(), !app.panes.is_empty());
    render::draw_tree_pane(
        frame,
        areas.tree,
        view,
        &mut app.tree,
        app.focus == Focus::Tree,
        app.glyphs,
    );
    report_visible_rows(app, view, areas.tree);
    // `arrange` both lays the stack out and resizes each visible group's
    // active tab to the grid it is about to be drawn into, so the emulator
    // is never read at a size it was not rendered at.
    app.terminal_area = areas.terminal;
    let group_rects = match areas.terminal {
        Some(area) => app.panes.arrange(area),
        None => Vec::new(),
    };
    app.panes
        .draw(frame, &group_rects, app.focus == Focus::Terminal);

    // The region map mirrors exactly what was just drawn, offsets included.
    let splitters = group_rects
        .iter()
        .take(group_rects.len().saturating_sub(1))
        .map(|r| super::layout::boundary_row(r.body))
        .collect();
    app.regions = RegionMap {
        // Filled in by `draw_popups` below, which is the pass that knows
        // where the menu actually landed.
        popup: None,
        tree: Block::default().borders(Borders::ALL).inner(areas.tree),
        tree_offset: app.tree.offset,
        groups: group_rects
            .iter()
            .map(|r| mouse::GroupRegion {
                strip: r.strip,
                grid: r.grid,
                tab_spans: r.tab_spans.clone(),
            })
            .collect(),
        splitters,
        splitter_cols: areas
            .terminal
            .map_or((0, 0), |a| (a.x, a.x.saturating_add(a.width))),
    };
    render::draw_status_bar(frame, areas.status, view, &app.tree, &status_hint(app));
    let area = frame.area();
    app.regions.popup = draw_popups(frame, area, app);
}

/// Tells the hub which worktree rows are actually on screen, so ahead/behind
/// is fetched for those and not for every row in the snapshot — the dominant
/// per-worktree cost (#1306), and the reason `SetVisibleRows` exists.
///
/// Sent only when the set changes: the command triggers fetches, and firing
/// it every frame would restart them ~60 times a second.
fn report_visible_rows(app: &mut App, view: &WorktreesViewModel, tree_area: Rect) {
    let inner = Block::default().borders(Borders::ALL).inner(tree_area);
    let rows = TreeState::visible_rows(view);
    let visible: Vec<PathBuf> = rows
        .iter()
        .skip(app.tree.offset)
        .take(usize::from(inner.height))
        .filter_map(|row| row.worktree_path(view))
        .collect();
    if visible != app.reported_visible {
        app.reported_visible.clone_from(&visible);
        let _ = app.commands.send(HubCommand::SetVisibleRows(visible));
    }
}

fn status_hint(app: &App) -> String {
    if let Some(notice) = &app.notice {
        return notice.clone();
    }
    match (&app.flow, app.focus) {
        (ActionFlow::Done { outcome }, _) => match outcome {
            actions::ActionOutcome::Done { summary } => summary.clone(),
            actions::ActionOutcome::BatchDone { results } => {
                let failed = results.iter().filter(|(_, r)| r.is_err()).count();
                if failed == 0 {
                    format!("done: {} target(s)", results.len())
                } else {
                    format!("{failed} of {} target(s) failed", results.len())
                }
            }
            actions::ActionOutcome::Failed { error } => format!("failed: {error}"),
        },
        (ActionFlow::Failed { error }, _) => format!("failed: {error}"),
        (_, Focus::Terminal) => {
            "alt-e tree  alt-t tab  alt-s split  alt-[/] cycle  alt-w close  alt-c copy".to_string()
        }
        (_, Focus::Tree) => {
            "↑↓ move  space mark  enter/alt-t shell tab  alt-⇧t claude tab  alt-⇧x codex tab  a/alt-m actions  c/C colour  q quit".to_string()
        }
    }
}

/// Draws whichever popup is open, and returns the hit map for it when that
/// popup takes the mouse (see [`popup_mouse_enabled`]). Every other popup
/// returns `None` and so stays inert, exactly as before #1602.
fn draw_popups(frame: &mut Frame<'_>, area: Rect, app: &mut App) -> Option<mouse::PopupRegion> {
    if app.quit_confirm {
        let modal = popup::ConfirmModal {
            prompt: actions::ConfirmPrompt {
                title: "Quit?".to_string(),
                body_lines: vec![
                    "A terminal tab is still running; quitting sends it SIGHUP.".to_string()
                ],
                ..Default::default()
            },
        };
        popup::draw_confirm_modal(frame, area, &modal);
        return None;
    }
    if let Some(prompt) = &app.prompt {
        popup::draw_prompt(
            frame,
            area,
            prompt.kind.title(),
            &prompt.input,
            &prompt.status,
        );
        return None;
    }
    if let Some(menu) = &mut app.menu {
        return Some(popup::draw_menu(frame, area, menu, app.glyphs));
    }
    match &app.relocate {
        Some(RelocateStep::PickSession {
            sessions, selected, ..
        }) => {
            // Prefer the transcript's first prompt over the bare UUID: an
            // id says nothing about which session you are moving.
            let labels: Vec<String> = sessions
                .iter()
                .map(|s| {
                    let when = relative_mtime(s.modified);
                    match relocate::transcript_preview(&s.jsonl_path, 48) {
                        Some(preview) => format!("{preview}  ({when})"),
                        None => format!("{}  ({when})", s.id),
                    }
                })
                .collect();
            let refs: Vec<&str> = labels.iter().map(String::as_str).collect();
            popup::draw_list_popup(frame, area, "Move which Claude session?", &refs, *selected);
            return None;
        }
        Some(RelocateStep::PickDestination {
            candidates,
            selected,
            ..
        }) => {
            let labels: Vec<String> = candidates.iter().map(|p| p.display().to_string()).collect();
            let refs: Vec<&str> = labels.iter().map(String::as_str).collect();
            popup::draw_list_popup(frame, area, "Move to which worktree?", &refs, *selected);
            return None;
        }
        Some(RelocateStep::Confirm { prompt, .. }) => {
            popup::draw_confirm_modal(
                frame,
                area,
                &popup::ConfirmModal {
                    prompt: prompt.clone(),
                },
            );
            return None;
        }
        None => {}
    }
    if let ActionFlow::AwaitingConfirm { prompt, .. } = &app.flow {
        popup::draw_confirm_modal(
            frame,
            area,
            &popup::ConfirmModal {
                prompt: prompt.clone(),
            },
        );
    }
    None
}

fn relative_mtime(modified: std::time::SystemTime) -> String {
    match std::time::SystemTime::now().duration_since(modified) {
        Ok(elapsed) => format!("{}s ago", elapsed.as_secs()),
        Err(_) => "just now".to_string(),
    }
}

// --- Mouse handling ---------------------------------------------------------

/// Whether the popup currently open takes the mouse.
///
/// The Phase 4a rule was "popups are chrome and chrome is inert". #1602
/// narrows that to exactly one exception — a menu you cannot click is not a
/// menu — and this predicate *is* that exception, so which popups are
/// clickable stays one legible decision rather than a scatter of
/// `is_some()` checks. Everything else keeps the old behaviour on purpose:
/// the confirm modal's keyboard-only `y`/`n` is a feature, not an oversight,
/// since it gates destructive actions.
fn popup_mouse_enabled(app: &App) -> bool {
    app.menu.is_some() && !blocking_modal_open(app)
}

/// Whether a popup that is *not* a context menu owns the screen.
///
/// `draw_popups` and `handle_key` walk their popups in different orders — a
/// menu draws above the relocate picker and the confirm modal but takes keys
/// after the picker — so a menu opened while one of these is up is either
/// visible and dead or replaces a modal that is still live in `app.flow`.
/// One predicate keeps "a context menu never appears over another modal" a
/// single decision, shared with [`popup_mouse_enabled`].
fn blocking_modal_open(app: &App) -> bool {
    app.quit_confirm
        || app.prompt.is_some()
        || app.relocate.is_some()
        || matches!(app.flow, ActionFlow::AwaitingConfirm { .. })
}

/// Handles one mouse event under the contract in `mouse.rs`. Returns
/// whether a redraw is needed.
async fn handle_mouse(
    app: &mut App,
    view: &WorktreesViewModel,
    dispatcher: &Dispatcher,
    mouse: MouseEvent,
) -> bool {
    if popup_mouse_enabled(app) {
        return handle_menu_mouse(app, view, dispatcher, mouse).await;
    }
    if app.quit_confirm
        || app.menu.is_some()
        || app.prompt.is_some()
        || app.relocate.is_some()
        || matches!(app.flow, ActionFlow::AwaitingConfirm { .. })
    {
        return false;
    }
    let (col, row, mods) = (mouse.column, mouse.row, mouse.modifiers);
    match mouse.kind {
        MouseEventKind::Down(button) => {
            app.notice = None;
            match app.regions.hit(col, row) {
                Hit::Tree { row: tree_row } => {
                    tree_mouse_down(app, view, tree_row, button, mods, (col, row))
                }
                Hit::Terminal {
                    group,
                    col: gc,
                    line,
                } => terminal_mouse_down(app, group, button, mods, (gc, line), (col, row)),
                Hit::TabStrip { group, tab } => {
                    strip_mouse_down(app, group, tab, button, (col, row))
                }
                Hit::Splitter { index } => {
                    // Only the left button resizes. Before #1602 the button
                    // was never checked here, so a right-drag on a boundary
                    // resized the pair — the latent bug the issue spotted.
                    match button {
                        MouseButton::Left => {
                            app.drag = DragOrigin::Splitter { index };
                            false
                        }
                        MouseButton::Right => {
                            let mut m =
                                popup::ActionMenu::with_entries("Layout", menu::splitter_menu());
                            m.anchor = popup::Anchor::At { col, row };
                            app.menu = Some(m);
                            app.menu_splitter = Some(index);
                            true
                        }
                        MouseButton::Middle => false,
                    }
                }
                Hit::Chrome => {
                    if button == MouseButton::Right {
                        let mut m = popup::ActionMenu::with_entries("Menu", menu::global_menu());
                        m.anchor = popup::Anchor::At { col, row };
                        app.menu = Some(m);
                        app.menu_splitter = None;
                        return true;
                    }
                    false
                }
                // The popup arms are unreachable here: `popup_mouse_enabled`
                // took every event while a menu was open, and with no menu
                // the map has no popup region to hit.
                Hit::PopupItem { .. }
                | Hit::PopupSubmenuItem { .. }
                | Hit::PopupInert
                | Hit::PopupOutside => false,
            }
        }
        MouseEventKind::Drag(button) => match app.drag {
            DragOrigin::Tree { anchor } => {
                let rows = TreeState::visible_rows(view).len();
                app.tree.set_cursor(app.regions.tree_row_clamped(row), rows);
                app.tree.mark_range(view, anchor, app.tree.cursor);
                true
            }
            DragOrigin::Terminal { group } => {
                let Some((gc, line)) = app.regions.clamp_to_grid(group, col, row) else {
                    return false;
                };
                if let Some(tab) = app.panes.group_tab(group) {
                    tab.selection_update(gc, line);
                }
                true
            }
            DragOrigin::Splitter { index } => drag_splitter(app, index, row),
            DragOrigin::Child { group } => {
                forward_to_child(app, group, MouseEventKind::Drag(button), mods, (col, row));
                false
            }
            DragOrigin::None => false,
        },
        MouseEventKind::Up(button) => {
            if let DragOrigin::Child { group } = std::mem::take(&mut app.drag) {
                forward_to_child(app, group, MouseEventKind::Up(button), mods, (col, row));
            }
            false
        }
        MouseEventKind::Moved => {
            // Only a child that asked for all-motion reporting cares.
            if let Hit::Terminal { group, .. } = app.regions.hit(col, row) {
                forward_to_child(app, group, MouseEventKind::Moved, mods, (col, row));
            }
            false
        }
        MouseEventKind::ScrollUp | MouseEventKind::ScrollDown => {
            let up = mouse.kind == MouseEventKind::ScrollUp;
            match app.regions.hit(col, row) {
                Hit::Tree { .. } => {
                    let rows = TreeState::visible_rows(view).len();
                    app.tree.move_cursor(if up { -1 } else { 1 }, rows);
                    true
                }
                // The wheel over a tab strip cycles that group's tabs.
                Hit::TabStrip { group, .. } => {
                    app.panes.focused = group;
                    app.panes.cycle_tab(if up { -1 } else { 1 });
                    true
                }
                Hit::Terminal {
                    group,
                    col: gc,
                    line,
                } => {
                    let Some(tab) = app.panes.group_tab(group) else {
                        return false;
                    };
                    match mouse::route_wheel(up, mods, gc, line, tab.mode()) {
                        WheelRoute::Forward(bytes) | WheelRoute::ArrowKeys(bytes) => {
                            if tab.is_alive() {
                                tab.write_input(bytes);
                            }
                            false
                        }
                        WheelRoute::ScrollDisplay(lines) => {
                            tab.scroll(Scroll::Delta(lines));
                            true
                        }
                    }
                }
                Hit::PopupItem { .. }
                | Hit::PopupSubmenuItem { .. }
                | Hit::PopupInert
                | Hit::PopupOutside
                | Hit::Splitter { .. }
                | Hit::Chrome => false,
            }
        }
        MouseEventKind::ScrollLeft | MouseEventKind::ScrollRight => {
            if let Hit::Terminal { group, .. } = app.regions.hit(col, row) {
                forward_to_child(app, group, mouse.kind, mods, (col, row));
            }
            false
        }
    }
}

/// Handles one mouse event while a context menu is open (contract §7: the
/// menu is modal over what it covers and inert beyond it).
///
/// Every event here is **consumed** — none of them reaches the region under
/// the menu, including the click that dismisses it.
async fn handle_menu_mouse(
    app: &mut App,
    view: &WorktreesViewModel,
    dispatcher: &Dispatcher,
    mouse: MouseEvent,
) -> bool {
    // A menu that has not been drawn yet has no region, so every position is
    // "outside" it. Without this a click before the first frame would arm the
    // menu instead of dismissing it.
    let hit = if app.regions.popup.is_some() {
        app.regions.hit(mouse.column, mouse.row)
    } else {
        Hit::PopupOutside
    };
    match mouse.kind {
        // Hover follows the pointer, as every other menu on the platform
        // does — but only redraws when the highlight actually moves, or the
        // UI would repaint at pointer-motion rate.
        MouseEventKind::Moved | MouseEventKind::Drag(_) => {
            let Some(menu) = app.menu.as_mut() else {
                return false;
            };
            match hit {
                Hit::PopupSubmenuItem { index } => {
                    if menu.submenu_selected == index {
                        return false;
                    }
                    menu.submenu_selected = index;
                    true
                }
                Hit::PopupItem { index } => {
                    if menu.selected == index {
                        return false;
                    }
                    // Hovering a different parent row closes a submenu that
                    // is no longer the one under the pointer.
                    menu.close_submenu();
                    menu.select_index(index)
                }
                _ => false,
            }
        }
        MouseEventKind::Down(button) => {
            if matches!(hit, Hit::PopupOutside) {
                app.menu = None;
                app.regions.popup = None;
                // A *right*-click outside re-targets: dismiss, then treat the
                // press as a fresh context-menu request where it landed. Any
                // other button just dismisses, and is consumed either way —
                // contract §7's "never applied to what it landed on".
                if button == MouseButton::Right {
                    if let Hit::Tree { row: tree_row } = app.regions.hit(mouse.column, mouse.row) {
                        return tree_mouse_down(
                            app,
                            view,
                            tree_row,
                            button,
                            mouse.modifiers,
                            (mouse.column, mouse.row),
                        );
                    }
                }
                return true;
            }
            // Arm on a press that starts *inside* the menu. The press that
            // opened the menu happened outside it, so its release cannot
            // invoke anything — see `ActionMenu::armed`.
            if let Some(menu) = app.menu.as_mut() {
                menu.armed = true;
                match hit {
                    Hit::PopupItem { index } => {
                        // Leave the submenu of the row being pressed alone,
                        // so the release can *toggle* it shut. Closing it
                        // here would let `activate` reopen it on the release
                        // and make a second click on the parent a no-op.
                        if menu.open_submenu != Some(index) {
                            menu.close_submenu();
                        }
                        menu.select_index(index);
                    }
                    Hit::PopupSubmenuItem { index } => menu.submenu_selected = index,
                    _ => {}
                }
            }
            true
        }
        MouseEventKind::Up(_) => {
            let Some(menu) = app.menu.as_mut() else {
                return false;
            };
            if !menu.armed {
                return false; // the opening click's own release
            }
            match hit {
                Hit::PopupSubmenuItem { index } => menu.submenu_selected = index,
                // Releasing on the parent of the open submenu closes it —
                // the conventional toggle. `Down` deliberately left it open
                // so this can see that it was.
                Hit::PopupItem { index } if menu.open_submenu == Some(index) => {
                    menu.close_submenu();
                    return true;
                }
                Hit::PopupItem { index } => {
                    if !menu.select_index(index) {
                        return false;
                    }
                }
                _ => return false,
            }
            // A click on a submenu *row* expands it rather than dispatching,
            // exactly as `Enter` does — one `activate` for both routes.
            let Some(command) = menu.activate() else {
                return true;
            };
            invoke_menu_command(app, view, dispatcher, command).await;
            true
        }
        // The wheel scrolls the menu rather than the pane beneath it.
        MouseEventKind::ScrollUp | MouseEventKind::ScrollDown => {
            let up = mouse.kind == MouseEventKind::ScrollUp;
            if let Some(menu) = app.menu.as_mut() {
                menu.move_selection(if up { -1 } else { 1 });
            }
            true
        }
        MouseEventKind::ScrollLeft | MouseEventKind::ScrollRight => false,
    }
}

/// Dispatches one menu command and closes the menu — the single path shared
/// by `Enter` and by a mouse click, so the two entry points cannot drift.
async fn invoke_menu_command(
    app: &mut App,
    view: &WorktreesViewModel,
    dispatcher: &Dispatcher,
    command: popup::MenuCommand,
) {
    app.menu = None;
    match command {
        popup::MenuCommand::Action(
            action @ (ActionKind::MoveClaudeSessionHere | ActionKind::CopyClaudeSessionHere),
        ) => {
            let mode = if action == ActionKind::MoveClaudeSessionHere {
                RelocationMode::Move
            } else {
                RelocationMode::Copy
            };
            start_relocate_flow(app, view, mode);
        }
        popup::MenuCommand::Action(action) => {
            let targets = app.tree.targets(view);
            run_action(app, dispatcher, action, targets).await;
        }
        // Re-uses the chord's own handler rather than reimplementing it, so a
        // menu entry and its keyboard shortcut cannot drift apart.
        popup::MenuCommand::Chrome(chrome) => handle_chrome_key(app, view, chrome),
        popup::MenuCommand::Ui(ui) => run_ui_action(app, ui),
    }
}

/// Runs a menu-only command — the handful with no chord and no
/// [`ActionKind`] behind them.
fn run_ui_action(app: &mut App, ui: popup::UiAction) {
    match ui {
        popup::UiAction::CloseOtherTabs | popup::UiAction::CloseTabsToRight => {
            let Some(addr) = app.menu_tab else {
                return;
            };
            let closed = if ui == popup::UiAction::CloseOtherTabs {
                app.panes.close_other_tabs(addr)
            } else {
                app.panes.close_tabs_to_right(addr)
            };
            // Every closed tab may have retired a worktree's "here" cue, so
            // each one is checked — not just the last.
            let still_open = app.panes.open_worktrees();
            for worktree in closed {
                if !still_open.contains(&worktree) {
                    let _ = app.commands.send(HubCommand::ClearOpenTab(worktree));
                }
            }
            if app.panes.is_empty() {
                app.focus = Focus::Tree;
            }
        }
        popup::UiAction::SelectAll => {
            if let Some(tab) = app.panes.active_tab() {
                tab.select_all();
            }
        }
        popup::UiAction::ClearSelection => {
            if let Some(tab) = app.panes.active_tab() {
                tab.clear_selection();
            }
        }
        popup::UiAction::ScrollToBottom => {
            if let Some(tab) = app.panes.active_tab() {
                tab.scroll_to_bottom();
            }
        }
        popup::UiAction::CloseGroupAbove | popup::UiAction::CloseGroupBelow => {
            let Some(splitter) = app.menu_splitter else {
                return;
            };
            // Splitter `n` sits between groups `n` and `n + 1`.
            let group = if ui == popup::UiAction::CloseGroupAbove {
                splitter
            } else {
                splitter + 1
            };
            let closed = app.panes.close_group(group);
            let still_open = app.panes.open_worktrees();
            for worktree in closed {
                if !still_open.contains(&worktree) {
                    let _ = app.commands.send(HubCommand::ClearOpenTab(worktree));
                }
            }
            if app.panes.is_empty() {
                app.focus = Focus::Tree;
            }
        }
        // Routes through the same confirm gate `q` uses, rather than a second
        // quit path: a live child still gets asked about.
        popup::UiAction::Quit => {
            if app.panes.any_alive() {
                app.quit_confirm = true;
            } else {
                app.quit_requested = true;
            }
        }
    }
}

/// A button-down on a tab strip: left activates the tab (or focuses the
/// group when the click is past the last one), middle closes it — the
/// conventional tab-strip gestures.
fn strip_mouse_down(
    app: &mut App,
    group: usize,
    tab: Option<usize>,
    button: MouseButton,
    (col, row): (u16, u16),
) -> bool {
    app.focus = Focus::Terminal;
    app.drag = DragOrigin::None;
    app.panes.focused = group.min(app.panes.group_count().saturating_sub(1));
    let Some(tab) = tab else {
        return true;
    };
    match button {
        MouseButton::Middle => {
            let addr = panes::TabAddr { group, tab };
            if let Some(worktree) = app.panes.close_tab(addr) {
                if !app.panes.open_worktrees().contains(&worktree) {
                    let _ = app.commands.send(HubCommand::ClearOpenTab(worktree));
                }
                if app.panes.is_empty() {
                    app.focus = Focus::Tree;
                }
            }
        }
        MouseButton::Left => {
            app.panes.focus(panes::TabAddr { group, tab });
        }
        MouseButton::Right => {
            // Focus first, so the menu's subject is the tab you clicked and
            // is also the tab you can see highlighted — matching left-click.
            let addr = panes::TabAddr { group, tab };
            app.panes.focus(addr);
            let entries = menu::strip_menu(
                app.panes.group_count(),
                group,
                app.panes.groups.get(group).map_or(0, |g| g.tabs.len()),
                tab,
            );
            let mut m = popup::ActionMenu::with_entries("Tab", entries);
            m.anchor = popup::Anchor::At { col, row };
            app.menu = Some(m);
            app.menu_tab = Some(addr);
        }
    }
    true
}

/// Drags splitter `index` to screen row `row`, resizing only the two groups
/// either side of it.
fn drag_splitter(app: &mut App, index: usize, row: u16) -> bool {
    let Some(area) = app.terminal_area else {
        return false;
    };
    let next = super::layout::drag_splitter(area, &app.panes.weights, index, row);
    if next == app.panes.weights {
        return false;
    }
    app.panes.weights = next;
    true
}

/// A button-down on tree row `tree_row` (which may be past the last row).
fn tree_mouse_down(
    app: &mut App,
    view: &WorktreesViewModel,
    tree_row: usize,
    button: MouseButton,
    mods: KeyModifiers,
    (col, row): (u16, u16),
) -> bool {
    app.focus = Focus::Tree;
    app.drag = DragOrigin::None;
    let rows = TreeState::visible_rows(view).len();
    if tree_row >= rows {
        return true; // below the last row: just the focus change
    }
    let count = app.clicks.click(col, row, Instant::now());
    match mouse::classify_tree_click(button, mods, count) {
        TreeClick::Focus => app.tree.set_cursor(tree_row, rows),
        TreeClick::ToggleMark => {
            app.tree.set_cursor(tree_row, rows);
            if let Some(path) = cursor_row_path(&app.tree, view) {
                app.tree.toggle_mark(path);
            }
        }
        TreeClick::ExtendRange => {
            let from = app.tree.cursor;
            app.tree.set_cursor(tree_row, rows);
            app.tree.mark_range(view, from, tree_row);
        }
        TreeClick::Open => {
            app.tree.set_cursor(tree_row, rows);
            open_tab_for_cursor(app, view, TabKind::Shell, false);
        }
        TreeClick::ContextMenu => {
            // The universal convention: right-clicking inside the marked set
            // acts on the whole set; right-clicking outside it moves the
            // cursor and acts on that row alone. Both end at
            // `tree.targets`, so `applicable_actions` filters unchanged.
            let inside_marks =
                row_path(view, tree_row).is_some_and(|path| app.tree.marked.contains(&path));
            if !inside_marks {
                app.tree.set_cursor(tree_row, rows);
                app.tree.clear_marks();
            }
            let targets = app.tree.targets(view);
            let mut menu = popup::ActionMenu::with_entries(
                if inside_marks { "Marked" } else { "Actions" },
                menu::tree_menu(&targets),
            );
            menu.anchor = popup::Anchor::At { col, row };
            menu.origin_row = row_path(view, tree_row);
            app.menu = Some(menu);
        }
    }
    if button == MouseButton::Left {
        app.drag = DragOrigin::Tree { anchor: tree_row };
    }
    true
}

/// A button-down on group `group`'s grid at (`gc`, `line`): the child's if
/// it asked for the mouse (contract §4), else the start of a selection —
/// simple, word or line by click count. Middle/right buttons neither paste
/// nor select: there is no clipboard→child path here by design.
fn terminal_mouse_down(
    app: &mut App,
    group: usize,
    button: MouseButton,
    mods: KeyModifiers,
    (gc, line): (u16, u16),
    (col, row): (u16, u16),
) -> bool {
    app.focus = Focus::Terminal;
    app.drag = DragOrigin::None;
    // Clicking a group focuses it, so the next key goes where the eye is.
    app.panes.focused = group.min(app.panes.group_count().saturating_sub(1));
    let click = app.clicks.click(col, row, Instant::now());
    let Some(tab) = app.panes.group_tab(group) else {
        return true;
    };
    let mode = tab.mode();
    if tab.is_alive() && mouse::forwards_to_child(mode, mods) {
        if let Some(bytes) = mouse::encode_mouse(MouseEventKind::Down(button), mods, gc, line, mode)
        {
            tab.write_input(bytes);
        }
        app.drag = DragOrigin::Child { group };
        return true;
    }
    if button == MouseButton::Left {
        let ty = match click {
            1 => SelectionType::Simple,
            2 => SelectionType::Semantic,
            _ => SelectionType::Lines,
        };
        tab.selection_start(gc, line, ty);
        app.drag = DragOrigin::Terminal { group };
        return true;
    }
    if button == MouseButton::Right {
        // Reached only when the child did *not* take the event above:
        // contract §4 keeps its priority untouched, and `⌥` is how you take
        // the mouse back from a reporting child — the same rule the left
        // button already follows, so no new modifier and no new precedence.
        let has_selection = tab.selection_to_string().is_some();
        let mut m = popup::ActionMenu::with_entries("Terminal", menu::grid_menu(has_selection));
        m.anchor = popup::Anchor::At { col, row };
        app.menu = Some(m);
        app.menu_tab = app.panes.groups.get(group).map(|g| panes::TabAddr {
            group,
            tab: g.active,
        });
    }
    true
}

/// Encodes `kind` at the screen position (clamped into group `group`'s grid
/// — a child drag stays in the grid like any other) for a live child that
/// asked for the mouse, and writes it.
fn forward_to_child(
    app: &App,
    group: usize,
    kind: MouseEventKind,
    mods: KeyModifiers,
    (col, row): (u16, u16),
) {
    let Some(tab) = app.panes.group_tab(group).filter(|t| t.is_alive()) else {
        return;
    };
    let Some((gc, line)) = app.regions.clamp_to_grid(group, col, row) else {
        return;
    };
    let mode = tab.mode();
    if !mouse::forwards_to_child(mode, mods) {
        return;
    }
    if let Some(bytes) = mouse::encode_mouse(kind, mods, gc, line, mode) {
        tab.write_input(bytes);
    }
}

// --- Key handling -----------------------------------------------------------

/// Handles one key press. Returns `true` when the app should quit.
async fn handle_key(
    app: &mut App,
    view: &WorktreesViewModel,
    dispatcher: &Dispatcher,
    key: KeyEvent,
) -> bool {
    if app.quit_confirm {
        match key.code {
            KeyCode::Char('y') | KeyCode::Enter => return true,
            KeyCode::Char('n') | KeyCode::Esc => app.quit_confirm = false,
            _ => {}
        }
        return false;
    }

    // Chrome chords first, in every focus state and over every popup.
    if let Some(chrome) = keys::chrome_key(&key) {
        handle_chrome_key(app, view, chrome);
        return false;
    }

    // An open prompt takes every remaining key: it is a text field, so a
    // bare letter must type rather than trigger a tree command.
    if app.prompt.is_some() {
        handle_prompt_key(app, view, key).await;
        return false;
    }

    // A focused, live terminal takes everything else verbatim.
    if app.focus == Focus::Terminal {
        match app.panes.active_tab().filter(|t| t.is_alive()) {
            Some(tab) => {
                if let KeyRoute::Passthrough(bytes) = keys::route(&key, tab.mode()) {
                    tab.write_input(bytes);
                }
                return false;
            }
            None => app.focus = Focus::Tree, // the child exited; fall through
        }
    }

    let code = key.code;
    if app.relocate.is_some() {
        handle_relocate_key(app, view, dispatcher, code);
        return false;
    }
    if let Some(menu) = &mut app.menu {
        match code {
            KeyCode::Up | KeyCode::Char('k') => menu.move_selection(-1),
            KeyCode::Down | KeyCode::Char('j') => menu.move_selection(1),
            // One `Esc` closes one level: the submenu first, the menu only
            // once no submenu is open.
            KeyCode::Esc => {
                if !menu.close_submenu() {
                    app.menu = None;
                }
            }
            KeyCode::Right => {
                menu.open_selected_submenu();
            }
            KeyCode::Left => {
                menu.close_submenu();
            }
            KeyCode::Home => menu.select_end(false),
            KeyCode::End => menu.select_end(true),
            KeyCode::Enter => {
                if let Some(command) = menu.activate() {
                    invoke_menu_command(app, view, dispatcher, command).await;
                }
            }
            _ => {}
        }
        return false;
    }

    match &app.flow {
        ActionFlow::AwaitingConfirm {
            action, targets, ..
        } => {
            match code {
                KeyCode::Char('y') | KeyCode::Enter => {
                    let action = *action;
                    let targets = targets.clone();
                    app.flow = ActionFlow::Executing {
                        action,
                        targets: targets.clone(),
                    };
                    let outcome = dispatcher.execute(action, &targets).await;
                    app.flow = ActionFlow::Done { outcome };
                }
                KeyCode::Char('n') | KeyCode::Esc => app.flow = ActionFlow::Idle,
                _ => {}
            }
            return false;
        }
        ActionFlow::Done { .. } | ActionFlow::Failed { .. } => {
            app.flow = ActionFlow::Idle; // any key dismisses
            return false;
        }
        _ => {}
    }

    // Tree-focused, no popup: navigation, marking, and the entry points into
    // the action menu / row-colour pickers / terminal tabs.
    match code {
        KeyCode::Char('q') => {
            if app.panes.any_alive() {
                app.quit_confirm = true;
            } else {
                return true;
            }
        }
        // Esc clears an active multi-select first; only quits once nothing
        // is marked, so a stray Esc while reviewing a selection can't lose it.
        KeyCode::Esc => {
            if !app.tree.marked.is_empty() {
                app.tree.clear_marks();
            } else if app.panes.any_alive() {
                app.quit_confirm = true;
            } else {
                return true;
            }
        }
        KeyCode::Up | KeyCode::Char('k') => {
            let rows = TreeState::visible_rows(view).len();
            app.tree.move_cursor(-1, rows);
        }
        KeyCode::Down | KeyCode::Char('j') => {
            let rows = TreeState::visible_rows(view).len();
            app.tree.move_cursor(1, rows);
        }
        KeyCode::Char(' ') => {
            if let Some(path) = cursor_row_path(&app.tree, view) {
                app.tree.toggle_mark(path);
            }
        }
        KeyCode::Enter => open_tab_for_cursor(app, view, TabKind::Shell, false),
        // The platform-conventional menu key. Handled here rather than in
        // `keys::chrome_key` on purpose: `encode_key` already sends F10 to a
        // child, and only Alt-chords are chrome (ADR-0072 §5). Tree-focused
        // is exactly where no child is listening, so nothing is stolen.
        //
        // Matched with *or without* `⇧` deliberately. The convention is
        // ⇧F10, but terminals disagree about whether they report the
        // modifier at all (some send a bare `\x1b[21~`, some `\x1b[21;2~`,
        // some a different key entirely), and the "nothing is stolen"
        // argument covers bare F10 just as well. `alt-m` is the chord for
        // terminals that send neither.
        KeyCode::F(10) => open_context_menu_for_focus(app, view),
        KeyCode::Char('a') => {
            let targets = app.tree.targets(view);
            let mut menu = popup::ActionMenu::with_entries("Actions", menu::tree_menu(&targets));
            // Same subject, same guard as the right-click and `alt-m`
            // routes: this menu builds the identical entries, so it must not
            // outlive its row either.
            menu.origin_row = cursor_row_path(&app.tree, view);
            app.menu = Some(menu);
        }
        KeyCode::Char('c') => {
            app.menu = Some(popup::ActionMenu::new(menu::row_color_items()));
        }
        KeyCode::Char('C') => {
            let targets = app.tree.targets(view);
            let outcome = dispatcher
                .execute(ActionKind::ClearRowColor, &targets)
                .await;
            app.flow = ActionFlow::Done { outcome };
        }
        // The command palette, the issue footer's `:` hint.
        KeyCode::Char(':') => {
            app.prompt = Some(Prompt {
                kind: PromptKind::Palette,
                input: String::new(),
                status: String::new(),
            });
        }
        _ => {}
    }
    false
}

/// Handles one key while a prompt is open. `Esc` cancels, `Enter` runs,
/// `Backspace` deletes, and any printable character types.
async fn handle_prompt_key(app: &mut App, view: &WorktreesViewModel, key: KeyEvent) {
    let Some(prompt) = app.prompt.as_mut() else {
        return;
    };
    match key.code {
        KeyCode::Esc => app.prompt = None,
        KeyCode::Backspace => {
            prompt.input.pop();
            prompt.status.clear();
        }
        KeyCode::Char(c) => {
            prompt.input.push(c);
            prompt.status.clear();
        }
        KeyCode::Enter => match prompt.kind {
            PromptKind::Find => {
                let needle = prompt.input.clone();
                let found = app
                    .panes
                    .active_tab()
                    .is_some_and(|tab| tab.find_in_scrollback(&needle));
                // Stay open so `Enter` again steps to the next match back.
                if let Some(prompt) = app.prompt.as_mut() {
                    prompt.status = if found {
                        String::new()
                    } else {
                        "no match".to_string()
                    };
                }
            }
            PromptKind::Palette => {
                let query = prompt.input.clone();
                app.prompt = None;
                let targets = app.tree.targets(view);
                let matches = filter_palette(palette_entries(&targets), &query);
                match matches.first() {
                    Some(item) => {
                        // `palette_entries` is built from `applicable_actions`,
                        // so every entry is an Action; a Chrome/Ui command
                        // cannot reach the palette.
                        let popup::MenuCommand::Action(action) = item.command else {
                            return;
                        };
                        if matches!(
                            action,
                            ActionKind::MoveClaudeSessionHere | ActionKind::CopyClaudeSessionHere
                        ) {
                            let mode = if action == ActionKind::MoveClaudeSessionHere {
                                RelocationMode::Move
                            } else {
                                RelocationMode::Copy
                            };
                            start_relocate_flow(app, view, mode);
                        } else {
                            // The palette opens the menu at the match rather
                            // than running it outright, so a destructive
                            // action still goes through its confirm.
                            app.menu = Some(popup::ActionMenu::new(matches));
                        }
                    }
                    None => app.notice = Some(format!("no command matching {query:?}")),
                }
            }
        },
        _ => {}
    }
}

fn handle_chrome_key(app: &mut App, view: &WorktreesViewModel, chrome: ChromeKey) {
    match chrome {
        ChromeKey::FocusTree => app.focus = Focus::Tree,
        ChromeKey::FocusTerminal => {
            if app.panes.is_empty() {
                app.notice = Some("no terminal tab — enter or alt-t opens one".to_string());
            } else {
                app.focus = Focus::Terminal;
            }
        }
        ChromeKey::NewShellTab => open_tab_for_cursor(app, view, TabKind::Shell, false),
        ChromeKey::NewClaudeTab => open_tab_for_cursor(app, view, TabKind::Claude, false),
        ChromeKey::NewCodexTab => open_tab_for_cursor(app, view, TabKind::Codex, false),
        ChromeKey::SplitShellTab => open_tab_for_cursor(app, view, TabKind::Shell, true),
        ChromeKey::CloseTab => app.close_tab(),
        ChromeKey::NextTab => app.panes.cycle_tab(1),
        ChromeKey::PrevTab => app.panes.cycle_tab(-1),
        ChromeKey::SelectTab(index) => {
            if !app.panes.select_tab(index) {
                app.notice = Some(format!("no tab {}", index + 1));
            }
        }
        ChromeKey::NextGroup => app.panes.cycle_group(1),
        ChromeKey::PrevGroup => app.panes.cycle_group(-1),
        ChromeKey::MoveTabDown => {
            if !app.panes.move_tab_to_group(1) {
                app.notice = Some("no group below to move this tab to".to_string());
            }
        }
        ChromeKey::MoveTabUp => {
            if !app.panes.move_tab_to_group(-1) {
                app.notice = Some("no group above to move this tab to".to_string());
            }
        }
        ChromeKey::ResetLayout => app.panes.reset_weights(),
        ChromeKey::ClearAllRowColors => {
            // Non-destructive and re-doable by hand, so no confirm — the
            // same reasoning `C` (clear one row) already follows.
            let _ = app.commands.send(HubCommand::ClearAllRowColors);
            app.notice = Some("cleared every row colour".to_string());
        }
        ChromeKey::Find => {
            if app.panes.active_tab().is_some() {
                app.prompt = Some(Prompt {
                    kind: PromptKind::Find,
                    input: String::new(),
                    status: String::new(),
                });
            } else {
                app.notice = Some("no terminal tab to search".to_string());
            }
        }
        ChromeKey::Copy => {
            let text = app
                .panes
                .active_tab()
                .and_then(TerminalTab::selection_to_string);
            app.notice = Some(match text {
                Some(text) if clipboard::copy_text(&text).is_ok() => {
                    // Copying consumes the selection, as in tmux/screen.
                    if let Some(tab) = app.panes.active_tab() {
                        tab.clear_selection();
                    }
                    "copied".to_string()
                }
                Some(_) => "clipboard unavailable".to_string(),
                None => "nothing selected".to_string(),
            });
        }
        ChromeKey::ContextMenu => open_context_menu_for_focus(app, view),
        ChromeKey::ScrollPageUp => {
            if let Some(tab) = app.panes.active_tab() {
                tab.scroll(Scroll::PageUp);
            }
        }
        ChromeKey::ScrollPageDown => {
            if let Some(tab) = app.panes.active_tab() {
                tab.scroll(Scroll::PageDown);
            }
        }
    }
}

/// Opens (or focuses) a `kind` tab in the cursor worktree, in a new group
/// below when `split`. The initial size is a placeholder — the first `draw`
/// resizes the emulator to the real pane before its grid is ever read.
fn open_tab_for_cursor(app: &mut App, view: &WorktreesViewModel, kind: TabKind, split: bool) {
    let Some(worktree) = app.cursor_worktree(view) else {
        app.notice = Some("no row selected".to_string());
        return;
    };
    // Refuse a split that could not be drawn rather than silently dropping
    // the new group off the bottom of the pane.
    if split {
        let height = app.terminal_area.map_or(0, |a| a.height);
        if height < panes::min_height_for(app.panes.group_count() + 1) {
            app.notice = Some("not enough height to split — close a group first".to_string());
            return;
        }
    }
    app.open_tab(
        kind,
        worktree,
        GridSize {
            cols: 80,
            lines: 24,
        },
        split,
    );
}

/// Runs the generic check→(confirm)→execute flow for every [`ActionKind`]
/// except the two session-relocation variants (routed separately — see
/// [`start_relocate_flow`]).
async fn run_action(
    app: &mut App,
    dispatcher: &Dispatcher,
    action: ActionKind,
    targets: Vec<Target>,
) {
    app.flow = ActionFlow::Checking {
        action,
        targets: targets.clone(),
    };
    match dispatcher.check(action, &targets).await {
        CheckReport::ProceedWithoutConfirm => {
            app.flow = ActionFlow::Executing {
                action,
                targets: targets.clone(),
            };
            let outcome = dispatcher.execute(action, &targets).await;
            app.flow = ActionFlow::Done { outcome };
        }
        CheckReport::NeedsConfirm { prompt, .. } => {
            app.flow = ActionFlow::AwaitingConfirm {
                action,
                targets,
                prompt,
            };
        }
        CheckReport::Refused { reason } => {
            app.flow = ActionFlow::Failed { error: reason };
        }
    }
}

/// Opens the context menu for whatever currently has focus, anchored where
/// the eye already is: the cursor row in the tree, the focused grid's
/// top-left otherwise. The keyboard route into every menu the mouse can
/// reach (`alt-m`, and `⇧F10` while the tree has focus).
fn open_context_menu_for_focus(app: &mut App, view: &WorktreesViewModel) {
    // Chrome chords are dispatched over every popup, so this entry point must
    // gate itself: a context menu drawn over a two-phase confirm would let
    // `Enter` dispatch a fresh action and discard the pending confirmation.
    // Same predicate `popup_mouse_enabled` uses, so "a context menu never
    // appears over another modal" stays one decision.
    if blocking_modal_open(app) {
        return;
    }
    // The menu must match the surface that has focus, not always the tree —
    // `alt-m` over a terminal offers the grid's entries.
    if app.focus == Focus::Terminal {
        let group = app.panes.focused;
        let Some(tab) = app.panes.group_tab(group) else {
            app.notice = Some("no terminal tab".to_string());
            return;
        };
        let has_selection = tab.selection_to_string().is_some();
        // Anchored at the emulator's own cursor, which is where the eye
        // already is; the grid's top-left is the fallback when the cursor is
        // hidden or scrolled out of view.
        let cursor = tab.cursor_position();
        let anchor = app
            .regions
            .groups
            .get(group)
            .map_or(popup::Anchor::Centered, |g| {
                let (col, line) = cursor.unwrap_or((0, 0));
                popup::Anchor::At {
                    col: g.grid.x.saturating_add(col),
                    row: g.grid.y.saturating_add(line),
                }
            });
        let mut m = popup::ActionMenu::with_entries("Terminal", menu::grid_menu(has_selection));
        m.anchor = anchor;
        app.menu = Some(m);
        app.menu_tab = app.panes.groups.get(group).map(|g| panes::TabAddr {
            group,
            tab: g.active,
        });
        return;
    }
    let targets = app.tree.targets(view);
    let entries = menu::tree_menu(&targets);
    if entries.is_empty() {
        app.notice = Some("no actions for this row".to_string());
        return;
    }
    let row = app
        .tree
        .cursor
        .saturating_sub(app.tree.offset)
        .try_into()
        .unwrap_or(u16::MAX);
    let mut m = popup::ActionMenu::with_entries("Actions", entries);
    m.anchor = popup::Anchor::At {
        col: app.regions.tree.x,
        row: app.regions.tree.y.saturating_add(row),
    };
    m.origin_row = cursor_row_path(&app.tree, view);
    app.menu = Some(m);
    app.menu_tab = None;
}

/// Closes a context menu whose subject row has gone.
///
/// The tree is live: a daemon push can remove a worktree while its menu is
/// open. Checked every frame, because that push is exactly what redraws.
fn dismiss_menu_if_origin_gone(app: &mut App, view: &WorktreesViewModel) {
    let Some(origin) = app.menu.as_ref().and_then(|m| m.origin_row.clone()) else {
        return;
    };
    let still_there = TreeState::visible_rows(view)
        .iter()
        .any(|row| row.path(view) == Some(origin.as_path()));
    if !still_there {
        app.menu = None;
        app.notice = Some("that row is gone — menu closed".to_string());
    }
}

/// The path of tree row `index`, or `None` when it is past the last row.
fn row_path(view: &WorktreesViewModel, index: usize) -> Option<PathBuf> {
    TreeState::visible_rows(view)
        .get(index)?
        .path(view)
        .map(std::path::Path::to_path_buf)
}

/// The cursor row's path — a repo root or a worktree path — regardless of
/// mark state (used for `space` to toggle a mark on the row under the
/// cursor).
fn cursor_row_path(tree: &TreeState, view: &WorktreesViewModel) -> Option<PathBuf> {
    match tree.targets_for_cursor_only(view).first()? {
        Target::Repo { root, .. } => Some(root.clone()),
        Target::Worktree { path, .. } => Some(path.clone()),
    }
}

/// Starts the Move/Copy-Claude-Session-Here wizard from the cursor row (the
/// action menu only offers this action for a single worktree target with at
/// least one session — see `actions::applicable_actions` — so the cursor row
/// is unambiguous here).
fn start_relocate_flow(app: &mut App, view: &WorktreesViewModel, mode: RelocationMode) {
    let Some(Target::Worktree { path, .. }) = tree_only_target(&app.tree, view) else {
        app.flow = ActionFlow::Failed {
            error: "no worktree row selected".to_string(),
        };
        return;
    };
    let Some(source_dir) = relocate::project_dir_for(&path) else {
        app.flow = ActionFlow::Failed {
            error: "could not resolve the Claude projects directory".to_string(),
        };
        return;
    };
    let mut sessions = match relocate::enumerate_sessions(&source_dir) {
        Ok(sessions) => sessions,
        Err(e) => {
            app.flow = ActionFlow::Failed {
                error: format!("{e:#}"),
            };
            return;
        }
    };
    if sessions.is_empty() {
        app.flow = ActionFlow::Failed {
            error: "no Claude sessions found here".to_string(),
        };
        return;
    }
    if sessions.len() == 1 {
        let session = sessions.remove(0);
        let candidates = other_worktree_paths(view, &path);
        app.relocate = Some(RelocateStep::PickDestination {
            mode,
            source_dir,
            session,
            candidates,
            selected: 0,
        });
    } else {
        app.relocate = Some(RelocateStep::PickSession {
            mode,
            source_worktree: path,
            source_dir,
            sessions,
            selected: 0,
        });
    }
}

fn tree_only_target(tree: &TreeState, view: &WorktreesViewModel) -> Option<Target> {
    tree.targets_for_cursor_only(view).into_iter().next()
}

fn other_worktree_paths(view: &WorktreesViewModel, exclude: &Path) -> Vec<PathBuf> {
    view.repos
        .iter()
        .flat_map(|repo| repo.worktrees.iter())
        .map(|wt| wt.path.clone())
        .filter(|p| p != exclude)
        .collect()
}

fn handle_relocate_key(
    app: &mut App,
    view: &WorktreesViewModel,
    dispatcher: &Dispatcher,
    code: KeyCode,
) {
    match code {
        KeyCode::Esc => app.relocate = None,
        KeyCode::Up | KeyCode::Char('k') => move_relocate_selection(app, -1),
        KeyCode::Down | KeyCode::Char('j') => move_relocate_selection(app, 1),
        KeyCode::Enter | KeyCode::Char('y') => advance_relocate(app, view, dispatcher),
        KeyCode::Char('n') => {
            if matches!(app.relocate, Some(RelocateStep::Confirm { .. })) {
                app.relocate = None;
            }
        }
        _ => {}
    }
}

fn move_relocate_selection(app: &mut App, delta: isize) {
    match &mut app.relocate {
        Some(RelocateStep::PickSession {
            sessions, selected, ..
        }) => *selected = clamp_selection(*selected, delta, sessions.len()),
        Some(RelocateStep::PickDestination {
            candidates,
            selected,
            ..
        }) => *selected = clamp_selection(*selected, delta, candidates.len()),
        Some(RelocateStep::Confirm { .. }) | None => {}
    }
}

fn clamp_selection(current: usize, delta: isize, len: usize) -> usize {
    if len == 0 {
        return 0;
    }
    let max = len - 1;
    let current = current.min(max) as isize;
    (current + delta).clamp(0, max as isize) as usize
}

fn advance_relocate(app: &mut App, view: &WorktreesViewModel, dispatcher: &Dispatcher) {
    match app.relocate.take() {
        Some(RelocateStep::PickSession {
            mode,
            source_worktree,
            source_dir,
            mut sessions,
            selected,
        }) => {
            if selected >= sessions.len() {
                return;
            }
            let session = sessions.swap_remove(selected);
            let candidates = other_worktree_paths(view, &source_worktree);
            app.relocate = Some(RelocateStep::PickDestination {
                mode,
                source_dir,
                session,
                candidates,
                selected: 0,
            });
        }
        Some(RelocateStep::PickDestination {
            mode,
            source_dir,
            session,
            candidates,
            selected,
            ..
        }) => {
            let Some(dest_worktree) = candidates.into_iter().nth(selected) else {
                return;
            };
            match dispatcher.check_relocate_session(&source_dir, &session, &dest_worktree) {
                CheckReport::NeedsConfirm { prompt, .. } => {
                    app.relocate = Some(RelocateStep::Confirm {
                        mode,
                        source_dir,
                        session,
                        dest_worktree,
                        prompt,
                    });
                }
                CheckReport::Refused { reason } => {
                    app.flow = ActionFlow::Failed { error: reason };
                }
                CheckReport::ProceedWithoutConfirm => {
                    let outcome = dispatcher.execute_relocate_session(
                        &source_dir,
                        &session,
                        &dest_worktree,
                        mode,
                    );
                    app.flow = ActionFlow::Done { outcome };
                }
            }
        }
        Some(RelocateStep::Confirm {
            mode,
            source_dir,
            session,
            dest_worktree,
            ..
        }) => {
            let outcome =
                dispatcher.execute_relocate_session(&source_dir, &session, &dest_worktree, mode);
            app.flow = ActionFlow::Done { outcome };
        }
        None => {}
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    use crossterm::event::KeyModifiers;
    use ratatui::backend::TestBackend;

    use super::super::client::WorktreesClient;
    use super::super::view_model::{RepoRow, WorktreeRow};

    fn view_with(paths: &[&str]) -> WorktreesViewModel {
        let worktrees = paths
            .iter()
            .map(|p| WorktreeRow {
                path: PathBuf::from(p),
                branch: Some("main".to_string()),
                head_sha: None,
                upstream_sha: None,
                is_main: false,
                open: false,
                window_key: None,
                pr: None,
                pr_none: false,
                operation: None,
                rebasing: false,
                pushing: false,
                ahead_behind: super::super::view_model::AheadBehindState::Unknown,
                sessions: Vec::new(),
                row_color: None,
                here: false,
            })
            .collect();
        WorktreesViewModel {
            repos: vec![RepoRow {
                main_repo: "repo".to_string(),
                github: None,
                root: PathBuf::from("/repo"),
                polling_enabled: false,
                row_color: None,
                worktrees,
            }],
            ..Default::default()
        }
    }

    /// An app wired to a nonexistent daemon socket (no action here reaches
    /// it) with the hub-command receiver returned for assertions.
    fn test_app() -> (App, Dispatcher, mpsc::UnboundedReceiver<HubCommand>) {
        let (commands, commands_rx) = mpsc::unbounded_channel();
        let (pty_tx, _pty_rx) = mpsc::unbounded_channel();
        let dispatcher = Dispatcher::new(
            WorktreesClient::new("/tmp/nonexistent-omni-dev-app-test.sock"),
            commands.clone(),
        );
        let app = App {
            tree: TreeState::default(),
            flow: ActionFlow::Idle,
            menu: None,
            relocate: None,
            focus: Focus::Tree,
            panes: panes::PaneLayout::default(),
            glyphs: GlyphMode::Unicode,
            prompt: None,
            reported_visible: Vec::new(),
            quit_confirm: false,
            quit_requested: false,
            notice: None,
            pty_tx,
            commands,
            regions: RegionMap::default(),
            terminal_area: None,
            menu_tab: None,
            menu_splitter: None,
            drag: DragOrigin::None,
            clicks: mouse::ClickTracker::default(),
        };
        (app, dispatcher, commands_rx)
    }

    fn press(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    fn alt(c: char) -> KeyEvent {
        KeyEvent::new(KeyCode::Char(c), KeyModifiers::ALT)
    }

    fn alt_key(code: KeyCode, extra: KeyModifiers) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::ALT | extra)
    }

    /// Installs an already-spawned tab as the app's only tab — the pane
    /// stack's equivalent of Phase 3's `app.terminal = Some(tab)`.
    #[cfg(unix)]
    fn install_tab(app: &mut App, tab: TerminalTab) {
        app.panes
            .open_tab(move |_| Ok(tab))
            .expect("installing a prebuilt tab cannot fail");
    }

    /// The first rendered group's grid rect.
    fn grid_rect(app: &App) -> Rect {
        app.regions
            .groups
            .first()
            .map(|g| g.grid)
            .expect("a terminal region")
    }

    /// The app's single active tab, for assertions.
    fn only_tab(app: &App) -> &TerminalTab {
        app.panes.active_tab().expect("a tab")
    }

    fn only_tab_mut(app: &mut App) -> Option<&mut TerminalTab> {
        let focused = app.panes.focused;
        app.panes.groups.get_mut(focused)?.active_tab_mut()
    }

    /// Shuts every tab down, so a test's children never outlive it.
    fn shutdown_all(app: &mut App) {
        for group in &mut app.panes.groups {
            for tab in &mut group.tabs {
                tab.shutdown();
            }
        }
    }

    fn mouse_at(kind: MouseEventKind, col: u16, row: u16, modifiers: KeyModifiers) -> MouseEvent {
        MouseEvent {
            kind,
            column: col,
            row,
            modifiers,
        }
    }

    fn draw_into(terminal: &mut Terminal<TestBackend>, view: &WorktreesViewModel, app: &mut App) {
        terminal.draw(|frame| draw(frame, view, app)).unwrap();
    }

    /// Polls `cond` for up to ten seconds.
    async fn wait_until(mut cond: impl FnMut() -> bool) -> bool {
        for _ in 0..100 {
            if cond() {
                return true;
            }
            tokio::time::sleep(Duration::from_millis(100)).await;
        }
        false
    }

    #[cfg(unix)]
    fn scripted_tab(app: &App, script: &str, cwd: PathBuf) -> TerminalTab {
        let request = super::super::terminal::pty::SpawnRequest {
            tab: 1,
            program: Some((
                "/bin/sh".to_string(),
                vec!["-c".to_string(), script.to_string()],
            )),
            cwd,
            size: GridSize { cols: 40, lines: 6 },
            extra_env: Vec::new(),
        };
        TerminalTab::from_request(TabKind::Shell, request, app.pty_tx.clone()).unwrap()
    }

    fn buffer_text(terminal: &Terminal<TestBackend>) -> String {
        terminal
            .backend()
            .buffer()
            .content
            .iter()
            .map(ratatui::buffer::Cell::symbol)
            .collect()
    }

    #[tokio::test]
    async fn tree_keys_move_mark_open_menus_and_quit() {
        let (mut app, dispatcher, mut commands) = test_app();
        let view = view_with(&["/repo/a", "/repo/b"]);

        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('j'))).await);
        assert_eq!(app.tree.cursor, 1);
        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('k'))).await);
        assert_eq!(app.tree.cursor, 0);
        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::Down)).await);

        // Space marks the cursor row; Esc clears marks before it quits.
        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char(' '))).await);
        assert_eq!(app.tree.marked.len(), 1);
        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::Esc)).await);
        assert!(app.tree.marked.is_empty());
        assert!(handle_key(&mut app, &view, &dispatcher, press(KeyCode::Esc)).await);
        assert!(handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('q'))).await);

        // The action menu opens on `a`, navigates, and closes on Esc.
        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('a'))).await);
        assert!(app.menu.is_some());
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Down)).await;
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('k'))).await;
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::End)).await;
        let end_selected = app.menu.as_ref().unwrap().selected;
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Home)).await;
        assert_eq!(
            app.menu.as_ref().unwrap().selected,
            0,
            "Home lands on the first item"
        );
        assert_ne!(end_selected, 0, "End had landed elsewhere first");
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Esc)).await;
        assert!(app.menu.is_none());

        // The colour picker dispatches a local SetRowColor through the hub.
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('c'))).await;
        assert!(app.menu.is_some());
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Enter)).await;
        assert!(matches!(app.flow, ActionFlow::Done { .. }));
        assert!(matches!(
            commands.try_recv(),
            Ok(HubCommand::SetRowColor(..))
        ));
        assert!(status_hint(&app).starts_with("Set colour"));
        // Any key dismisses the outcome.
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('x'))).await;
        assert_eq!(app.flow, ActionFlow::Idle);

        // `C` clears directly, no popup.
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('C'))).await;
        assert!(matches!(
            commands.try_recv(),
            Ok(HubCommand::ClearRowColor(_))
        ));
        assert!(matches!(app.flow, ActionFlow::Done { .. }));
        app.flow = ActionFlow::Idle;

        // An unknown key is ignored.
        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::F(9))).await);
    }

    #[tokio::test]
    async fn an_action_that_needs_the_daemon_fails_visibly_when_it_is_down() {
        let (mut app, dispatcher, _commands) = test_app();
        let view = view_with(&["/repo/a"]);
        app.tree.cursor = 1; // the worktree row, not the repo header
                             // Open the menu and pick "Close Window" (ProceedWithoutConfirm, one
                             // daemon call) — the socket does not exist, so the batch reports it.
        let targets = app.tree.targets(&view);
        run_action(&mut app, &dispatcher, ActionKind::CloseWindow, targets).await;
        match &app.flow {
            ActionFlow::Done {
                outcome: actions::ActionOutcome::BatchDone { results },
            } => assert!(results.iter().all(|(_, r)| r.is_err())),
            other => panic!("unexpected flow: {other:?}"),
        }
        assert!(status_hint(&app).contains("failed"));

        // A two-phase check against a dead daemon is refused, not confirmed.
        let targets = app.tree.targets(&view);
        run_action(&mut app, &dispatcher, ActionKind::CloseWorktree, targets).await;
        assert!(matches!(app.flow, ActionFlow::Failed { .. }));
        assert!(status_hint(&app).starts_with("failed:"));

        // A confirm that arrives is answered by y/n.
        app.flow = ActionFlow::AwaitingConfirm {
            action: ActionKind::CloseWorktree,
            targets: Vec::new(),
            prompt: actions::ConfirmPrompt::default(),
        };
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('n'))).await;
        assert_eq!(app.flow, ActionFlow::Idle);
        app.flow = ActionFlow::AwaitingConfirm {
            action: ActionKind::CloseWorktree,
            targets: Vec::new(),
            prompt: actions::ConfirmPrompt::default(),
        };
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('y'))).await;
        assert!(matches!(app.flow, ActionFlow::Done { .. }));
    }

    #[tokio::test]
    async fn alt_m_and_f10_both_open_the_context_menu_from_the_tree() {
        let (mut app, dispatcher, _commands) = test_app();
        let view = view_with(&["/repo/a"]);
        app.tree.cursor = 1; // a worktree row, so there are actions to offer

        handle_key(&mut app, &view, &dispatcher, alt('m')).await;
        assert!(app.menu.is_some(), "alt-m opens the menu");
        assert!(
            app.menu
                .as_ref()
                .and_then(|m| m.origin_row.as_ref())
                .is_some(),
            "and records the row it acts on, like the right-click route"
        );
        assert!(
            matches!(
                app.menu.as_ref().map(|m| m.anchor),
                Some(popup::Anchor::At { .. })
            ),
            "anchored at the cursor, not centred like the `a` menu"
        );
        app.menu = None;

        // F10 with and without the conventional shift: terminals disagree
        // about whether they report the modifier, and neither steals a key
        // from a child while the tree has focus.
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::F(10))).await;
        assert!(app.menu.is_some(), "bare F10 opens it");
        app.menu = None;
        handle_key(
            &mut app,
            &view,
            &dispatcher,
            KeyEvent::new(KeyCode::F(10), KeyModifiers::SHIFT),
        )
        .await;
        assert!(app.menu.is_some(), "shift-F10 opens it too");
    }

    #[tokio::test]
    async fn the_a_menu_and_the_context_menu_offer_the_same_entries() {
        // The two entry points must not drift: one filter, two routes.
        let (mut app, dispatcher, _commands) = test_app();
        let view = view_with(&["/repo/a"]);
        app.tree.cursor = 1;

        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('a'))).await;
        let from_a = app.menu.take().expect("`a` opens a menu").entries;
        handle_key(&mut app, &view, &dispatcher, alt('m')).await;
        let from_alt_m = app.menu.take().expect("alt-m opens a menu").entries;
        assert_eq!(from_a, from_alt_m);
    }

    #[tokio::test]
    async fn the_context_menu_key_is_inert_over_another_modal() {
        let (mut app, dispatcher, _commands) = test_app();
        let view = view_with(&["/repo/a"]);
        app.tree.cursor = 1;

        // Chrome chords are dispatched over every popup, and `draw_popups`
        // ranks a menu *above* the confirm modal while `handle_key` ranks it
        // *below* the relocate picker. So an ungated alt-m yields either a
        // menu you can see and not drive, or one that silently replaces a
        // pending two-phase confirmation.
        app.flow = ActionFlow::AwaitingConfirm {
            action: ActionKind::CloseWorktree,
            targets: app.tree.targets(&view),
            prompt: actions::ConfirmPrompt {
                title: "Close?".to_string(),
                ..Default::default()
            },
        };
        handle_key(&mut app, &view, &dispatcher, alt('m')).await;
        assert!(app.menu.is_none(), "no menu over a confirm modal");
        assert!(
            matches!(app.flow, ActionFlow::AwaitingConfirm { .. }),
            "and the pending confirm survives"
        );
        app.flow = ActionFlow::Idle;

        app.prompt = Some(Prompt {
            kind: PromptKind::Palette,
            input: String::new(),
            status: String::new(),
        });
        handle_key(&mut app, &view, &dispatcher, alt('m')).await;
        assert!(app.menu.is_none(), "no menu over a prompt");
        app.prompt = None;

        // And with nothing in the way it still works.
        handle_key(&mut app, &view, &dispatcher, alt('m')).await;
        assert!(app.menu.is_some());
    }

    #[tokio::test]
    async fn chrome_chords_without_a_terminal_leave_notices() {
        let (mut app, dispatcher, _commands) = test_app();
        let view = view_with(&["/repo/a"]);
        handle_key(&mut app, &view, &dispatcher, alt('l')).await;
        assert!(app
            .notice
            .as_deref()
            .unwrap_or("")
            .contains("no terminal tab"));
        handle_key(&mut app, &view, &dispatcher, alt('c')).await;
        assert_eq!(app.notice.as_deref(), Some("nothing selected"));
        handle_key(&mut app, &view, &dispatcher, alt('w')).await; // no tab: no-op
        assert_eq!(app.focus, Focus::Tree);
        handle_key(&mut app, &view, &dispatcher, alt('e')).await;
        assert_eq!(app.focus, Focus::Tree);
        handle_key(
            &mut app,
            &view,
            &dispatcher,
            KeyEvent::new(KeyCode::PageUp, KeyModifiers::SHIFT),
        )
        .await;
        handle_key(
            &mut app,
            &view,
            &dispatcher,
            KeyEvent::new(KeyCode::PageDown, KeyModifiers::SHIFT),
        )
        .await;
        // A stray PTY event for a tab that no longer exists is ignored.
        assert!(!app.handle_pty_event(99, TermEvent::Wakeup));
        app.forward_focus(true); // no terminal: no-op
    }

    #[tokio::test]
    async fn relocate_wizard_fails_cleanly_without_sessions_and_cancels() {
        let (mut app, dispatcher, _commands) = test_app();
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().to_string_lossy().into_owned();
        let view = view_with(&[&path, "/repo/other"]);

        // No Claude sessions exist for a fresh temp dir.
        start_relocate_flow(&mut app, &view, RelocationMode::Move);
        assert!(matches!(app.flow, ActionFlow::Failed { .. }));
        app.flow = ActionFlow::Idle;

        // Navigating and cancelling each picker step.
        let session = actions::relocate_types::SessionInfo {
            id: "s1".to_string(),
            jsonl_path: dir.path().join("s1.jsonl"),
            modified: std::time::SystemTime::UNIX_EPOCH,
            has_sidecar: false,
        };
        app.relocate = Some(RelocateStep::PickSession {
            mode: RelocationMode::Copy,
            source_worktree: dir.path().to_path_buf(),
            source_dir: dir.path().to_path_buf(),
            sessions: vec![session.clone(), session.clone()],
            selected: 0,
        });
        let mut picker_terminal = Terminal::new(TestBackend::new(80, 24)).unwrap();
        picker_terminal
            .draw(|frame| draw(frame, &view, &mut app))
            .unwrap();
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Down)).await;
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Up)).await;
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Enter)).await;
        assert!(matches!(
            app.relocate,
            Some(RelocateStep::PickDestination { .. })
        ));
        picker_terminal
            .draw(|frame| draw(frame, &view, &mut app))
            .unwrap();
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('j'))).await;
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('n'))).await; // no-op here
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Esc)).await;
        assert!(app.relocate.is_none());

        // The confirm step can be declined.
        app.relocate = Some(RelocateStep::Confirm {
            mode: RelocationMode::Copy,
            source_dir: dir.path().to_path_buf(),
            session,
            dest_worktree: PathBuf::from("/repo/other"),
            prompt: actions::ConfirmPrompt::default(),
        });
        let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap();
        terminal.draw(|frame| draw(frame, &view, &mut app)).unwrap();
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('n'))).await;
        assert!(app.relocate.is_none());
        assert_eq!(clamp_selection(5, 1, 0), 0);
        assert!(relative_mtime(std::time::SystemTime::now()).ends_with("ago"));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_terminal_tab_takes_focus_keys_and_closes_cleanly() {
        let (mut app, dispatcher, mut commands) = test_app();
        let dir = tempfile::tempdir().unwrap();
        let here = dir.path().to_path_buf();
        let view = view_with(&[&here.to_string_lossy(), "/repo/other"]);

        // Inject a scripted shell as the tab, exactly as open_tab would.
        let request = super::super::terminal::pty::SpawnRequest {
            tab: 1,
            program: Some((
                "/bin/sh".to_string(),
                vec!["-c".to_string(), "sleep 5".to_string()],
            )),
            cwd: here.clone(),
            size: GridSize { cols: 40, lines: 6 },
            extra_env: Vec::new(),
        };
        let tab = TerminalTab::from_request(TabKind::Shell, request, app.pty_tx.clone()).unwrap();
        install_tab(&mut app, tab);
        app.focus = Focus::Terminal;

        // Keys go to the child, Esc included; chords are still chrome.
        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('x'))).await);
        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::Esc)).await);
        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::CapsLock)).await);
        handle_key(&mut app, &view, &dispatcher, alt('e')).await;
        assert_eq!(app.focus, Focus::Tree);
        handle_key(&mut app, &view, &dispatcher, alt('l')).await;
        assert_eq!(app.focus, Focus::Terminal);
        assert!(status_hint(&app).contains("alt-e tree"));
        app.forward_focus(false);
        app.forward_focus(true);

        // Opening the same worktree again focuses the tab it already has
        // rather than opening a duplicate (Phase 4b: a second worktree now
        // opens a second tab instead of being refused).
        app.focus = Focus::Tree;
        app.open_tab(
            TabKind::Shell,
            here.clone(),
            GridSize {
                cols: 80,
                lines: 24,
            },
            false,
        );
        assert_eq!(app.focus, Focus::Terminal);
        assert_eq!(app.panes.groups[0].tabs.len(), 1, "no duplicate tab");

        // Drawing lays out both panes, resizes the emulator to the pane, and
        // shows the quit confirm when `q` is pressed with a live child.
        let mut terminal = Terminal::new(TestBackend::new(100, 20)).unwrap();
        terminal.draw(|frame| draw(frame, &view, &mut app)).unwrap();
        assert!(buffer_text(&terminal).contains("WORKTREES"));
        app.focus = Focus::Tree;
        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('q'))).await);
        assert!(app.quit_confirm);
        terminal.draw(|frame| draw(frame, &view, &mut app)).unwrap();
        assert!(buffer_text(&terminal).contains("Quit?"));
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('n'))).await;
        assert!(!app.quit_confirm);
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Esc)).await;
        assert!(app.quit_confirm);
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('x'))).await; // ignored
        assert!(handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('y'))).await);
        app.quit_confirm = false;

        // Live PTY events flow through the tab; then alt-w closes it.
        assert!(app.handle_pty_event(1, TermEvent::Wakeup));
        assert!(!app.handle_pty_event(1, TermEvent::Bell));
        assert!(app.handle_pty_event(1, TermEvent::ChildExit(std::process::ExitStatus::default())));
        assert!(app
            .notice
            .as_deref()
            .unwrap_or("")
            .contains("terminal exited"));
        only_tab_mut(&mut app).unwrap().exit_status = None; // pretend it is still live
        handle_key(&mut app, &view, &dispatcher, alt('w')).await;
        assert!(app.panes.is_empty());
        assert_eq!(app.focus, Focus::Tree);
        assert!(
            drained_clear_open_tab(&mut commands, &here),
            "closing the last tab clears the here cue"
        );
    }

    /// Drains the hub channel looking for `ClearOpenTab(path)`. Drawing also
    /// posts `SetVisibleRows`, so the wanted command is not necessarily
    /// first in the queue.
    fn drained_clear_open_tab(
        commands: &mut mpsc::UnboundedReceiver<HubCommand>,
        path: &Path,
    ) -> bool {
        std::iter::from_fn(|| commands.try_recv().ok())
            .any(|cmd| matches!(cmd, HubCommand::ClearOpenTab(p) if p == path))
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn open_tab_for_cursor_spawns_and_reports_here_beside_an_exited_tab() {
        let (mut app, _dispatcher, mut commands) = test_app();
        let dir = tempfile::tempdir().unwrap();
        let here = dir.path().to_path_buf();
        let view = view_with(&[&here.to_string_lossy()]);
        app.tree.cursor = 1; // the worktree row, not the repo header

        // Route the real spawn through a scripted child by pre-seeding an
        // exited tab: open_tab must close it and spawn afresh.
        let request = super::super::terminal::pty::SpawnRequest {
            tab: 1,
            program: Some((
                "/bin/sh".to_string(),
                vec!["-c".to_string(), "true".to_string()],
            )),
            cwd: here.clone(),
            size: GridSize { cols: 40, lines: 6 },
            extra_env: Vec::new(),
        };
        let mut tab =
            TerminalTab::from_request(TabKind::Shell, request, app.pty_tx.clone()).unwrap();
        tab.exit_status = Some(std::process::ExitStatus::default());
        install_tab(&mut app, tab);

        // A missing cursor row is a notice, not a spawn.
        let empty = WorktreesViewModel::default();
        open_tab_for_cursor(&mut app, &empty, TabKind::Shell, false);
        assert_eq!(app.notice.as_deref(), Some("no row selected"));

        // With a row: an exited tab is not reused (it keeps its grid and
        // exit status on screen until closed), so the user's shell is
        // spawned as a second tab beside it and reported open.
        open_tab_for_cursor(&mut app, &view, TabKind::Shell, false);
        match commands.try_recv() {
            Ok(HubCommand::SetOpenTab(p)) => assert_eq!(p, here),
            other => {
                // Spawning the login shell can legitimately fail on a
                // minimal CI image; then the notice carries the error.
                assert!(
                    app.notice.is_some(),
                    "neither a tab nor a notice: {other:?}"
                );
            }
        }
        shutdown_all(&mut app);
    }

    #[tokio::test]
    async fn mouse_on_the_tree_focuses_marks_ranges_scrolls_and_ignores_chrome() {
        let (mut app, dispatcher, _commands) = test_app();
        let view = view_with(&["/repo/a", "/repo/b", "/repo/c"]); // 4 rows with the header
        let mut terminal = Terminal::new(TestBackend::new(80, 12)).unwrap();
        draw_into(&mut terminal, &view, &mut app);
        let tree = app.regions.tree;
        assert_eq!((tree.x, tree.y), (1, 1), "inside the border");
        let none = KeyModifiers::NONE;
        let down = |row: u16, mods| mouse_at(MouseEventKind::Down(MouseButton::Left), 5, row, mods);

        // A drag with no drag in progress (no preceding press, or one that
        // did not start a drag) is inert.
        assert_eq!(app.drag, DragOrigin::None);
        assert!(
            !handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(MouseEventKind::Drag(MouseButton::Left), 5, 3, none)
            )
            .await
        );

        // The border is chrome; a click there does nothing.
        assert!(!handle_mouse(&mut app, &view, &dispatcher, down(0, none)).await);
        // A click on row 2 moves the cursor there.
        assert!(handle_mouse(&mut app, &view, &dispatcher, down(tree.y + 2, none)).await);
        assert_eq!(app.tree.cursor, 2);
        assert_eq!(app.drag, DragOrigin::Tree { anchor: 2 });
        assert!(
            !handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(MouseEventKind::Up(MouseButton::Left), 5, 3, none)
            )
            .await
        );
        assert_eq!(app.drag, DragOrigin::None);
        assert!(app.tree.marked.is_empty(), "a click alone marks nothing");

        // ^-click toggles a mark; ⇧-click marks the range from the cursor.
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                down(tree.y + 3, KeyModifiers::CONTROL)
            )
            .await
        );
        assert!(app.tree.marked.contains(&PathBuf::from("/repo/c")));
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                down(tree.y + 1, KeyModifiers::SHIFT)
            )
            .await
        );
        assert_eq!(app.tree.cursor, 1);
        assert_eq!(app.tree.marked.len(), 3, "rows 1..=3 marked");
        app.tree.clear_marks();

        // A drag from row 1 to below the pane range-marks down to the last
        // row and stops there (clamped to the tree).
        assert!(handle_mouse(&mut app, &view, &dispatcher, down(tree.y + 1, none)).await);
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(MouseEventKind::Drag(MouseButton::Left), 200, 200, none)
            )
            .await
        );
        assert_eq!(app.tree.cursor, 3);
        assert_eq!(app.tree.marked.len(), 3);
        handle_mouse(
            &mut app,
            &view,
            &dispatcher,
            mouse_at(MouseEventKind::Up(MouseButton::Left), 200, 200, none),
        )
        .await;

        // The wheel moves the cursor; below the last row only focus changes.
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(MouseEventKind::ScrollUp, 5, tree.y, none)
            )
            .await
        );
        assert_eq!(app.tree.cursor, 2);
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(MouseEventKind::ScrollDown, 5, tree.y, none)
            )
            .await
        );
        assert_eq!(app.tree.cursor, 3);
        assert!(handle_mouse(&mut app, &view, &dispatcher, down(tree.y + 8, none)).await);
        assert_eq!(app.tree.cursor, 3);
        // A right-click focuses without starting a drag.
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(MouseEventKind::Down(MouseButton::Right), 5, tree.y, none)
            )
            .await
        );
        assert_eq!(app.tree.cursor, 0);
        assert_eq!(app.drag, DragOrigin::None);
        assert!(
            !handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(MouseEventKind::Drag(MouseButton::Right), 5, 3, none)
            )
            .await
        );
        // Moves and horizontal wheel are inert with no terminal.
        assert!(
            !handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(MouseEventKind::Moved, 5, 3, none)
            )
            .await
        );
        assert!(
            !handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(MouseEventKind::ScrollLeft, 5, 3, none)
            )
            .await
        );

        // #1602 contract §7: a menu takes the mouse. A click outside it
        // dismisses it, and that click is *consumed* — it must not also move
        // the cursor to the row it landed on.
        app.menu = Some(popup::ActionMenu::new(Vec::new()));
        let cursor_before = app.tree.cursor;
        assert!(handle_mouse(&mut app, &view, &dispatcher, down(tree.y, none)).await);
        assert!(app.menu.is_none(), "the outside click dismissed the menu");
        assert_eq!(
            app.tree.cursor, cursor_before,
            "and was consumed, not applied to the row underneath"
        );

        // Every *other* popup stays inert, exactly as before: the confirm
        // modal's keyboard-only y/n is a feature, not an oversight.
        app.quit_confirm = true;
        assert!(!handle_mouse(&mut app, &view, &dispatcher, down(tree.y, none)).await);
        app.quit_confirm = false;
    }

    #[tokio::test]
    async fn menu_mouse_hovers_arms_scrolls_and_invokes_under_the_pointer() {
        let (mut app, dispatcher, mut commands) = test_app();
        let view = view_with(&["/repo/a"]);
        let none = KeyModifiers::NONE;
        let colors = crate::cli::worktrees::ui::row_colors::KNOWN_ROW_COLORS;
        app.menu = Some(popup::ActionMenu::new(vec![
            popup::MenuItem::action(ActionKind::SetRowColor(colors[0]), "a"),
            popup::MenuItem::action(ActionKind::SetRowColor(colors[1]), "b"),
        ]));
        // A hand-built region, standing in for what `draw_menu` would have
        // reported: two one-row items inside a small popup rect.
        app.regions.popup = Some(mouse::PopupRegion {
            submenu: None,
            rect: Rect::new(9, 4, 12, 4),
            items: vec![(0, Rect::new(10, 5, 10, 1)), (1, Rect::new(10, 6, 10, 1))],
        });
        let at = |kind, row| mouse_at(kind, 10, row, none);

        // Hovering a different item moves the highlight and asks for a
        // redraw; hovering the one already selected does not.
        assert!(handle_mouse(&mut app, &view, &dispatcher, at(MouseEventKind::Moved, 6)).await);
        assert_eq!(app.menu.as_ref().unwrap().selected, 1);
        assert!(!handle_mouse(&mut app, &view, &dispatcher, at(MouseEventKind::Moved, 6)).await);

        // The release that opened the menu lands here too, unarmed — it must
        // be ignored rather than invoking whatever is under it.
        assert!(
            !handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                at(MouseEventKind::Up(MouseButton::Right), 6)
            )
            .await
        );
        assert!(app.menu.is_some(), "an unarmed release does not dismiss");

        // The wheel moves the selection without arming anything.
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                at(MouseEventKind::ScrollUp, 6)
            )
            .await
        );
        assert_eq!(app.menu.as_ref().unwrap().selected, 0);
        assert!(!app.menu.as_ref().unwrap().armed);
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                at(MouseEventKind::ScrollDown, 6)
            )
            .await
        );
        assert_eq!(app.menu.as_ref().unwrap().selected, 1);

        // A press that starts inside the menu arms it and selects under the
        // pointer; the matching release then invokes that item and closes
        // the menu.
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                at(MouseEventKind::Down(MouseButton::Right), 5)
            )
            .await
        );
        assert!(app.menu.as_ref().unwrap().armed);
        assert_eq!(app.menu.as_ref().unwrap().selected, 0);
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                at(MouseEventKind::Up(MouseButton::Right), 5)
            )
            .await
        );
        assert!(app.menu.is_none(), "invoking a command closes the menu");
        assert!(matches!(
            commands.try_recv(),
            Ok(HubCommand::SetRowColor(..))
        ));
        assert!(matches!(app.flow, ActionFlow::Done { .. }));
    }

    #[tokio::test]
    async fn menu_command_move_and_copy_claude_session_start_the_relocate_wizard() {
        let (mut app, dispatcher, _commands) = test_app();
        let view = view_with(&["/repo/a"]);

        // Both variants route through the same relocate wizard — with no
        // Claude sessions for this row, it fails cleanly rather than hanging
        // (mirrors `relocate_wizard_fails_cleanly_without_sessions_and_cancels`).
        app.menu = Some(popup::ActionMenu::new(Vec::new()));
        invoke_menu_command(
            &mut app,
            &view,
            &dispatcher,
            popup::MenuCommand::Action(ActionKind::MoveClaudeSessionHere),
        )
        .await;
        assert!(app.menu.is_none());
        assert!(matches!(app.flow, ActionFlow::Failed { .. }));
        app.flow = ActionFlow::Idle;

        app.menu = Some(popup::ActionMenu::new(Vec::new()));
        invoke_menu_command(
            &mut app,
            &view,
            &dispatcher,
            popup::MenuCommand::Action(ActionKind::CopyClaudeSessionHere),
        )
        .await;
        assert!(app.menu.is_none());
        assert!(matches!(app.flow, ActionFlow::Failed { .. }));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn ui_action_close_other_and_close_to_right_clear_the_here_cue_for_every_closed_tab() {
        let (mut app, dispatcher, mut commands) = test_app();
        let view = view_with(&["/repo/a"]);
        let dirs: Vec<tempfile::TempDir> = (0..3).map(|_| tempfile::tempdir().unwrap()).collect();
        for d in &dirs {
            let tab = scripted_tab(&app, "sleep 5", d.path().to_path_buf());
            install_tab(&mut app, tab);
        }
        assert_eq!(app.panes.groups[0].tabs.len(), 3);

        // Closing everything but tab 1 clears the cue for tabs 0 and 2, but
        // not for the surviving anchor.
        app.menu_tab = Some(panes::TabAddr { group: 0, tab: 1 });
        app.menu = Some(popup::ActionMenu::new(Vec::new()));
        invoke_menu_command(
            &mut app,
            &view,
            &dispatcher,
            popup::MenuCommand::Ui(popup::UiAction::CloseOtherTabs),
        )
        .await;
        assert!(app.menu.is_none());
        assert_eq!(app.panes.groups[0].tabs.len(), 1, "only the anchor remains");
        let cleared: Vec<PathBuf> = std::iter::from_fn(|| commands.try_recv().ok())
            .filter_map(|cmd| match cmd {
                HubCommand::ClearOpenTab(p) => Some(p),
                _ => None,
            })
            .collect();
        assert!(cleared.contains(&dirs[0].path().to_path_buf()));
        assert!(cleared.contains(&dirs[2].path().to_path_buf()));
        assert!(!cleared.contains(&dirs[1].path().to_path_buf()));

        // Same for `CloseTabsToRight`, with a fresh set of tabs so none of
        // them overlaps a worktree that is still open from phase one.
        let dirs2: Vec<tempfile::TempDir> = (0..3).map(|_| tempfile::tempdir().unwrap()).collect();
        for d in &dirs2 {
            let tab = scripted_tab(&app, "sleep 5", d.path().to_path_buf());
            install_tab(&mut app, tab);
        }
        assert_eq!(app.panes.groups[0].tabs.len(), 4, "the anchor plus 3 more");
        app.menu_tab = Some(panes::TabAddr { group: 0, tab: 1 });
        app.menu = Some(popup::ActionMenu::new(Vec::new()));
        invoke_menu_command(
            &mut app,
            &view,
            &dispatcher,
            popup::MenuCommand::Ui(popup::UiAction::CloseTabsToRight),
        )
        .await;
        assert_eq!(
            app.panes.groups[0].tabs.len(),
            2,
            "the two tabs left of it survive"
        );
        let cleared: Vec<PathBuf> = std::iter::from_fn(|| commands.try_recv().ok())
            .filter_map(|cmd| match cmd {
                HubCommand::ClearOpenTab(p) => Some(p),
                _ => None,
            })
            .collect();
        assert!(cleared.contains(&dirs2[1].path().to_path_buf()));
        assert!(cleared.contains(&dirs2[2].path().to_path_buf()));
        assert!(!cleared.contains(&dirs2[0].path().to_path_buf()));

        shutdown_all(&mut app);
    }

    /// A stale `menu_tab` naming a command run with nothing open at all —
    /// the closes are no-ops, but the menu still resets `focus` to the tree
    /// since the layout was already empty.
    #[tokio::test]
    async fn ui_action_close_resets_focus_to_tree_when_the_layout_is_already_empty() {
        let (mut app, dispatcher, _commands) = test_app();
        let view = view_with(&["/repo/a"]);
        app.focus = Focus::Terminal;
        app.menu_tab = Some(panes::TabAddr { group: 0, tab: 0 });
        app.menu = Some(popup::ActionMenu::new(Vec::new()));

        invoke_menu_command(
            &mut app,
            &view,
            &dispatcher,
            popup::MenuCommand::Ui(popup::UiAction::CloseOtherTabs),
        )
        .await;

        assert_eq!(app.focus, Focus::Tree);
    }

    /// A `menu` command with no `menu_tab` set (the palette and the command
    /// menu never set one) is a no-op rather than a panic.
    #[tokio::test]
    async fn ui_action_close_variants_without_a_menu_tab_are_a_no_op() {
        let (mut app, dispatcher, _commands) = test_app();
        let view = view_with(&["/repo/a"]);
        app.menu_tab = None;
        app.menu = Some(popup::ActionMenu::new(Vec::new()));

        invoke_menu_command(
            &mut app,
            &view,
            &dispatcher,
            popup::MenuCommand::Ui(popup::UiAction::CloseTabsToRight),
        )
        .await;

        assert!(app.menu.is_none(), "the command still closes the menu");
        assert!(app.panes.is_empty());
    }

    /// `SelectAll`, `ClearSelection` and `ScrollToBottom` forward to the
    /// active tab exactly like their chord equivalents — this just pins that
    /// the menu wiring reaches them.
    #[cfg(unix)]
    #[tokio::test]
    async fn ui_action_select_all_clear_selection_and_scroll_to_bottom_touch_the_active_tab() {
        let (mut app, dispatcher, _commands) = test_app();
        let view = view_with(&["/repo/a"]);
        let dir = tempfile::tempdir().unwrap();
        let tab = scripted_tab(&app, "sleep 5", dir.path().to_path_buf());
        install_tab(&mut app, tab);

        for ui in [
            popup::UiAction::SelectAll,
            popup::UiAction::ClearSelection,
            popup::UiAction::ScrollToBottom,
        ] {
            app.menu = Some(popup::ActionMenu::new(Vec::new()));
            invoke_menu_command(&mut app, &view, &dispatcher, popup::MenuCommand::Ui(ui)).await;
            assert!(app.menu.is_none());
        }

        shutdown_all(&mut app);
    }

    #[tokio::test]
    async fn clicking_a_submenu_row_toggles_it_open_and_shut() {
        let (mut app, dispatcher, _commands) = test_app();
        let view = view_with(&["/repo/a"]);
        app.menu = Some(popup::ActionMenu::with_entries(
            "Actions",
            vec![
                popup::MenuEntry::Item(popup::MenuItem::action(ActionKind::Focus, "Open Worktree")),
                popup::MenuEntry::Submenu {
                    label: "Row Colour",
                    items: vec![popup::MenuItem::action(
                        ActionKind::SetRowColor("red"),
                        "red",
                    )],
                },
            ],
        ));
        // Stands in for what `draw_menu` would have reported.
        app.regions.popup = Some(mouse::PopupRegion {
            submenu: None,
            rect: Rect::new(9, 4, 12, 4),
            items: vec![(0, Rect::new(10, 5, 10, 1)), (1, Rect::new(10, 6, 10, 1))],
        });
        let none = KeyModifiers::NONE;
        let click = |row: u16| {
            [
                mouse_at(MouseEventKind::Down(MouseButton::Left), 12, row, none),
                mouse_at(MouseEventKind::Up(MouseButton::Left), 12, row, none),
            ]
        };

        for event in click(6) {
            handle_mouse(&mut app, &view, &dispatcher, event).await;
        }
        assert_eq!(
            app.menu.as_ref().and_then(|m| m.open_submenu),
            Some(1),
            "the first click on the submenu row opens it"
        );

        for event in click(6) {
            handle_mouse(&mut app, &view, &dispatcher, event).await;
        }
        assert_eq!(
            app.menu.as_ref().and_then(|m| m.open_submenu),
            None,
            "and the second closes it rather than reopening it"
        );
        assert!(app.menu.is_some(), "the menu itself stays open either way");
    }

    #[tokio::test]
    async fn a_context_menu_closes_when_its_subject_row_disappears() {
        let (mut app, dispatcher, _commands) = test_app();
        let view = view_with(&["/repo/wt-1", "/repo/wt-2"]);
        let mut terminal = Terminal::new(TestBackend::new(80, 12)).unwrap();
        draw_into(&mut terminal, &view, &mut app);

        // Right-click the second worktree row: the menu takes it as subject.
        let row = app.regions.tree.y + 2;
        handle_mouse(
            &mut app,
            &view,
            &dispatcher,
            mouse_at(
                MouseEventKind::Down(MouseButton::Right),
                5,
                row,
                KeyModifiers::NONE,
            ),
        )
        .await;
        assert!(app.menu.is_some(), "the right-click opened a menu");
        assert!(
            app.menu
                .as_ref()
                .and_then(|m| m.origin_row.as_ref())
                .is_some(),
            "and recorded which row it acts on"
        );

        // A daemon push removes that worktree while the menu is open. The
        // menu must not survive to act on whatever slid into its place.
        let shrunk = view_with(&["/repo/wt-1"]);
        draw_into(&mut terminal, &shrunk, &mut app);
        assert!(app.menu.is_none(), "the menu closed with its subject");
        assert!(app.notice.is_some(), "and said why");

        // A menu with no row subject (the `c` picker) is unaffected.
        app.menu = Some(popup::ActionMenu::new(menu::row_color_items()));
        draw_into(&mut terminal, &shrunk, &mut app);
        assert!(app.menu.is_some(), "no subject, nothing to outlive");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_double_click_on_a_row_opens_a_shell_tab_there() {
        let (mut app, dispatcher, _commands) = test_app();
        let dir = tempfile::tempdir().unwrap();
        let view = view_with(&[&dir.path().to_string_lossy()]);
        let mut terminal = Terminal::new(TestBackend::new(80, 12)).unwrap();
        draw_into(&mut terminal, &view, &mut app);
        let y = app.regions.tree.y + 1; // the worktree row
        let click = mouse_at(
            MouseEventKind::Down(MouseButton::Left),
            5,
            y,
            KeyModifiers::NONE,
        );
        handle_mouse(&mut app, &view, &dispatcher, click).await;
        handle_mouse(
            &mut app,
            &view,
            &dispatcher,
            mouse_at(
                MouseEventKind::Up(MouseButton::Left),
                5,
                y,
                KeyModifiers::NONE,
            ),
        )
        .await;
        handle_mouse(&mut app, &view, &dispatcher, click).await;
        assert_eq!(app.tree.cursor, 1);
        // Either the login shell spawned (and took focus) or, on a minimal
        // image, the failure is reported — never silence.
        assert!(
            !app.panes.is_empty() || app.notice.is_some(),
            "double-click neither opened a tab nor reported a failure"
        );
        if !app.panes.is_empty() {
            assert_eq!(app.focus, Focus::Terminal);
        }
        app.close_tab();
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn mouse_on_the_terminal_selects_by_drag_word_and_line_and_scrolls() {
        let (mut app, dispatcher, _commands) = test_app();
        let dir = tempfile::tempdir().unwrap();
        let view = view_with(&[&dir.path().to_string_lossy()]);
        let tab = scripted_tab(
            &app,
            "printf 'hello world\\nsecond line\\n'; sleep 3",
            dir.path().to_path_buf(),
        );
        install_tab(&mut app, tab);
        let mut terminal = Terminal::new(TestBackend::new(100, 12)).unwrap();
        draw_into(&mut terminal, &view, &mut app);
        let grid = grid_rect(&app);
        assert!(
            wait_until(|| only_tab(&app).selection_to_string().is_none() && {
                draw_into(&mut terminal, &view, &mut app);
                buffer_text(&terminal).contains("second line")
            })
            .await,
            "the child's output never rendered"
        );
        let none = KeyModifiers::NONE;
        let at = |kind, col: u16, line: u16| mouse_at(kind, grid.x + col, grid.y + line, none);

        // Click focuses the terminal; drag selects; the drag is clamped so
        // overshooting the pane still ends on its last cell.
        app.focus = Focus::Tree;
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                at(MouseEventKind::Down(MouseButton::Left), 0, 0)
            )
            .await
        );
        assert_eq!(app.focus, Focus::Terminal);
        assert_eq!(app.drag, DragOrigin::Terminal { group: 0 });
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                at(MouseEventKind::Drag(MouseButton::Left), 4, 0)
            )
            .await
        );
        assert!(
            !handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                at(MouseEventKind::Up(MouseButton::Left), 4, 0)
            )
            .await
        );
        assert_eq!(app.drag, DragOrigin::None);
        assert_eq!(
            only_tab(&app).selection_to_string().as_deref(),
            Some("hello")
        );
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                at(MouseEventKind::Down(MouseButton::Left), 0, 1)
            )
            .await
        );
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(MouseEventKind::Drag(MouseButton::Left), 0, 0, none)
            )
            .await
        );
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(MouseEventKind::Drag(MouseButton::Left), 500, 500, none)
            )
            .await
        );
        let clamped = only_tab(&app).selection_to_string().unwrap();
        assert!(clamped.starts_with("second line"), "got {clamped:?}");
        handle_mouse(
            &mut app,
            &view,
            &dispatcher,
            at(MouseEventKind::Up(MouseButton::Left), 0, 1),
        )
        .await;

        // Double-click selects the word, triple-click the line.
        let dbl = at(MouseEventKind::Down(MouseButton::Left), 7, 0);
        handle_mouse(&mut app, &view, &dispatcher, dbl).await;
        handle_mouse(
            &mut app,
            &view,
            &dispatcher,
            at(MouseEventKind::Up(MouseButton::Left), 7, 0),
        )
        .await;
        handle_mouse(&mut app, &view, &dispatcher, dbl).await;
        assert_eq!(
            only_tab(&app).selection_to_string().as_deref(),
            Some("world")
        );
        handle_mouse(
            &mut app,
            &view,
            &dispatcher,
            at(MouseEventKind::Up(MouseButton::Left), 7, 0),
        )
        .await;
        handle_mouse(&mut app, &view, &dispatcher, dbl).await;
        // A line selection's text carries the line's own trailing newline.
        let line = only_tab(&app).selection_to_string();
        assert_eq!(line.as_deref().map(str::trim_end), Some("hello world"));
        handle_mouse(
            &mut app,
            &view,
            &dispatcher,
            at(MouseEventKind::Up(MouseButton::Left), 7, 0),
        )
        .await;
        draw_into(&mut terminal, &view, &mut app); // the selection renders
                                                   // alt-c copies (OSC 52 fallback in CI) and consumes the selection.
        handle_chrome_key(&mut app, &view, ChromeKey::Copy);
        assert_eq!(app.notice.as_deref(), Some("copied"));
        assert!(only_tab(&app).selection_to_string().is_none());

        // The wheel scrolls the emulator's history (no child mouse mode, not
        // the alt screen); a middle click neither pastes nor selects.
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                at(MouseEventKind::ScrollUp, 1, 1)
            )
            .await
        );
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                at(MouseEventKind::ScrollDown, 1, 1)
            )
            .await
        );
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                at(MouseEventKind::Down(MouseButton::Middle), 1, 1)
            )
            .await
        );
        assert_eq!(app.drag, DragOrigin::None);
        assert!(
            !handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                at(MouseEventKind::Moved, 1, 1)
            )
            .await
        );
        assert!(
            !handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                at(MouseEventKind::ScrollRight, 1, 1)
            )
            .await
        );
        app.close_tab();
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_child_that_asked_for_the_mouse_receives_it_unless_alt_is_held() {
        let (mut app, dispatcher, _commands) = test_app();
        let dir = tempfile::tempdir().unwrap();
        let view = view_with(&[&dir.path().to_string_lossy()]);
        // Enable SGR click reporting, then print the first nine bytes the
        // TUI sends (exactly one SGR press) in a form the grid can show.
        let script = "stty -echo -icanon min 1 time 0; printf '\\033[?1000h\\033[?1006h'; \
                      dd bs=1 count=9 2>/dev/null | od -An -c; sleep 2";
        let tab = scripted_tab(&app, script, dir.path().to_path_buf());
        install_tab(&mut app, tab);
        let mut terminal = Terminal::new(TestBackend::new(100, 12)).unwrap();
        draw_into(&mut terminal, &view, &mut app);
        let grid = grid_rect(&app);
        assert!(
            wait_until(|| only_tab(&app).mode().contains(TermMode::SGR_MOUSE)).await,
            "the child never enabled mouse reporting"
        );
        let none = KeyModifiers::NONE;

        // Alt-click: the TUI keeps the mouse and starts a selection.
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(
                    MouseEventKind::Down(MouseButton::Left),
                    grid.x,
                    grid.y,
                    KeyModifiers::ALT
                )
            )
            .await
        );
        assert_eq!(app.drag, DragOrigin::Terminal { group: 0 });
        handle_mouse(
            &mut app,
            &view,
            &dispatcher,
            mouse_at(
                MouseEventKind::Up(MouseButton::Left),
                grid.x,
                grid.y,
                KeyModifiers::ALT,
            ),
        )
        .await;

        // A plain click goes to the child, as does its release and any
        // motion in between; the child prints what it got.
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(
                    MouseEventKind::Down(MouseButton::Left),
                    grid.x,
                    grid.y,
                    none
                )
            )
            .await
        );
        assert_eq!(app.drag, DragOrigin::Child { group: 0 });
        assert!(
            !handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(
                    MouseEventKind::Drag(MouseButton::Left),
                    grid.x + 1,
                    grid.y,
                    none
                )
            )
            .await
        );
        assert!(
            !handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(
                    MouseEventKind::Up(MouseButton::Left),
                    grid.x + 1,
                    grid.y,
                    none
                )
            )
            .await
        );
        assert_eq!(app.drag, DragOrigin::None);
        assert!(
            wait_until(|| {
                draw_into(&mut terminal, &view, &mut app);
                let text: String = buffer_text(&terminal).split_whitespace().collect();
                text.contains("033[<0;1;1M")
            })
            .await,
            "the child never echoed the SGR press: {}",
            buffer_text(&terminal)
        );
        // A wheel notch is forwarded too (no redraw needed for that).
        assert!(
            !handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(MouseEventKind::ScrollUp, grid.x, grid.y, none)
            )
            .await
        );
        app.close_tab();
    }

    /// Contract §4 regression (#1602 Phase 3): right-click priority must
    /// match left-click's. A reporting child gets a right-click encoded and
    /// written to it with **no** menu opening; `⌥` takes the mouse back and
    /// opens the terminal-grid menu, writing nothing. Setup mirrors
    /// `a_child_that_asked_for_the_mouse_receives_it_unless_alt_is_held`
    /// exactly: same `dd`-then-`od` script that blocks for one 9-byte SGR
    /// press and echoes it back.
    #[cfg(unix)]
    #[tokio::test]
    async fn right_click_on_a_reporting_child_forwards_unless_alt_is_held() {
        let (mut app, dispatcher, _commands) = test_app();
        let dir = tempfile::tempdir().unwrap();
        let view = view_with(&[&dir.path().to_string_lossy()]);
        let script = "stty -echo -icanon min 1 time 0; printf '\\033[?1000h\\033[?1006h'; \
                      dd bs=1 count=9 2>/dev/null | od -An -c; sleep 2";
        let tab = scripted_tab(&app, script, dir.path().to_path_buf());
        install_tab(&mut app, tab);
        let mut terminal = Terminal::new(TestBackend::new(100, 12)).unwrap();
        draw_into(&mut terminal, &view, &mut app);
        let grid = grid_rect(&app);
        assert!(
            wait_until(|| only_tab(&app).mode().contains(TermMode::SGR_MOUSE)).await,
            "the child never enabled mouse reporting"
        );
        let none = KeyModifiers::NONE;

        // Alt-right-click: the TUI keeps the mouse and opens the grid menu
        // instead of forwarding — the same rule the left button already
        // follows for taking the mouse back from a reporting child. Nothing
        // is written: the `dd` in the script is still blocked on its first
        // read, which the next case's assertions depend on.
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(
                    MouseEventKind::Down(MouseButton::Right),
                    grid.x,
                    grid.y,
                    KeyModifiers::ALT
                )
            )
            .await
        );
        assert!(app.menu.is_some(), "alt-right-click should open the menu");
        assert_eq!(
            app.drag,
            DragOrigin::None,
            "opening the menu starts no drag"
        );
        app.menu = None; // close it so the next click isn't eaten by the popup

        // A plain right-click goes to the child instead, with no menu.
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(
                    MouseEventKind::Down(MouseButton::Right),
                    grid.x,
                    grid.y,
                    none
                )
            )
            .await
        );
        assert!(
            app.menu.is_none(),
            "the child took the mouse; no menu should open"
        );
        assert_eq!(app.drag, DragOrigin::Child { group: 0 });
        assert!(
            wait_until(|| {
                draw_into(&mut terminal, &view, &mut app);
                let text: String = buffer_text(&terminal).split_whitespace().collect();
                text.contains("033[<2;1;1M")
            })
            .await,
            "the child never echoed the right-click SGR press \
             (or the alt-held click leaked bytes to it): {}",
            buffer_text(&terminal)
        );
        app.close_tab();
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn tab_chords_split_cycle_select_move_and_reset_the_stack() {
        let (mut app, dispatcher, mut commands) = test_app();
        let dir = tempfile::tempdir().unwrap();
        let here = dir.path().to_path_buf();
        let view = view_with(&[&here.to_string_lossy(), "/repo/other"]);
        let mut terminal = Terminal::new(TestBackend::new(100, 30)).unwrap();

        // Seed one tab, then draw so a terminal area exists for splits.
        let tab = scripted_tab(&app, "sleep 5", here.clone());
        install_tab(&mut app, tab);
        draw_into(&mut terminal, &view, &mut app);
        assert_eq!(app.panes.group_count(), 1);

        // alt-s splits into a second group; alt-↑/↓ move focus between them.
        app.tree.cursor = 1;
        handle_key(&mut app, &view, &dispatcher, alt('s')).await;
        assert_eq!(app.panes.group_count(), 2, "alt-s split the stack");
        assert_eq!(app.panes.focused, 1);
        draw_into(&mut terminal, &view, &mut app);
        handle_key(
            &mut app,
            &view,
            &dispatcher,
            alt_key(KeyCode::Up, KeyModifiers::NONE),
        )
        .await;
        assert_eq!(app.panes.focused, 0);
        handle_key(
            &mut app,
            &view,
            &dispatcher,
            alt_key(KeyCode::Down, KeyModifiers::NONE),
        )
        .await;
        assert_eq!(app.panes.focused, 1);

        // alt-⇧↑ moves the tab into the group above, emptying its own.
        handle_key(
            &mut app,
            &view,
            &dispatcher,
            alt_key(KeyCode::Up, KeyModifiers::SHIFT),
        )
        .await;
        assert_eq!(app.panes.group_count(), 1);
        assert_eq!(app.panes.groups[0].tabs.len(), 2);
        // With one group there is nowhere to move to, and it says so.
        handle_key(
            &mut app,
            &view,
            &dispatcher,
            alt_key(KeyCode::Down, KeyModifiers::SHIFT),
        )
        .await;
        assert!(app.notice.as_deref().unwrap_or("").contains("no group"));

        // alt-[ / alt-] cycle tabs, alt-1..9 select, out of range notices.
        assert_eq!(app.panes.groups[0].active, 1);
        handle_key(&mut app, &view, &dispatcher, alt(']')).await;
        assert_eq!(app.panes.groups[0].active, 0, "wraps");
        handle_key(&mut app, &view, &dispatcher, alt('[')).await;
        assert_eq!(app.panes.groups[0].active, 1);
        handle_key(&mut app, &view, &dispatcher, alt('1')).await;
        assert_eq!(app.panes.groups[0].active, 0);
        handle_key(&mut app, &view, &dispatcher, alt('9')).await;
        assert!(app.notice.as_deref().unwrap_or("").contains("no tab 9"));

        // alt-0 resets the weights.
        app.panes.weights = vec![7];
        handle_key(&mut app, &view, &dispatcher, alt('0')).await;
        assert_eq!(app.panes.weights, vec![1]);

        // Both tabs are on one worktree, so the cue only clears at the last
        // close — the ref-counted `here` rule.
        while let Ok(cmd) = commands.try_recv() {
            drop(cmd); // discard the opens
        }
        handle_key(&mut app, &view, &dispatcher, alt('w')).await;
        assert!(app.panes.any_alive(), "one tab left");
        assert!(
            !drained_clear_open_tab(&mut commands, &here),
            "the cue stays while a tab remains"
        );
        handle_key(&mut app, &view, &dispatcher, alt('w')).await;
        assert!(app.panes.is_empty());
        assert!(
            drained_clear_open_tab(&mut commands, &here),
            "the last close clears the cue"
        );
        assert_eq!(app.focus, Focus::Tree);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_split_is_refused_when_the_pane_is_too_short_to_draw_it() {
        let (mut app, dispatcher, _commands) = test_app();
        let dir = tempfile::tempdir().unwrap();
        let here = dir.path().to_path_buf();
        let view = view_with(&[&here.to_string_lossy()]);
        let tab = scripted_tab(&app, "sleep 5", here);
        install_tab(&mut app, tab);
        // Six rows of terminal cannot hold two four-row groups.
        let mut terminal = Terminal::new(TestBackend::new(100, 7)).unwrap();
        draw_into(&mut terminal, &view, &mut app);
        app.tree.cursor = 1;
        handle_key(&mut app, &view, &dispatcher, alt('s')).await;
        assert_eq!(app.panes.group_count(), 1, "the split was refused");
        assert!(app
            .notice
            .as_deref()
            .unwrap_or("")
            .contains("not enough height"));
        app.close_tab();
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn the_tab_strip_activates_closes_and_the_splitter_resizes() {
        let (mut app, dispatcher, _commands) = test_app();
        let dir = tempfile::tempdir().unwrap();
        let here = dir.path().to_path_buf();
        let view = view_with(&[&here.to_string_lossy()]);
        let mut terminal = Terminal::new(TestBackend::new(100, 30)).unwrap();

        // Two tabs in one group, then a second group below.
        for _ in 0..2 {
            let tab = scripted_tab(&app, "sleep 5", here.clone());
            install_tab(&mut app, tab);
        }
        let tab = scripted_tab(&app, "sleep 5", here);
        app.panes.split(move |_| Ok(tab)).unwrap();
        draw_into(&mut terminal, &view, &mut app);
        assert_eq!(app.regions.groups.len(), 2);
        assert_eq!(app.regions.splitters.len(), 1);

        // Clicking tab 1 on the first strip activates it and focuses group 0.
        let strip = app.regions.groups[0].strip;
        let spans = app.regions.groups[0].tab_spans.clone();
        assert_eq!(spans.len(), 2, "two tabs on the strip");
        let none = KeyModifiers::NONE;
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(
                    MouseEventKind::Down(MouseButton::Left),
                    spans[0].0,
                    strip.y,
                    none
                )
            )
            .await
        );
        assert_eq!(app.panes.focused, 0);
        assert_eq!(app.panes.groups[0].active, 0);
        assert_eq!(app.focus, Focus::Terminal);

        // The wheel over a strip cycles that group's tabs.
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(MouseEventKind::ScrollDown, spans[0].0, strip.y, none)
            )
            .await
        );
        assert_eq!(app.panes.groups[0].active, 1);

        // Dragging the splitter up shrinks the first group; only the pair
        // either side changes, and it never goes below the minimum.
        let splitter = app.regions.splitters[0];
        let before = app.panes.weights.clone();
        // Pressing on a splitter changes nothing visible — it only arms the
        // drag — so it asks for no redraw.
        assert!(
            !handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(MouseEventKind::Down(MouseButton::Left), 60, splitter, none)
            )
            .await
        );
        assert_eq!(app.drag, DragOrigin::Splitter { index: 0 });
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(
                    MouseEventKind::Drag(MouseButton::Left),
                    60,
                    splitter - 4,
                    none
                )
            )
            .await
        );
        assert_ne!(app.panes.weights, before, "the drag moved the boundary");
        draw_into(&mut terminal, &view, &mut app);
        let rects = app.panes.arrange(app.terminal_area.unwrap());
        assert!(rects.iter().all(|r| r.body.height >= 3));
        handle_mouse(
            &mut app,
            &view,
            &dispatcher,
            mouse_at(
                MouseEventKind::Up(MouseButton::Left),
                60,
                splitter - 4,
                none,
            ),
        )
        .await;
        assert_eq!(app.drag, DragOrigin::None);

        // A middle click on a tab closes just that tab.
        draw_into(&mut terminal, &view, &mut app);
        let spans = app.regions.groups[0].tab_spans.clone();
        let strip_y = app.regions.groups[0].strip.y;
        let before = app.panes.groups[0].tabs.len();
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(
                    MouseEventKind::Down(MouseButton::Middle),
                    spans[0].0,
                    strip_y,
                    none
                )
            )
            .await
        );
        assert_eq!(app.panes.groups[0].tabs.len(), before - 1);

        shutdown_all(&mut app);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn right_clicking_a_tab_focuses_it_before_opening_the_strip_menu() {
        let (mut app, dispatcher, _commands) = test_app();
        let dir = tempfile::tempdir().unwrap();
        let here = dir.path().to_path_buf();
        let view = view_with(&[&here.to_string_lossy()]);
        let mut terminal = Terminal::new(TestBackend::new(100, 30)).unwrap();

        for _ in 0..2 {
            let tab = scripted_tab(&app, "sleep 5", here.clone());
            install_tab(&mut app, tab);
        }
        draw_into(&mut terminal, &view, &mut app);
        let strip = app.regions.groups[0].strip;
        let spans = app.regions.groups[0].tab_spans.clone();
        assert_eq!(spans.len(), 2, "two tabs on the strip");
        assert_eq!(app.panes.groups[0].active, 1, "the second tab opened last");

        let none = KeyModifiers::NONE;
        assert!(
            handle_mouse(
                &mut app,
                &view,
                &dispatcher,
                mouse_at(
                    MouseEventKind::Down(MouseButton::Right),
                    spans[0].0,
                    strip.y,
                    none
                )
            )
            .await
        );
        assert_eq!(
            app.panes.groups[0].active, 0,
            "right-click focuses the tab under the pointer, like left-click"
        );
        assert_eq!(app.focus, Focus::Terminal);
        let menu = app.menu.as_ref().expect("the strip menu opened");
        assert_eq!(menu.title, "Tab");
        assert_eq!(
            menu.anchor,
            popup::Anchor::At {
                col: spans[0].0,
                row: strip.y
            }
        );
        assert_eq!(app.menu_tab, Some(panes::TabAddr { group: 0, tab: 0 }));

        shutdown_all(&mut app);
    }

    #[tokio::test]
    async fn the_command_palette_filters_by_label_and_opens_the_menu_at_the_match() {
        let (mut app, dispatcher, _commands) = test_app();
        let view = view_with(&["/repo/a"]);
        app.tree.cursor = 1;

        // `:` opens the palette; letters type into it rather than running
        // tree commands (`c` would otherwise open the colour picker).
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char(':'))).await;
        assert!(app.prompt.is_some());
        for c in "copy dir".chars() {
            handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char(c))).await;
        }
        assert!(app.menu.is_none(), "typing did not trigger a tree command");
        let mut terminal = Terminal::new(TestBackend::new(80, 20)).unwrap();
        draw_into(&mut terminal, &view, &mut app);
        assert!(buffer_text(&terminal).contains("copy dir"));

        // Backspace deletes; Enter opens the menu at the filtered match so
        // the action still goes through its normal confirm path.
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Backspace)).await;
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Enter)).await;
        assert!(app.prompt.is_none());
        assert!(app.menu.is_some(), "the palette opened the action menu");
        draw_into(&mut terminal, &view, &mut app);
        app.menu = None;

        // A query matching nothing says so instead of doing something else.
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char(':'))).await;
        for c in "zzzz".chars() {
            handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char(c))).await;
        }
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Enter)).await;
        assert!(app.menu.is_none());
        assert!(app.notice.as_deref().unwrap_or("").contains("no command"));

        // Esc cancels without running anything.
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char(':'))).await;
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Esc)).await;
        assert!(app.prompt.is_none());
    }

    #[test]
    fn filter_palette_matches_case_insensitively_and_keeps_everything_when_empty() {
        let items = vec![
            popup::MenuItem::action(ActionKind::CopyDirectory, "Copy Directory"),
            popup::MenuItem::action(ActionKind::Focus, "Focus Worktree"),
        ];
        assert_eq!(filter_palette(items.clone(), "").len(), 2);
        assert_eq!(filter_palette(items.clone(), "copy").len(), 1);
        assert_eq!(filter_palette(items.clone(), "COPY").len(), 1);
        assert_eq!(filter_palette(items.clone(), "work").len(), 1);
        assert!(filter_palette(items, "nothing").is_empty());
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn find_searches_the_scrollback_and_reports_a_miss() {
        let (mut app, dispatcher, _commands) = test_app();
        let dir = tempfile::tempdir().unwrap();
        let here = dir.path().to_path_buf();
        let view = view_with(&[&here.to_string_lossy()]);

        // Without a tab there is nothing to search, and it says so.
        handle_key(&mut app, &view, &dispatcher, alt('f')).await;
        assert!(app.prompt.is_none());
        assert!(app.notice.as_deref().unwrap_or("").contains("no terminal"));

        // Print enough lines to push the needle into scrollback.
        let tab = scripted_tab(
            &app,
            "i=0; while [ $i -lt 60 ]; do echo line-$i; i=$((i+1)); done; \
             echo NEEDLE-HERE; i=0; while [ $i -lt 60 ]; do echo tail-$i; i=$((i+1)); done; \
             sleep 3",
            here,
        );
        install_tab(&mut app, tab);
        let mut terminal = Terminal::new(TestBackend::new(100, 20)).unwrap();
        assert!(
            wait_until(|| {
                draw_into(&mut terminal, &view, &mut app);
                buffer_text(&terminal).contains("tail-59")
            })
            .await,
            "the child never finished printing"
        );

        handle_key(&mut app, &view, &dispatcher, alt('f')).await;
        assert!(app.prompt.is_some());
        for c in "needle".chars() {
            handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char(c))).await;
        }
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Enter)).await;
        // A hit scrolls the display back and leaves no error status.
        let prompt = app.prompt.as_ref().expect("the find prompt stays open");
        assert_eq!(prompt.status, "", "case-insensitive match should be found");
        draw_into(&mut terminal, &view, &mut app);
        assert!(
            buffer_text(&terminal).contains("NEEDLE-HERE"),
            "the match was scrolled into view"
        );

        // A miss reports it rather than scrolling somewhere arbitrary.
        for _ in 0..6 {
            handle_key(&mut app, &view, &dispatcher, press(KeyCode::Backspace)).await;
        }
        for c in "nowhere".chars() {
            handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char(c))).await;
        }
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Enter)).await;
        assert_eq!(app.prompt.as_ref().unwrap().status, "no match");
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Esc)).await;
        assert!(app.prompt.is_none());
        shutdown_all(&mut app);
    }

    #[tokio::test]
    async fn visible_rows_are_reported_once_per_change_not_once_per_frame() {
        let (mut app, _dispatcher, mut commands) = test_app();
        let view = view_with(&["/repo/a", "/repo/b"]);
        let mut terminal = Terminal::new(TestBackend::new(80, 20)).unwrap();

        draw_into(&mut terminal, &view, &mut app);
        let first = commands.try_recv();
        match first {
            Ok(HubCommand::SetVisibleRows(rows)) => {
                assert_eq!(rows.len(), 2, "both worktree rows are visible");
                assert!(rows.iter().all(|p| p.starts_with("/repo/")));
                assert!(
                    !rows.contains(&PathBuf::from("/repo")),
                    "the repo header is not a worktree row"
                );
            }
            other => panic!("expected SetVisibleRows, got {other:?}"),
        }
        // Redrawing the same view must not re-send: the command triggers
        // ahead/behind fetches, and repeating it every frame would restart
        // them ~60 times a second.
        for _ in 0..5 {
            draw_into(&mut terminal, &view, &mut app);
        }
        assert!(
            commands.try_recv().is_err(),
            "an unchanged visible set was re-reported"
        );

        // A pane too short to show every row reports only what fits.
        let mut small = Terminal::new(TestBackend::new(80, 4)).unwrap();
        draw_into(&mut small, &view, &mut app);
        match commands.try_recv() {
            Ok(HubCommand::SetVisibleRows(rows)) => assert!(
                rows.len() < 2,
                "a 4-row pane cannot show both worktrees: {rows:?}"
            ),
            other => panic!("expected a new SetVisibleRows, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn alt_shift_c_clears_every_row_colour() {
        let (mut app, dispatcher, mut commands) = test_app();
        let view = view_with(&["/repo/a"]);
        app.tree.cursor = 1;

        handle_key(
            &mut app,
            &view,
            &dispatcher,
            KeyEvent::new(KeyCode::Char('C'), KeyModifiers::ALT),
        )
        .await;
        assert!(matches!(
            commands.try_recv(),
            Ok(HubCommand::ClearAllRowColors)
        ));
        assert_eq!(app.notice.as_deref(), Some("cleared every row colour"));

        // The shifted spelling with the SHIFT bit set reaches it too.
        handle_key(
            &mut app,
            &view,
            &dispatcher,
            KeyEvent::new(KeyCode::Char('c'), KeyModifiers::ALT | KeyModifiers::SHIFT),
        )
        .await;
        assert!(matches!(
            commands.try_recv(),
            Ok(HubCommand::ClearAllRowColors)
        ));

        // Plain alt-c is still Copy, not a clear-all.
        handle_key(&mut app, &view, &dispatcher, alt('c')).await;
        assert_eq!(app.notice.as_deref(), Some("nothing selected"));
        assert!(commands.try_recv().is_err());
    }

    #[test]
    fn layout_gives_the_tree_the_full_width_until_a_tab_exists() {
        let area = Rect::new(0, 0, 100, 30);
        let without = layout(area, false);
        assert_eq!(without.tree.width, 100);
        assert!(without.terminal.is_none());
        assert_eq!(without.status.height, 1);

        let with = layout(area, true);
        let terminal = with.terminal.expect("a terminal pane");
        assert_eq!(with.tree.width + terminal.width, 100);
        assert!(terminal.width >= 20);
        assert_eq!(with.tree.height, 29);
    }
}