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
//! Dispatch helpers — pulled out of `src/tui.rs` so the event-loop
//! file stays focused on the crossterm read+route+draw cycle.
//!
//! Every fn here is a free fn (not a method) that takes `&mut App`
//! or `&App`. They're called from `tui::dispatch_key` /
//! `dispatch_mouse` via `crate::app::dispatch::*`.
//!
//! Extracted from `tui.rs` in the file-split refactor. Pure
//! non-destructive move.

use super::*;
use crate::command;
use crate::edit_op::EditOp;
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::layout::Rect;
use std::io;

/// Drain `app.image_paint_requests` and emit the protocol-specific image
/// escapes directly to stdout. Called after `terminal.draw()` so the
/// images paint *on top of* the placeholder cells ratatui reserved.
///
/// Also handles clearing stale placements: when image panes disappear
/// (closed / scrolled out), we emit a `clear-all` so the previous
/// frame's images don't linger.
pub(crate) fn emit_image_placements(app: &mut App) {
    use crate::image::ImageProtocol;
    use std::io::Write;
    let protocol = app.image_protocol;
    if matches!(protocol, ImageProtocol::None) {
        app.image_paint_requests.clear();
        app.had_image_pane = false;
        return;
    }
    let pending = std::mem::take(&mut app.image_paint_requests);
    let any_now = !pending.is_empty();
    // qa-feature 2026-07-02 — skip the whole clear+re-emit dance when
    // the paint set is identical to last frame. The terminal keeps
    // the previously-painted image on screen, which stops the
    // per-frame flash. Also spares stdout bandwidth for a re-transmit
    // of a large PNG every frame.
    let current_paints: Vec<(crate::layout::PaneId, ratatui::layout::Rect)> =
        pending.iter().map(|r| (r.pane_id, r.area)).collect();
    if any_now && current_paints == app.last_image_paints {
        app.had_image_pane = true;
        return;
    }
    let needs_clear = any_now || app.had_image_pane;
    let mut out = io::stdout();
    if needs_clear && matches!(protocol, ImageProtocol::Kitty) {
        let _ = out.write_all(crate::image::kitty::clear_all().as_bytes());
    }
    for req in pending {
        // Move cursor to the area's top-left (1-based row;col).
        let _ = write!(
            out,
            "\x1b[{};{}H",
            req.area.y.saturating_add(1),
            req.area.x.saturating_add(1)
        );
        match protocol {
            ImageProtocol::Kitty => {
                if let Ok(esc) = crate::image::kitty::encode_placement(
                    &req.png_bytes,
                    req.area.width,
                    req.area.height,
                ) {
                    let _ = out.write_all(esc.as_bytes());
                }
            }
            ImageProtocol::Iterm2 => {
                let esc = crate::image::iterm2::encode_placement(
                    &req.png_bytes,
                    req.area.width,
                    req.area.height,
                );
                let _ = out.write_all(esc.as_bytes());
            }
            ImageProtocol::Sixel => {
                if let Ok(esc) = crate::image::sixel::encode_placement(
                    &req.png_bytes,
                    req.area.width,
                    req.area.height,
                ) {
                    let _ = out.write_all(esc.as_bytes());
                }
            }
            ImageProtocol::None => {}
        }
    }
    let _ = out.flush();
    app.had_image_pane = any_now;
    app.last_image_paints = current_paints;
}

/// Update [`App::dot_recording`] / [`App::dot_keys`] based on the mode +
/// chord-state transition this dispatch caused. The recording starts
/// when a "change" begins and finalizes when it ends. Boundaries:
///
/// - Normal + no chord pending → Insert ⇒ start recording (this `key`).
/// - Normal + no chord pending → Normal + chord pending (e.g. `d` from
///   normal opens operator-pending) ⇒ start recording.
/// - During recording (chord still pending OR in Insert) ⇒ append.
/// - End of recording: chord cleared and (mode is Normal OR back from
///   Insert), AND a buffer mutation occurred ⇒ finalize into `dot_keys`.
/// - End of recording with no mutation (e.g. user `Esc`'d the operator
///   before completing it) ⇒ discard.
/// - One-shot Normal-mode mutation with no chord (e.g. `p`) ⇒ record this
///   `key` and finalize immediately.
pub(crate) fn record_dot(
    app: &mut crate::app::App,
    key: KeyEvent,
    mode_before: Option<crate::input::EditingMode>,
    mode_after: Option<crate::input::EditingMode>,
    pending_before: Option<String>,
    pending_after: Option<String>,
    edited: bool,
) {
    use crate::input::EditingMode;
    let (Some(before), Some(after)) = (mode_before, mode_after) else {
        return;
    };
    let recording = app.dot_recording.is_some();
    // 1. Already recording — append. Then check if we just finalized.
    if recording {
        if let Some(rec) = &mut app.dot_recording {
            rec.push(key);
        }
        if edited {
            app.dot_recording_saw_edit = true;
        }
        let in_flight = after == EditingMode::Insert || pending_after.is_some();
        if !in_flight {
            // Recording terminated. If any earlier keystroke in the
            // session produced a mutation, finalize. Otherwise discard
            // (the chord was cancelled — e.g. ESC out of operator-pending).
            if app.dot_recording_saw_edit {
                if let Some(rec) = app.dot_recording.take() {
                    app.dot_keys = rec;
                }
            } else {
                app.dot_recording = None;
            }
            app.dot_recording_saw_edit = false;
        }
        return;
    }
    // 2. Not currently recording — does this key start a new change?
    let in_flight_after = after == EditingMode::Insert || pending_after.is_some();
    let started_change =
        before == EditingMode::Normal && pending_before.is_none() && in_flight_after;
    if started_change {
        app.dot_recording = Some(vec![key]);
        app.dot_recording_saw_edit = edited;
        return;
    }
    // 3. Visual → Insert (visual `c`) starts a change too. All three
    //    visual flavours (charwise, linewise, blockwise) count.
    if before.is_visual() && after == EditingMode::Insert {
        app.dot_recording = Some(vec![key]);
        app.dot_recording_saw_edit = edited;
        return;
    }
    // 4. One-shot Normal-mode mutation (`p`, `~`, `u`, etc.) — record the
    //    single key and finalize.
    if before == EditingMode::Normal
        && after == EditingMode::Normal
        && pending_before.is_none()
        && pending_after.is_none()
        && edited
    {
        app.dot_keys = vec![key];
    }
    // 5. Visual op (e.g. `vlld`) ⇒ also a one-shot capture.
    //    Covers V-LINE and V-BLOCK too.
    if before.is_visual() && after == EditingMode::Normal && edited {
        app.dot_keys = vec![key];
    }
}

/// Vim abbreviation trigger: chars that "complete" the previous word and
/// signal expansion. Roughly: whitespace + most punctuation. Letters /
/// digits / `_` are *not* triggers (they keep the word in flight).
pub(crate) fn is_abbreviation_trigger(c: char) -> bool {
    c.is_whitespace()
        || matches!(
            c,
            '.' | ',' | ';' | ':' | '!' | '?' | ')' | ']' | '}' | '"' | '\'' | '`'
        )
}

pub(crate) fn pane_viewport(app: &App) -> usize {
    app.active
        .and_then(|cur| {
            app.rects
                .editor_panes
                .iter()
                .find(|(_, p)| *p == cur)
                .map(|(r, _)| r.height as usize)
        })
        .unwrap_or(20)
        .max(1)
}

