mnml-rs 0.2.13

A NvChad-style terminal IDE in Rust — vim or standard editing, LSP, git, and an embedded HTTP client.
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
//! Left-click (`MouseEventKind::Down(MouseButton::Left)`) dispatch
//! — extracted from `mouse/mod.rs` (T-5 of the file-split refactor,
//! 2026-06-29). At ~1700 lines this was the biggest chunk of
//! dispatch_mouse: every clickable surface — rail rows, palette
//! bar buttons, statusline chips, panel chrome, dock widgets,
//! pane bodies, scrollbars, drag-start, drop targets, and so on.
//!
//! Public surface: `handle_down_left(app, m, x, y, ...)`. Called
//! from `dispatch_mouse`'s left-Down arm. Returns nothing; each
//! consuming branch uses `return` to exit this function only,
//! leaving the outer match arm to complete naturally.

use ratatui::crossterm::event::{KeyModifiers, MouseEvent};

use super::{send_macos_player, send_mixr_command};
use crate::app::App;
use crate::command;
use crate::pane::Pane;

/// Max gap between two clicks at the same (x, y) that still counts
/// as a double-click. mouse-round-14 SEV-2 F1 2026-07-14 — bumped
/// from 450 → 700 ms because natural trackpad cadence lands
/// around 350-600 ms between clicks (particularly for the
/// divider-equalize / tab-close double-click paths), and the render
/// + poll_sleep + drain-iter overhead under the IPC channel eats
/// another ~40-80 ms on top of the human timing. 700 ms is macOS
/// System-Preferences → Trackpad's "slow" end and still fast
/// enough that two intentionally-separate clicks don't misfire as
/// a double.
const DOUBLE_CLICK_MAX_MS: u128 = 700;