pub(crate) fn apply_app_command(app: &mut App, cmd: crate::input::AppCommand) {
    use crate::input::AppCommand::*;
    match cmd {
        Save => {
            command::run("file.save", app);
        }
        ExCommand(s) => {
            // Push onto persistent ex history (de-duped against newest,
            // capped at 100). The handler-side history mirror is updated
            // on launch from `App.ex_history` via `set_ex_history`.
            if app.ex_history.last() != Some(&s) {
                app.ex_history.push(s.clone());
                if app.ex_history.len() > 100 {
                    let drop = app.ex_history.len() - 100;
                    app.ex_history.drain(..drop);
                }
            }
            app.run_ex_command(&s);
        }
        RunCommand(id) => {
            command::run(&id, app);
        }
        DotRepeat(n) => {
            app.pending_dot_count = Some(n);
            app.dot_replay();
        }
        SetMark(c) => app.set_mark_at_cursor(c),
        JumpToMarkLine(c) => app.jump_to_mark(c, false),
        JumpToMarkExact(c) => app.jump_to_mark(c, true),
        MacroRecordInto(c) => {
            app.set_pending_macro_register(c);
            app.macro_toggle();
        }
        MacroReplayFrom { reg, count } => {
            for _ in 0..count.max(1) {
                app.set_pending_macro_register(reg);
                app.macro_replay();
            }
        }
        BlockInsertStart { append } => app.block_insert_start(append),
        BlockChangeStart => app.block_change_start(),
        BlockReplaceWith { ch } => app.block_replace_with(ch),
        FilterLinesFromCursor { count } => app.begin_filter_lines_from_cursor(count),
        FilterParagraphFromCursor { around } => app.begin_filter_paragraph_from_cursor(around),
        OperatorLinewiseTo { op, target } => app.vim_operator_linewise_to(op, target),
        CmdlineTabComplete => app.cmdline_tab_complete(),
        CmdlinePopupMove(delta) => app.cmdline_popup_move(delta as isize),
        CmdlineInsertCursorWord(big) => app.cmdline_insert_cursor_word(big),
        CmdlinePasteFromClipboard => app.cmdline_paste_from_clipboard(),
        CmdlineEnter(typed) => {
            // Only substitute the popup-highlighted match when the
            // user explicitly navigated via ↓ / Tab (selected > 0).
            // Index 0 (auto-first) keeps the typed text so vim
            // abbreviations like `:reg<Enter>` don't get rewritten
            // to `:registers`. Mirrors no_pane_cmdline_commit in
            // tui.rs. (Vim path runs through this — the saved
            // completion state stays alive on the App after vim
            // clears its own cmdline, so we read head +
            // matches[selected] directly rather than calling
            // accept_current().)
            let effective = if app.cmdline_popup_selected > 0
                && let Some(state) = app.cmdline_complete_state.as_ref()
                && let Some(suffix) = state.matches.get(app.cmdline_popup_selected)
            {
                format!("{}{}", state.head, suffix)
            } else {
                typed.clone()
            };
            // 2026-06-20 — mirror the ExCommand arm: also push onto
            // App.ex_history so vim's `q:` window sees the entry.
            if app.ex_history.last() != Some(&effective) {
                app.ex_history.push(effective.clone());
                if app.ex_history.len() > 100 {
                    let drop = app.ex_history.len() - 100;
                    app.ex_history.drain(..drop);
                }
            }
            app.run_ex_command(&effective);
        }
        RepeatInsertStart { count, above } => app.repeat_insert_start(count as usize, above),
        FlashStart(a, b) => app.flash_start(a, b),
    }
}

/// Translate a click within an editor pane's text rect to a `(file_row,
/// file_col)`. Wrap-aware: when `[ui] wrap` is on, the visible row is
/// walked via [`Buffer::wrap_to_file_pos`] so clicks inside a wrapped
/// continuation land on the right char column. With wrap off this is
/// the classic `visible_to_file_row` + `h_scroll` mapping.
pub(crate) fn click_to_file_pos(
    b: &crate::buffer::Buffer,
    tr: Rect,
    wrap: bool,
    x: u16,
    y: u16,
) -> (usize, usize) {
    let visible_row = (y.saturating_sub(tr.y)) as usize;
    let click_col = (x.saturating_sub(tr.x)) as usize;
    let tw = tr.width as usize;
    if wrap && tw > 0 {
        let (row, char_start) = b
            .wrap_to_file_pos(b.scroll, visible_row, tw)
            .unwrap_or((b.scroll, 0));
        (row, char_start + click_col)
    } else {
        let row = b
            .visible_to_file_row(b.scroll, visible_row)
            .unwrap_or(b.scroll);
        (row, b.h_scroll + click_col)
    }
}

/// Which clickable statusline chip (if any) sits under the given mouse coords.
/// Used by the hover-tooltip system; right-click + left-click handlers do their
/// own per-chip rect checks since they need to act, not just identify.
pub(crate) fn hover_chip_at(app: &App, x: u16, y: u16) -> Option<crate::HoverChip> {
    // mouse-round-9 SEV-2 2026-07-11 — divider hover. Checked
    // early so it wins over any coarser pane-body chip check
    // (though dividers don't overlap panes so this is safe).
    if app.rects.split_dividers.iter().any(|d| {
        x >= d.rect.x
            && x < d.rect.x + d.rect.width
            && y >= d.rect.y
            && y < d.rect.y + d.rect.height
    }) {
        return Some(crate::HoverChip::SplitDivider);
    }
    // #polish 2026-07-06 — gutter sign-column marks (git change,
    // diagnostic, breakpoint, DAP arrow). Checked FIRST so a mark in
    // an editor pane wins over the coarser editor-pane hover
    // arm below.
    if let Some(&(_, pane_id, line_no, kind)) = app
        .rects
        .gutter_marks
        .iter()
        .find(|(r, _, _, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::GutterMark {
            pane_id,
            line_no,
            kind,
        });
    }
    // 2026-06-21 — Claude Agents dashboard topbar chips: each
    // chip rect is registered with its TopbarChipKind so the
    // tooltip can explain what it cycles + the keyboard chord.
    if let Some(&(_, _, kind)) = app
        .rects
        .claude_agents_topbar_chips
        .iter()
        .find(|(r, _, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::ClaudeAgentsTopbarChip(kind));
    }
    if let Some(r) = app.rects.statusline_stress_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineStress);
    }
    if let Some(r) = app.rects.palette_stress_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::PaletteStress);
    }
    if let Some((idx, _)) = app
        .rects
        .toast_stack_rects
        .iter()
        .enumerate()
        .find(|(_, r)| contains(**r, x, y))
    {
        return Some(crate::HoverChip::ToastBox(idx));
    }
    if let Some(r) = app.rects.statusline_mode_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineMode);
    }
    if let Some(r) = app.rects.statusline_branch_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineBranch);
    }
    if let Some(r) = app.rects.statusline_workspace_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineWorkspace);
    }
    if let Some(r) = app.rects.statusline_clock_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineClock);
    }
    if let Some(r) = app.rects.statusline_lsp_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineLsp);
    }
    if let Some(r) = app.rects.statusline_wrap_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineWrap);
    }
    if let Some(r) = app.rects.statusline_ai_claude_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineAiClaude);
    }
    if let Some(r) = app.rects.statusline_ai_codex_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineAiCodex);
    }
    if let Some(r) = app.rects.statusline_autosave_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineAutosave);
    }
    // #polish 2026-07-06 — new left-lane statusline chips.
    if let Some(r) = app.rects.statusline_file_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineFile);
    }
    if let Some(r) = app.rects.statusline_diagnostics_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineDiagnostics);
    }
    if let Some(r) = app.rects.statusline_symbol_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineSymbol);
    }
    if let Some(r) = app.rects.statusline_pr_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslinePr);
    }
    if let Some(r) = app.rects.statusline_language_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineLanguage);
    }
    if let Some(r) = app.rects.statusline_macro_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineMacroRec);
    }
    if let Some(r) = app.rects.statusline_find_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineFind);
    }
    if let Some(r) = app.rects.statusline_sel_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineSel);
    }
    if let Some(r) = app.rects.statusline_progress_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineProgress);
    }
    if let Some(r) = app.rects.statusline_bg_tasks_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineBgTasks);
    }
    if let Some(r) = app.rects.statusline_ai_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineAi);
    }
    // #21 v5 — Request pane top-bar chip hover detection.
    if let Some(r) = app.rects.request_method_button
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::RequestTopBarChip(
            crate::RequestTopBarChip::Method,
        ));
    }
    if let Some(r) = app.rects.request_env_button
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::RequestTopBarChip(
            crate::RequestTopBarChip::Env,
        ));
    }
    if let Some(r) = app.rects.request_send_button
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::RequestTopBarChip(
            crate::RequestTopBarChip::Send,
        ));
    }
    if let Some(r) = app.rects.request_save_button
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::RequestTopBarChip(
            crate::RequestTopBarChip::Save,
        ));
    }
    if let Some(r) = app.rects.request_clear_button
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::RequestTopBarChip(
            crate::RequestTopBarChip::Clear,
        ));
    }
    if let Some(r) = app.rects.request_code_button
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::RequestTopBarChip(
            crate::RequestTopBarChip::Code,
        ));
    }
    if let Some(r) = app.rects.request_split_toggle
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::RequestSplitToggle);
    }
    if let Some(r) = app.rects.request_edit_split_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::RequestEditSplitChip);
    }
    if let Some((idx, _)) = app
        .rects
        .http_panel_section_chips
        .iter()
        .enumerate()
        .find(|(_, (r, _, _))| contains(*r, x, y))
    {
        return Some(crate::HoverChip::HttpSectionChip(idx));
    }
    if let Some((idx, _)) = app
        .rects
        .http_panel_icon_buttons
        .iter()
        .enumerate()
        .find(|(_, (r, _))| contains(*r, x, y))
    {
        return Some(crate::HoverChip::HttpToolbarChip(idx));
    }
    if let Some(r) = app.rects.tree_up_row
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::TreeUpRow);
    }
    if let Some(r) = app.rects.request_edit_split_divider
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::RequestEditSplitDivider);
    }
    if let Some((idx, _)) = app
        .rects
        .http_panel_collection_new_request_chips
        .iter()
        .enumerate()
        .find(|(_, (r, _))| contains(*r, x, y))
    {
        return Some(crate::HoverChip::HttpCollectionAddRequestChip(idx));
    }
    if let Some((idx, _)) = app
        .rects
        .request_var_click_rects
        .iter()
        .enumerate()
        .find(|(_, (r, _))| contains(*r, x, y))
    {
        return Some(crate::HoverChip::RequestVarToken(idx));
    }
    if let Some(r) = app.rects.request_response_copy_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::RequestResponseCopy);
    }
    if let Some(r) = app.rects.request_response_wrap_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::RequestResponseWrap);
    }
    if let Some(r) = app.rects.request_response_ai_prompt_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::RequestResponseAiPrompt);
    }
    if let Some(r) = app.rects.request_format_button
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::RequestResponseFormat);
    }
    if let Some(r) = app.rects.pending_undo_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::PendingUndoChip);
    }
    if let Some(r) = app.rects.bufferline_new_request_button
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::BufferlineNewRequest);
    }
    // #polish 2026-07-06 — scrollbar hover. Any scrollbar
    // matches; the tooltip is the same for all of them.
    if app.rects.scrollbars.iter().any(|h| contains(h.area, x, y)) {
        return Some(crate::HoverChip::ScrollbarThumb);
    }
    if let Some(r) = app.rects.right_panel_edge
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::RightPanelGrip);
    }
    if let Some(r) = app.rects.tree_edge
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::TreeRailGrip);
    }
    if let Some(&(_, idx)) = app
        .rects
        .menu_bar_words
        .iter()
        .find(|(r, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::MenuBarWord(idx));
    }
    // Task #929 (2026-08-12) — when a menu-bar dropdown is open,
    // hover a row inside it to route hover-help through
    // `InfoViewTarget::MenuItem`. `menu_bar_items` is only
    // populated while `app.menu_open` is `Some`, but we gate on
    // both for defence in depth. `item_idx` uses the encoded
    // format from `ui/menu_bar.rs`: raw index (< 1000) for
    // top-level rows, `1000 + parent*100 + sub` for submenu rows.
    // The MenuBarItem resolver in `ui/info_view_copy.rs` decodes
    // the same way.
    if let Some(open) = app.menu_open.as_ref()
        && let Some(&(_, item_idx)) = app
            .rects
            .menu_bar_items
            .iter()
            .find(|(r, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::MenuBarItem {
            menu_idx: open.menu_idx,
            item_idx,
        });
    }
    if let Some(r) = app.rects.statusline_filesize_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineFilesize);
    }
    if let Some(r) = app.rects.statusline_lncol_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineLnCol);
    }
    // 2026-08-17 — data-driven statusline chips (both manifest
    // `[[statusline_segments]]` and IPC-set `DynamicSegment`s).
    // Checked before the launcher/integration rects further down
    // because the statusline row is above the rail, but that
    // ordering is defensive — the rects belong to different
    // regions and don't overlap in practice.
    if let Some(idx) = app
        .rects
        .statusline_segment_hits
        .iter()
        .position(|(r, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::StatuslineSegment(idx));
    }
    // 2026-08-01 (P2) — launcher_icon_rects hit-test removed with
    // the LauncherIcon retirement.
    if let Some(&(_, cmd_id)) = app
        .rects
        .tree_icon_buttons
        .iter()
        .find(|(r, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::TreeIcon(cmd_id));
    }
    if let Some(tr) = app.rects.tree_toggle
        && contains(tr, x, y)
    {
        return Some(crate::HoverChip::WorkspaceHeader);
    }
    if let Some(&(_, ws_idx)) = app
        .rects
        .extra_workspace_toggles
        .iter()
        .find(|(r, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::ExtraWorkspaceHeader(ws_idx));
    }
    if let Some(&(_, icon_idx)) = app
        .rects
        .integration_icon_rects
        .iter()
        .find(|(r, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::IntegrationIcon(icon_idx));
    }
    if let Some(&(_, section)) = app
        .rects
        .activity_bar_icons
        .iter()
        .find(|(r, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::ActivityBarIcon(section));
    }
    if let Some(r) = app.rects.statusline_mixr_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineNowPlaying);
    }
    // qa-feature 2026-06-30 — GitGraph lane cell hover.
    if let Some(&(_, pane_id, commit_idx, lane_idx)) = app
        .rects
        .git_graph_lane_cells
        .iter()
        .find(|(r, _, _, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::GitGraphLane {
            pane_id,
            commit_idx,
            lane_idx,
        });
    }
    // qa-feature 2026-07-01 — GitGraph commit subject hover.
    if let Some(&(_, pane_id, commit_idx)) = app
        .rects
        .git_graph_subject_cells
        .iter()
        .find(|(r, _, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::GitGraphCommitMsg {
            pane_id,
            commit_idx,
        });
    }
    if let Some(r) = app.rects.palette_sidebar_button
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::PaletteSidebarButton);
    }
    if let Some(r) = app.rects.palette_right_panel_button
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::PaletteRightPanelButton);
    }
    if let Some(r) = app.rects.palette_back_button
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::PaletteBackButton);
    }
    if let Some(r) = app.rects.palette_forward_button
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::PaletteForwardButton);
    }
    if let Some(r) = app.rects.palette_search_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::PaletteSearchChip);
    }
    if let Some(r) = app.rects.palette_dropdown_button
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::PaletteDropdownButton);
    }
    if let Some(r) = app.rects.palette_add_integration_button
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::PaletteAddIntegration);
    }
    if let Some(&(_, leaf_active, tab_pane)) = app
        .rects
        .split_tab_close
        .iter()
        .find(|(r, _, _)| contains(*r, x, y))
    {
        let _ = leaf_active;
        return Some(crate::HoverChip::SplitTabClose(tab_pane));
    }
    if let Some(&(_, leaf_active, tab_pane)) = app
        .rects
        .split_tab_chips
        .iter()
        .find(|(r, _, _)| contains(*r, x, y))
    {
        let _ = leaf_active;
        return Some(crate::HoverChip::SplitTabChip(tab_pane));
    }
    // vscode-user-mouse 2026-07-30 SEV-3 #5 — per-leaf `+` chip had
    // no hover tooltip so users didn't know what it did until they
    // clicked (and were surprised — SEV-2 #2). Match `split_tab_chips`
    // above: stores (rect, leaf_active_pane).
    if let Some(&(_, leaf_active)) = app
        .rects
        .split_tab_plus_buttons
        .iter()
        .find(|(r, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::SplitTabPlus(leaf_active));
    }
    // Right-panel tab strip chips. v3 polish.
    if let Some(&(_, tab_idx)) = app
        .rects
        .right_panel_tabs
        .iter()
        .find(|(r, _)| contains(*r, x, y))
        && let Some(&pid) = app.right_panel_panes.get(tab_idx)
    {
        return Some(crate::HoverChip::RightPanelTab(pid));
    }
    if let Some(r) = app.rects.right_panel_close
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::RightPanelClose);
    }
    if let Some(r) = app.rects.agents_panel_new_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::AgentsPanelChip(
            crate::AgentsPanelChipKind::NewSession,
        ));
    }
    if let Some(r) = app.rects.agents_panel_pr_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::AgentsPanelChip(
            crate::AgentsPanelChipKind::FromPr,
        ));
    }
    if let Some(r) = app.rects.agents_panel_view_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::AgentsPanelChip(
            crate::AgentsPanelChipKind::ViewToggle,
        ));
    }
    if let Some(r) = app.rects.cloud_agents_new_run_button
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::CloudAgentsNewRunButton);
    }
    if let Some(r) = app.rects.activity_bar_gear
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::ActivityBarGear);
    }
    if app
        .rects
        .split_strip_ai_buttons
        .iter()
        .any(|(r, _, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::SplitStripAiButton);
    }
    if let Some(r) = app.rects.statusline_mixr_play_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineMixrPlay);
    }
    if let Some(r) = app.rects.statusline_mixr_ffwd_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineMixrFfwd);
    }
    if let Some(r) = app.rects.statusline_test_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineTestChip);
    }
    if app
        .rects
        .split_strip_term_buttons
        .iter()
        .any(|(r, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::SplitStripTermButton);
    }
    if let Some(&(_, _, dir)) = app
        .rects
        .split_strip_buttons
        .iter()
        .find(|(r, _, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::SplitStripButton(dir));
    }
    if let Some(&(_, action)) = app
        .rects
        .rail_git_header_buttons
        .iter()
        .find(|(r, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::RailHeaderChip(action));
    }
    // mouse-round-16 F6 2026-07-17 — git-graph toolbar chips.
    if let Some(&(_, _, action)) = app
        .rects
        .git_toolbar_buttons
        .iter()
        .find(|(r, _, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::GitToolbarChip(action));
    }
    // Test the close badge FIRST so its tooltip wins over the
    // generic tab tooltip when the pointer is over the trailing
    // `×`/`●` cells (the badge rect is a 2-cell strip inside the
    // tab rect, so the generic tab arm would otherwise shadow it).
    if let Some(&(_, pid)) = app
        .rects
        .bufferline_tab_close
        .iter()
        .find(|(r, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::BufferlineTabClose(pid));
    }
    if let Some(&(_, pid)) = app
        .rects
        .bufferline_tabs
        .iter()
        .find(|(r, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::BufferlineTab(pid));
    }
    // Sessions activity panel — vertical tabs of Pty sessions.
    if let Some(&(_, pid)) = app
        .rects
        .session_tabs
        .iter()
        .find(|(r, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::SessionsTab(pid));
    }
    if let Some(r) = app.rects.bufferline_new_tab_button
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::BufferlineNewTab);
    }
    if let Some(r) = app.rects.bufferline_tabs_label
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::BufferlineTabsLabel);
    }
    if let Some(r) = app.rects.bufferline_theme_toggle
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::BufferlineThemeToggle);
    }
    if let Some(r) = app.rects.bufferline_window_close
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::BufferlineWindowClose);
    }
    // Task #875 (R5 SEV-3 F6) — tab-page pips + their close badges.
    // The close-badge rect (`bufferline_tab_page_close`) is a 1-cell
    // rect placed immediately AFTER the pip's rect (adjacent, not
    // overlapping — see `bufferline::paint_right_cluster`), so the
    // check order here is really "close-badge first because it's
    // narrower and more specific," not for overlap-precedence.
    if let Some(&(_, idx)) = app
        .rects
        .bufferline_tab_page_close
        .iter()
        .find(|(r, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::BufferlineTabPageClose(idx));
    }
    if let Some(&(_, idx)) = app
        .rects
        .bufferline_tab_page_chips
        .iter()
        .find(|(r, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::BufferlineTabPage(idx));
    }
    // Task #875 (R5 SEV-3 F7) — Integrations panel tab-strip chips.
    if let Some(r) = app.rects.integrations_tab_installed
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::IntegrationsTabInstalled);
    }
    if let Some(r) = app.rects.integrations_tab_marketplace
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::IntegrationsTabMarketplace);
    }
    if let Some(r) = app.rects.integrations_tab_refresh
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::IntegrationsTabRefresh);
    }
    if let Some(r) = app.rects.integrations_tab_sort
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::IntegrationsTabSort);
    }
    // Task #875 (R5 SEV-3 F8) — statusline coverage chip.
    if let Some(r) = app.rects.statusline_coverage_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::StatuslineCoverage);
    }
    if let Some(&(_, _, action)) = app
        .rects
        .diff_toolbar_buttons
        .iter()
        .find(|(r, _, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::DiffToolbar(action));
    }
    if app
        .rects
        .fold_chips
        .iter()
        .any(|(r, _, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::FoldChip);
    }
    if app
        .rects
        .code_lens_chips
        .iter()
        .any(|(r, _, _)| contains(*r, x, y))
    {
        return Some(crate::HoverChip::CodeLensChip);
    }
    // 2026-08-07 vscode-user r2 F2 — HoverChip::DockEmptyChip + its
    // tooltip body were defined but this arm was missing, so
    // hovering the chip produced no popup.
    if let Some(r) = app.rects.dock_empty_chip
        && contains(r, x, y)
    {
        return Some(crate::HoverChip::DockEmptyChip);
    }
    None
}