pub(super) fn handle_down_left(app: &mut App, m: MouseEvent, x: u16, y: u16) {
    if app.debug_click_inspector {
        let hits = app.rects.inspect_click_targets(x, y);
        let msg = if hits.is_empty() {
            format!("click @ ({x}, {y}): no PaneRects hit")
        } else {
            format!("click @ ({x}, {y}): {}", hits.join(" · "))
        };
        app.toast(msg);
    }
    // #20 Pattern B — confirm modal takes priority over every
    // other click when it's up.
    if app.pending_confirm.is_some() {
        if let Some(r) = app.rects.confirm_modal_cancel
            && crate::app::dispatch::contains(r, x, y)
        {
            app.dismiss_pending_confirm();
            return;
        }
        if let Some(r) = app.rects.confirm_modal_confirm
            && crate::app::dispatch::contains(r, x, y)
        {
            app.commit_pending_confirm();
            return;
        }
        // Click outside modal — swallow the click so users don't
        // accidentally trigger stuff underneath.
        return;
    }
    // #20 — undo chip wins the click over almost anything else so
    // it's easy to hit. Only anchored while `pending_undo` is set,
    // so no ordinary flow is stolen from.
    if let Some(r) = app.rects.pending_undo_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.commit_pending_undo();
        return;
    }
    // First-launch wizard hit rects (2026-08-14 — fixes the
    // "yes/no rows not clickable" bug). Only registered while the
    // wizard overlay is up, so no ordinary flow is intercepted.
    if app.first_launch.is_some()
        && let Some(&(_, hit)) = app
            .rects
            .first_launch_hits
            .iter()
            .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        match hit {
            crate::ui::first_launch_overlay::FirstLaunchHit::NerdFontOk(ok) => {
                app.wizard_set_nerd_font_ok(ok);
            }
        }
        return;
    }
    // vscode-mouse SEV-2 2026-08-05 — when a menu dropdown is open,
    // handle its clicks BEFORE any body-of-app rect check so a click
    // on a menu item doesn't fall through to the tree/pane rect
    // underneath. Previously the menu_bar_items check ran after
    // marketplace/integration/tree checks, and if the current
    // frame's rects had already been reset but the menu hadn't
    // re-rendered yet, the item click would silently activate the
    // element behind the dropdown.
    if let Some(open) = app.menu_open.as_ref().cloned() {
        // 1. Item hit — fire the palette command + close, OR open a
        // submenu, OR fire a submenu item.
        if let Some(&(_, encoded_idx)) = app
            .rects
            .menu_bar_items
            .iter()
            .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
        {
            let menus = crate::menu_bar::bar(app);
            if encoded_idx >= 1000 {
                // Submenu Action row: encoded as `1000 + parent*100 + sub`.
                let rest = encoded_idx - 1000;
                let parent_idx = rest / 100;
                let sub_idx = rest % 100;
                if let Some(menu) = menus.get(open.menu_idx)
                    && let Some(crate::menu_bar::MenuItem::Submenu { items, .. }) =
                        menu.items.get(parent_idx)
                    && let Some(crate::menu_bar::MenuItem::Action { command_id, .. }) =
                        items.get(sub_idx)
                {
                    let id = command_id.clone();
                    app.menu_open = None;
                    crate::command::run(&id, app);
                }
                return;
            }
            if let Some(menu) = menus.get(open.menu_idx) {
                match menu.items.get(encoded_idx) {
                    Some(crate::menu_bar::MenuItem::Action { command_id, .. }) => {
                        let id = command_id.clone();
                        app.menu_open = None;
                        crate::command::run(&id, app);
                    }
                    Some(crate::menu_bar::MenuItem::Submenu { .. }) => {
                        // Open (or re-open) the submenu with its first
                        // action highlighted.
                        if let Some(state) = app.menu_open.as_mut() {
                            state.item_idx = encoded_idx;
                            state.sub_item_idx = Some(0);
                        }
                    }
                    _ => {}
                }
            }
            return;
        }
        // 2. Word hit on the SAME menu — toggle (close). Different
        // word → let the normal menu_bar_words handler switch.
        if let Some(&(_, menu_idx)) = app
            .rects
            .menu_bar_words
            .iter()
            .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
            && menu_idx == open.menu_idx
        {
            app.menu_open = None;
            return;
        }
        // 3. Click anywhere else with menu open → close menu and
        // swallow the click. The user's intent was "dismiss," not
        // "activate what's behind the panel."
        //
        // If the click hit a different menu word (case 2), fall
        // through so the menu_bar_words handler below can switch.
        // R11 vscode-mouse SEV-2 — the `»` overflow chip's own rect
        // isn't in `menu_bar_words`, so before this exception a
        // click on `»` matched the outside-click null path here,
        // wiping `menu_open` BEFORE the overflow-chip handler
        // below could read it to compute the next hidden menu.
        // Result: every `»` click bounced back to first-hidden.
        // Treat overflow-chip clicks as inside-the-menu-bar too.
        let click_on_menu_word = app
            .rects
            .menu_bar_words
            .iter()
            .any(|(r, _)| crate::app::dispatch::contains(*r, x, y));
        let click_on_overflow_chip = app
            .rects
            .menu_bar_overflow
            .is_some_and(|(r, _)| crate::app::dispatch::contains(r, x, y));
        if !click_on_menu_word && !click_on_overflow_chip {
            app.menu_open = None;
            return;
        }
    }
    // 2026-07-19 — the activity-bar icons live on a 4-cell strip at
    // the far-left of the rail; hover-tooltips consistently report
    // the correct section but clicks were being swallowed by stale
    // rects from other panels (session_tabs, extra_workspace_bodies,
    // right_panel_empty_*, and so on) that carried over from prior
    // frames when their host panel wasn't the active section. Every
    // fix we've shipped for that class of bug patched one panel at a
    // time; move the activity-bar check ABOVE all the other cascade
    // arms so no stale integration-panel rect can ever shadow the icon
    // strip. Small blast radius — the activity bar is a 4-column
    // sliver and its icons are ONLY there.
    if let Some(&(_, section)) = app
        .rects
        .activity_bar_icons
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        // 2026-07-20 — LauncherIcon is a pinned-integration shortcut:
        // fire the underlying chip's command (spawns a Pty pane in
        // the main area, no side panel). Skip set_activity_section
        // so the sidebar doesn't flip to a nonexistent "Launcher"
        // section.
        if let crate::app::ActivitySection::LauncherIcon(idx) = section {
            let cmd = app
                .config
                .ui
                .activity_bar_pinned_integrations
                .get(idx as usize)
                .and_then(|id| app.config.ui.integration_icons.iter().find(|i| &i.id == id))
                .map(|ic| ic.command.clone());
            if let Some(cmd) = cmd {
                if let Some(rest) = cmd.strip_prefix(':') {
                    app.run_ex_command(rest);
                } else {
                    crate::command::run(&cmd, app);
                }
            }
            return;
        }
        app.set_activity_section(section);
        if matches!(section, crate::app::ActivitySection::Git) {
            crate::command::run("git.graph", app);
        }
        if let crate::app::ActivitySection::Mount(idx) = section {
            app.open_mount_from_manifest(idx);
        }
        return;
    }
    if let Some(r) = app.rects.activity_bar_gear
        && crate::app::dispatch::contains(r, x, y)
    {
        app.open_settings_overlay();
        return;
    }
    // #polish 2026-07-06 — click on the `· <repo-name>` chip in
    // the GIT rail header opens the repo switcher picker.
    if let Some(r) = app.rects.git_repo_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        crate::command::run("git.switch_repo", app);
        return;
    }
    // #polish 2026-07-06 — click the right-panel `+` chip opens
    // a small menu with the 5 panel kinds.
    if let Some(r) = app.rects.right_panel_new_button
        && crate::app::dispatch::contains(r, x, y)
    {
        use crate::context_menu::{ContextMenu, MenuAction, MenuItem};
        let items = vec![
            MenuItem::new("Outline", MenuAction::Command("outline.show")),
            MenuItem::new("Problems", MenuAction::Command("lsp.diagnostics")),
            MenuItem::new("AI chat", MenuAction::Command("ai.chat")),
            MenuItem::new("Grep", MenuAction::Command("find.grep")),
            MenuItem::new("Tests", MenuAction::Command("test.run")),
        ];
        app.context_menu = Some(ContextMenu::new(
            Some("Add panel".to_string()),
            (x, y),
            items,
        ));
        return;
    }
    // Grab the rail's right-edge resize handle first — its grip
    // band shares the rail's rightmost column with the file-tree
    // scrollbar, so the (specific, ~4-row) resize zone must win
    // there before the (full-height) scrollbar claims the click.
    // #polish 2026-07-06 — double-click on a rail edge resets
    // the width to the config default before drag-detection
    // consumes the click. Same VS Code / Chrome tab-strip
    // convention: click-drag to resize, double-click to reset.
    let is_double_click = {
        let now = std::time::Instant::now();
        matches!(app.last_click, Some((t, lx, ly, count))
            if count >= 1
                && (x as i32 - lx as i32).abs() <= 1
                && (y as i32 - ly as i32).abs() <= 1
                && now.duration_since(t) < std::time::Duration::from_millis(500))
    };
    if is_double_click
        && let Some(r) = app.rects.tree_edge
        && crate::app::dispatch::contains(r, x, y)
    {
        app.tree_width = app.config.ui.tree_width;
        app.toast("tree width reset");
        return;
    }
    if is_double_click
        && let Some(r) = app.rects.right_panel_edge
        && crate::app::dispatch::contains(r, x, y)
    {
        app.right_panel_width = app.config.ui.right_panel_width;
        app.toast("right panel width reset");
        return;
    }
    if app.begin_tree_edge_drag(x, y) {
        return;
    }
    // vscode-user-mouse SEV-1 — mirror for the right-panel
    // grip. Without this, the field stayed false and the
    // grip was decorative.
    if app.maybe_start_right_panel_edge_drag(x, y) {
        return;
    }
    // Right-panel v3: tab strip click → switch active tab.
    // Checked BEFORE the × close since the tabs occupy the
    // left half of the same row.
    if let Some(&(_, tab_idx)) = app
        .rects
        .right_panel_tabs
        .iter()
        .find(|(rect, _)| crate::app::dispatch::contains(*rect, x, y))
    {
        app.right_panel_active_idx = tab_idx;
        return;
    }
    // mouse-polish F-2 — empty-state command lines as
    // click targets so a mouse-first user can populate
    // the panel without typing.
    if let Some(rect) = app.rects.right_panel_empty_outline
        && crate::app::dispatch::contains(rect, x, y)
    {
        crate::command::run("outline.show", app);
        return;
    }
    if let Some(rect) = app.rects.right_panel_empty_diagnostics
        && crate::app::dispatch::contains(rect, x, y)
    {
        crate::command::run("lsp.diagnostics", app);
        return;
    }
    // design-critic 2026-06-28 #3 — 3 more empty-state
    // click rects so all 5 routable commands are mouse
    // reachable from the empty state.
    if let Some(rect) = app.rects.right_panel_empty_ai
        && crate::app::dispatch::contains(rect, x, y)
    {
        crate::command::run("ai.chat", app);
        return;
    }
    if let Some(rect) = app.rects.right_panel_empty_grep
        && crate::app::dispatch::contains(rect, x, y)
    {
        crate::command::run("find.grep", app);
        return;
    }
    if let Some(rect) = app.rects.right_panel_empty_test
        && crate::app::dispatch::contains(rect, x, y)
    {
        // mouse-round-7 SEV-2 2026-07-11 — `test.run` didn't exist,
        // so the click silently no-op'd. Fall through the `_file` /
        // `_all` variants; `_file` toasts helpfully when no editor is
        // open.
        if crate::command::registry().get("test.run_file").is_some() {
            crate::command::run("test.run_file", app);
        } else {
            crate::command::run("test.run_all", app);
        }
        return;
    }
    // Right-panel v3 `×` on the header closes the active
    // tab (panel stays open; next tab takes its place, or
    // empty-state returns if it was the last).
    if let Some(rect) = app.rects.right_panel_close
        && crate::app::dispatch::contains(rect, x, y)
    {
        if let Some(pid) = app.right_panel_active_pane_id() {
            // crash-investigator SEV-1 #3: close_pane FIRST.
            // On a dirty editor this exits early with a close
            // prompt; the pane is still in right_panel_panes
            // so confirm-discard routes through
            // remove_pane_storage which now also drops the
            // right-panel record. For non-dirty panes,
            // remove_pane_storage takes care of the shift.
            app.close_pane(pid);
        }
        return;
    }
    // 2026-08-07 vscode-user r2 F1 SEV-2 — bottom-panel `×` chip
    // was drawn but never wired to a click handler. Hides the
    // panel (mirrors Ctrl+Shift+J), which also drains hosted
    // panes so they don't linger as ghost bufferline entries.
    if let Some(rect) = app.rects.bottom_panel_close
        && crate::app::dispatch::contains(rect, x, y)
    {
        crate::command::run("view.toggle_bottom_panel", app);
        return;
    }
    // qa-feature 2026-07-02 — markdown pane swap chips at the top of
    // MdPreview + Editor(.md) panes. Checked BEFORE scrollbars so the
    // chip at the far-right of the banner row isn't shadowed by
    // anything below.
    if let Some(&(_, pid)) = app
        .rects
        .md_preview_edit_buttons
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.md_preview_to_edit(pid);
        return;
    }
    if let Some(&(_, pid)) = app
        .rects
        .editor_md_preview_buttons
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.md_edit_to_preview(pid);
        return;
    }
    // Grab a scrollbar (editor / diff / embedded-diff / tree) before
    // any pane-level handler — the bar sits inside the pane's
    // own rect, so without this short-circuit a click on the
    // bar would also land in the editor / row-select handlers
    // below and shift the cursor / row selection.
    if app.begin_scrollbar_drag(x, y) {
        return;
    }
    // Grab the GitGraph commit-list ↔ detail-panel divider?
    if app.begin_git_graph_detail_drag(x, y) {
        return;
    }
    // mouse-round-12 SEV-2 F2 2026-07-14 — divider double-click
    // equalize must be checked BEFORE begin_divider_drag; the
    // round-11 fallback at ~line 2760 was unreachable because
    // begin_divider_drag returns unconditionally on divider hit.
    // Match the same 450 ms double-click window, then consume.
    if app
        .rects
        .split_dividers
        .iter()
        .any(|d| crate::app::dispatch::contains(d.rect, x, y))
    {
        let now = std::time::Instant::now();
        let is_double = matches!(
            app.last_click,
            Some((prev, px, py, c))
                if px == x
                    && py == y
                    && c >= 1
                    && now.duration_since(prev) < std::time::Duration::from_millis(DOUBLE_CLICK_MAX_MS as u64)
        );
        app.last_click = Some((now, x, y, if is_double { 2 } else { 1 }));
        if is_double {
            app.equalize_splits();
            // mouse-round-15 SEV-2 F1 2026-07-15 — don't early-return.
            // The user's second Down may be intended as a drag start,
            // not a "dbl-click to equalize" (unambiguous only at Up
            // time). Fall through to begin_divider_drag so the drag
            // still arms — the user's drag continues from the just-
            // equalized position, which is a strictly better outcome
            // than "click-then-drag within 700 ms silently drops the
            // drag."
        }
    }
    // Grab a split divider? (do this first — it sits between two pane rects)
    if app.begin_divider_drag(x, y) {
        return;
    }
    // Click on a fold chip → unfold that block. Match before the
    // editor-pane click handler so the chip "owns" the click.
    if let Some(&(_, pid, start)) = app
        .rects
        .fold_chips
        .iter()
        .find(|(r, _, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.active = Some(pid);
        app.focus_pane();
        if let Some(Pane::Editor(b)) = app.panes.get_mut(pid) {
            b.folds.remove(&start);
        }
        return;
    }
    // VS Code-style fold arrow in the sign column → toggle the fold
    // at that line. `toggle_fold_at_cursor` uses the cursor's
    // position, so seek the cursor to the clicked line first
    // (its first non-whitespace char, matching how vim's `za` on a
    // header line behaves). 2026-07-11.
    if let Some(&(_, pid, line_no)) = app
        .rects
        .fold_arrows
        .iter()
        .find(|(r, _, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.active = Some(pid);
        app.focus_pane();
        if let Some(Pane::Editor(b)) = app.panes.get_mut(pid) {
            b.editor.place_cursor(line_no, 0);
        }
        app.toggle_fold_at_cursor();
        return;
    }
    // Click on a code-lens chip → fire its `workspace/executeCommand`.
    // Same priority as fold chips — chip owns the click.
    if let Some(&(_, pid, lens_idx)) = app
        .rects
        .code_lens_chips
        .iter()
        .find(|(r, _, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.active = Some(pid);
        app.focus_pane();
        app.trigger_code_lens(pid, lens_idx);
        return;
    }
    // Click on a WIP-detail button → fire its action (stage/unstage
    // file or all, open commit prompt, request AI commit message).
    // High priority so the button "owns" the click instead of the
    // pane-focus handler eating it.
    if let Some((_, pid, action)) = app
        .rects
        .wip_buttons
        .iter()
        .find(|(r, _, _)| crate::app::dispatch::contains(*r, x, y))
        .cloned()
    {
        app.active = Some(pid);
        app.focus_pane();
        // Clicking a button blurs the textarea so the user
        // doesn't keep typing into a no-longer-visible field.
        app.blur_active_wip_commit_textarea();
        app.run_wip_action(action);
        return;
    }
    // Click on a WIP-detail file row (not the button) →
    // open that file's diff (`Pane::Diff`) so the user can
    // browse Hunk / Inline / Split views.
    if let Some((_, pid, abs_path, staged)) = app
        .rects
        .wip_file_rows
        .iter()
        .find(|(r, _, _, _)| crate::app::dispatch::contains(*r, x, y))
        .cloned()
    {
        app.active = Some(pid);
        app.focus_pane();
        app.blur_active_wip_commit_textarea();
        app.click_wip_file_row(abs_path, staged);
        return;
    }
    // Click inside the WIP commit textarea rect → focus it.
    // Wins over the pane-focus handler so the click both
    // focuses the GitGraph pane AND focuses the textarea.
    if let Some((r, pid)) = app.rects.wip_commit_textarea
        && crate::app::dispatch::contains(r, x, y)
    {
        app.active = Some(pid);
        app.focus_pane();
        app.focus_wip_commit_textarea(pid);
        return;
    }
    // Click on a GitGraph top-toolbar button → fire its action.
    // Pull / Push / Fetch / Branch / Commit / Stash / Pop /
    // Reflog / Terminal. High priority so the button owns the
    // click.
    if let Some(&(_, pid, action)) = app
        .rects
        .git_toolbar_buttons
        .iter()
        .find(|(r, _, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.active = Some(pid);
        app.focus_pane();
        app.run_git_toolbar_action(action);
        return;
    }
    // Click on a per-hunk action chip ([Stage] / [Unstage]
    // / [Discard]) in the Hunk view's header row → dispatch
    // the action against that hunk. Runs before the
    // toolbar / row click handlers so the chip "owns" the
    // click.
    if let Some(&(_, pid, hi, action)) = app
        .rects
        .diff_hunk_buttons
        .iter()
        .find(|(r, _, _, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.active = Some(pid);
        app.focus_pane();
        app.apply_hunk_action(pid, hi, action);
        return;
    }
    // Click on a Diff pane toolbar button → switch view mode
    // or toggle wrap. Also store the choice as the App-level
    // preference so every subsequent diff opens in that mode.
    // Works against both a standalone `Pane::Diff` and a
    // `Pane::GitGraph` with an embedded diff (when the user
    // clicked a file from a commit's right-side detail panel
    // and the diff opened in-place on the left).
    if let Some(&(_, pid, action)) = app
        .rects
        .diff_toolbar_buttons
        .iter()
        .find(|(r, _, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.active = Some(pid);
        app.focus_pane();
        // `Close` is special — clears embedded diff if any,
        // else closes the standalone Pane::Diff. Returns
        // before the view-mode handling block since the
        // pane may no longer exist after closing.
        if matches!(action, crate::DiffToolbarAction::Close) {
            match app.panes.get_mut(pid) {
                Some(Pane::GitGraph(g)) if g.embedded_diff.is_some() => {
                    g.embedded_diff = None;
                }
                Some(Pane::Diff(_)) => {
                    app.close_pane(pid);
                }
                _ => {}
            }
            return;
        }
        let mut new_wrap_pref: Option<bool> = None;
        let mut new_mode_pref: Option<crate::pane::DiffViewMode> = None;
        let dv: Option<&mut crate::pane::DiffView> = match app.panes.get_mut(pid) {
            Some(Pane::Diff(d)) => Some(d),
            Some(Pane::GitGraph(g)) => g.embedded_diff.as_mut(),
            _ => None,
        };
        if let Some(d) = dv {
            match action {
                crate::DiffToolbarAction::ViewInline => {
                    d.view_mode = crate::pane::DiffViewMode::Inline;
                    new_mode_pref = Some(d.view_mode);
                }
                crate::DiffToolbarAction::ViewHunk => {
                    d.view_mode = crate::pane::DiffViewMode::Hunk;
                    new_mode_pref = Some(d.view_mode);
                }
                crate::DiffToolbarAction::ViewSplit => {
                    d.view_mode = crate::pane::DiffViewMode::Split;
                    new_mode_pref = Some(d.view_mode);
                }
                crate::DiffToolbarAction::ToggleWrap => {
                    d.wrap = !d.wrap;
                    new_wrap_pref = Some(d.wrap);
                }
                crate::DiffToolbarAction::Close => unreachable!(),
            }
        }
        if let Some(m) = new_mode_pref {
            app.diff_view_mode_pref = m;
        }
        if let Some(w) = new_wrap_pref {
            app.diff_wrap_pref = w;
        }
        return;
    }
    // Click on a commit-detail changed-file row → open that
    // file's diff for the selected commit.
    if let Some(&(_, pid, file_idx)) = app
        .rects
        .commit_file_rows
        .iter()
        .find(|(r, _, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.active = Some(pid);
        app.focus_pane();
        app.click_commit_file_row(pid, file_idx);
        return;
    }
    // Click on a request-pane tab chip → switch view (Edit ⇄ Response).
    if let Some(&(_, pid, view)) = app
        .rects
        .request_tabs
        .iter()
        .find(|(r, _, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.active = Some(pid);
        app.focus_pane();
        if let Some(Pane::Request(rp)) = app.panes.get_mut(pid) {
            rp.view = view;
        }
        return;
    }
    // Click on a row in the cmdline completion popup →
    // accept that match (writes the completion into the
    // cmdline and bumps cmdline_popup_selected so subsequent
    // Tabs continue from there). 2026-06-19 — discoverability
    // gold: users can mouse-pick from the popup.
    if let Some(&(_, idx)) = app
        .rects
        .cmdline_popup_items
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.cmdline_popup_accept(idx);
        return;
    }
    // Click on an Auth-tab action row → dispatch to the
    // matching App method (prompt or palette command).
    if let Some((_, id)) = app
        .rects
        .request_auth_rows
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
        .cloned()
    {
        app.http_auth_row_clicked(&id);
        return;
    }
    // Click on the AI section header → opens a prompt
    // asking what the user wants to know (custom Q + A).
    // The `a` key still fires the default debug prompt
    // (no question, just 'why is this not working').
    if let Some(r) = app.rects.request_ai_section
        && crate::app::dispatch::contains(r, x, y)
    {
        app.ai_ask_about_request_prompt();
        return;
    }
    // Click on the "▶ Send" button in the Request pane's top row
    // → fires the request. During Sending the button flips to
    // "⟳ Abort" (see `draw_send_box`) and the click routes to
    // `http.abort` instead. Same effect as the `r` chord over the
    // Request pane and the `http.send` / `http.abort` commands.
    if let Some(r) = app.rects.request_send_button
        && crate::app::dispatch::contains(r, x, y)
    {
        // vscode-user-mouse SEV-2 2026-07-10: a click on any Request-
        // pane chrome (send/save/clear/…) fires the action but never
        // switched focus to the pane, so the follow-up keystroke
        // routed to wherever focus WAS (usually Tree, after opening
        // via the file browser). Snap focus so `r` / typing lands
        // where the user just clicked.
        app.focus_pane();
        let is_sending = matches!(
            app.active.and_then(|i| app.panes.get(i)),
            Some(crate::pane::Pane::Request(rp))
                if matches!(rp.state, crate::request_pane::RunState::Sending)
        );
        if is_sending {
            crate::command::run("http.abort", app);
        } else {
            crate::command::run("http.send", app);
        }
        return;
    }
    // Click on the "⎘ Save" button → save the active Request
    // pane's fields to its source file, or open a Save-As prompt
    // when no source file is set yet.
    if let Some(r) = app.rects.request_save_button
        && crate::app::dispatch::contains(r, x, y)
    {
        app.focus_pane();
        app.http_save_or_prompt_save_as();
        return;
    }
    // Click on the "✕ Clear" button → reset the active Request
    // pane's fields to a blank template. Same code path as the
    // sidebar's `+ New request` chip; toasts a hint.
    if let Some(r) = app.rects.request_clear_button
        && crate::app::dispatch::contains(r, x, y)
    {
        app.focus_pane();
        // #20 v2 — snapshot the pane before clearing so `↶ Undo`
        // can restore the URL / body / headers / etc. Skips the
        // snapshot when the active pane isn't a Request (no-op
        // clear anyway).
        if let Some(cur) = app.active
            && let Some(crate::pane::Pane::Request(rp)) = app.panes.get(cur)
        {
            let action = crate::app::UndoAction::RestoreRequestPane {
                pane_id: cur,
                method: rp.request.method.clone(),
                url: rp.request.url.clone(),
                body: rp.request.body.clone(),
                headers_buffer: rp.headers_buffer.clone(),
                source_buffer: rp.source_buffer.clone(),
            };
            app.http_panel_new_request();
            app.set_pending_undo("cleared request".to_string(), action);
            app.toast("cleared");
        } else {
            app.http_panel_new_request();
            app.toast("cleared");
        }
        return;
    }
    // Click on the "{ } Format" button → prettify the JSON body
    // in place. No-op + toast on non-JSON bodies. Same as
    // Shift+Alt+F chord.
    if let Some(r) = app.rects.request_format_button
        && crate::app::dispatch::contains(r, x, y)
    {
        app.focus_pane();
        app.http_format_body();
        return;
    }
    // Click on the "↻ Reroll" chip → regenerate body dynamic values.
    if let Some(r) = app.rects.request_regenerate_button
        && crate::app::dispatch::contains(r, x, y)
    {
        app.focus_pane();
        app.http_regenerate_body();
        return;
    }
    // Click on "</> Code" → open the Generate Code language
    // picker (Bruno-style).
    if let Some(r) = app.rects.request_code_button
        && crate::app::dispatch::contains(r, x, y)
    {
        app.focus_pane();
        app.http_generate_code_prompt();
        return;
    }
    // Click on the Env chip → open the env picker.
    if let Some(r) = app.rects.request_env_button
        && crate::app::dispatch::contains(r, x, y)
    {
        app.focus_pane();
        app.open_http_env_picker();
        return;
    }
    // Click on the "JSON ▼" content-type chip → open the
    // response-format override picker.
    if let Some(r) = app.rects.request_response_type_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.http_response_format_prompt();
        return;
    }
    // Click on the "copy" chip → copy the response body.
    if let Some(r) = app.rects.request_response_copy_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.http_copy_response_body();
        return;
    }
    // Click on the "wrap" chip → toggle body wrap.
    if let Some(r) = app.rects.request_response_wrap_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.http_toggle_response_wrap();
        return;
    }
    // Click on the `⚡ AI` chip → copy AI-ready debug prompt.
    if let Some(r) = app.rects.request_response_ai_prompt_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.http_copy_ai_prompt();
        return;
    }
    // Click on the split-orientation toggle chip → cycle
    // Vertical <-> Horizontal for the active Request pane. Same
    // as `Ctrl+\` chord.
    if let Some(r) = app.rects.request_split_toggle
        && crate::app::dispatch::contains(r, x, y)
    {
        if let Some(cur) = app.active
            && let Some(crate::pane::Pane::Request(rp)) = app.panes.get_mut(cur)
        {
            rp.split_orientation = rp.split_orientation.toggle();
        }
        return;
    }
    // Click on a Response sub-tab chip (Body / Headers / Timeline
    // / Tests) → switch the active pane's `response_tab`.
    // api-round-14 SEV-2 2026-07-16 — also snap the pane's view
    // to Response AND focus_pane() so the documented `/`-search
    // and `j`/`k` scroll bindings actually reach the response
    // renderer. Was: only set `response_tab` — the pane could
    // still be in ViewMode::Edit or focus could still be on the
    // tree, so the next keystroke silently corrupted the URL
    // instead of scrolling / searching.
    if let Some((_, tab)) = app
        .rects
        .request_response_tabs
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        let tab = *tab;
        if let Some(cur) = app.active
            && let Some(crate::pane::Pane::Request(rp)) = app.panes.get_mut(cur)
        {
            rp.response_tab = tab;
            rp.view = crate::request_pane::ViewMode::Response;
        }
        app.focus_pane();
        return;
    }
    // Click on a Vars-tab row → cell-level routing (#23 v3).
    // Sentinel keys work the same as Params / Headers:
    //   `\0VAL<key>`  → start inline value edit
    //   `\0NAME<key>` → start inline rename
    //   `\0DEL<key>`  → delete env var
    //   `\0COMMIT`    → no-op for Vars (no draft-add row)
    //   ""            → add-row (falls through to palette prompt)
    //   any other     → whole-row click (falls through to palette prompt)
    if let Some((_, key, _)) = app
        .rects
        .request_vars_rows
        .iter()
        .find(|(r, _, _)| crate::app::dispatch::contains(*r, x, y))
        .cloned()
    {
        // api-round-13 SEV-2 A 2026-07-15 — a click that starts an
        // inline KV edit must also move keyboard focus to the pane,
        // otherwise every subsequent keystroke routes to whichever
        // handler currently owns focus (typically the tree, if the
        // request pane was opened as a preview from the tree/
        // COLLECTIONS list). Symptom: the cell renders `value▏` but
        // every key/backspace/Enter/Tab/Esc is silently swallowed;
        // only another mouse click elsewhere recovers.
        app.focus_pane();
        if key == "\0COMMIT" {
            return;
        }
        if let Some(row_key) = key.strip_prefix("\0VAL") {
            app.http_kv_edit_begin(crate::request_pane::KvEditKind::Vars, row_key.to_string());
            return;
        }
        if let Some(row_key) = key.strip_prefix("\0NAME") {
            app.http_kv_edit_begin_name(crate::request_pane::KvEditKind::Vars, row_key.to_string());
            return;
        }
        if let Some(row_key) = key.strip_prefix("\0DEL") {
            app.http_delete_env_key(row_key);
            return;
        }
        if key.is_empty() {
            app.accept_env_vars("+add");
        } else {
            app.accept_env_vars(&key);
        }
        return;
    }
    // Click on a Params- or Headers-tab row → empty key
    // (`+ Add row`) starts the inline draft; non-empty key
    // deletes that row (whole-row hitbox for v1). The dispatch
    // routes to params vs headers based on the active pane's
    // current edit_tab.
    if let Some((_, key, kind)) = app
        .rects
        .request_params_rows
        .iter()
        .find(|(r, _, _)| crate::app::dispatch::contains(*r, x, y))
        .cloned()
    {
        // api-round-13 SEV-2 A 2026-07-15 — same pane-focus fix
        // as request_vars_rows above. See comment there.
        app.focus_pane();
        // Kind is now carried on the rect itself (fix 2026-07-07) so
        // secondary-side clicks in a side-by-side edit split route
        // to the right params/headers path even when the primary
        // tab is something else. Was: read rp.edit_tab, which
        // reflected only the primary side.
        let is_headers = matches!(kind, crate::ui::request_view::KvTableKind::Headers);
        // Sentinel-key routing. The `\0` prefix can't appear in
        // any HTTP header name or URL query key, so no user data
        // collides:
        //   `\0COMMIT`    — draft-row ✓ cell → commit + new row
        //   `\0VAL<name>` — value cell     → start value edit
        //   `\0NAME<name>` — name cell     → start rename edit
        //   `\0DEL<name>`  — ✕ cell        → delete row
        if key == "\0COMMIT" {
            if is_headers {
                app.http_headers_add_commit(true);
            } else {
                app.http_params_add_commit(true);
            }
            return;
        }
        if let Some(row_key) = key.strip_prefix("\0VAL") {
            let kind = if is_headers {
                crate::request_pane::KvEditKind::Headers
            } else {
                crate::request_pane::KvEditKind::Params
            };
            app.http_kv_edit_begin(kind, row_key.to_string());
            return;
        }
        if let Some(row_key) = key.strip_prefix("\0NAME") {
            let kind = if is_headers {
                crate::request_pane::KvEditKind::Headers
            } else {
                crate::request_pane::KvEditKind::Params
            };
            app.http_kv_edit_begin_name(kind, row_key.to_string());
            return;
        }
        if let Some(row_key) = key.strip_prefix("\0DEL") {
            if is_headers {
                app.http_headers_delete(row_key);
            } else {
                app.http_params_delete(row_key);
            }
            return;
        }
        if key.is_empty() {
            if is_headers {
                app.http_headers_add();
            } else {
                app.http_params_add();
            }
        } else if is_headers {
            // Backwards-compat with whole-row rects registered
            // outside render_kv_table (Vars tab still uses them).
            app.http_headers_delete(&key);
        } else {
            app.http_params_delete(&key);
        }
        return;
    }
    // Click on a `{{VAR}}` token in a Request pane's URL / body.
    // Resolved var (defined in active env) → jump to the env-file
    // definition line so the user can inspect/edit the value.
    // Unresolved var (red) → open the env-value edit prompt
    // directly, so defining a missing var is one click instead of
    // right-click → Set value…. Dynamic `$foo` vars keep the
    // jump-to-def behavior (they resolve to built-ins; there's no
    // env file to prompt for). #polish 2026-07-07.
    if let Some((_, name)) = app
        .rects
        .request_var_click_rects
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        let name = name.clone();
        // api-round-12 SEV-2 2026-07-14 — was 2-tier
        // `EnvSet::select` (empty on `.mnml`-only workspaces),
        // so `resolved` was always `false` and a click on a
        // GREEN (resolved) var wrongly opened the "Set value…"
        // prompt instead of jump-to-definition. Route through
        // the shared 5-tier helper.
        let envset = app.active_envset();
        let resolved = match name.strip_prefix('$') {
            Some(dyn_name) => crate::http::template::dynamic_var(dyn_name).is_some(),
            None => envset.lookup(&name).is_some(),
        };
        if resolved || name.starts_with('$') {
            app.open_env_var_definition(&name);
        } else {
            app.accept_env_vars(&name);
        }
        return;
    }
    // Click on a Request pane Edit-view tab chip (Body /
    // Headers / Params / Vars / Source) → switch the
    // pane's edit_tab.
    if let Some(&(_, pid, tab)) = app
        .rects
        .request_edit_tabs
        .iter()
        .find(|(r, _, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.active = Some(pid);
        app.focus_pane();
        if let Some(Pane::Request(rp)) = app.panes.get_mut(pid) {
            rp.view = crate::request_pane::ViewMode::Edit;
            rp.edit_tab = tab;
            if tab == crate::request_pane::EditTab::Source {
                rp.focus = crate::request_pane::EditField::Source;
            } else if rp.focus == crate::request_pane::EditField::Source {
                rp.focus = crate::request_pane::EditField::Url;
            }
        }
        return;
    }
    // Click on the SECONDARY tab strip (right side of a side-by-side
    // edit split) → change `edit_tab_split`, not the primary tab.
    if let Some(&(_, pid, tab)) = app
        .rects
        .request_edit_tabs_split
        .iter()
        .find(|(r, _, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.active = Some(pid);
        app.focus_pane();
        if let Some(Pane::Request(rp)) = app.panes.get_mut(pid) {
            rp.view = crate::request_pane::ViewMode::Edit;
            rp.edit_tab_split = Some(tab);
        }
        return;
    }
    // Click on the `⇔` edit-split chip → toggle the split.
    if let Some(r) = app.rects.request_edit_split_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        if let Some(pid) = app.active
            && let Some(Pane::Request(rp)) = app.panes.get_mut(pid)
        {
            rp.view = crate::request_pane::ViewMode::Edit;
            rp.toggle_edit_split();
        }
        return;
    }
    // Click on the edit-split divider → cycle the ratio (30/50/70).
    // A cheap replacement for full drag-resize until it's needed.
    if let Some(r) = app.rects.request_edit_split_divider
        && crate::app::dispatch::contains(r, x, y)
    {
        if let Some(pid) = app.active
            && let Some(Pane::Request(rp)) = app.panes.get_mut(pid)
        {
            rp.edit_split_ratio = match rp.edit_split_ratio {
                0..=39 => 50,
                40..=59 => 70,
                _ => 30,
            };
        }
        return;
    }
    // Click on a request-pane Edit-mode field row → focus that field.
    // 2026-06-19 — vscode-user-mouse agent caught that the
    // caret was never positioned at the click site (it stayed
    // wherever it was, typically end-of-value). For the URL
    // field — the most common edit target — compute the byte
    // position from the visual column and update url_cursor.
    // Headers / Body are multi-line; positioning their carets
    // by click requires per-row mapping that's a v2 follow-up;
    // they still get focused so the user can type / use arrows.
    if let Some(&(rect, pid, field)) = app
        .rects
        .request_fields
        .iter()
        .find(|(r, _, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.active = Some(pid);
        app.focus_pane();
        if let Some(Pane::Request(rp)) = app.panes.get_mut(pid) {
            rp.view = crate::request_pane::ViewMode::Edit;
            rp.focus = field;
            // Method box click opens the verb-picker context
            // menu (GET/POST/PUT/PATCH/DELETE/HEAD/OPTIONS →
            // click one to set). No width guard needed anymore —
            // Method has its own bordered sub-panel (width 14)
            // and can't be confused with a headers or body row
            // click.
            if matches!(field, crate::request_pane::EditField::Method) {
                let _ = rp;
                app.open_method_dropdown((x, y));
                return;
            }
            if matches!(field, crate::request_pane::EditField::Url) {
                // URL row layout: " URL  <value>". Label
                // offset = leading-space + "URL" + 2 spaces ≈
                // 6 cells. Visual column within the value =
                // click x - rect.x - label_offset. Convert
                // visual column to a byte position via
                // char_indices(); clamp to value length.
                //
                // 2026-07-24 fix: request_view.rs moved "URL" to
                // the pane border title; the value row now starts
                // just 1 cell in (a single leading space padding).
                // Old `label_offset = 6` (from the inline
                // " URL  <value>" layout) mis-clamped clicks by 5
                // chars. api-workflow-user finding 2026-07-24.
                let dx = x.saturating_sub(rect.x);
                let label_offset: u16 = 1;
                let visual_col = dx.saturating_sub(label_offset) as usize;
                let url = &rp.request.url;
                let byte_pos = url
                    .char_indices()
                    .nth(visual_col)
                    .map(|(i, _)| i)
                    .unwrap_or(url.len());
                rp.url_cursor = byte_pos;
            }
        }
        return;
    }
    // Bufferline overflow chevrons — scroll the tab strip by one.
    if let Some(r) = app.rects.bufferline_overflow_left
        && crate::app::dispatch::contains(r, x, y)
    {
        if app.bufferline_first_visible > 0 {
            app.bufferline_first_visible -= 1;
            // qa-7th vscode SEV-2 — stamp the active pane so the
            // auto-scroll-to-keep-active-visible logic in
            // ui::bufferline::draw doesn't immediately clobber
            // this manual scroll. Cleared when active changes.
            app.bufferline_active_at_scroll = app.active;
        }
        return;
    }
    if let Some(r) = app.rects.bufferline_overflow_right
        && crate::app::dispatch::contains(r, x, y)
    {
        // qa-8th crash SEV-3 2026-06-30 — was app.panes.len(),
        // which includes right_panel_panes (not in the bufferline
        // visible list). The render-side clamp swallowed the
        // extra clicks silently. Use the actual visible count.
        let visible_count = app.panes.len().saturating_sub(app.right_panel_panes.len());
        if app.bufferline_first_visible + 1 < visible_count {
            app.bufferline_first_visible += 1;
            app.bufferline_active_at_scroll = app.active;
        }
        return;
    }
    // qa-feature 2026-07-01 — click the [×] on an exited pty's banner
    // to close the pane (alternative to Ctrl+W).
    if let Some(&(_, id)) = app
        .rects
        .pty_exit_close_buttons
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.close_pane(id);
        return;
    }
    // qa-feature 2026-07-01 — Installed / Marketplace tab chips in the
    // Integrations panel. Click switches the active sub-view.
    // 2026-07-25 — move focus to Tree so subsequent keyboard nav
    // (arrows, `/` filter, Enter) targets the panel instead of a
    // previously-focused pane.
    // 2026-08-05 — scroll is per-tab now; switching preserves the
    // last scroll position on each tab (removed the reset-to-top).
    if let Some(rect) = app.rects.integrations_tab_installed
        && crate::app::dispatch::contains(rect, x, y)
    {
        app.focus = crate::focus::Focus::Tree;
        app.integrations_panel_tab = crate::app::IntegrationsPanelTab::Installed;
        return;
    }
    if let Some(rect) = app.rects.integrations_tab_marketplace
        && crate::app::dispatch::contains(rect, x, y)
    {
        app.focus = crate::focus::Focus::Tree;
        app.integrations_panel_tab = crate::app::IntegrationsPanelTab::Marketplace;
        return;
    }
    // #1056 — third tab (In-Development). Only registered when
    // `[marketplace] show_dev_tab = true`, so this branch is inert
    // when the option is off.
    if let Some(rect) = app.rects.integrations_tab_in_dev
        && crate::app::dispatch::contains(rect, x, y)
    {
        app.focus = crate::focus::Focus::Tree;
        app.integrations_panel_tab = crate::app::IntegrationsPanelTab::InDev;
        return;
    }
    // 2026-08-04 — click the ⟳ chip on the tab row → refresh the
    // active tab's data source. Marketplace: re-fetch crates.io +
    // GitHub launcher entries (async, doesn't block the tick).
    // Installed: re-scan `<ws>/.mnml/integrations/` and
    // `~/.config/mnml/integrations/` so a manifest just-written by
    // an integration `<name> --install` surfaces immediately.
    if let Some(rect) = app.rects.integrations_tab_refresh
        && crate::app::dispatch::contains(rect, x, y)
    {
        app.focus = crate::focus::Focus::Tree;
        match app.integrations_panel_tab {
            crate::app::IntegrationsPanelTab::Marketplace
            | crate::app::IntegrationsPanelTab::InDev => app.refresh_marketplace(),
            crate::app::IntegrationsPanelTab::Installed => app.refresh_integration_manifests(),
        }
        return;
    }
    // 2026-08-07 — click the sort chip → cycle the active tab's sort
    // mode. Per-tab so switching Installed ↔ Marketplace preserves
    // each side's selected mode.
    if let Some(rect) = app.rects.integrations_tab_sort
        && crate::app::dispatch::contains(rect, x, y)
    {
        app.focus = crate::focus::Focus::Tree;
        match app.integrations_panel_tab {
            crate::app::IntegrationsPanelTab::Installed => {
                app.installed_sort = app.installed_sort.cycle();
                app.toast(format!("sort: {}", app.installed_sort.label()));
            }
            crate::app::IntegrationsPanelTab::Marketplace
            | crate::app::IntegrationsPanelTab::InDev => {
                app.marketplace_sort = app.marketplace_sort.cycle();
                app.toast(format!("sort: {}", app.marketplace_sort.label()));
            }
        }
        return;
    }
    // Integrations filter chip — click to focus filter input.
    // 2026-07-25 — also move `app.focus` back to Tree. Otherwise if
    // the user had an integration pane open (focus == Focus::Pane),
    // clicking the filter chip flipped `_filter_focused` but the
    // key-absorption block in tui/mod.rs is gated on `focus == Tree`,
    // so typed chars fell through to the open pane instead.
    if let Some(rect) = app.rects.integrations_filter_chip
        && crate::app::dispatch::contains(rect, x, y)
    {
        app.focus = crate::focus::Focus::Tree;
        app.integrations_panel_filter_focused = true;
        return;
    }
    // `+ Add integration` chip at the bottom → switch the panel to
    // the Marketplace tab. Same discoverable entry point as `+ New
    // note` on Notes and `+ New session` on Sessions.
    if let Some(rect) = app.rects.integrations_add_chip
        && crate::app::dispatch::contains(rect, x, y)
    {
        app.integrations_panel_tab = crate::app::IntegrationsPanelTab::Marketplace;
        app.toast("switched to Marketplace — pick an integration to install");
        return;
    }
    // Bufferline tab — clicking the close badge closes; clicking elsewhere on the tab activates.
    if let Some(&(_, id)) = app
        .rects
        .bufferline_tab_close
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        // mouse-round-16 SEV-2 F1 2026-07-16 — require physical
        // mouse movement between tab-close clicks. Round-15's
        // `last_click = None` reset only broke dbl-CLICK state;
        // the raw second click at the same coord still closed
        // whatever tab had slid into that slot. Now: if the last
        // close fired at this exact (col, row) AND the pointer
        // hasn't moved since, swallow the click. The user must
        // physically move the mouse to close the next tab —
        // matches VS Code / Chrome tab-close behavior.
        if app.last_tab_close_at == Some((x, y)) {
            return;
        }
        app.close_pane(id);
        app.last_tab_close_at = Some((x, y));
        // Also reset last_click for the round-15 double-click
        // state (harmless if already None; kept for defense in depth).
        app.last_click = None;
        return;
    }
    if let Some(&(_, id)) = app
        .rects
        .bufferline_tabs
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        // Arm a drag — the buffer-switch (reveal) is deferred to
        // mouse-up so a drag-to-split doesn't first swap the grabbed
        // tab into the pane (which would make the drop land on its own
        // pane). A subsequent Drag into another tab's rect reorders;
        // a Drag onto a pane body splits. On a plain click (up on the
        // same tab) the Up handler reveals.
        app.rects.bufferline_drag_tab = Some(id);
        return;
    }
    // Pty-pane tab strip — click `+` to add a new Claude session
    // as a TAB of that strip's leaf (no split); click a session
    // tab to switch; click the `×` to kill that session. Test
    // close BEFORE switch so the badge wins over the chip body.
    if let Some(&(_, pid)) = app
        .rects
        .pty_tab_close
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.close_pane(pid);
        return;
    }
    if let Some(&(_, owner)) = app
        .rects
        .pty_tab_new
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        let profile = crate::pty_pane::BinaryProfile::claude_code(app.workspace.clone());
        app.add_pty_tab(owner, profile);
        return;
    }
    if let Some(&(_, pid)) = app
        .rects
        .pty_tabs
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.reveal_pane(pid);
        return;
    }
    // Bufferline right cluster — Claude / Codex launch chips,
    // `+` new tab, per-tabpage chip / close, theme toggle,
    // window close. Order matters (the `⊗` rect sits adjacent
    // to its chip; check close before chip).
    // Palette top-bar — sidebar / back / forward / chip / dropdown.
    if let Some(r) = app.rects.palette_sidebar_button
        && crate::app::dispatch::contains(r, x, y)
    {
        let _ = crate::command::run("view.toggle_tree", app);
        return;
    }
    if let Some(r) = app.rects.palette_right_panel_button
        && crate::app::dispatch::contains(r, x, y)
    {
        let _ = crate::command::run("view.toggle_right_panel", app);
        return;
    }
    if let Some(r) = app.rects.palette_add_integration_button
        && crate::app::dispatch::contains(r, x, y)
    {
        let _ = crate::command::run("integrations.add", app);
        return;
    }
    if let Some(r) = app.rects.palette_back_button
        && crate::app::dispatch::contains(r, x, y)
    {
        let _ = crate::command::run("buffer.prev", app);
        return;
    }
    if let Some(r) = app.rects.palette_forward_button
        && crate::app::dispatch::contains(r, x, y)
    {
        let _ = crate::command::run("buffer.next", app);
        return;
    }
    if let Some(r) = app.rects.palette_search_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.open_command_palette();
        return;
    }
    if let Some(r) = app.rects.palette_dropdown_button
        && crate::app::dispatch::contains(r, x, y)
    {
        let _ = crate::command::run("picker.recent", app);
        return;
    }
    // Launcher-icon strip — click hands off to the configured
    // command (registered command id, or ex-cmdline string).
    // 2026-08-01 (P2) — launcher_icon_rects click routing deleted.
    if let Some(r) = app.rects.bufferline_new_tab_button
        && crate::app::dispatch::contains(r, x, y)
    {
        app.tab_new(None);
        return;
    }
    // Inline `+` new-request chip — sits just past the last tab in
    // the bufferline. Only rendered when at least one Request pane
    // is already open (see `paint` in bufferline.rs).
    if let Some(r) = app.rects.bufferline_new_request_button
        && crate::app::dispatch::contains(r, x, y)
    {
        app.open_new_request_pane();
        return;
    }
    if let Some(&(_, idx)) = app
        .rects
        .bufferline_tab_page_close
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.tab_close_at(idx);
        return;
    }
    if let Some(&(_, idx)) = app
        .rects
        .bufferline_tab_page_chips
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.switch_tab(idx);
        // Arm a drag — a subsequent mouse-drag over a
        // different chip's rect swaps the two tabs.
        app.dragging_tab_page = Some(app.active_layout);
        return;
    }
    // 2026-06-22 — per-split tab chip clicks (multi-tab
    // leaves). Close × FIRST so a close-button click in the
    // chip body doesn't get swallowed by the chip-switch.
    if let Some(&(_, leaf_active, tab_pane)) = app
        .rects
        .split_tab_close
        .iter()
        .find(|(r, _, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.close_split_tab(leaf_active, tab_pane);
        return;
    }
    // AI launch button in the split-strip cluster. Focus the clicked
    // leaf, then fire the matching `ai.*_new` command so each click
    // spawns a fresh session (#19). The chip's `tag` disambiguates
    // Claude vs. Codex for the `"both"` config mode.
    if let Some(&(_, leaf_active, tag)) = app
        .rects
        .split_strip_ai_buttons
        .iter()
        .find(|(r, _, _)| crate::app::dispatch::contains(*r, x, y))
    {
        // 2026-07-18 — aligned with the sidebar integration chip:
        // `ai.claude_code` / `ai.codex` (reveal-or-open) instead of
        // the always-spawn `_new` variants. Click reveals an
        // existing pane if one is open, or spawns one if not.
        // Right-click's menu still offers explicit New / Fork for
        // multi-session workflows. User complaint: split-strip chip
        // and sidebar chip did different things.
        let cmd = if tag == 1 {
            "ai.codex"
        } else {
            "ai.claude_code"
        };
        if let Some(la) = leaf_active {
            app.active = Some(la);
            app.focus = crate::focus::Focus::Pane;
        }
        crate::command::run(cmd, app);
        return;
    }
    // Terminal button in the split-strip cluster.
    // Focus the clicked leaf (if any), then open a shell in a
    // split (mirrors the `term.shell` palette command). In the
    // "no files open" state the button still fires; open_shell
    // creates the first pane.
    if let Some(&(_, leaf_active)) = app
        .rects
        .split_strip_term_buttons
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        if let Some(la) = leaf_active {
            app.active = Some(la);
            app.focus = crate::focus::Focus::Pane;
        }
        app.open_shell();
        return;
    }
    // one-tab-type 2026-07-18 — `+` chip in a per-leaf tab strip.
    // Click → focus that leaf + open the SAME 10-item context menu
    // the empty-state `+` chip uses (user report: "when I have a
    // file open and click +, I expected the menu like we did
    // earlier"). Behavior parity between the two `+` chips means
    // muscle memory carries over.
    if let Some(&(r, leaf_active)) = app
        .rects
        .split_tab_plus_buttons
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.active = Some(leaf_active);
        app.focus = crate::focus::Focus::Pane;
        use crate::context_menu::{ContextMenu, MenuAction, MenuItem};
        let mut items = vec![
            MenuItem::new("New scratch buffer", MenuAction::Command("scratch.new")),
            MenuItem::new("Open file…", MenuAction::Command("picker.files")),
            MenuItem::new("Recent files", MenuAction::Command("picker.recent")),
            MenuItem::new(
                "From clipboard",
                MenuAction::Command("scratch.from_clipboard"),
            ),
            MenuItem::new("New HTTP request", MenuAction::Command("http.new")),
            MenuItem::new("New shell", MenuAction::Command("term.shell")),
            MenuItem::new("New browser tab", MenuAction::Command("browser.open")),
            MenuItem::new(
                "New Claude Code session",
                MenuAction::Command("ai.claude_code_new"),
            ),
            MenuItem::new("New Codex session", MenuAction::Command("ai.codex_new")),
            MenuItem::new("New tab page", MenuAction::Command("tab.new")),
        ];
        // 2026-07-19 — append every enabled integration chip as its
        // own "Open <tooltip>" menu row so users can launch a rail
        // integration from the `+` tab menu without hunting for its
        // chip. The chip's own command string is dispatched
        // identically to a chip click (`:<ex>` runs as ex-command,
        // anything else through the command registry).
        for icon in app.config.ui.integration_icons.iter().filter(|i| i.enabled) {
            let label = icon
                .label
                .clone()
                .unwrap_or_else(|| icon.id.replace('_', " "));
            items.push(MenuItem::new(
                format!("Open {label}"),
                MenuAction::RunCmd(icon.command.clone()),
            ));
        }
        let mut menu = ContextMenu::new(Some("Create…".into()), (r.x, r.y + 1), items);
        menu.selected = 0;
        menu.interacted = true;
        app.context_menu = Some(menu);
        return;
    }
    // Claude 2×2 auto-tile placeholder card — click fills the BR
    // quadrant with a fresh Claude session.
    if let Some(r) = app.rects.ai_placeholder_card
        && crate::app::dispatch::contains(r, x, y)
    {
        app.open_claude_code_new();
        return;
    }
    // one-tab-type 2026-07-18 — empty-state `+` chip on the top
    // row. Click opens a positional context menu anchored at the
    // chip (not a centered picker) with 10 "create something"
    // options. Default highlight is "New scratch buffer" so Enter
    // fires it instantly.
    if let Some(r) = app.rects.bufferline_empty_plus
        && crate::app::dispatch::contains(r, x, y)
    {
        use crate::context_menu::{ContextMenu, MenuAction, MenuItem};
        let mut items = vec![
            MenuItem::new("New scratch buffer", MenuAction::Command("scratch.new")),
            MenuItem::new("Open file…", MenuAction::Command("picker.files")),
            MenuItem::new("Recent files", MenuAction::Command("picker.recent")),
            MenuItem::new(
                "From clipboard",
                MenuAction::Command("scratch.from_clipboard"),
            ),
            MenuItem::new("New HTTP request", MenuAction::Command("http.new")),
            MenuItem::new("New shell", MenuAction::Command("term.shell")),
            MenuItem::new("New browser tab", MenuAction::Command("browser.open")),
            MenuItem::new(
                "New Claude Code session",
                MenuAction::Command("ai.claude_code_new"),
            ),
            MenuItem::new("New Codex session", MenuAction::Command("ai.codex_new")),
            MenuItem::new("New tab page", MenuAction::Command("tab.new")),
        ];
        // 2026-07-19 — append every enabled integration chip as its
        // own "Open <tooltip>" menu row so users can launch a rail
        // integration from the `+` tab menu without hunting for its
        // chip. The chip's own command string is dispatched
        // identically to a chip click (`:<ex>` runs as ex-command,
        // anything else through the command registry).
        for icon in app.config.ui.integration_icons.iter().filter(|i| i.enabled) {
            let label = icon
                .label
                .clone()
                .unwrap_or_else(|| icon.id.replace('_', " "));
            items.push(MenuItem::new(
                format!("Open {label}"),
                MenuAction::RunCmd(icon.command.clone()),
            ));
        }
        // Anchor the menu near the chip so it doesn't fly to the
        // screen center — sits just below-left of the click.
        let mut menu = ContextMenu::new(Some("Create…".into()), (r.x, r.y + 1), items);
        // Default highlight = New scratch (index 0). Force
        // interacted=true so the highlight is visible immediately.
        menu.selected = 0;
        menu.interacted = true;
        app.context_menu = Some(menu);
        return;
    }
    // 2026-06-22 — per-split split-editor buttons at the right of
    // the strip. Focus the clicked leaf's active pane, then dispatch
    // split_active(dir). 2026-07-18 — when there's no active pane
    // (fresh workspace, all tabs closed) use `open_scratch_split`
    // which lays out two empty scratch editors in the direction.
    if let Some(&(_, leaf_active, dir)) = app
        .rects
        .split_strip_buttons
        .iter()
        .find(|(r, _, _)| crate::app::dispatch::contains(*r, x, y))
    {
        if let Some(la) = leaf_active {
            app.active = Some(la);
            app.focus = crate::focus::Focus::Pane;
            app.split_active(dir);
        } else {
            app.open_scratch_split(dir);
        }
        return;
    }
    // #1018 — maximize / restore button (rightmost in the per-leaf
    // strip cluster). Click → focus this leaf so the toggle acts on
    // the leaf whose button was clicked (not whichever pane happened
    // to hold focus), then flip the zoom.
    if let Some(&(_, leaf_active)) = app
        .rects
        .split_strip_maximize_buttons
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        if let Some(la) = leaf_active {
            app.active = Some(la);
            app.focus = crate::focus::Focus::Pane;
        }
        // #1096 (2026-08-20) — in full-screen, the button's glyph
        // flipped to the compress arrows so it reads as "exit
        // full-screen." Route accordingly instead of firing
        // toggle_zoom (which would flip an unrelated per-leaf zoom
        // that has no visible effect while chrome is hidden).
        if app.fullscreen_mode {
            app.toggle_fullscreen_mode();
        } else {
            app.toggle_zoom_active_leaf();
        }
        return;
    }
    if let Some(&(_, leaf_active, tab_pane)) = app
        .rects
        .split_tab_chips
        .iter()
        .find(|(r, _, _)| crate::app::dispatch::contains(*r, x, y))
    {
        // 2026-06-27 — arm a drag like the bufferline tab
        // handler does, so per-leaf tabs are also
        // drag-to-split / drag-to-move. Without this,
        // a click on a per-leaf tab activated the tab
        // and returned, never setting bufferline_drag_tab,
        // so subsequent Drag / Moved events did nothing.
        // The bufferline_drag_tab field doubles as the
        // drag-source for both global bufferline AND
        // per-leaf strips — the pane id is the same.
        app.rects.bufferline_drag_tab = Some(tab_pane);
        // Switch the visible tab immediately so the click
        // also activates as the user expects. The mouse-up
        // handler will still see bufferline_drag_tab Some
        // and route through drop / reveal logic.
        let now = std::time::Instant::now();
        let is_double = matches!(
            app.last_click,
            Some((prev, px, py, _))
                if px == x
                    && py == y
                    && now.duration_since(prev) < std::time::Duration::from_millis(DOUBLE_CLICK_MAX_MS as u64)
        );
        app.last_click = Some((now, x, y, if is_double { 2 } else { 1 }));
        if is_double && let Some(Pane::Editor(b)) = app.panes.get_mut(tab_pane) {
            b.is_preview = false;
        }
        // qa-feature 2026-07-02 — preserve tree focus across
        // split-tab double-click promote. Same rationale as the
        // bufferline path in up_left.rs — arrow-browsing survives.
        let was_tree_focus = matches!(app.focus, crate::focus::Focus::Tree);
        app.switch_split_tab(leaf_active, tab_pane);
        if was_tree_focus {
            app.focus_tree();
        }
        return;
    }
    if let Some(r) = app.rects.bufferline_theme_toggle
        && crate::app::dispatch::contains(r, x, y)
    {
        // NvChad convention: the slider is a binary toggle between
        // `[ui] theme` ↔ `[ui] theme_toggle`. Falls back to opening
        // the picker when `theme_toggle` is unconfigured.
        if app.config.ui.theme_toggle.is_some() {
            app.toggle_theme();
        } else {
            app.open_theme_picker();
        }
        return;
    }
    if let Some(r) = app.rects.bufferline_window_close
        && crate::app::dispatch::contains(r, x, y)
    {
        // The × in the top-right cluster is a "close mnml" affordance
        // (matches the tooltip). Was routing to close_active_pane which
        // no-oped when nothing was open; users hovering "close mnml"
        // and clicking got no response.
        app.request_quit();
        return;
    }
    // Statusline branch chip → open the commit graph. Always-visible
    // click target for git.graph (vs the keyboard-only `<leader>g l`).
    if let Some(r) = app.rects.statusline_branch_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        let _ = crate::command::run("git.graph", app);
        return;
    }
    // Hover-help panel → left-click on the `⋮` kebab opens the
    // per-panel context menu (Close, later: About, settings). The
    // rest of the panel body is inert; the old click-anywhere-
    // closes behavior surprised users who clicked to read a shortcut
    // and lost the panel. 2026-08-11.
    if let Some(r) = app.rects.hover_help_kebab
        && crate::app::dispatch::contains(r, x, y)
    {
        app.open_hover_help_kebab_menu((r.x, r.y + 1));
        return;
    }
    // Hover-help `Try it →` action buttons — checked before the
    // whole-panel inert-click catch-all below, so a click landing on
    // one of these narrow rows fires its palette command instead of
    // being swallowed. 2026-08-16 — wires up `InfoViewCopy::try_it`,
    // which the framework carried since Phase 1 but never dispatched.
    if let Some((_, cmd_id)) = app
        .rects
        .hover_help_try_it
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
        .cloned()
    {
        let _ = crate::command::run(&cmd_id, app);
        return;
    }
    // Hover-help `→ Manual` docs link — opens the site manual page.
    if let Some((r, url)) = app.rects.hover_help_docs.clone()
        && crate::app::dispatch::contains(r, x, y)
    {
        crate::app::open_url_external(&url);
        app.toast("opened in browser");
        return;
    }
    // Body clicks inside the info panel are swallowed so they don't
    // fall through to tree / statusline hit-tests below.
    if let Some(r) = app.rects.hover_help_strip
        && crate::app::dispatch::contains(r, x, y)
    {
        return;
    }
    // Statusline test-runner chip → focus the test pane.
    if let Some(r) = app.rects.statusline_test_chip
        && crate::app::dispatch::contains(r, x, y)
        && let Some((_, pane_idx)) = app.last_test_run
        && pane_idx < app.panes.len()
    {
        app.active = Some(pane_idx);
        app.focus_pane();
        return;
    }
    // Statusline AI Claude chip — unlinked → link prompt;
    // linked → open the Claude usage pane. #876.
    // 2026-08-16 — Pane::AiUsage was split into two per-product
    // panes; Claude chip now opens Pane::ClaudeUsage.
    if let Some(r) = app.rects.statusline_ai_claude_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        if crate::ai_usage::read_claude_token().is_none() {
            app.open_link_claude_token_prompt();
        } else {
            app.open_claude_usage_pane();
        }
        return;
    }
    // Task #944 rename UX (2026-08-16) — pencil hitrect on a
    // Claude Usage pane section header. Click → open the rename
    // prompt seeded with that account's current name. Checked
    // BEFORE generic pane-body clicks so a click on the pencil
    // doesn't get consumed by the pane's focus-then-nothing path.
    {
        let hit = app
            .rects
            .claude_usage_pencils
            .iter()
            .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
            .map(|(_, name)| name.clone());
        if let Some(name) = hit {
            app.open_claude_account_rename_prompt(name);
            return;
        }
    }
    // Statusline AI Codex chip → open the Codex usage pane.
    // 2026-08-16 — was a toast + refresh; the pane surface makes
    // the tokens/sessions/last-error legible without hover, matches
    // the Claude chip's affordance, and still nudges a refresh via
    // `open_codex_usage_pane`.
    if let Some(r) = app.rects.statusline_ai_codex_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.open_codex_usage_pane();
        return;
    }
    // Statusline coverage chip (#889) → open the coverage integration
    // Pty pane (provided by `mnml-tattle-coverage`). The built-in
    // Pane::Coverage was removed in favor of the external tool, which
    // also shows Istanbul coverage alongside the feature-coverage
    // sparklines this chip renders.
    if let Some(r) = app.rects.statusline_coverage_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        let _ = crate::command::run("tattle_coverage_ext.open", app);
        return;
    }
    // Statusline mode chip → toggle input style (vim ↔ standard).
    if let Some(r) = app.rects.statusline_mode_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        let _ = crate::command::run("editor.toggle_keymap", app);
        return;
    }
    // Dynamic statusline segments — both manifest-declared
    // `[[statusline_segments]]` chips (see
    // `src/app/statusline_segments.rs`) and IPC-driven segments
    // set via an integration's `statusline_set_segment` call. Both use
    // the same `DynamicSegment.click_command` field so a click
    // fires whichever palette command the source declared.
    // 2026-08-17 (data-driven statusline chips).
    if let Some((_, seg_id)) = app
        .rects
        .statusline_segment_hits
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        let seg_id = seg_id.clone();
        if let Some(cmd) = app
            .dynamic_segments
            .iter()
            .find(|d| d.id == seg_id)
            .and_then(|d| d.click_command.clone())
        {
            let _ = crate::command::run(&cmd, app);
        }
        return;
    }
    // Cmdline bar — click anywhere on the bottom 1-row strip
    // opens the ex-cmdline (same as typing `:`). Checked
    // BEFORE the statusline chips because the bar sits below
    // the statusline and overlapping hit-rects are otherwise
    // resolved top-down. A click while the cmdline is
    // already open is a no-op (let the user keep typing).
    //
    // 2026-06-20 — check the right-side `⟳ … running…`
    // indicator FIRST so clicks there abort the in-flight
    // op instead of opening the cmdline. Same area covers
    // both targets; narrower one wins.
    if let Some(r) = app.rects.cmdline_inflight
        && crate::app::dispatch::contains(r, x, y)
    {
        app.http_abort_all();
        return;
    }
    // 2026-06-20 — toast `[name]` mention: click reveals
    // the matching pane (substring match on pane title).
    if let Some((r, name)) = app.rects.cmdline_toast_target.clone()
        && crate::app::dispatch::contains(r, x, y)
        && let Some((idx, _)) = app
            .panes
            .iter()
            .enumerate()
            .find(|(_, p)| p.title().contains(&name))
    {
        app.active = Some(idx);
        app.focus_pane();
        app.reveal_pane(idx);
        return;
    }
    if app.no_pane_cmdline.is_none()
        && let Some(r) = app.rects.cmdline_bar
        && crate::app::dispatch::contains(r, x, y)
    {
        app.open_ex_command_prompt();
        return;
    }
    // Statusline workspace / active-repo chip → open the repo picker
    // (single-repo workspace toasts "only one repo").
    if let Some(r) = app.rects.statusline_workspace_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.open_repo_picker();
        return;
    }
    // Statusline clock chip → flip between local and UTC.
    if let Some(r) = app.rects.statusline_clock_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.clock_show_utc = !app.clock_show_utc;
        app.toast(if app.clock_show_utc {
            "clock: UTC"
        } else {
            "clock: local"
        });
        return;
    }
    // Play / pause control — source-aware: mixr → pause IPC,
    // Apple Music / Spotify → AppleScript `playpause`. Checked
    // before the track-text chip because the three sit
    // adjacent. Returns silently when no source matches
    // (cluster is in idle form).
    if let Some(r) = app.rects.statusline_mixr_play_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        let source = app
            .now_playing
            .as_ref()
            .map(|np| np.source.as_str())
            .unwrap_or("");
        if source.eq_ignore_ascii_case("mixr") {
            send_mixr_command("pause");
        } else if !source.is_empty() {
            send_macos_player(source, "playpause");
        }
        return;
    }
    // Ffwd control — mixr → teleport (jump on beat to just
    // before mix-out); Apple Music / Spotify → next track via
    // AppleScript.
    if let Some(r) = app.rects.statusline_mixr_ffwd_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        let source = app
            .now_playing
            .as_ref()
            .map(|np| np.source.as_str())
            .unwrap_or("");
        if source.eq_ignore_ascii_case("mixr") {
            send_mixr_command("teleport");
        } else if !source.is_empty() {
            send_macos_player(source, "next track");
        }
        return;
    }
    // Track text — source-aware activate:
    //   * mixr        → `mixr.show` (open / cycle the docked
    //                   panel; today's behavior)
    //   * Music       → AppleScript `activate` (brings the app
    //                   forward without changing playback)
    //   * Spotify     → AppleScript `activate`
    //   * idle (none) → activate the user's preferred app
    //                   (`ui.preferred_music_app`), opening
    //                   Music / Spotify or the mixr panel
    //                   based on the Settings pick.
    // 2026-08-22 — idle-state play-glyph chip: one-tap start-playing.
    // Bound to `mixr.play_now` (spawns `mixr --play --panel browse`
    // when Beatport-authed; falls back to a browser-only open with
    // a "sign in first" toast otherwise). Checked BEFORE the label
    // chip so the split rects behave as two distinct clicks.
    if let Some(r) = app.rects.statusline_music_action_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        // Only mixr backs a play-a-chart flow today; Music/Spotify
        // idle clicks still fire below via the label chip. Route
        // through the command dispatcher so palette / chord users
        // get the same behavior.
        match app.config.ui.preferred_music_app.as_str() {
            "music" => send_macos_player("Music", "playpause"),
            "spotify" => send_macos_player("Spotify", "playpause"),
            _ => {
                command::run("mixr.play_now", app);
            }
        }
        return;
    }
    if let Some(r) = app.rects.statusline_mixr_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        let source = app
            .now_playing
            .as_ref()
            .map(|np| np.source.as_str())
            .unwrap_or("");
        if source.eq_ignore_ascii_case("mixr") {
            command::run("mixr.show", app);
        } else if !source.is_empty() {
            send_macos_player(source, "activate");
        } else {
            // Idle — use the preferred-app pick.
            match app.config.ui.preferred_music_app.as_str() {
                "music" => send_macos_player("Music", "activate"),
                "spotify" => send_macos_player("Spotify", "activate"),
                _ => {
                    command::run("mixr.show", app);
                }
            }
        }
        return;
    }
    // LSP chip → :LspStatus toast (breakdown of running servers).
    if let Some(r) = app.rects.statusline_lsp_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.run_ex_command("LspStatus");
        return;
    }
    // WRAP chip → toggle `[ui] wrap`.
    if let Some(r) = app.rects.statusline_wrap_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.toggle_wrap();
        return;
    }
    // Autosave chip → :set autosave_secs= prompt (palette command).
    if let Some(r) = app.rects.statusline_autosave_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.toast(format!(
            "autosave: {}s (`:set autosave_secs=N` to change)",
            app.config.editor.autosave_secs
        ));
        return;
    }
    // Filesize chip → :Stat toast.
    if let Some(r) = app.rects.statusline_filesize_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.run_ex_command("Stat");
        return;
    }
    // Ln/Col chip → goto-line prompt.
    if let Some(r) = app.rects.statusline_lncol_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        let _ = crate::command::run("editor.goto_line", app);
        return;
    }
    // #polish 2026-07-06 — file chip → reveal active buffer in tree.
    if let Some(r) = app.rects.statusline_file_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        let _ = crate::command::run("view.reveal_active", app);
        return;
    }
    // #polish 2026-07-06 — diagnostics chip → open diagnostics panel.
    if let Some(r) = app.rects.statusline_diagnostics_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        let _ = crate::command::run("lsp.diagnostics", app);
        return;
    }
    // #polish 2026-07-06 — symbol crumb → open outline pane.
    if let Some(r) = app.rects.statusline_symbol_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        let _ = crate::command::run("outline.show", app);
        return;
    }
    // #polish 2026-07-06 — PR badge → open web URL.
    if let Some(r) = app.rects.statusline_pr_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        if let Some(pr) = app
            .git_rail
            .pulls
            .iter()
            .find(|p| p.is_current_branch)
            .cloned()
        {
            crate::app::open_url_external(&pr.web_url);
            app.toast(format!("opened {}{}", pr.host_tag, pr.number_label));
        }
        return;
    }
    // #polish 2026-07-06 — macro rec chip → stop recording.
    if let Some(r) = app.rects.statusline_macro_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        let _ = crate::command::run("vim.macro_toggle", app);
        return;
    }
    // #polish 2026-07-06 — find chip → reopen find prompt.
    if let Some(r) = app.rects.statusline_find_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        let _ = crate::command::run("find.find", app);
        return;
    }
    // #polish 2026-07-06 — language chip → toast the detected
    // language + hint the editorconfig / extension source.
    if let Some(r) = app.rects.statusline_language_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        let lang = app
            .active_editor()
            .and_then(|b| b.language_ext.clone())
            .unwrap_or_else(|| "".to_string());
        app.toast(format!("language: {lang} (via file extension)"));
        return;
    }
    // (activity-bar icons + gear are handled near the top of the
    // cascade now — 2026-07-19 — to keep stale integration-panel rects
    // from ever shadowing them.)
    // Search activity-bar section result rows — click → open
    // the hit's file at its line:col. Checked before tree
    // icons since they may overlap (tree_icon_buttons spans
    // the same width).
    if let Some(&(_, idx)) = app
        .rects
        .search_section_hit_rects
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.search_section_open_hit(idx);
        return;
    }
    // #1112 f/u (2026-08-21) — Search section flag chips: click
    // toggles + re-runs the current query. Dispatches through the
    // palette command so state flip, toast, and rerun all happen
    // atomically (no drift with the keyboard entry path).
    if let Some(&(_, ch)) = app
        .rects
        .search_section_flag_rects
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        let cmd = match ch {
            'c' => "search.toggle_case_sensitive",
            'w' => "search.toggle_whole_word",
            'r' => "search.toggle_regex",
            _ => return,
        };
        let _ = crate::command::run(cmd, app);
        return;
    }
    // File-tree toolbar icons (row 0 of the rail). Check BEFORE
    // the WORKSPACE-toggle below since the workspace header is row 1
    // and the icon row sits above it. Each chip dispatches a palette
    // command by id.
    if let Some(&(_, cmd_id)) = app
        .rects
        .tree_icon_buttons
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        let _ = crate::command::run(cmd_id, app);
        return;
    }
    // 2026-07-31 — Integration detail pane button click. Focus the
    // pane, move the cursor to the clicked row, then fire it. Runs
    // BEFORE the activity-panel `integration_icon_rects` cascade
    // because the detail pane's own rects overlay the same area
    // if a click lands there.
    if let Some(&(_, pane_id, action_idx)) = app
        .rects
        .integration_detail_buttons
        .iter()
        .find(|(r, _, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.active = Some(pane_id);
        // If it's a right-panel host, refocus the right panel too.
        if app.right_panel_panes.contains(&pane_id) {
            app.focus = crate::focus::Focus::RightPanel;
        } else {
            app.focus_pane();
        }
        if let Some(crate::pane::Pane::IntegrationDetail(d)) = app.panes.get_mut(pane_id) {
            d.cursor = action_idx;
        }
        crate::ui::integration_detail_view::fire_action(app, pane_id, action_idx);
        return;
    }
    // INTEGRATIONS icon — hand off to the configured command.
    // Two command forms supported:
    //   `:<ex>`  → mnml ex command
    //   `<id>`   → mnml registered command id
    // Check BEFORE the section-toggle below.
    // 2026-08-16 — "↑ Update to <ver>" chip on an installed
    // marketplace row. Checked BEFORE marketplace_row_rects (a
    // superset rect) so the chip click doesn't fall through to
    // "open detail pane" behavior. Silent no-op if we can't
    // classify the entry's InstallSpec (shouldn't happen — the
    // chip only renders for entries we know how to update).
    if let Some(id) = app
        .rects
        .update_chip_rects
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
        .map(|(_, id)| id.clone())
    {
        // #992 (2026-08-18) — routing moved to
        // App::apply_integration_update so the chip-click here and
        // the right-click "Update to X" menu item stay in lockstep.
        app.apply_integration_update(&id);
        return;
    }
    // P4c (2026-08-01) — click on a marketplace entry row → install
    // action. Checked BEFORE the integration icon row cascade below,
    // so a marketplace row doesn't get swallowed by a co-located
    // icon rect (unlikely — different tabs — but safest).
    if let Some(&(_, mp_idx)) = app
        .rects
        .marketplace_row_rects
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        // 2026-08-06 — was `install_marketplace_entry(mp_idx)`
        // (immediate install, zero confirmation — user surprise).
        // Then briefly a confirm dialog. Now: opens the existing
        // integration-detail pane in the main area so the user
        // sees description / source / links first, and the pane's
        // `[Install]` button routes to the same confirm dialog.
        if let Some(entry) = app.marketplace_entries.get(mp_idx) {
            let id = entry.id.clone();
            app.open_integration_detail_pane(&id);
        }
        return;
    }
    if let Some(&(_, icon_idx)) = app
        .rects
        .integration_icon_rects
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
        && let Some(icon) = app.config.ui.integration_icons.get(icon_idx)
    {
        // api-workflow-user F4 — disabled chips still appear
        // in the RAIL strip (binary-availability-filtered) but
        // shouldn't fire on left-click. Toast a hint instead
        // so the user knows the menu is available.
        if !icon.enabled {
            let label = icon
                .label
                .clone()
                .filter(|s| !s.is_empty())
                .unwrap_or_else(|| icon.id.clone());
            app.toast(format!("{label}: disabled (right-click → Enable)"));
            return;
        }
        let cmd = icon.command.clone();
        if let Some(rest) = cmd.strip_prefix(':') {
            app.run_ex_command(rest);
        } else {
            crate::command::run(&cmd, app);
        }
        return;
    }
    // Menu-bar item click — handled earlier by the menu-open
    // early guard (see the `if let Some(open) = app.menu_open ...`
    // block near the top of this handler). By the time execution
    // reaches here `menu_open` is always None and this rect check
    // was previously guarded on `menu_open.is_some()`, so it's
    // dead code — removed 2026-08-05 per reviewer drift-risk
    // note. Menu-bar word click below is still live (it fires
    // when NO menu is open yet).

    // Menu-bar overflow chip (`»`) — click cycles through the
    // hidden menus. First click opens the first hidden; subsequent
    // clicks advance to the next hidden one, wrapping when past
    // the last. R9 vscode-mouse SEV-2 + R10 follow-up (was: click
    // always opened the SAME first-hidden menu, so 5 other menus
    // stayed unreachable at 120-cell width).
    if let Some((rect, first_hidden_idx)) = app.rects.menu_bar_overflow
        && crate::app::dispatch::contains(rect, x, y)
    {
        let total_menus = crate::menu_bar::bar(app).len();
        let next_idx = match app.menu_open.as_ref().map(|s| s.menu_idx) {
            Some(cur) if cur + 1 < total_menus => {
                // Advance to next menu, wrap to first-hidden if
                // we walked off the last menu entirely.
                let candidate = cur + 1;
                if candidate < total_menus {
                    candidate
                } else {
                    first_hidden_idx
                }
            }
            _ => first_hidden_idx,
        };
        app.menu_open = Some(crate::menu_bar::MenuOpenState::new_mouse(next_idx));
        return;
    }

    // Menu-bar word click — toggle the dropdown.
    if let Some(&(_, menu_idx)) = app
        .rects
        .menu_bar_words
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        let already_open = app
            .menu_open
            .as_ref()
            .is_some_and(|s| s.menu_idx == menu_idx);
        app.menu_open = if already_open {
            None
        } else {
            Some(crate::menu_bar::MenuOpenState::new_mouse(menu_idx))
        };
        return;
    }
    // Click anywhere else while a menu is open → close it.
    // Fall through to the rest of the dispatch (the click
    // still hits the underlying target).
    if app.menu_open.is_some() {
        app.menu_open = None;
        // Don't return — the click goes through to the
        // underlying target (e.g. an editor pane, a tab).
    }
    // `> INTEGRATIONS` section header — arm drag-resize. On
    // mouse-up: !moved → toggle collapse; moved → commit
    // the new max height.
    if let Some(tr) = app.rects.integration_section_toggle
        && crate::app::dispatch::contains(tr, x, y)
    {
        app.rail_section_drag = Some(crate::app::RailSectionDrag {
            kind: crate::app::RailSectionKind::Integrations,
            start_y: y,
            start_h: app.rects.integration_section_h.max(1),
            moved: false,
        });
        return;
    }
    // The `> WORKSPACE-NAME` section header — clicking it toggles the
    // workspace section's expand/collapse state (VS-Code Explorer-style).
    // qa-feature 2026-07-01 — Alt+click on the header ALSO fully
    // expands or fully collapses every dir inside the primary tree,
    // matching the recursive alt-click gesture on individual dir rows.
    if let Some(tr) = app.rects.tree_toggle
        && crate::app::dispatch::contains(tr, x, y)
    {
        if m.modifiers.contains(KeyModifiers::ALT) {
            let was_expanded = app.tree_root_expanded;
            if was_expanded {
                app.tree.collapse_all();
            } else {
                app.tree.expand_all_dirs();
            }
        }
        app.toggle_tree_root_expanded();
        return;
    }
    // GIT header right-aligned chip cluster — Fetch / Pull / Push /
    // Stage all / Commit / Graph. Check BEFORE the toggle so the
    // chip wins over the section-collapse gesture.
    if let Some(&(_, action)) = app
        .rects
        .rail_git_header_buttons
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.run_git_rail_header_action(action);
        return;
    }
    // qa-feature 2026-06-30 — GitGraph repo-switch pill. The
    // sidebar's pill is anchored to the GIT pane's repo, so the
    // most useful click action is `switch_active_repo` (changes
    // what the git pane is looking at, which is what the user
    // expects from a dropdown next to the repo name). Fallback
    // cascade: 2+ repos → open_repo_picker; extras configured →
    // open_workspace_picker; else open_workspaces_editor so the
    // click leads somewhere even on a single-repo single-WS setup.
    if let Some(rect) = app.rects.git_graph_repo_switch
        && crate::app::dispatch::contains(rect, x, y)
    {
        if app.repos.len() > 1 {
            app.open_repo_picker();
        } else if !app.extra_workspaces.is_empty() {
            app.open_workspace_picker();
        } else {
            app.open_workspaces_editor();
        }
        return;
    }
    // GitGraph column header click → cycle sort. Falls through to
    // the row-click handler since the header row is OUTSIDE
    // `app.rects.list_rows`.
    if let Some(&(_, col)) = app
        .rects
        .git_graph_column_headers
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        if let Some(cur) = app.active
            && let Some(crate::pane::Pane::GitGraph(g)) = app.panes.get_mut(cur)
        {
            g.cycle_sort(col);
        }
        return;
    }
    // The `> GIT` section header — arm drag-resize. Mouse-up
    // without movement falls through to the toggle; movement
    // commits the new max height.
    if let Some(tr) = app.rects.git_section_toggle
        && crate::app::dispatch::contains(tr, x, y)
    {
        app.rail_section_drag = Some(crate::app::RailSectionDrag {
            kind: crate::app::RailSectionKind::Git,
            start_y: y,
            start_h: app.rects.git_section_h.max(1),
            moved: false,
        });
        return;
    }
    // qa-feature 2026-07-01 — click on an extra's `○` marker
    // promotes it to primary (same as right-click → Set as
    // workspace). Sits inside the toggle rect; this check has to
    // come FIRST so the promotion wins over the section-toggle.
    if let Some(&(_, ws_idx)) = app
        .rects
        .extra_workspace_promote_dots
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        if let Some(path) = app.extra_workspaces.get(ws_idx).map(|w| w.root.clone()) {
            app.set_workspace_to(path);
        }
        return;
    }
    // Extra-workspace section header → toggle expansion.
    // qa-feature 2026-07-01 — Alt+click on an extra's header ALSO
    // fully expands/collapses every dir inside that extra's tree,
    // matching the recursive alt-click gesture on individual dir
    // rows. Symmetrical with the primary header handling above.
    if let Some(&(_, ws_idx)) = app
        .rects
        .extra_workspace_toggles
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        if m.modifiers.contains(KeyModifiers::ALT)
            && let Some(ws) = app.extra_workspaces.get_mut(ws_idx)
        {
            let was_expanded = ws.expanded;
            if was_expanded {
                ws.tree.collapse_all();
            } else {
                ws.tree.expand_all_dirs();
            }
        }
        app.toggle_extra_workspace(ws_idx);
        return;
    }
    // Extra-workspace row click → focus / select / open in that tree.
    if let Some(&(tr, ws_idx, scroll)) = app
        .rects
        .extra_workspace_bodies
        .iter()
        .find(|(r, _, _)| crate::app::dispatch::contains(*r, x, y))
    {
        let row_idx = (y - tr.y) as usize + scroll;
        let alt = m.modifiers.contains(KeyModifiers::ALT);
        app.click_extra_workspace_row_ex(ws_idx, row_idx, alt);
        return;
    }
    // Tree? (no header now — row 0 of the rail is the first entry)
    if let Some(tr) = app.rects.tree
        && crate::app::dispatch::contains(tr, x, y)
    {
        app.focus_tree();
        app.rail_section = crate::app::RailSection::Workspace;
        // Clicking the primary tree returns focus from any
        // extra workspace; cursor highlight follows.
        app.focused_extra_ws = None;
        // VS Code preview/pin gesture: single-click on a file
        // opens it as a preview tab (replaceable by the next
        // single-click); double-click promotes to a real tab
        // (the editor's `open_path` non-preview path is the
        // promotion). Use the same `last_click` tracker the
        // editor uses for word/line select.
        // vscode-mouse-2026-06-10 SEV-2 #5.
        let now = std::time::Instant::now();
        let count = match app.last_click {
            Some((prev, px, py, c))
                if px == x
                    && py == y
                    && now.duration_since(prev)
                        < std::time::Duration::from_millis(DOUBLE_CLICK_MAX_MS as u64) =>
            {
                (c + 1).min(3)
            }
            _ => 1,
        };
        app.last_click = Some((now, x, y, count));
        {
            let idx = (y - tr.y) as usize + app.rects.tree_scroll;
            if idx < app.tree.visible_rows().len() {
                app.tree.set_cursor(idx);
                // Arm a drag — the source is captured here; the
                // actual move happens on mouse-up over a different
                // directory row. Alt held = copy instead of move
                // (Finder / VS Code convention). Read the modifier
                // at drag-start; the state at drop time is assumed
                // to match, matching how OS file managers behave.
                if let Some(row) = app.tree.selected_row() {
                    let alt = m.modifiers.contains(KeyModifiers::ALT);
                    app.begin_tree_drag_with_mode(row.path.clone(), row.is_dir, y, alt);
                }
                if let Some(row) = app.tree.selected_row()
                    && row.is_dir
                {
                    // Multi-repo workspace: clicking a depth-0
                    // repo dir also switches the active repo
                    // (so the git rail / branches / PRs follow
                    // the user's focus). The dir then expands /
                    // collapses normally.
                    if row.depth == 0 && app.repos.len() > 1 {
                        let repo_hit = app.repos.iter().position(|r| r.path == row.path);
                        if let Some(idx) = repo_hit
                            && idx != app.active_repo
                        {
                            app.switch_active_repo(idx);
                        }
                    }
                    // qa-feature 2026-07-01 — Alt+click on a dir
                    // row recursively expands/collapses that
                    // subtree. Was originally Shift+click but
                    // Ghostty (and most terminals) reserve
                    // Shift+click for text-selection, so the
                    // modifier never reaches mnml. Alt+click
                    // (⌥+click on macOS) passes through cleanly
                    // and is what VS Code uses for the same
                    // gesture anyway.
                    if m.modifiers.contains(KeyModifiers::ALT) {
                        app.tree.toggle_current_recursive();
                    } else {
                        app.tree.toggle_current();
                    }
                }
                // Files: the open is DEFERRED to mouse-up. On a
                // plain click the Up handler opens it (preview, or
                // a permanent tab on double-click); if the user
                // instead click-holds and drags, it becomes a
                // drag (onto a pane body → drag-to-split; onto a
                // tree dir → move-in-tree) and never opens here.
                // Opening on Down made a drag impossible — the
                // file flashed open the instant you pressed.
            }
        }
        return;
    }
    // A GIT-section row — focus the rail's git section + run the row's
    // default action (checkout the branch / open shell in the worktree).
    if let Some(&(_, hit)) = app
        .rects
        .git_rail_rows
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.click_git_rail(hit);
        return;
    }
    // Empty-state `+ dock` chip → fire dock.new_text_br.
    // 2026-08-07 vscode-mouse r1 F1 SEV-2 — was `dock.new_text`
    // (BottomLeft), but the chip itself is painted at bottom-RIGHT
    // (`ui/dock.rs:482-486`). Corner mismatch surprised users who
    // expect the button to act where it sits.
    if let Some(r) = app.rects.dock_empty_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        crate::command::run("dock.new_text_br", app);
        return;
    }
    // Open kebab-menu row click → apply choice + close.
    // Checked FIRST so a click on a menu row wins over
    // anything underneath (the menu is an overlay).
    if app.dock_kebab_menu.is_some()
        && let Some(&(_, idx)) = app
            .rects
            .dock_kebab_rows
            .iter()
            .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        if let Some(menu) = app.dock_kebab_menu.as_ref()
            && let Some(item) = menu.items.get(idx).copied()
        {
            let wid = menu.widget_id;
            crate::dock::apply_kebab_choice(app, wid, item);
        }
        return;
    }
    // Click ANYWHERE else with the kebab menu open → close it.
    if app.dock_kebab_menu.is_some() {
        app.dock_kebab_menu = None;
        // Fall through — let the click hit whatever it
        // was meant for.
    }
    // Dock widget kebab `⋮` click → open the menu.
    // Checked BEFORE the title-bar / body so the kebab
    // wins.
    if let Some(&(r, id)) = app
        .rects
        .dock_widget_kebabs
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        if let Some(w) = app.dock_widgets.iter().find(|w| w.id == id) {
            app.dock_kebab_menu = Some(crate::dock::KebabMenuState::build(w, r.x, r.y));
        }
        return;
    }
    // Dock widget title bar mouse-down → arm a drag. Final
    // corner resolves on mouse-up based on which quadrant
    // of the editor body the cursor ended up in.
    if let Some(&(_, id)) = app
        .rects
        .dock_widget_titles
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.dock_drag_id = Some(id);
        app.dock_drag_cursor = Some((x, y));
        return;
    }
    // Dock widget body click → toast (placeholder; content-
    // specific actions can hook in later).
    if let Some(&(_, id)) = app
        .rects
        .dock_widget_bodies
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        if let Some(w) = app.dock_widgets.iter().find(|w| w.id == id) {
            let title = w.title.clone();
            app.toast(format!("dock: {title}"));
        }
        return;
    }
    // Workspaces editor kebab `⋮` click → open per-row menu.
    if app.workspaces_editor_open
        && let Some(&(_, idx)) = app
            .rects
            .workspaces_editor_kebabs
            .iter()
            .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.open_workspaces_editor_kebab(idx, (x, y));
        return;
    }
    // Workspaces editor row click → focus + Enter
    // equivalent (rename for normal rows; add for the
    // `+ Add` action).
    if app.workspaces_editor_open
        && let Some(&(_, code)) = app
            .rects
            .workspaces_editor_rows
            .iter()
            .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        if code >= 0 {
            let idx = code as usize;
            app.workspaces_editor_selected = idx;
            app.workspaces_editor_open_rename(idx);
        } else {
            crate::command::run("view.add_workspace", app);
        }
        return;
    }
    // Click outside the overlay (when open) closes it.
    if app.workspaces_editor_open && app.context_menu.is_none() {
        // Fall through normally; clicks anywhere outside
        // dismiss like Esc.
        app.close_workspaces_editor();
        return;
    }
    // Workspace-picker chevron → toggle the dropdown.
    if let Some(r) = app.rects.workspace_picker_chevron
        && crate::app::dispatch::contains(r, x, y)
    {
        app.workspace_picker_open = !app.workspace_picker_open;
        if !app.workspace_picker_open {
            app.workspace_picker_filter.clear();
        }
        return;
    }
    // Workspace NAME (not chevron) → open the repo picker
    // when multi-repo. Single-repo: fall through to other
    // tree-row handlers below.
    if let Some(r) = app.rects.workspace_name_rect
        && crate::app::dispatch::contains(r, x, y)
        && app.repos.len() > 1
    {
        app.open_repo_picker();
        return;
    }
    // `..` row → navigate the workspace root up one level.
    if let Some(r) = app.rects.tree_up_row
        && crate::app::dispatch::contains(r, x, y)
    {
        app.navigate_workspace_up();
        return;
    }
    // Workspace-picker row click → switch + close.
    if let Some(&(_, ws_idx)) = app
        .rects
        .workspace_picker_rows
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.switch_workspace(ws_idx);
        app.workspace_picker_open = false;
        app.workspace_picker_filter.clear();
        return;
    }
    // Workspace-picker filter input → focus stays implicit
    // (no separate focus flag; the dropdown owns the
    // keyboard while open). Click anywhere outside the
    // picker closes it.
    if app.workspace_picker_open
        && app
            .rects
            .workspace_picker_filter_input
            .is_none_or(|r| !crate::app::dispatch::contains(r, x, y))
        && app
            .rects
            .workspace_picker_rows
            .iter()
            .all(|(r, _)| !crate::app::dispatch::contains(*r, x, y))
    {
        app.workspace_picker_open = false;
        app.workspace_picker_filter.clear();
        // Fall through — let the click hit whatever's under.
    }
    // qa-feature 2026-06-30 — click a section header in the git
    // palette toggles collapse. Wins over the filter / row hit-tests
    // since headers are exclusive rows.
    if let Some((_, label)) = app
        .rects
        .git_palette_section_headers
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
        .cloned()
    {
        if app.git_palette_collapsed_sections.contains(&label) {
            app.git_palette_collapsed_sections.remove(&label);
        } else {
            app.git_palette_collapsed_sections.insert(label);
        }
        return;
    }
    // qa-feature 2026-06-30 — click a folder header (`▾ chore (4)`)
    // toggles its collapse. Key is `SECTION:folder` so the same
    // folder name under LOCAL vs REMOTE doesn't clash.
    if let Some((_, key)) = app
        .rects
        .git_palette_folder_headers
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
        .cloned()
    {
        if app.git_palette_collapsed_folders.contains(&key) {
            app.git_palette_collapsed_folders.remove(&key);
        } else {
            app.git_palette_collapsed_folders.insert(key);
        }
        return;
    }
    // Git-palette filter input — click to focus + start typing.
    if let Some(r) = app.rects.git_palette_filter_input
        && crate::app::dispatch::contains(r, x, y)
    {
        app.git_palette_filter_focused = true;
        return;
    }
    // Click anywhere else inside the rail (or outside) while
    // the filter is focused → unfocus (keeps the typed text
    // so navigating doesn't lose what they typed).
    if app.git_palette_filter_focused {
        app.git_palette_filter_focused = false;
    }
    // Sessions panel `/` filter row → focus. Checked BEFORE the
    // chip / tab handlers below so it wins when the row overlaps.
    if let Some(r) = app.rects.sessions_panel_filter_input
        && crate::app::dispatch::contains(r, x, y)
    {
        app.sessions_panel_filter_focused = true;
        return;
    }
    // Sessions panel `+ New session` chip → spawn a NEW Claude
    // Code pane. Checked BEFORE tab clicks so a click on the chip
    // wins.
    //
    // 2026-07-18 — was `ai.claude_code`, which is the "reveal or
    // open" command that re-focuses an existing Claude Code pane
    // instead of spawning a fresh one. User: "when I open a Claude
    // Code session and then click new session again, nothing
    // happens" — because the existing pane was already focused,
    // the reveal became a no-op. Use `ai.claude_code_new`
    // (always-spawn) instead.
    if let Some(r) = app.rects.session_new_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        crate::command::run("ai.claude_code_new", app);
        return;
    }
    // HTTP panel — sectioned sidebar (#10 v2). Order: chip rects
    // first (they sit inside header rows), then row rects, then
    // header rows themselves (the collapse-toggle catch-all).
    // Per-section chip cluster (filter / refresh / capture / clear).
    // Checked before the older section-specific rect handlers below so
    // routing goes through the shared HttpChipKind dispatch.
    if let Some((_, section, kind)) = app
        .rects
        .http_panel_section_chips
        .iter()
        .find(|(r, _, _)| crate::app::dispatch::contains(*r, x, y))
        .copied()
    {
        use crate::app::HttpChipKind;
        match kind {
            HttpChipKind::Filter => {
                // Same focus + section snap as the filter-input rect
                // click above — otherwise keystrokes route to the
                // previously-focused pane. vscode-user-mouse SEV-2
                // 2026-07-10.
                app.focus = crate::focus::Focus::Tree;
                app.active_section = crate::app::ActivitySection::Http;
                app.http_panel_filter_focused = true;
            }
            HttpChipKind::Refresh => {
                crate::command::run("http.refresh", app);
            }
            HttpChipKind::Capture => {
                crate::command::run("http.capture_start", app);
            }
            HttpChipKind::Clear => match section {
                1 => app.http_panel_clear_recent(),
                2 => app.http_panel_clear_captured(),
                _ => {
                    // MOCKS / COLLECTIONS — the ✕ chip clears the
                    // filter as a safe default (destructive delete-
                    // all was too dangerous to bind to a single
                    // click).
                    app.http_panel_filter.clear();
                    app.http_panel_filter_focused = false;
                }
            },
            HttpChipKind::New => match section {
                3 => {
                    crate::command::run("http.new_env", app);
                }
                6 => {
                    crate::command::run("http.new_collection", app);
                }
                _ => app.toast("no `new` action for this section"),
            },
        }
        return;
    }
    if let Some(r) = app.rects.http_panel_capture_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        crate::command::run("http.capture_start", app);
        return;
    }
    if let Some(r) = app.rects.http_panel_captured_clear_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.http_panel_clear_captured();
        return;
    }
    if let Some(r) = app.rects.http_panel_recent_clear_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.http_panel_clear_recent();
        return;
    }
    if let Some(r) = app.rects.http_panel_discover_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        crate::command::run("http.paste_curl", app);
        return;
    }
    if let Some(r) = app.rects.http_panel_new_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.http_panel_new_request();
        return;
    }
    if let Some(r) = app.rects.http_panel_filter_input
        && crate::app::dispatch::contains(r, x, y)
    {
        // vscode-user-mouse SEV-2 2026-07-10 fix: setting the panel
        // filter focus flag alone wasn't enough — the keystroke
        // absorber in `dispatch_key` also gates on `app.focus ==
        // Focus::Tree` + `app.active_section == Http`. Without also
        // moving focus + section, typing after the click still
        // routed to whatever pane last had focus. Snap both to
        // match the visual focus indicator.
        app.focus = crate::focus::Focus::Tree;
        app.active_section = crate::app::ActivitySection::Http;
        app.http_panel_filter_focused = true;
        return;
    }
    if let Some((_, path)) = app
        .rects
        .http_panel_files
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        let path = path.clone();
        app.open_path(&path);
        return;
    }
    if let Some((_, idx)) = app
        .rects
        .http_panel_recent_rows
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        let idx = *idx;
        if let Some(entry) = app.http_panel_recent_cache.get(idx).cloned() {
            let (curl, method, url) = crate::http::history::entry_to_curl(&entry);
            app.open_curl_scratch(&curl, &method, &url);
        }
        return;
    }
    if let Some((_, idx)) = app
        .rects
        .http_panel_captured_rows
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        let idx = *idx;
        if let Some(row) = app.http_panel_captured_cache.get(idx).cloned() {
            app.open_curl_scratch(&row.to_curl(), &row.method, &row.url);
        }
        return;
    }
    if let Some((_, section)) = app
        .rects
        .http_panel_section_headers
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        let idx = *section as usize;
        if idx < app.http_panel_section_collapsed.len() {
            app.http_panel_section_collapsed[idx] = !app.http_panel_section_collapsed[idx];
        }
        return;
    }
    // ENVS section — env-row click switches active env; new chip
    // opens the create-env prompt.
    if let Some((_, name)) = app
        .rects
        .http_panel_env_rows
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
        .cloned()
    {
        app.accept_http_env(&name);
        return;
    }
    if let Some(r) = app.rects.http_panel_env_new_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.http_new_env_prompt();
        return;
    }
    // #polish 2026-07-06 — `+ New chain` / `+ New collection` chips
    // mirror the `+ New env` idiom for creation from the sidebar.
    if let Some(r) = app.rects.http_panel_chain_new_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.http_new_chain_prompt();
        return;
    }
    if let Some(r) = app.rects.http_panel_collection_new_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.http_new_collection_prompt();
        return;
    }
    // CHAINS row → run that chain.
    if let Some((_, path)) = app
        .rects
        .http_panel_chain_rows
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
        .cloned()
    {
        app.http_chain_run_path(path);
        return;
    }
    // MOCKS row → replay that mock into the active Request pane.
    if let Some((_, path)) = app
        .rects
        .http_panel_mock_rows
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
        .cloned()
    {
        app.http_replay_mock_from_path(&path);
        return;
    }
    // #22 — Collections file row → open the file as a Request pane.
    if let Some((_, path)) = app
        .rects
        .http_panel_collection_rows
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
        .cloned()
    {
        app.open_path(&path);
        return;
    }
    // #polish 2026-07-06 — per-collection `+` chip (new request in
    // THIS collection). Checked BEFORE the row-wide collapse toggle
    // so the chip cell wins over the row body.
    if let Some((_, root)) = app
        .rects
        .http_panel_collection_new_request_chips
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
        .cloned()
    {
        app.http_new_request_in_collection(&root);
        return;
    }
    // #polish 2026-07-06 — HTTP panel header toolbar chips (↺ refresh,
    // ↕ collapse-all). Runs the mapped command directly.
    if let Some((_, cmd_id)) = app
        .rects
        .http_panel_icon_buttons
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
        .cloned()
    {
        let _ = crate::command::run(cmd_id, app);
        return;
    }
    // #22 v2 — Collections folder row → toggle expand/collapse.
    if let Some((_, dir)) = app
        .rects
        .http_panel_collection_folder_rows
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
        .cloned()
    {
        if !app.http_panel_collections_collapsed_dirs.remove(&dir) {
            app.http_panel_collections_collapsed_dirs.insert(dir);
        }
        return;
    }
    // `↓ Import…` → open the import picker (Postman / HAR).
    if let Some(r) = app.rects.http_panel_import_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.http_import_prompt();
        return;
    }
    // Notes panel — filter row, file rows, `+ New note` chip (#8).
    if let Some(r) = app.rects.notes_panel_filter_input
        && crate::app::dispatch::contains(r, x, y)
    {
        app.notes_panel_filter_focused = true;
        return;
    }
    if let Some(r) = app.rects.notes_panel_new_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.notes_panel_new_note();
        return;
    }
    if let Some((_, path)) = app
        .rects
        .notes_panel_files
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        let path = path.clone();
        app.open_path(&path);
        return;
    }
    // Findings panel — row click opens the .md file (2026-08-07).
    if let Some((_, path)) = app
        .rects
        .findings_panel_files
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        let path = path.clone();
        app.open_path(&path);
        return;
    }
    // TODOs panel — refresh chip + row click (#9).
    if let Some(r) = app.rects.todos_panel_filter_input
        && crate::app::dispatch::contains(r, x, y)
    {
        app.todos_panel_filter_focused = true;
        return;
    }
    if let Some(r) = app.rects.todos_panel_refresh_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.todos_panel_refresh();
        return;
    }
    if let Some(&(_, idx)) = app
        .rects
        .todos_panel_rows
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        if let Some(hit) = app.todos_hits.get(idx) {
            let path = hit.path.clone();
            let line = hit.line.to_string();
            app.open_path(&path);
            app.goto_line_str(&line);
        }
        return;
    }
    // Agents rail panel — filter input, + New, and row
    // clicks.
    if let Some(r) = app.rects.agents_panel_filter_input
        && crate::app::dispatch::contains(r, x, y)
    {
        app.agents_panel_filter_focused = true;
        return;
    }
    if let Some(r) = app.rects.agents_panel_new_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        crate::command::run("ai.claude_code", app);
        return;
    }
    if let Some(r) = app.rects.agents_panel_pr_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.open_new_cloud_agent_wizard();
        return;
    }
    // View-mode toggle chip → switch between by-status
    // and by-workspace grouping.
    if let Some(r) = app.rects.agents_panel_view_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.agents_panel_group_by_workspace = !app.agents_panel_group_by_workspace;
        app.agents_panel_expanded_workspaces.clear();
        return;
    }
    // Workspace header (by-workspace view only) → toggle
    // expansion for that workspace.
    if let Some((_, ws)) = app
        .rects
        .agents_panel_workspace_headers
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
        .cloned()
    {
        if app.agents_panel_expanded_workspaces.contains(&ws) {
            app.agents_panel_expanded_workspaces.remove(&ws);
        } else {
            app.agents_panel_expanded_workspaces.insert(ws);
        }
        return;
    }
    if let Some(&(_, row_idx)) = app
        .rects
        .agents_panel_rows
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        if let Some(row) = app.agents_panel_rows.get(row_idx).cloned() {
            match row.source {
                crate::claude_agents::AgentSource::Ecs => {
                    // Cloud rows can't be resumed locally —
                    // copy the runId so the user can paste
                    // it into Slack / a browser, and toast
                    // what we know about the run.
                    app.clipboard.set(row.session_id.clone(), false);
                    let summary = row
                        .last_assistant_msg
                        .clone()
                        .unwrap_or_else(|| "(cloud run)".to_string());
                    app.toast(format!("{} · {} · runId copied", row.workspace, summary));
                }
                _ => {
                    // Resume in a fresh pty — mirrors the
                    // dashboard's `R` chord.
                    app.resume_claude_session_in_pty(&row.session_id);
                }
            }
        }
        return;
    }
    // Cloud Agents panel — filter input + row clicks +
    // density chip (compact ↔ standard) + + New Cloud
    // Agent button.
    if let Some(r) = app.rects.cloud_agents_view_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.cloud_agents_toggle_view();
        return;
    }
    if let Some(r) = app.rects.cloud_agents_new_run_button
        && crate::app::dispatch::contains(r, x, y)
    {
        app.open_new_cloud_run_wizard();
        return;
    }
    if let Some(r) = app.rects.cloud_agents_change_defaults_chip
        && crate::app::dispatch::contains(r, x, y)
    {
        app.open_new_cloud_run_wizard();
        return;
    }
    if let Some(r) = app.rects.cloud_agents_quick_input
        && crate::app::dispatch::contains(r, x, y)
    {
        app.cloud_run_prompt_focused = true;
        app.cloud_agents_filter_focused = false;
        return;
    }
    if let Some(r) = app.rects.cloud_agents_filter_input
        && crate::app::dispatch::contains(r, x, y)
    {
        app.cloud_agents_filter_focused = true;
        return;
    }
    if let Some(&(_, row_idx)) = app
        .rects
        .cloud_agents_rows
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        // 2026-06-27 — single-click on a cloud-agent row now
        // opens the full detail pane (summary, links,
        // artifacts, logs) instead of just copying the runId.
        // The runId is still accessible via the right-click
        // menu / palette.
        app.open_cloud_agent_run(row_idx);
        return;
    }
    // Click anywhere else inside the rail while either
    // agents filter is focused → unfocus.
    if app.agents_panel_filter_focused {
        app.agents_panel_filter_focused = false;
    }
    if app.cloud_agents_filter_focused {
        app.cloud_agents_filter_focused = false;
    }
    if app.http_panel_filter_focused {
        app.http_panel_filter_focused = false;
    }
    if app.todos_panel_filter_focused {
        app.todos_panel_filter_focused = false;
    }
    if app.notes_panel_filter_focused {
        app.notes_panel_filter_focused = false;
    }
    if app.sessions_panel_filter_focused {
        app.sessions_panel_filter_focused = false;
    }
    // Sessions panel tab (vertical-tab strip shown when
    // `ActivitySection::Sessions` is active). Click →
    // focus that Pty pane. Also arms a drag — mouse-up
    // over another tab swaps them.
    if let Some(&(_, pid)) = app
        .rects
        .session_tabs
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.active = Some(pid);
        app.focus_pane();
        app.session_drag_pid = Some(pid);
        return;
    }
    // Git-palette row (the GitKraken-style panel shown when
    // `ActivitySection::Git` is active). Maps to the same
    // `GitRailHit` dispatch as the legacy rail.
    if let Some(&(_, hit)) = app
        .rects
        .git_palette_rows
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        // GitKraken-style: left-click on a ref (branch /
        // remote / worktree / tag / stash) HIGHLIGHTS the
        // ref's commit in the open git-graph pane. The
        // action (checkout / cd / pop / etc.) lives on
        // the right-click context menu. PRs still open in
        // the browser since they're not graph commits.
        // qa-feature 2026-06-30 — stamp the clicked row's
        // identifier so git_palette::draw can paint the
        // highlight bg on its render call. Click feedback was
        // missing — clicking a branch jumped the graph but the
        // sidebar row looked unselected.
        match &hit {
            crate::ui::git_palette::GitPaletteHit::Branch(i) => {
                if let Some(b) = app.git_rail.branches.get(*i) {
                    app.git_palette_selected = Some(b.name.clone());
                }
            }
            crate::ui::git_palette::GitPaletteHit::Worktree(i) => {
                if let Some(wt) = app.git_rail.worktrees.get(*i) {
                    app.git_palette_selected = Some(wt.label.clone());
                }
            }
            crate::ui::git_palette::GitPaletteHit::RemoteBranch(i) => {
                if let Some(name) = app.git_rail.remote_branches.get(*i).cloned() {
                    app.git_palette_selected = Some(name);
                }
            }
            crate::ui::git_palette::GitPaletteHit::Stash(i) => {
                if let Some(st) = app.git_rail.stashes.get(*i) {
                    app.git_palette_selected = Some(st.id.clone());
                }
            }
            crate::ui::git_palette::GitPaletteHit::Tag(i) => {
                if let Some(name) = app.git_rail.tags.get(*i).cloned() {
                    app.git_palette_selected = Some(name);
                }
            }
            crate::ui::git_palette::GitPaletteHit::Pull(_) => {
                // PRs open in browser; no in-sidebar selection
                // semantics.
            }
        }
        match hit {
            crate::ui::git_palette::GitPaletteHit::Branch(i) => {
                if let Some(b) = app.git_rail.branches.get(i) {
                    let name = b.name.clone();
                    app.git_jump_to_ref(&name);
                }
            }
            crate::ui::git_palette::GitPaletteHit::Worktree(i) => {
                if let Some(wt) = app.git_rail.worktrees.get(i) {
                    let label = wt.label.clone();
                    app.git_jump_to_ref(&label);
                }
            }
            crate::ui::git_palette::GitPaletteHit::Pull(i) => {
                // PRs aren't commits — open in browser
                // (same as the legacy rail).
                app.click_git_rail(crate::git::rail::GitRailHit::Pull(i));
            }
            crate::ui::git_palette::GitPaletteHit::RemoteBranch(i) => {
                if let Some(name) = app.git_rail.remote_branches.get(i).cloned() {
                    app.git_jump_to_ref(&name);
                }
            }
            crate::ui::git_palette::GitPaletteHit::Stash(i) => {
                if let Some(st) = app.git_rail.stashes.get(i) {
                    let id = st.id.clone();
                    app.git_jump_to_ref(&id);
                }
            }
            crate::ui::git_palette::GitPaletteHit::Tag(i) => {
                if let Some(name) = app.git_rail.tags.get(i).cloned() {
                    app.git_jump_to_ref(&name);
                }
            }
        }
        return;
    }
    // Claude Agents — Files drill-down file row click → open
    // the file in an editor pane.
    if let Some(path) = app
        .rects
        .claude_drill_files
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
        .map(|(_, p)| p.clone())
    {
        let pb = std::path::PathBuf::from(&path);
        app.open_path(&pb);
        return;
    }
    // SCM/CI pane row click? Match before the generic editor-pane
    // handler since these panes also register editor-pane rects.
    // Single click: focus + select that row. If it's a header,
    // toggle collapse (sibling to Enter). Double-click on a data
    // row: open in browser.
    if let Some(&(_, pid, flat_idx)) = app
        .rects
        .list_rows
        .iter()
        .find(|(r, _, _)| crate::app::dispatch::contains(*r, x, y))
    {
        app.active = Some(pid);
        app.focus_pane();
        let now = std::time::Instant::now();
        let count = match app.last_click {
            Some((prev, px, py, c))
                if px == x
                    && py == y
                    && now.duration_since(prev)
                        < std::time::Duration::from_millis(DOUBLE_CLICK_MAX_MS as u64) =>
            {
                (c + 1).min(3)
            }
            _ => 1,
        };
        app.last_click = Some((now, x, y, count));
        // Click on a list row blurs the WIP commit textarea
        // (the user is moving focus to the commits / status
        // list, not the editor box).
        app.blur_active_wip_commit_textarea();
        crate::app::dispatch::handle_scm_row_click(app, pid, flat_idx, count >= 2);
        return;
    }

    // Editor text in some split leaf? Focus that leaf and place the cursor.
    // Click on a toast box → dismiss that toast. mouse-round-10
    // SEV-2 2026-07-12 — was silent fall-through into the pane
    // beneath.
    if let Some((idx, _)) = app
        .rects
        .toast_stack_rects
        .iter()
        .enumerate()
        .find(|(_, r)| crate::app::dispatch::contains(**r, x, y))
    {
        if idx < app.toast_stack.len() {
            app.toast_stack.remove(idx);
            // The primary `App.toast` field mirrors the newest
            // stack entry; if we just dismissed it, clear the
            // legacy slot too so the fade-out picks up.
            if idx == 0 {
                app.toast = None;
            }
        }
        return;
    }
    // Double-click on a split divider → equalize splits (VS Code
    // convention — double-click a resize handle to reset the ratio).
    // mouse-round-9 SEV-2 2026-07-11. mouse-round-11 SEV-2
    // 2026-07-12 — was gated on `hover_divider_idx` which never
    // gets set under IPC-driven click-only sequences (no Moved
    // events precede the click). Fall back to a direct hit-test
    // against `split_dividers` so the IPC harness + real mouse
    // both work.
    let over_divider = app.hover_divider_idx.is_some()
        || app
            .rects
            .split_dividers
            .iter()
            .any(|d| crate::app::dispatch::contains(d.rect, x, y));
    if over_divider {
        let now = std::time::Instant::now();
        let is_double = matches!(
            app.last_click,
            Some((prev, px, py, c))
                if px == x
                    && py == y
                    && c >= 1
                    && now.duration_since(prev) < std::time::Duration::from_millis(DOUBLE_CLICK_MAX_MS as u64)
        );
        app.last_click = Some((now, x, y, if is_double { 2 } else { 1 }));
        if is_double {
            app.equalize_splits();
            return;
        }
    }
    // Left-click on an editor's gutter → select the whole line.
    // Shift+gutter-click extends the selection down / up from
    // the anchor to that line. VS Code's line-numbers convention.
    // mouse-round-8 SEV-2 2026-07-11.
    if let Some(&(gr, pid)) = app
        .rects
        .editor_gutters
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        let row_in_pane = (y - gr.y) as usize;
        if let Some(Pane::Editor(b)) = app.panes.get_mut(pid) {
            let line = b.scroll + row_in_pane;
            let clamped = line.min(b.editor.line_count().saturating_sub(1));
            let clip = &mut app.clipboard;
            let shift = m.modifiers.contains(KeyModifiers::SHIFT);
            // For shift+gutter-click: DON'T place_cursor first (it
            // wipes the anchor); jump the cursor byte directly.
            if shift && b.editor.selection().is_some() {
                let (_lo, hi) = b.editor.line_byte_range(clamped);
                b.editor.set_cursor_byte(hi);
            } else {
                // Non-shift path: place cursor at line start, then
                // fire SelectLineToEnd — matches Ctrl+L semantics.
                b.editor.place_cursor(clamped, 0);
                b.apply_edit_ops(vec![crate::edit_op::EditOp::SelectLineToEnd], clip, 0);
            }
        }
        return;
    }
    // Track multi-click: 2 = select word, 3 = select line. The threshold
    // (450 ms, same cell) matches what most OSes use.
    if let Some(&(tr, pid)) = app
        .rects
        .editor_panes
        .iter()
        .find(|(r, _)| crate::app::dispatch::contains(*r, x, y))
    {
        // Alt+click → add an extra cursor at the clicked position
        // (VS Code convention). Skips the focus / drag-arm path so
        // the existing primary stays put.
        if m.modifiers.contains(KeyModifiers::ALT) {
            let wrap = app.config.ui.wrap;
            if let Some(Pane::Editor(b)) = app.panes.get_mut(pid) {
                let (row, col) = crate::app::dispatch::click_to_file_pos(b, tr, wrap, x, y);
                let byte = b.editor.byte_at_col_pub(row, col);
                b.editor.add_extra_cursor(byte);
            }
            return;
        }
        app.active = Some(pid);
        app.focus_pane();
        let now = std::time::Instant::now();
        let count = match app.last_click {
            Some((prev, px, py, c))
                if px == x
                    && py == y
                    && now.duration_since(prev)
                        < std::time::Duration::from_millis(DOUBLE_CLICK_MAX_MS as u64) =>
            {
                (c + 1).min(3)
            }
            _ => 1,
        };
        app.last_click = Some((now, x, y, count));
        // Ctrl+click → place cursor + fire `lsp.goto_definition`
        // (VS Code convention — "click through" identifiers).
        let ctrl_click = m.modifiers.contains(KeyModifiers::CONTROL);
        // Shift+click → extend the current selection to the click.
        // mouse-round-8 SEV-2 2026-07-11.
        let shift_click = m.modifiers.contains(KeyModifiers::SHIFT) && !ctrl_click;
        let wrap = app.config.ui.wrap;
        if let Some(Pane::Editor(b)) = app.panes.get_mut(pid) {
            let (row, col) = crate::app::dispatch::click_to_file_pos(b, tr, wrap, x, y);
            if shift_click {
                // Establish anchor at current cursor first (if not
                // already selecting), then extend cursor to click.
                // mouse-round-9 fix: was using place_cursor which
                // wipes the anchor immediately — use extend_cursor_to
                // for the click destination.
                let clip = &mut app.clipboard;
                if b.editor.selection().is_none() {
                    b.apply_edit_ops(vec![crate::edit_op::EditOp::SelectStart], clip, 0);
                }
                b.editor.extend_cursor_to(row, col);
            } else {
                b.editor.place_cursor(row, col);
                if count >= 2 {
                    let clip = &mut app.clipboard;
                    if let Some(Pane::Editor(b)) = app.panes.get_mut(pid) {
                        // mouse-round-8 SEV-3 2026-07-12 — triple-click
                        // in STANDARD mode fires SelectLineToEnd so
                        // typing replaces the whole line (matches
                        // VS Code / Sublime / GUI-editor convention).
                        // In vim mode, keep SelectLine (V-visual line)
                        // so muscle memory still yields the vim shape.
                        let op = if count == 2 {
                            crate::edit_op::EditOp::SelectWord
                        } else if b.editing_mode() == crate::input::EditingMode::None {
                            crate::edit_op::EditOp::SelectLineToEnd
                        } else {
                            crate::edit_op::EditOp::SelectLine
                        };
                        b.apply_edit_ops(vec![op], clip, 0);
                    }
                } else {
                    // Arm a potential drag-select. If the user actually
                    // drags, the first Drag event will SelectStart at
                    // the origin and move the cursor.
                    app.drag_select = Some((pid, row, col, false));
                }
            }
        }
        if ctrl_click {
            // Ctrl+Shift+Click → references picker; plain Ctrl+Click
            // → go-to-definition. Matches VS Code's "peek references"
            // / "go to definition" gestures.
            if m.modifiers.contains(KeyModifiers::SHIFT) {
                app.lsp_references();
            } else {
                app.lsp_goto_definition();
            }
        }
    }
}