/// Per-frame cap on the magnitude of a coalesced batched scroll
/// applied to a tree/list surface. The event-loop coalescer
/// already caps at 40 events; this is a final safety clamp so a
/// huge batch can't move the cursor across hundreds of rows in
/// one shot (which would feel like a teleport, not a scroll).
const LIST_SCROLL_PER_BATCH_CAP: i32 = 8;

/// Bucket capacity (in lines) for the flywheel dampener. One
/// "good flick" worth of intentional scroll.
const SCROLL_BUCKET_MAX: f32 = 25.0;

/// Refill rate (lines per second) for the flywheel dampener.
/// Steady-state active scrolling at ~12 lines/sec or slower
/// stays in the bucket indefinitely; a free-spin wheel that
/// keeps firing past intent will burn through and start
/// dropping events.
const SCROLL_BUCKET_REFILL: f32 = 12.0;

/// Apply the leaky-bucket scroll budget. Caller asks for `delta`
/// lines; we refill the bucket based on elapsed time since the
/// last call, then spend up to `delta` tokens. Returns the
/// magnitude that should actually be applied (always same sign
/// as input). 0 ⇒ drop the event entirely.
fn budgeted_scroll(app: &mut App, delta: i32) -> i32 {
    if delta == 0 {
        return 0;
    }
    let now = std::time::Instant::now();
    if let Some(prev) = app.scroll_bucket_last_refill {
        let elapsed = now.duration_since(prev).as_secs_f32();
        app.scroll_bucket =
            (app.scroll_bucket + elapsed * SCROLL_BUCKET_REFILL).min(SCROLL_BUCKET_MAX);
    } else {
        app.scroll_bucket = SCROLL_BUCKET_MAX;
    }
    app.scroll_bucket_last_refill = Some(now);
    let want = delta.unsigned_abs() as f32;
    let spend = want.min(app.scroll_bucket).floor();
    app.scroll_bucket -= spend;
    delta.signum() * (spend as i32)
}

/// Clamp the (already-coalesced) batched scroll magnitude to a
/// sane per-tick movement for list/tree surfaces. Replaced the
/// 80ms time-gate that used to spread bursts over time — that
/// just delayed the over-scroll instead of stopping it.
fn list_scroll_clamp(delta: i32) -> i32 {
    let sign = delta.signum();
    let mag = delta.unsigned_abs() as i32;
    sign * mag.min(LIST_SCROLL_PER_BATCH_CAP)
}

pub(crate) fn scroll_under(app: &mut App, x: u16, y: u16, delta: i32) {
    let delta = budgeted_scroll(app, delta);
    if delta == 0 {
        return;
    }
    // #polish 2026-07-06 — wheel over the bufferline strip cycles
    // through open buffers (Chrome / Firefox tab-strip convention).
    // Checked first so the strip's overlap with pane rects doesn't
    // let editor scroll steal the notch. Bounded to prev/next per
    // notch — no multi-step jump. Also applies over the overflow
    // arrow zones so the user can wheel there without missing.
    let on_bufferline_zone = app
        .rects
        .bufferline_tabs
        .iter()
        .any(|(r, _)| contains(*r, x, y))
        || app
            .rects
            .bufferline_overflow_left
            .map(|r| contains(r, x, y))
            .unwrap_or(false)
        || app
            .rects
            .bufferline_overflow_right
            .map(|r| contains(r, x, y))
            .unwrap_or(false);
    if on_bufferline_zone {
        if delta < 0 {
            app.prev_buffer();
        } else {
            app.next_buffer();
        }
        return;
    }
    // Wheel over the agents rail panel → scroll its content list. Checked
    // first + gated on the active section so the (stale) tree rect, which
    // overlaps the same rail region, can't shadow it. The render clamps the
    // offset to the content height each frame.
    if app.active_section == crate::app::ActivitySection::Agents
        && let Some(ar) = app.rects.agents_panel_area
        && contains(ar, x, y)
    {
        let d = list_scroll_clamp(delta);
        if d < 0 {
            app.agents_panel_scroll = app
                .agents_panel_scroll
                .saturating_sub(d.unsigned_abs() as usize);
        } else {
            app.agents_panel_scroll = app.agents_panel_scroll.saturating_add(d as usize);
        }
        return;
    }
    // qa-feature 2026-07-01 — wheel over the Integrations panel
    // scrolls its icon list. Bumps by 3 rows per notch (one icon
    // row) since each entry is 3 cells tall.
    if app.active_section == crate::app::ActivitySection::Integrations
        && let Some(ar) = app.rects.integrations_panel_area
        && contains(ar, x, y)
    {
        // 2026-08-05 — write to the tab-specific scroll field so
        // Installed / Marketplace remember independent positions.
        let d = list_scroll_clamp(delta);
        let step = 3usize;
        let target: &mut usize = match app.integrations_panel_tab {
            crate::app::IntegrationsPanelTab::Installed => {
                &mut app.integrations_panel_scroll_installed
            }
            crate::app::IntegrationsPanelTab::Marketplace => {
                &mut app.integrations_panel_scroll_marketplace
            }
            crate::app::IntegrationsPanelTab::InDev => &mut app.integrations_panel_scroll_in_dev,
        };
        if d < 0 {
            *target = target.saturating_sub(step * d.unsigned_abs() as usize);
        } else {
            *target = target.saturating_add(step * d as usize);
        }
        return;
    }
    // HTTP panel — wheel over a CAPTURED / RECENT row scrolls that
    // section past the SECTION_ROW_CAP visible slot. Checked BEFORE
    // the general tree wheel so a scroll over the panel doesn't
    // fall through and move the file-tree cursor. 2026-07-07.
    if app.active_section == crate::app::ActivitySection::Http {
        let d = list_scroll_clamp(delta);
        let bump = |cur: &mut usize, d: i32| {
            if d < 0 {
                *cur = cur.saturating_sub(d.unsigned_abs() as usize);
            } else {
                *cur = cur.saturating_add(d as usize);
            }
        };
        if app
            .rects
            .http_panel_captured_rows
            .iter()
            .any(|(r, _)| contains(*r, x, y))
        {
            bump(&mut app.http_panel_captured_scroll, d);
            return;
        }
        if app
            .rects
            .http_panel_recent_rows
            .iter()
            .any(|(r, _)| contains(*r, x, y))
        {
            bump(&mut app.http_panel_recent_scroll, d);
            return;
        }
        if app
            .rects
            .http_panel_mock_rows
            .iter()
            .any(|(r, _)| contains(*r, x, y))
        {
            bump(&mut app.http_panel_mocks_scroll, d);
            return;
        }
        if app
            .rects
            .http_panel_chain_rows
            .iter()
            .any(|(r, _)| contains(*r, x, y))
        {
            bump(&mut app.http_panel_chains_scroll, d);
            return;
        }
        if app
            .rects
            .http_panel_collection_folder_rows
            .iter()
            .any(|(r, _)| contains(*r, x, y))
            || app
                .rects
                .http_panel_collection_rows
                .iter()
                .any(|(r, _)| contains(*r, x, y))
        {
            bump(&mut app.http_panel_collections_scroll, d);
            return;
        }
    }
    if let Some(tr) = app.rects.tree
        && contains(tr, x, y)
    {
        // qa-feature 2026-07-01 — tree wheel moves exactly ONE
        // row per dispatched batch. Was: `list_scroll_clamp` +
        // per-line loop, which on macOS smooth-scrolling fires
        // several ScrollDown events per physical mouse notch —
        // the coalescer packs them into a batch of N, we moved
        // N rows, and the user saw the cursor skip 2-3 rows per
        // notch. Trackpad swipes still feel smooth because
        // separate physical swipes still produce separate
        // dispatches; only the WITHIN-batch amplification is
        // gone.
        if delta < 0 {
            app.tree.move_up();
        } else {
            app.tree.move_down();
        }
        return;
    }
    // qa-feature 2026-06-30 — wheel over the GIT palette area
    // (any row registered by git_palette::draw). Best-practice
    // sidebar scrolling would page the palette itself; until that
    // lands, route the wheel to the active GitGraph pane's
    // commits so the wheel does the obvious thing after clicking
    // a branch (scroll the commit list it just jumped to).
    if app.active_section == crate::app::ActivitySection::Git
        && let Some((row_rect, _)) = app.rects.git_palette_rows.first()
    {
        // Build the palette bounding box from row rects. If any
        // row contains the click point, treat as a palette hit.
        let bbox_x = row_rect.x;
        let bbox_w = row_rect.width;
        let bbox_y0 = app
            .rects
            .git_palette_rows
            .iter()
            .map(|(r, _)| r.y)
            .min()
            .unwrap_or(row_rect.y);
        let bbox_y1 = app
            .rects
            .git_palette_rows
            .iter()
            .map(|(r, _)| r.y)
            .max()
            .unwrap_or(row_rect.y);
        if x >= bbox_x && x < bbox_x + bbox_w && y >= bbox_y0 && y <= bbox_y1 {
            // Find the first open GitGraph pane and scroll it.
            for pane in app.panes.iter_mut() {
                if let crate::pane::Pane::GitGraph(g) = pane {
                    let d = list_scroll_clamp(delta);
                    g.move_selection(d as isize);
                    return;
                }
            }
        }
    }
    // Wheel over an extra workspace's tree body (the file list under
    // `> name`) → scroll that extra's tree cursor.
    if let Some(&(_, ws_idx, _)) = app
        .rects
        .extra_workspace_bodies
        .iter()
        .find(|(r, _, _)| contains(*r, x, y))
    {
        // qa-feature 2026-07-01 — 1 row per dispatched batch,
        // matching the primary tree fix above (avoids the
        // smooth-scrolling cursor-skip on macOS).
        if let Some(ws) = app.extra_workspaces.get_mut(ws_idx) {
            if delta < 0 {
                ws.tree.move_up();
            } else {
                ws.tree.move_down();
            }
        }
        return;
    }
    // Wheel over the GIT section header → cycle the active repo in
    // multi-repo workspaces (no-op when there's only one repo, so the
    // wheel falls through to the next rect). Up = previous, Down = next
    // — matches the bufferline / tab-strip wheel convention.
    if let Some(hr) = app.rects.git_section_toggle
        && contains(hr, x, y)
        && app.repos.len() > 1
    {
        app.cycle_active_repo(delta > 0);
        return;
    }
    // Wheel over any row in the GIT section → scroll the git rail cursor.
    if app
        .rects
        .git_rail_rows
        .iter()
        .any(|(r, _)| contains(*r, x, y))
    {
        let d = list_scroll_clamp(delta);
        for _ in 0..d.unsigned_abs() {
            if d < 0 {
                app.git_rail_move_up();
            } else {
                app.git_rail_move_down();
            }
        }
        return;
    }
    // Wheel over the bufferline → scroll the tab strip by one per tick.
    if let Some(br) = app.rects.bufferline
        && contains(br, x, y)
    {
        if delta < 0 {
            app.bufferline_first_visible = app.bufferline_first_visible.saturating_sub(1);
        } else if app.bufferline_first_visible + 1 < app.panes.len() {
            app.bufferline_first_visible += 1;
        }
        return;
    }
    // Scroll whichever split leaf is under the pointer (not necessarily the focused one).
    if let Some(&(tr, pid)) = app
        .rects
        .editor_panes
        .iter()
        .find(|(r, _)| contains(*r, x, y))
    {
        // Resolved before the &mut borrow on `app.panes` so the editor
        // arm below can branch on it without a second borrow on `app`.
        let follows_cursor = app.cursor_follows_wheel();
        let vp = (tr.height as usize).max(1);
        // Editor / md-preview / diff bodies amplify the per-tick
        // wheel delta — page-like scrolling at the natural rate
        // (tui.rs passes ±1 per tick; multiplying by EDITOR_WHEEL_GAIN
        // restores the prior "3 lines per tick" feel).
        const EDITOR_WHEEL_GAIN: usize = 3;
        match app.panes.get_mut(pid) {
            Some(Pane::Editor(b)) => {
                // Two policies per `[editor] wheel_moves_cursor`:
                //   - cursor follows ⇒ apply MoveUp/MoveDown N times;
                //     the renderer's keep-cursor-in-view clamp pulls
                //     `scroll` along with the cursor (vim canon, same
                //     as `Ctrl+E` / `Ctrl+Y`).
                //   - cursor pinned ⇒ write `scroll` directly and set
                //     `scroll_pinned` so the renderer skips the clamp
                //     this frame. Cursor stays where it was — may
                //     leave the viewport. Cleared the moment cursor
                //     moves (VS Code / Sublime canon).
                let n = delta.unsigned_abs() as usize * EDITOR_WHEEL_GAIN;
                if follows_cursor {
                    let op = if delta < 0 {
                        EditOp::MoveUp
                    } else {
                        EditOp::MoveDown
                    };
                    for _ in 0..n {
                        b.editor.apply(op.clone(), vp, &mut app.clipboard);
                    }
                } else {
                    b.scroll = if delta < 0 {
                        b.scroll.saturating_sub(n)
                    } else {
                        // Cap so we don't scroll past EOF. The "leave
                        // the last line on screen" tail-guard lives in
                        // the renderer.
                        let max = b.editor.line_count().saturating_sub(1);
                        (b.scroll + n).min(max)
                    };
                    b.scroll_pinned = true;
                }
            }
            Some(Pane::MdPreview(p)) => {
                let n = delta.unsigned_abs() as usize * EDITOR_WHEEL_GAIN;
                p.scroll = if delta < 0 {
                    p.scroll.saturating_sub(n)
                } else {
                    p.scroll + n
                };
            }
            Some(Pane::Diff(d)) => {
                let n = delta.unsigned_abs() as usize * EDITOR_WHEEL_GAIN;
                d.scroll = if delta < 0 {
                    d.scroll.saturating_sub(n)
                } else {
                    d.scroll + n
                };
            }
            Some(Pane::Request(rp)) => {
                let n = delta.unsigned_abs() as usize;
                rp.scroll = if delta < 0 {
                    rp.scroll.saturating_sub(n)
                } else {
                    rp.scroll + n
                };
            }
            Some(Pane::Pty(s)) => s.scroll_history(if delta < 0 {
                delta.unsigned_abs() as isize
            } else {
                -(delta.unsigned_abs() as isize)
            }),
            Some(Pane::Ai(a)) => {
                let n = delta.unsigned_abs() as usize;
                a.scroll = if delta < 0 {
                    a.scroll.saturating_sub(n)
                } else {
                    a.scroll + n
                };
            }
            Some(Pane::Tests(t)) => {
                let n = delta.unsigned_abs() as usize;
                t.scroll = if delta < 0 {
                    t.scroll.saturating_sub(n)
                } else {
                    t.scroll + n
                };
            }
            Some(Pane::GitGraph(g)) => {
                // Wheel over the embedded diff (file picked from the
                // right-side detail panel) scrolls the diff body
                // instead of moving the commit-list selection.
                if let Some(d) = g.embedded_diff.as_mut() {
                    let n = delta.unsigned_abs() as usize;
                    d.scroll = if delta < 0 {
                        d.scroll.saturating_sub(n)
                    } else {
                        d.scroll + n
                    };
                } else {
                    g.move_selection(if delta < 0 {
                        -(delta.unsigned_abs() as isize)
                    } else {
                        delta.unsigned_abs() as isize
                    });
                }
            }
            Some(Pane::GitStatus(g)) => {
                g.move_selection(if delta < 0 {
                    -(delta.unsigned_abs() as isize)
                } else {
                    delta.unsigned_abs() as isize
                });
            }
            Some(Pane::Diagnostics(d)) => {
                d.move_selection(if delta < 0 {
                    -(delta.unsigned_abs() as isize)
                } else {
                    delta.unsigned_abs() as isize
                });
            }
            Some(Pane::Grep(g)) => {
                g.move_selection(if delta < 0 {
                    -(delta.unsigned_abs() as isize)
                } else {
                    delta.unsigned_abs() as isize
                });
            }
            // `Pane::Trace` wheel-scroll moved to mnml-test-playwright.
            Some(Pane::Browser(b)) => {
                let step = if delta < 0 {
                    -(delta.unsigned_abs() as isize)
                } else {
                    delta.unsigned_abs() as isize
                };
                if b.dom_focus {
                    b.move_dom_sel(step);
                } else if b.net_focus {
                    b.move_net_sel(step);
                } else if b.cookies_focus {
                    b.move_cookies_sel(step);
                } else if b.storage_focus {
                    b.move_storage_sel(step);
                } else {
                    let n = delta.unsigned_abs() as usize;
                    b.scroll = if delta < 0 {
                        b.scroll.saturating_sub(n)
                    } else {
                        b.scroll.saturating_add(n)
                    };
                }
            }
            Some(Pane::Flaky(f)) => {
                f.move_selection(if delta < 0 {
                    -(delta.unsigned_abs() as isize)
                } else {
                    delta.unsigned_abs() as isize
                });
            }
            Some(Pane::Outline(o)) => {
                o.move_selection(if delta < 0 {
                    -(delta.unsigned_abs() as isize)
                } else {
                    delta.unsigned_abs() as isize
                });
            }
            Some(Pane::CmdlineHistory(h)) => {
                h.move_selection(if delta < 0 {
                    -(delta.unsigned_abs() as isize)
                } else {
                    delta.unsigned_abs() as isize
                });
            }
            Some(Pane::Quickfix(g)) => {
                g.move_selection(if delta < 0 {
                    -(delta.unsigned_abs() as isize)
                } else {
                    delta.unsigned_abs() as isize
                });
            }
            // AWS CodeBuild + LogTail wheel-scroll moved to
            // mnml-aws-codebuild; pipeline-log + SCM wheel-scroll
            // moved to the mnml-forge-* integrations.
            Some(Pane::Cheatsheet(c)) => {
                if delta < 0 {
                    c.move_up();
                } else {
                    c.move_down();
                }
            }
            Some(Pane::Debug(p)) => {
                // Wheel moves whichever sub-section currently has
                // keyboard focus — same routing rule as j/k.
                let d = delta.signum() as isize;
                let n = delta.unsigned_abs() as isize;
                let section = p.section;
                match section {
                    crate::pane::DebugSection::Stack => app.debug_pane_move(d * n),
                    crate::pane::DebugSection::Variables => app.debug_pane_vars_move(d * n),
                }
            }
            Some(Pane::DapRepl(_)) => {
                // Scroll the history. usize::MAX ⇒ pinned to tail;
                // any upward scroll lands at a concrete index.
                let mag = delta.unsigned_abs() as usize;
                if delta < 0 {
                    if let Some(Pane::DapRepl(p)) = app.panes.get_mut(pid) {
                        let total = p.history.len();
                        let cur = if p.scroll == usize::MAX {
                            total
                        } else {
                            p.scroll
                        };
                        p.scroll = cur.saturating_sub(mag);
                    }
                } else if let Some(Pane::DapRepl(p)) = app.panes.get_mut(pid) {
                    let total = p.history.len();
                    let new = if p.scroll == usize::MAX {
                        usize::MAX
                    } else {
                        let next = p.scroll.saturating_add(mag);
                        if next >= total { usize::MAX } else { next }
                    };
                    p.scroll = new;
                }
            }
            Some(Pane::Image(_)) => {
                // Nothing to scroll — the image pane is "what you see is
                // what you get". Future v2 could pan a too-large image.
            }
            Some(Pane::ClaudeAgents(p)) => {
                // Scroll the rows by delta.
                for _ in 0..delta.unsigned_abs() {
                    if delta < 0 {
                        p.move_up();
                    } else {
                        p.move_down();
                    }
                }
            }
            Some(Pane::Websocket(p)) => {
                // Wheel scrolls the log view; clamped in the
                // renderer so we just bump the offset here.
                let step = delta.unsigned_abs() as usize;
                if delta < 0 {
                    p.scroll = p.scroll.saturating_add(step);
                } else {
                    p.scroll = p.scroll.saturating_sub(step);
                }
            }
            Some(Pane::SpendReport(p)) => {
                // Wheel scrolls the per-workspace list; renderer
                // clamps. Selection follows.
                let step = delta.unsigned_abs() as usize;
                let n = p.snapshot.per_workspace.len();
                if n > 0 {
                    if delta < 0 {
                        p.selected = p.selected.saturating_sub(step);
                    } else {
                        p.selected = (p.selected + step).min(n - 1);
                    }
                }
            }
            Some(Pane::Mount(m)) => {
                // Forward as a scroll event — integration decides what
                // to do with it (scroll a list, change a chart, …).
                m.send_input(mnml_bridge::InputEvent::Scroll {
                    col: 0,
                    row: 0,
                    dy: delta as i16,
                });
            }
            Some(Pane::NewCloudAgentWizard(_)) | Some(Pane::NewCloudRunWizard(_)) => {
                // Wizard pane content is short and fits a single
                // page; no scroll affordance needed for v1.
            }
            Some(Pane::IntegrationDetail(p)) => {
                // 2026-08-07 — wheel scrolls the pane body (README +
                // description overflow). Was: walked the actionable-
                // row cursor, which meant the pane's long README was
                // unreachable — user reported "I can only see one
                // page of the description, no scrolling or arrowing
                // will let me go downward". Keyboard ↑/↓ still walks
                // the cursor for button/link selection.
                if delta < 0 {
                    p.scroll = p.scroll.saturating_sub(delta.unsigned_abs() as usize);
                } else {
                    p.scroll = p.scroll.saturating_add(delta as usize);
                }
            }
            Some(Pane::ClaudeUsage(p)) => {
                if delta < 0 {
                    p.scroll = p.scroll.saturating_sub(delta.unsigned_abs() as usize);
                } else {
                    p.scroll = p.scroll.saturating_add(delta as usize);
                }
            }
            Some(Pane::CodexUsage(p)) => {
                if delta < 0 {
                    p.scroll = p.scroll.saturating_sub(delta.unsigned_abs() as usize);
                } else {
                    p.scroll = p.scroll.saturating_add(delta as usize);
                }
            }
            Some(Pane::CloudAgentRun(p)) => {
                // Scroll the logs viewport. Negative delta = scroll up
                // (older lines); positive = down. Crossing past the
                // tail re-enables follow.
                let n = delta.unsigned_abs() as usize;
                if delta < 0 {
                    if p.log_scroll == usize::MAX {
                        // Currently following — start at the tail and
                        // back off `n` lines.
                        p.log_scroll = p.logs.len().saturating_sub(n);
                    } else {
                        p.log_scroll = p.log_scroll.saturating_sub(n);
                    }
                    p.log_follow = false;
                } else {
                    let max = p.logs.len();
                    let new = p.log_scroll.saturating_add(n).min(max);
                    if new >= max.saturating_sub(1) {
                        p.log_scroll = usize::MAX;
                        p.log_follow = true;
                    } else {
                        p.log_scroll = new;
                    }
                }
            }
            None => {}
        }
        // Each SCM/CI pane's max_idx depends on which view-mode is
        // active — same trap as the key handlers above (flat must match
        // the rendered layout).
        // GitLab pane wheel-scroll moved to mnml-forge-gitlab.
        let _ = delta;
        let _ = pid;
    }
}

pub(crate) fn contains(r: Rect, x: u16, y: u16) -> bool {
    x >= r.x && x < r.x.saturating_add(r.width) && y >= r.y && y < r.y.saturating_add(r.height)
}

/// Mouse click on a list-style pane row. Dispatches based on the pane
/// at `pane_id`. `flat_idx` is the index into either the active view's
/// flatten output (SCM/CI panes) or directly into the pane's items vec
/// (plain list panes). `is_double_click` ⇒ trigger the primary action.
pub(crate) fn handle_scm_row_click(
    app: &mut App,
    pane_id: usize,
    flat_idx: usize,
    is_double_click: bool,
) {
    use crate::pane::Pane;
    // Plain list panes — set selected, optionally fire primary action.
    if matches!(app.panes.get(pane_id), Some(Pane::Diagnostics(_))) {
        if let Some(Pane::Diagnostics(d)) = app.panes.get_mut(pane_id) {
            // flat_idx is the index into visible (filtered) rows.
            let n = d.visible_indices().len();
            if flat_idx < n {
                d.selected = flat_idx;
            }
        }
        if is_double_click {
            app.jump_to_selected_diagnostic();
        }
        return;
    }
    if matches!(app.panes.get(pane_id), Some(Pane::Outline(_))) {
        if let Some(Pane::Outline(o)) = app.panes.get_mut(pane_id) {
            let len = o.visible_indices().len();
            if flat_idx < len {
                o.selected = flat_idx;
            }
        }
        if is_double_click {
            app.jump_to_selected_outline();
        }
        return;
    }
    if matches!(app.panes.get(pane_id), Some(Pane::Flaky(_))) {
        if let Some(Pane::Flaky(f)) = app.panes.get_mut(pane_id)
            && flat_idx < f.items.len()
        {
            f.selected = flat_idx;
        }
        if is_double_click {
            app.jump_to_selected_flaky();
        }
        return;
    }
    if matches!(app.panes.get(pane_id), Some(Pane::Diff(_))) {
        if let Some(Pane::Diff(d)) = app.panes.get_mut(pane_id)
            && flat_idx < d.hunks.len()
        {
            d.cursor = flat_idx;
            // In Hunk mode, clicking a hunk row also toggles its
            // collapse (expanded-by-default — click chevron to
            // collapse one you don't need).
            if d.view_mode == crate::pane::DiffViewMode::Hunk {
                if d.hunk_collapsed.contains(&flat_idx) {
                    d.hunk_collapsed.remove(&flat_idx);
                } else {
                    d.hunk_collapsed.insert(flat_idx);
                }
            }
        }
        if is_double_click {
            app.jump_to_cursor_hunk();
        }
        return;
    }
    // CodeBuilds click handler moved to mnml-aws-codebuild.
    if matches!(app.panes.get(pane_id), Some(Pane::GitGraph(_))) {
        if let Some(Pane::GitGraph(g)) = app.panes.get_mut(pane_id) {
            // `flat_idx` is the *virtual* row index (0 = WIP if present,
            // then commits). `jump_to` clamps to total_rows AND calls
            // `reload_detail` so the right-side panel actually populates
            // — directly assigning `selected` skipped the reload, leaving
            // the detail empty after a click.
            g.jump_to(flat_idx);
        }
        if is_double_click {
            app.open_selected_commit_diff();
        }
        return;
    }
    if matches!(app.panes.get(pane_id), Some(Pane::Cheatsheet(_))) {
        if let Some(Pane::Cheatsheet(c)) = app.panes.get_mut(pane_id) {
            let n = c.visible_rows_len();
            if flat_idx < n {
                c.selected = flat_idx;
            }
        }
        if is_double_click {
            app.cheatsheet_run_selected();
        }
        return;
    }
    if matches!(app.panes.get(pane_id), Some(Pane::CmdlineHistory(_))) {
        if let Some(Pane::CmdlineHistory(h)) = app.panes.get_mut(pane_id)
            && flat_idx < h.entries.len()
        {
            h.selected = flat_idx;
        }
        if is_double_click {
            app.cmdline_history_accept();
        }
        return;
    }
    if matches!(app.panes.get(pane_id), Some(Pane::ClaudeAgents(_))) {
        if let Some(Pane::ClaudeAgents(p)) = app.panes.get_mut(pane_id) {
            let n = p.visible_indices().len();
            if flat_idx < n {
                p.selected = flat_idx;
                // claude-agents-power-user 2026-06-28 finding 2:
                // mouse click parity with keyboard nav — reset
                // detail_scroll so the new row's drill-down view
                // starts at the top instead of inheriting the
                // previous row's scroll offset.
                p.detail_scroll = 0;
            }
        }
        if is_double_click {
            app.claude_agents_action(crate::claude_agents::ClaudeAgentsAction::OpenTranscript);
        }
        return;
    }
    if matches!(app.panes.get(pane_id), Some(Pane::Tests(_))) {
        if let Some(Pane::Tests(t)) = app.panes.get_mut(pane_id)
            && let crate::playwright::TestsState::Done(r) = &t.state
            && flat_idx < r.tests.len()
        {
            t.selected = flat_idx;
        }
        if is_double_click {
            app.jump_to_selected_test();
        }
        return;
    }
    if matches!(app.panes.get(pane_id), Some(Pane::GitStatus(_))) {
        if let Some(Pane::GitStatus(g)) = app.panes.get_mut(pane_id) {
            let total = g.unstaged.len() + g.staged.len();
            if flat_idx < total {
                g.selected = flat_idx;
            }
        }
        if is_double_click {
            app.git_status_open_diff();
        }
        return;
    }
    if matches!(
        app.panes.get(pane_id),
        Some(Pane::Grep(_)) | Some(Pane::Quickfix(_))
    ) {
        // Both share the GrepPane struct; treat them identically.
        let len = match app.panes.get(pane_id) {
            Some(Pane::Grep(g)) | Some(Pane::Quickfix(g)) => g.hits.len(),
            _ => 0,
        };
        if let Some(pane) = app.panes.get_mut(pane_id) {
            let target = match pane {
                Pane::Grep(g) | Pane::Quickfix(g) => Some(g),
                _ => None,
            };
            if let Some(g) = target
                && flat_idx < len
            {
                g.selected = flat_idx;
            }
        }
        if is_double_click {
            app.jump_to_selected_grep_hit();
        }
        return;
    }
    // Browser sub-panels — clicks select the row inside whichever panel
    // is focused (network / DOM / cookies / storage). Double-click on a
    // network row opens it as a Request pane (sibling to Enter).
    if matches!(app.panes.get(pane_id), Some(Pane::Browser(_))) {
        let net_double_open = {
            let Some(Pane::Browser(b)) = app.panes.get_mut(pane_id) else {
                return;
            };
            if b.dom_focus {
                let n = b.visible_dom_indices().len();
                if flat_idx < n {
                    b.set_dom_sel(flat_idx);
                }
                false
            } else if b.cookies_focus {
                if flat_idx < b.cookies.len() {
                    b.cookies_sel = flat_idx;
                }
                false
            } else if b.storage_focus {
                if flat_idx < b.storage.len() {
                    b.storage_sel = flat_idx;
                }
                false
            } else if b.net_focus {
                let n = b.visible_net_indices().len();
                if flat_idx < n {
                    b.net_sel = flat_idx;
                }
                is_double_click
            } else {
                false
            }
        };
        if net_double_open {
            app.open_net_entry_as_request();
        }
        return;
    }
    // SCM/CI pane click dispatch moved with the panes themselves to
    // their standalone mnml-forge-* integration binaries.
    let _ = (app, pane_id);
}

/// Translate a key event into the byte sequence a pty child expects (xterm-ish).
pub(crate) fn pty_key_bytes(key: KeyEvent) -> Vec<u8> {
    let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
    let alt = key.modifiers.contains(KeyModifiers::ALT);
    let prefix_alt = |b: Vec<u8>| {
        if alt {
            let mut v = vec![0x1b];
            v.extend(b);
            v
        } else {
            b
        }
    };
    match key.code {
        KeyCode::Char(c) => {
            if ctrl {
                // Control char: letters → 1..26, plus the usual @ [ \ ] ^ _.
                let b = match c.to_ascii_lowercase() {
                    'a'..='z' => Some((c.to_ascii_lowercase() as u8) - b'a' + 1),
                    ' ' | '@' => Some(0),
                    '[' => Some(0x1b),
                    '\\' => Some(0x1c),
                    ']' => Some(0x1d),
                    '^' => Some(0x1e),
                    '_' | '?' => Some(0x1f),
                    _ => None,
                };
                match b {
                    Some(b) => prefix_alt(vec![b]),
                    None => prefix_alt(c.to_string().into_bytes()),
                }
            } else {
                prefix_alt(c.to_string().into_bytes())
            }
        }
        KeyCode::Enter => prefix_alt(vec![b'\r']),
        KeyCode::Tab => prefix_alt(vec![b'\t']),
        KeyCode::BackTab => b"\x1b[Z".to_vec(),
        KeyCode::Backspace => prefix_alt(vec![0x7f]),
        KeyCode::Esc => vec![0x1b],
        KeyCode::Up => b"\x1b[A".to_vec(),
        KeyCode::Down => b"\x1b[B".to_vec(),
        KeyCode::Right => b"\x1b[C".to_vec(),
        KeyCode::Left => b"\x1b[D".to_vec(),
        KeyCode::Home => b"\x1b[H".to_vec(),
        KeyCode::End => b"\x1b[F".to_vec(),
        KeyCode::PageUp => b"\x1b[5~".to_vec(),
        KeyCode::PageDown => b"\x1b[6~".to_vec(),
        KeyCode::Insert => b"\x1b[2~".to_vec(),
        KeyCode::Delete => b"\x1b[3~".to_vec(),
        KeyCode::F(n @ 1..=4) => format!("\x1bO{}", (b'P' + (n - 1)) as char).into_bytes(),
        KeyCode::F(n) => {
            // xterm "modifyOtherKeys"-ish CSI for F5..F12.
            let code = match n {
                5 => 15,
                6 => 17,
                7 => 18,
                8 => 19,
                9 => 20,
                10 => 21,
                11 => 23,
                12 => 24,
                _ => return Vec::new(),
            };
            format!("\x1b[{code}~").into_bytes()
        }
        _ => Vec::new(),
    }
}