quadraui 0.6.0

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
//! In-process headless test driver for [`AppLogic`] TUI apps.
//!
//! [`TuiDriver`] drives a *whole* [`AppLogic`] impl — the same type the
//! shipping `tui_*` examples instantiate — through the real
//! event → `handle` → `render` path, but against ratatui's in-memory
//! [`TestBackend`] instead of a live terminal. No TTY, no pty: it runs
//! under `cargo test` and is deterministic.
//!
//! ## What it tests that the primitive round-trips don't
//!
//! The per-primitive paint/click round-trips (e.g. `tui/tree.rs::tests`)
//! call a single `draw_*` fn on a hand-built struct and assert on the
//! buffer + the `hit_test` return value. They never construct an app,
//! never dispatch a [`UiEvent`] through [`AppLogic::handle`], and never
//! touch the run loop. [`TuiDriver`] tests the *example's wiring*: feed
//! a keystroke or a click, observe the re-rendered screen. It catches a
//! handler routing a click to the wrong target, a missing
//! [`Reaction::Redraw`], or stale state — none of which the primitive
//! tests can see.
//!
//! ## No drift from production
//!
//! [`Self::render`] and [`Self::dispatch`] call the same
//! [`super::run::render_frame`] / [`super::run::dispatch_event`] the live
//! runner uses, so the test path renders and pre-processes events
//! (text-selection, Ctrl-C copy) identically to `tui::run`. Mouse input
//! is a direct [`UiEvent::MouseDown`] in backend coordinates — no SGR
//! escape-sequence math, which is the ergonomic win over a pty runner
//! for click-heavy primitives.
//!
//! ## Limitations
//!
//! It renders into a `TestBackend` buffer, so it does **not** exercise
//! real ANSI/escape emission — terminal-protocol bugs (raw-mode setup,
//! escape parsing, SGR mouse decoding) are out of scope and need a
//! pty-based smoke test instead.
//!
//! ```no_run
//! # use quadraui::tui::testing::TuiDriver;
//! # use quadraui::{AppLogic, Backend, Reaction, UiEvent};
//! # fn demo<A: AppLogic + Default>() {
//! let mut driver = TuiDriver::new(A::default(), 100, 30);
//! driver.type_char('x');
//! assert!(driver.screen_contains("…"));
//! # }
//! ```

use std::cell::RefCell;
use std::rc::Rc;

use ratatui::backend::TestBackend;
use ratatui::Terminal;

/// Re-exported so a downstream test crate can name `Color`/`Modifier` (e.g.
/// `style.modifiers.contains(Modifier::ITALIC)`) without adding its own
/// `ratatui` dependency — it already depends on `quadraui` to get
/// [`TuiDriver`]. Scoped to `tui::testing` rather than the crate root to
/// avoid colliding with [`crate::types::Color`], which is re-exported there
/// already.
pub use ratatui::style::{Color, Modifier};

use crate::backend::Backend;
use crate::runner::{AppLogic, Reaction};
use crate::shell::{ShellApp, ShellConfig};
use crate::testing::driver_core::DriverCore;
use crate::testing::{
    Anchor, ConformanceDriver, DriverInput, FrameInventory, LogicalViewport, TextRun,
};
use crate::tui::backend::TuiBackend;
use crate::tui::run::{dispatch_event, render_frame, EventOutcome};
use crate::tui::text::char_cell_width;
use crate::{
    ButtonMask, Key, Modifiers, MouseButton, NamedKey, Point, Rect, ScrollDelta, UiEvent, WidgetId,
};

/// Build a [`TuiDriver`] that wraps `app` in the full
/// [`crate::shell_adapter::ShellAdapter`] stack, mirroring exactly what
/// [`crate::tui::shell_runner::run_with_shell`] does at runtime — but
/// returning a testable driver instead of entering the live event loop.
///
/// Use this constructor in tests that need to verify the full
/// `ShellApp → ShellAdapter → dispatch_event` integration path, e.g.
/// confirming that `register_text_region()` is reached via
/// `ShellAdapter::render()` and that the selection pipeline (drag → Ctrl-C)
/// works end-to-end for `run_with_shell` callers.
///
/// # Example
///
/// ```no_run
/// # use quadraui::tui::testing::driver_with_shell;
/// # use quadraui::{ShellApp, ShellConfig, Backend, ShellContext, Reaction, UiEvent};
/// # struct MyApp;
/// # impl ShellApp for MyApp {
/// #     fn render_content(&self, _: &mut dyn Backend, _: &quadraui::compose::app_shell::AppShellLayout) {}
/// #     fn handle(&mut self, _: UiEvent, _: &mut dyn Backend, _: &ShellContext) -> Reaction { Reaction::Continue }
/// # }
/// let config = ShellConfig::new("Demo", vec![]);
/// let mut driver = driver_with_shell(MyApp, config, 80, 24);
/// assert!(driver.screen_contains("Demo"));
/// ```
pub fn driver_with_shell<A: ShellApp + 'static>(
    app: A,
    config: ShellConfig,
    width: u16,
    height: u16,
) -> TuiDriver<impl AppLogic> {
    let adapter = crate::shell_adapter::build_shell_adapter(app, config);
    TuiDriver::new(adapter, width, height)
}

/// The style painted onto one rendered cell: foreground, background, and
/// text modifiers (bold/italic/underline/…).
///
/// Mirrors `ratatui::buffer::Cell::style()`'s three fields but drops the
/// `sub_modifier`/`underline_color` ratatui carries for *diffing* two
/// styles against each other — a rendered cell has no "subtracted"
/// modifiers, only the resolved `add_modifier` bits ratatui reports back as
/// [`Modifier`], which is what a driver test wants to assert against.
/// `fg`/`bg` are ratatui's own [`Color`] (re-exported as
/// [`self::Color`], see [`TuiDriver::style_at`]) rather than
/// `quadraui::types::Color` because that's what the rasterisers actually
/// paint into the buffer — comparing against a theme token means wrapping
/// the token with [`crate::tui::ratatui_color`] first.
///
/// `#[non_exhaustive]`: fields may grow (e.g. `underline_color`, dropped
/// from this first cut — see above) without that being a breaking change
/// for callers. `CellStyle` is only ever returned, never constructed, by
/// consumers, so this only forbids exhaustive destructuring, not field
/// access.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct CellStyle {
    pub fg: Color,
    pub bg: Color,
    pub modifiers: Modifier,
}

/// Drives an [`AppLogic`] impl headlessly for tests.
///
/// Construct with [`Self::new`] (which runs `setup` + paints the first
/// frame), poke it with [`Self::press`] / [`Self::type_char`] /
/// [`Self::press_named`] / [`Self::click`], and read the rendered grid
/// back with [`Self::screen`] / [`Self::screen_contains`] / [`Self::find`],
/// or its style with [`Self::style_at`] / [`Self::styled_row`].
pub struct TuiDriver<A: AppLogic> {
    core: DriverCore<TuiBackend, A>,
    terminal: Rc<RefCell<Terminal<TestBackend>>>,
}

impl<A: AppLogic> TuiDriver<A> {
    /// Build a driver for `app` on a `width`×`height` cell grid, run the
    /// app's `setup` hook, and paint the first frame.
    pub fn new(app: A, width: u16, height: u16) -> Self {
        let terminal =
            Terminal::new(TestBackend::new(width, height)).expect("TestBackend terminal");
        let terminal = Rc::new(RefCell::new(terminal));
        let mut backend = TuiBackend::new();
        // Wire the same `Terminal` this driver renders through as the
        // nested dialog loop's paint target — see
        // `tui::services`'s module doc, "Dialogs" section. Lets a test
        // drive `PlatformServices::show_file_open_dialog` et al. through
        // a real `AppLogic` via [`Self::queue_dialog_events`], the same
        // shape `super::run::run_with` wires for the live runner.
        let dialog_surface: Rc<RefCell<dyn crate::tui::services::DialogSurface>> = terminal.clone();
        backend.tui_services().set_dialog_surface(dialog_surface);
        // Default to **scripted** dialog mode with an empty queue, not
        // "read real crossterm input": an empty
        // `scripted_dialog_events` still synthesizes a single Escape on
        // the nested loop's first iteration (see
        // `TuiPlatformServices::next_dialog_events`), so a dialog opened
        // without a prior `Self::queue_dialog_events` call resolves
        // immediately via Escape instead of blocking on
        // `crossterm::event::poll` against this *process's* real stdin —
        // which under `cargo test` has no controlling terminal and would
        // otherwise spin the nested loop forever (`poll` erroring
        // immediately, over and over, with nothing to wait on). A test
        // that wants real scripted input calls `queue_dialog_events`
        // before triggering the dialog, same as always.
        backend
            .tui_services()
            .queue_dialog_events(std::iter::empty());
        // Seed the viewport from the driver's terminal size BEFORE setup,
        // exactly as the live runner does. Without this,
        // `app.setup()` would read the default 80×24 viewport instead of
        // the requested `width`×`height`, so any setup-time sizing (e.g.
        // `TerminalApp` spawning its PTY) would use the wrong dimensions.
        backend.begin_frame(crate::Viewport::new(width as f32, height as f32, 1.0));
        let mut app = app;
        app.setup(&mut backend);
        let mut driver = Self {
            core: DriverCore::new(app, backend),
            terminal,
        };
        driver.render();
        driver
    }

    /// Seed the nested dialog loop's scripted input — see
    /// [`crate::tui::services::TuiPlatformServices::queue_dialog_events`].
    /// Must be called *before* the event that triggers a
    /// `show_file_open_dialog`/`show_file_save_dialog`/
    /// `show_message_dialog` call — the loop resolves synchronously
    /// inside that one [`Self::dispatch`]/[`Self::press`]-family call,
    /// with no way to be fed more input mid-call.
    pub fn queue_dialog_events(&self, events: impl IntoIterator<Item = UiEvent>) {
        self.core
            .backend()
            .tui_services()
            .queue_dialog_events(events);
    }

    /// Repaint one frame through the shared production render path.
    ///
    /// Consumes any pending [`crate::Backend::request_full_repaint`]
    /// request the same way the live runner's
    /// `tui::run::TuiRunner::step`/`pump` frame loop does — `Terminal::clear()` before
    /// this frame's `render_frame` call — so a driver test can exercise
    /// the same "next frame paints as if blank" behaviour a real terminal
    /// session gets, with no real terminal to observe the clear on
    /// directly.
    pub fn render(&mut self) {
        let full_repaint = self.core.backend_mut().take_full_repaint_requested();
        let (backend, app) = self.core.parts_mut();
        let mut terminal = self.terminal.borrow_mut();
        if full_repaint {
            terminal.clear().expect("TestBackend clear is infallible");
        }
        render_frame(&mut terminal, backend, app).expect("TestBackend render is infallible");
    }

    /// Resize the underlying `TestBackend`'s physical cell buffer to
    /// `width`×`height` — **without** touching [`TuiBackend`]'s cached
    /// [`crate::Viewport`] or any layout state a previous [`Self::render`]
    /// cached (e.g. [`Self::tab_center`]'s `cached_tab_bar_layout`). Those
    /// stay exactly as they were after the last repaint, at whatever size
    /// the driver last actually painted.
    ///
    /// This deliberately does **not** go through [`Self::render`] /
    /// `Terminal::draw`'s `autoresize`: that path re-derives `TuiBackend`'s
    /// per-frame `Viewport` from the buffer's own post-resize `frame.area()`
    /// on *every* call, so a full `Self::render` right after a resize always
    /// self-heals — a test that only ever resized-then-rendered would never
    /// observe a mismatch. To construct the exact stale-layout-vs-shrunk-buffer
    /// race a test calls this to shrink *only* the physical buffer first, then
    /// reads [`Self::backend`]'s still-stale, larger viewport (or a cached
    /// layout) to drive a click or a direct paint against it, asserting
    /// the result degrades gracefully — truncates, ignores an
    /// out-of-bounds hit — instead of panicking. Call [`Self::render`]
    /// afterward, once the test is done observing the stale state, to
    /// restore a consistent frame at the new size (it will resync
    /// `TuiBackend`'s viewport to match, same as the live runner does on a
    /// real terminal resize).
    ///
    /// Uses `ratatui::backend::TestBackend::resize` directly on the raw
    /// cell buffer; no `Terminal::resize`/`autoresize` bookkeeping
    /// (viewport area, cursor position, scrollback wiring) runs here
    /// either — this is a strictly lower-level knob than either.
    pub fn resize(&mut self, width: u16, height: u16) {
        self.terminal
            .borrow_mut()
            .backend_mut()
            .resize(width, height);
    }

    /// Feed one synthetic event through the **full production pipeline**:
    /// backend translation ([`TuiBackend::translate_injected`] — drag
    /// state, accelerator matching, double-click folding) followed by the
    /// shared [`dispatch_event`] for each resulting event. Repaints on
    /// redraw and latches `exited`. Returns the strongest [`Reaction`]
    /// (Exit > Redraw > Continue) for convenient assertions.
    ///
    /// Routing through `translate_injected` (not straight to
    /// `dispatch_event`) is what makes drag sequences work: a `MouseDown`
    /// in a registered text region begins a `TextSelection` drag, and a
    /// following `MouseMoved` is translated into `TextSelectionChanged` —
    /// exactly as `wait_events` does for real crossterm input.
    pub fn dispatch(&mut self, event: UiEvent) -> Reaction {
        if self.core.exited() {
            return Reaction::Exit;
        }
        let mut result = Reaction::Continue;
        let translated = self.core.backend_mut().translate_injected(vec![event]);
        for ev in translated {
            let outcome = {
                let (backend, app) = self.core.parts_mut();
                dispatch_event(ev, backend, app)
            };
            match &outcome {
                EventOutcome::Continue => {}
                EventOutcome::Redraw => self.render(),
                // Arm the same bookkeeping the live runner
                // would via `Backend::request_frame_in` — harmless on a
                // driver with no real timer loop, and lets a test assert
                // on `backend().frame_requests()` /
                // `backend().pending_frame_delay()` afterward.
                EventOutcome::RedrawAfter(d) => {
                    self.core.backend_mut().request_frame_in(*d);
                }
                EventOutcome::Exit => {
                    self.core.mark_exited();
                    return Reaction::Exit;
                }
            }
            // `Redraw` always wins over `RedrawAfter`, and
            // two `RedrawAfter`s in the same batch keep the *earlier*
            // deadline rather than whichever arrived first — see
            // `Reaction::merge`'s doc.
            result = result.merge(outcome.into());
        }
        result
    }

    /// Deliver every [`UiEvent::User`] payload queued via
    /// [`crate::Backend::waker`] since the last call, through the same
    /// production dispatch pipeline [`Self::dispatch`] uses.
    ///
    /// Unlike `dispatch`, this doesn't take an event — it drains
    /// [`TuiBackend::drain_user_events`] (the same `user_events` queue the
    /// live runner's `poll_events`/`wait_events` fold in) and dispatches
    /// whatever a background thread queued via `backend().waker()` in the
    /// meantime. This is the driver-tier proof that a background thread
    /// can wake the UI at all: call `backend().waker()` to get the
    /// `Send + Sync` closure, invoke it from a spawned thread, join, then
    /// call this to observe the delivery — see `tests::` in this module
    /// for the full round trip.
    pub fn pump_user_events(&mut self) -> Reaction {
        if self.core.exited() {
            return Reaction::Exit;
        }
        let events = self.core.backend_mut().drain_user_events();
        let mut result = Reaction::Continue;
        for ev in events {
            let outcome = {
                let (backend, app) = self.core.parts_mut();
                dispatch_event(ev, backend, app)
            };
            match &outcome {
                EventOutcome::Continue => {}
                EventOutcome::Redraw => self.render(),
                // See `Self::dispatch`'s identical arm.
                EventOutcome::RedrawAfter(d) => {
                    self.core.backend_mut().request_frame_in(*d);
                }
                EventOutcome::Exit => {
                    self.core.mark_exited();
                    return Reaction::Exit;
                }
            }
            // See `Self::dispatch`'s identical merge.
            result = result.merge(outcome.into());
        }
        result
    }

    /// Run one [`AppLogic::tick`], applying its [`Reaction`] exactly as
    /// the live runner's loop does.
    ///
    /// The live TUI loop calls `app.tick(backend)` once after every event
    /// batch — including the empty batch a bare poll timeout produces —
    /// and matches the returned `Reaction` the same four ways
    /// [`Self::dispatch`] matches an `EventOutcome`: nothing on
    /// `Continue`, repaint on `Redraw`, `Backend::request_frame_in` on
    /// `RedrawAfter`, latch `exited` on `Exit`. See `tui::run::TuiRunner::step`/`pump`.
    ///
    /// Time-driven app state — a spinner frame, a caret blink, a
    /// countdown, a background-job poll — lives entirely in `tick`, so
    /// without this a driver test can only ever observe an app's
    /// event-driven half. Nothing here *waits*: the driver has no event
    /// loop and no real timer, so a test drives the animation by calling
    /// this once per frame it wants to advance rather than sleeping. Pair
    /// it with [`TuiBackend::frame_requests`] /
    /// [`TuiBackend::pending_frame_delay`] (via [`Self::backend`]) to
    /// assert on the *scheduling* the app asked for, which is otherwise
    /// invisible from the painted screen.
    ///
    /// Short-circuits to [`Reaction::Exit`] once the app has exited,
    /// matching [`Self::dispatch`].
    pub fn tick(&mut self) -> Reaction {
        if self.core.exited() {
            return Reaction::Exit;
        }
        let reaction = {
            let (backend, app) = self.core.parts_mut();
            app.tick(backend)
        };
        match reaction {
            Reaction::Continue => Reaction::Continue,
            Reaction::Redraw => {
                self.render();
                Reaction::Redraw
            }
            Reaction::RedrawAfter(d) => {
                self.core.backend_mut().request_frame_in(d);
                Reaction::RedrawAfter(d)
            }
            Reaction::Exit => {
                self.core.mark_exited();
                Reaction::Exit
            }
        }
    }

    /// Press a key (no modifiers).
    pub fn press(&mut self, key: Key) -> Reaction {
        DriverInput::press(self, key)
    }

    /// Type a single character key (no modifiers).
    pub fn type_char(&mut self, c: char) -> Reaction {
        DriverInput::type_char(self, c)
    }

    /// Press a named (non-printable) key, e.g. [`NamedKey::Enter`].
    pub fn press_named(&mut self, key: NamedKey) -> Reaction {
        DriverInput::press_named(self, key)
    }

    /// Press a character key with Ctrl held (e.g. `ctrl_char('c')` to
    /// trigger the runner's copy-on-selection path).
    pub fn ctrl_char(&mut self, c: char) -> Reaction {
        DriverInput::ctrl_char(self, c)
    }

    /// Left-click at backend coordinates `(x, y)` (cell units for TUI),
    /// delivered as a [`UiEvent::MouseDown`] — the event primitives'
    /// hit-test paths consume.
    pub fn click(&mut self, x: f32, y: f32) -> Reaction {
        DriverInput::click(self, x, y)
    }

    /// Press the left mouse button down at `(x, y)`. Begins a drag if it
    /// lands on a draggable target (text region, scrollbar thumb).
    pub fn mouse_down(&mut self, x: f32, y: f32) -> Reaction {
        self.dispatch(UiEvent::MouseDown {
            widget: None,
            button: MouseButton::Left,
            position: Point::new(x, y),
            modifiers: Modifiers::default(),
        })
    }

    /// Move the cursor to `(x, y)` with the left button held. During an
    /// active drag this is translated to the drag's high-level event
    /// (e.g. [`UiEvent::TextSelectionChanged`] /
    /// [`UiEvent::ScrollOffsetChanged`]).
    pub fn mouse_move(&mut self, x: f32, y: f32) -> Reaction {
        self.dispatch(UiEvent::MouseMoved {
            position: Point::new(x, y),
            buttons: ButtonMask {
                left: true,
                ..ButtonMask::default()
            },
        })
    }

    /// Release the left mouse button at `(x, y)`, ending any active drag.
    pub fn mouse_up(&mut self, x: f32, y: f32) -> Reaction {
        self.dispatch(UiEvent::MouseUp {
            widget: None,
            button: MouseButton::Left,
            position: Point::new(x, y),
        })
    }

    /// Left-button drag from `(x0, y0)` to `(x1, y1)`: down → move → up.
    pub fn drag(&mut self, x0: f32, y0: f32, x1: f32, y1: f32) -> Reaction {
        DriverInput::drag(self, x0, y0, x1, y1)
    }

    /// Deliver a [`UiEvent::DoubleClick`] at `(x, y)` directly — the same
    /// event `TuiBackend`'s `DoubleClickDetector` would eventually
    /// synthesise from two close-together `MouseDown`s, but produced here
    /// with no dependence on wall-clock timing. A test that
    /// fired two `click()`s and relied on the 400ms/1.5-cell detector
    /// window was a race against real time — flaky under load, identical
    /// on the 1st and 1000th call here since no clock is consulted.
    ///
    /// Still routed through [`Self::dispatch`] (backend translation +
    /// `dispatch_event`), not straight to `app.handle`, so it sees the
    /// same pre-processing (e.g. `clear_selection_display`) a real
    /// detector-folded double click would — see the module doc's "No
    /// drift from production" note. `apply_dispatch`/`DoubleClickDetector`
    /// both pass a `DoubleClick` event through unchanged, so this doesn't
    /// risk a second fold.
    pub fn double_click(&mut self, x: f32, y: f32) -> Reaction {
        self.dispatch(UiEvent::DoubleClick {
            widget: None,
            position: Point::new(x, y),
        })
    }

    /// Press-and-release the middle mouse button at `(x, y)`, delivered as
    /// a [`UiEvent::MouseDown`] with [`MouseButton::Middle`]. Shorthand for
    /// [`Self::click_with`] with the default modifiers.
    pub fn middle_click(&mut self, x: f32, y: f32) -> Reaction {
        self.click_with(MouseButton::Middle, Modifiers::default(), x, y)
    }

    /// Press-and-release the right mouse button at `(x, y)`, delivered as
    /// a [`UiEvent::MouseDown`] with [`MouseButton::Right`]. Shorthand for
    /// [`Self::click_with`] with the default modifiers.
    pub fn right_click(&mut self, x: f32, y: f32) -> Reaction {
        self.click_with(MouseButton::Right, Modifiers::default(), x, y)
    }

    /// Click at `(x, y)` with an arbitrary [`MouseButton`] and
    /// [`Modifiers`], delivered as a [`UiEvent::MouseDown`] — the general
    /// form [`Self::click`]/[`Self::middle_click`]/[`Self::right_click`]
    /// build on. Lets a test assert modifier-gated behaviour (e.g.
    /// Ctrl-click) without hand-assembling the event.
    pub fn click_with(
        &mut self,
        button: MouseButton,
        modifiers: Modifiers,
        x: f32,
        y: f32,
    ) -> Reaction {
        self.dispatch(UiEvent::MouseDown {
            widget: None,
            button,
            position: Point::new(x, y),
            modifiers,
        })
    }

    /// Enable or disable double-click folding for subsequent
    /// [`Self::click`]/[`Self::mouse_down`] calls. Defaults
    /// to `true` — today's behaviour, where two `click()`s landing inside
    /// `TuiBackend`'s `DoubleClickDetector` window (400ms, 1.5 cells) fold
    /// into a single `DoubleClick`. Pass `false` when a test means two
    /// *separate* single clicks — e.g. exercising click-outside-to-dismiss
    /// twice in a row — so it deterministically gets two `MouseDown`s
    /// instead of a result that depends on how much wall-clock time
    /// elapsed between the two `dispatch` calls.
    pub fn set_double_click_folding(&mut self, enabled: bool) {
        self.core.backend_mut().set_double_click_folding(enabled);
    }

    /// Whether the app has returned [`Reaction::Exit`].
    pub fn exited(&self) -> bool {
        self.core.exited()
    }

    /// The current rendered screen as newline-joined rows.
    ///
    /// Wide-char aware: strides by each glyph's
    /// [`char_cell_width`], the same way [`Self::row_cells`] does, rather
    /// than one buffer column per iteration. A double-width glyph's
    /// reserved continuation cell is always blank by construction and never
    /// reaches `next` in `Buffer::diff`'s output, so `TestBackend` never
    /// actually writes it — it just retains whatever was in that column
    /// *before* this frame, which for a freshly-painted glyph is
    /// `Cell::default()`'s `symbol()`, `" "`. Reading column-by-column
    /// therefore inserted a phantom space after every wide glyph that was
    /// never really there (a real terminal shows the glyph occupying both
    /// columns with nothing "under" it), which made `screen_contains`/`screen_has`
    /// — the direct backer of the conformance suite's `assert_screen_has` step —
    /// report a needle spanning a wide glyph as absent even though
    /// [`Self::find_bounds`] (already wide-char aware) found it painted as one
    /// contiguous run. Striding here brings `screen()` in line with what
    /// `row_cells`/`find_bounds`/`inventory` already saw, and with what
    /// [`crate::tui::vt_testing::TuiVtDriver::screen`]'s vt100-observed
    /// twin reports for the identical content.
    pub fn screen(&self) -> String {
        let terminal = self.terminal.borrow();
        let buf = terminal.backend().buffer();
        let area = buf.area;
        let mut out = String::new();
        for y in area.top()..area.bottom() {
            let mut x = area.left();
            while x < area.right() {
                let symbol = buf[(x, y)].symbol();
                let ch = symbol.chars().next().unwrap_or(' ');
                out.push_str(symbol);
                x += char_cell_width(ch).max(1);
            }
            out.push('\n');
        }
        out
    }

    /// True if any rendered row contains `needle`.
    pub fn screen_contains(&self, needle: &str) -> bool {
        self.screen().contains(needle)
    }

    /// The style a rasteriser painted onto one cell: foreground, background,
    /// and text modifiers (bold/italic/underline/…).
    ///
    /// [`Self::screen`] only surfaces glyphs, so a driver test can prove a
    /// cell exists but not, e.g., that it's the *preview*-tab italic rather
    /// than the permanent-tab plain style — both stringify
    /// identically. `style_at` reads the same buffer cell `screen()` does,
    /// just its [`ratatui::buffer::Cell::style`] instead of its symbol.
    ///
    /// `fg`/`bg`/`modifiers` are `ratatui`'s own [`Color`]/[`Modifier`],
    /// re-exported from this module (`quadraui::tui::testing::Modifier`) so
    /// a downstream test crate can assert on them (`style.modifiers
    /// .contains(Modifier::ITALIC)`) without adding its own `ratatui`
    /// dependency — it already depends on `quadraui` to get `TuiDriver`.
    pub fn style_at(&self, x: u16, y: u16) -> Option<CellStyle> {
        let terminal = self.terminal.borrow();
        let buf = terminal.backend().buffer();
        let area = buf.area;
        if x < area.left() || x >= area.right() || y < area.top() || y >= area.bottom() {
            return None;
        }
        let cell = &buf[(x, y)];
        Some(CellStyle {
            fg: cell.fg,
            bg: cell.bg,
            modifiers: cell.modifier,
        })
    }

    /// [`Self::style_at`] for every cell of row `y`, left to right — one
    /// entry per cell, so a test can assert "every cell of the tab label is
    /// italic" without indexing arithmetic. Empty if `y` is out of range.
    ///
    /// `styled_row(y).len()` equals the buffer width (`area.width`) for any
    /// in-range `y` — always one entry per cell, unlike [`Self::screen`],
    /// whose row length before the trailing `\n` is only the same count for
    /// buffers with no wide characters: `screen()` concatenates each cell's
    /// `symbol()`, so a double-width glyph's continuation cell contributes
    /// zero chars there, while `styled_row` still emits an entry for it
    /// (its char defaults to `' '`, since a continuation cell's `symbol()`
    /// is empty).
    pub fn styled_row(&self, y: u16) -> Vec<(char, CellStyle)> {
        let terminal = self.terminal.borrow();
        let buf = terminal.backend().buffer();
        let area = buf.area;
        if y < area.top() || y >= area.bottom() {
            return Vec::new();
        }
        (area.left()..area.right())
            .map(|x| {
                let cell = &buf[(x, y)];
                let ch = cell.symbol().chars().next().unwrap_or(' ');
                (
                    ch,
                    CellStyle {
                        fg: cell.fg,
                        bg: cell.bg,
                        modifiers: cell.modifier,
                    },
                )
            })
            .collect()
    }

    /// Access the app state for test assertions.
    ///
    /// Useful when the test app records side-effects (e.g. last copied text,
    /// selection changes) that would otherwise require screen-scraping.
    pub fn app(&self) -> &A {
        self.core.app()
    }

    /// Mutable access to the app state for tests that need to poke state
    /// directly rather than through a scripted [`UiEvent`] — e.g. asserting
    /// a render-time invariant (like editor cursor placement) across a
    /// state change with no dedicated event/handler of its own.
    pub fn app_mut(&mut self) -> &mut A {
        self.core.app_mut()
    }

    /// Access the backend for test assertions (e.g. active selection state,
    /// drag state).
    pub fn backend(&self) -> &TuiBackend {
        self.core.backend()
    }

    /// The `(x, y)` position `Terminal::draw` last applied to the
    /// underlying `TestBackend` via `Frame::set_cursor_position` —
    /// reflecting [`super::run::render_frame`]'s `take_last_cursor_position`
    /// handoff from `TuiBackend::draw_editor`.
    ///
    /// Note `TestBackend` tracks only the last-set position, not whether
    /// the cursor is currently hidden — so this always returns the most
    /// recent position ever applied, even on a later frame that painted no
    /// editor and would hide the real terminal cursor. Fine for asserting
    /// "the editor's cursor position reached the Frame", not for asserting
    /// hide/show transitions.
    pub fn terminal_cursor_position(&mut self) -> Option<(u16, u16)> {
        self.terminal
            .borrow_mut()
            .get_cursor_position()
            .ok()
            .map(|p| (p.x, p.y))
    }

    /// This row's cells as `(char, cell_x, cell_width)` triples, in
    /// left-to-right order — the shared scan [`Self::find_bounds`] and
    /// [`ConformanceDriver::inventory`] both walk.
    ///
    /// Skips the reserved continuation cell(s) a double-width glyph's
    /// rendering leaves behind: ratatui resets them to a blank cell whose
    /// `symbol()` reads back as `" "`, indistinguishable from a real space
    /// by content alone, so the *width* of the character just placed (via
    /// [`char_cell_width`]), not the following cell's symbol, drives how
    /// far `x` advances. Without this, two adjacent double-width
    /// characters (e.g. CJK) get a spurious blank cell wedged between them
    /// in the reconstructed row, and a needle spanning them would never
    /// match.
    fn row_cells(&self, y: u16) -> Vec<(char, u16, u16)> {
        let terminal = self.terminal.borrow();
        let buf = terminal.backend().buffer();
        let area = buf.area;
        let mut cells = Vec::new();
        let mut x = area.left();
        while x < area.right() {
            let symbol = buf[(x, y)].symbol();
            let ch = symbol.chars().next().unwrap_or(' ');
            let w = char_cell_width(ch).max(1);
            cells.push((ch, x, w));
            x += w;
        }
        cells
    }

    /// Cell bounds of the first row containing `needle`, wide-char aware
    /// (see [`Self::row_cells`]): a needle spanning two double-width
    /// glyphs (CJK, most emoji) matches and reports the full cell span,
    /// not just its first character's cell.
    pub fn find_bounds(&self, needle: &str) -> Option<Rect> {
        let needle: Vec<char> = needle.chars().collect();
        if needle.is_empty() {
            return None;
        }
        let area = self.terminal.borrow().backend().buffer().area;
        for y in area.top()..area.bottom() {
            let cells = self.row_cells(y);
            if cells.len() < needle.len() {
                continue;
            }
            if let Some(start) = cells
                .windows(needle.len())
                .position(|w| w.iter().map(|(c, _, _)| *c).eq(needle.iter().copied()))
            {
                let (_, start_x, _) = cells[start];
                let (_, last_x, last_w) = cells[start + needle.len() - 1];
                let width = (last_x + last_w).saturating_sub(start_x);
                return Some(Rect::new(start_x as f32, y as f32, width as f32, 1.0));
            }
        }
        None
    }

    /// Coordinates of the first row containing `needle`, at the center of
    /// the matched span's *first* cell — preserved from earlier behaviour
    /// (a click there always lands inside the match regardless of span width)
    /// even though [`Self::find_bounds`] now reports the full wide-char-aware
    /// span. Callers that want the full span's center use `find_bounds`
    /// directly (e.g. [`ConformanceDriver::click_text_at`]'s `Anchor::Center`).
    pub fn find(&self, needle: &str) -> Option<(f32, f32)> {
        self.find_bounds(needle)
            .map(|b| (b.x + 0.5, b.y + b.height / 2.0))
    }

    /// Cell coordinates of tab `tab_idx`'s center in the tab bar `bar`, for
    /// [`Self::click`] to land on that specific tab.
    ///
    /// `find` can't do this job: every tab paints the same chrome (and a
    /// closed/active tab's label may repeat elsewhere on screen), so there
    /// is no needle that disambiguates "tab 3" from "tab 0". This instead
    /// resolves against the [`crate::TabBarLayout`] `TuiBackend::draw_tab_bar`
    /// cached the last time `bar` painted — `None` if `bar` didn't paint
    /// this frame, or if `tab_idx` is scrolled out of view behind the
    /// bar's `scroll_offset`.
    pub fn tab_center(&self, bar: &WidgetId, tab_idx: usize) -> Option<(f32, f32)> {
        let (rect, layout) = self.core.backend().cached_tab_bar_layout(bar)?;
        let (cx, cy) = layout.tab_center(tab_idx)?;
        Some((rect.x + cx, rect.y + cy))
    }

    /// Cell coordinates of tab `tab_idx`'s close-button center in the tab
    /// bar `bar` — the `×`/`●` glyph every tab shares, so [`Self::find`]
    /// can't target one tab's close button over another's.
    ///
    /// `None` for the same reasons as [`Self::tab_center`], plus: the tab
    /// drew no close button this frame (`is_closable: false` on the tab,
    /// or `show_tab_close: false` on the bar).
    pub fn tab_close_center(&self, bar: &WidgetId, tab_idx: usize) -> Option<(f32, f32)> {
        let (rect, layout) = self.core.backend().cached_tab_bar_layout(bar)?;
        let (cx, cy) = layout.tab_close_center(tab_idx)?;
        Some((rect.x + cx, rect.y + cy))
    }
}

/// The four raw primitives [`DriverInput`]'s default `press`/`type_char`/
/// `press_named`/`ctrl_char`/`click`/`drag` methods build on — see that
/// trait's doc for why `dispatch`/`mouse_down`/`mouse_move`/`mouse_up`
/// stay required (genuinely per-backend) rather than shared.
/// `TuiDriver` doesn't also adopt [`crate::testing::PixelClickConformance`]
/// — its `ConformanceDriver::click_text_at`/`drag_text`/`scroll_at` stay
/// bespoke below, since TUI's cell-unit `+0.5`/`-0.5` edge offsets (vs the
/// pixel backends' `+1.0`/`-1.0`) and `self.screen()`-dump panic messages
/// are real, load-bearing divergences, not accidental duplication.
impl<A: AppLogic> DriverInput for TuiDriver<A> {
    fn dispatch(&mut self, event: UiEvent) -> Reaction {
        self.dispatch(event)
    }

    fn mouse_down(&mut self, x: f32, y: f32) -> Reaction {
        self.mouse_down(x, y)
    }

    fn mouse_move(&mut self, x: f32, y: f32) -> Reaction {
        self.mouse_move(x, y)
    }

    fn mouse_up(&mut self, x: f32, y: f32) -> Reaction {
        self.mouse_up(x, y)
    }
}

impl<A: AppLogic> ConformanceDriver for TuiDriver<A> {
    type App = A;

    fn new_fixture(app: Self::App, viewport: LogicalViewport) -> Self {
        // TUI's native unit *is* the cell, so a `LogicalViewport` maps
        // straight through — no char_width/line_height scaling needed
        // (contrast `GtkDriver::new_fixture`, a pixel backend).
        TuiDriver::new(app, viewport.cols as u16, viewport.rows as u16)
    }

    fn backend_caps(&self) -> crate::BackendCaps {
        // Straight off the real `TuiBackend` this driver wraps — never a
        // re-statement.
        crate::Backend::backend_caps(self.core.backend())
    }

    fn press_named(&mut self, key: NamedKey) {
        TuiDriver::press_named(self, key);
    }

    fn type_char(&mut self, c: char) {
        TuiDriver::type_char(self, c);
    }

    fn ctrl_char(&mut self, c: char) {
        TuiDriver::ctrl_char(self, c);
    }

    fn click_text_at(&mut self, needle: &str, at: Anchor) {
        let bounds = self
            .find_bounds(needle)
            .unwrap_or_else(|| panic!("TuiDriver: {needle:?} not painted:\n{}", self.screen()));
        let y = bounds.y + bounds.height / 2.0;
        let x = match at {
            Anchor::Center => bounds.x + bounds.width / 2.0,
            // Half a cell in from each edge — the outermost cell's
            // center — so the click reliably lands inside the run even
            // for a single-cell-wide match.
            Anchor::LeftEdge => bounds.x + 0.5,
            Anchor::RightEdge => bounds.x + bounds.width - 0.5,
        };
        self.click(x, y);
    }

    fn drag_text(&mut self, from: &str, to: &str) {
        let (x0, y0) = self
            .find(from)
            .unwrap_or_else(|| panic!("TuiDriver: {from:?} not painted:\n{}", self.screen()));
        let (x1, y1) = self
            .find(to)
            .unwrap_or_else(|| panic!("TuiDriver: {to:?} not painted:\n{}", self.screen()));
        self.drag(x0, y0, x1, y1);
    }

    fn scroll_at(&mut self, needle: &str, lines: i32) {
        let (x, y) = self
            .find(needle)
            .unwrap_or_else(|| panic!("TuiDriver: {needle:?} not painted:\n{}", self.screen()));
        let line_height = self.core.backend().line_height();
        self.dispatch(UiEvent::Scroll {
            widget: None,
            delta: ScrollDelta::new(0.0, lines as f32 * line_height),
            position: Point::new(x, y),
        });
    }

    fn inventory(&self) -> FrameInventory {
        let area = self.terminal.borrow().backend().buffer().area;
        let mut text_runs = Vec::new();
        for y in area.top()..area.bottom() {
            let cells = self.row_cells(y);
            let mut run: Option<(String, u16, u16)> = None; // (text, start_x, end_x)
            for (ch, x, w) in cells {
                if ch == ' ' {
                    if let Some((text, start_x, end_x)) = run.take() {
                        text_runs.push(TextRun {
                            text,
                            bounds: Rect::new(
                                start_x as f32,
                                y as f32,
                                (end_x - start_x) as f32,
                                1.0,
                            ),
                        });
                    }
                    continue;
                }
                match &mut run {
                    Some((text, _start_x, end_x)) => {
                        text.push(ch);
                        *end_x = x + w;
                    }
                    None => run = Some((ch.to_string(), x, x + w)),
                }
            }
            if let Some((text, start_x, end_x)) = run {
                text_runs.push(TextRun {
                    text,
                    bounds: Rect::new(start_x as f32, y as f32, (end_x - start_x) as f32, 1.0),
                });
            }
        }
        FrameInventory {
            text_runs,
            // Zones registered this frame via `Backend::register_zone` —
            // currently the shell-chrome zones `AppShell::render` records
            // (activity-bar items, sidebar header/content, status bar,
            // ...). Primitives that don't yet call `register_zone`
            // contribute no zone.
            zones: self.core.backend().zones().to_vec(),
        }
    }

    fn screen_has(&self, needle: &str) -> bool {
        self.screen_contains(needle)
    }

    fn exited(&self) -> bool {
        TuiDriver::exited(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Viewport;
    use std::cell::{Cell, RefCell};
    use std::rc::Rc;

    /// Minimal app that records the viewport it observes in `setup()`.
    ///
    /// `setup()` must see the driver's real terminal size, not the
    /// `Viewport::default()` (80×24) that `TuiBackend::new()` seeds. An app
    /// that sizes a side effect from the setup-time viewport (e.g. `TerminalApp`
    /// spawning its PTY) would otherwise under-fill the pane until the first
    /// resize event.
    struct SetupViewportRecorder {
        seen: Rc<Cell<Option<Viewport>>>,
    }

    impl AppLogic for SetupViewportRecorder {
        type AreaId = ();

        fn setup(&mut self, backend: &mut dyn Backend) {
            self.seen.set(Some(backend.viewport()));
        }

        fn render(&self, _backend: &mut dyn Backend, _area: ()) {}

        fn handle(&mut self, _event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
            Reaction::Continue
        }
    }

    /// App that requests a full repaint whenever it handles
    /// a key press, and otherwise does nothing.
    struct FullRepaintRequester;

    impl AppLogic for FullRepaintRequester {
        type AreaId = ();

        fn render(&self, _backend: &mut dyn Backend, _area: ()) {}

        fn handle(&mut self, event: UiEvent, backend: &mut dyn Backend) -> Reaction {
            if matches!(event, UiEvent::KeyPressed { .. }) {
                backend.request_full_repaint();
                return Reaction::Redraw;
            }
            Reaction::Continue
        }
    }

    /// `TuiDriver::dispatch` routes through [`TuiDriver::render`] on a
    /// `Redraw` reaction, exactly like the live runner's frame loop — so a
    /// `Backend::request_full_repaint` call made from `handle` must be
    /// consumed by that same `render` call, not left pending. Verified
    /// indirectly: if `render` had consumed it, a direct
    /// `take_full_repaint_requested` call made *after* the dispatch returns
    /// `false` (already cleared); if `render` never consulted it at all, that
    /// same call would still see the original `true` and this assertion would
    /// fail.
    #[test]
    fn dispatch_consumes_a_pending_full_repaint_request_via_render() {
        let mut driver = TuiDriver::new(FullRepaintRequester, 20, 5);

        let reaction = driver.press(Key::Named(NamedKey::Enter));
        assert_eq!(reaction, Reaction::Redraw);

        assert!(
            !driver.core.backend_mut().take_full_repaint_requested(),
            "TuiDriver::render must consume the pending full-repaint \
             request during the redraw `dispatch` already triggered"
        );
    }

    /// Prove `render` doesn't just *consume* the pending flag (see the test
    /// above) but actually forces `ratatui::Terminal::clear()`'s effect —
    /// the next frame repaints every cell unconditionally, even one the
    /// app's own (unchanged) content never touches.
    ///
    /// `FullRepaintRequester::render` never paints anything, so once the
    /// first frame lands the widget-side content stays blank forever —
    /// ratatui's diff cache always agrees "nothing changed" and would
    /// normally skip re-sending every cell. We simulate the exact kind of
    /// external drift `request_full_repaint`'s doc names (a PTY writing
    /// straight into the shared terminal, bypassing ratatui's own
    /// `Buffer` tracking) by calling `ratatui::backend::Backend::draw`
    /// directly on the `TestBackend`, underneath `Terminal`'s diff — a
    /// stale glyph ratatui's cache has no idea appeared.
    ///
    /// Without a pending full-repaint request, a plain redraw leaves that
    /// stale glyph in place (diff sees no change at that cell, so it's
    /// never told to repaint it) — matching the symptom. With
    /// `request_full_repaint()` set first, `render` must clear it, proving
    /// `Terminal::clear()` actually ran rather than the flag merely being
    /// read and discarded.
    #[test]
    fn render_actually_clears_stale_content_outside_the_diff_cache() {
        use ratatui::backend::Backend as RatatuiBackend;
        use ratatui::buffer::Cell;

        let mut driver = TuiDriver::new(FullRepaintRequester, 10, 3);

        // Inject a "stale" glyph directly into the physical backend,
        // underneath `Terminal`'s own previous-buffer diff tracking —
        // ratatui has no record that this cell ever changed.
        let mut stale = Cell::default();
        stale.set_symbol("X");
        RatatuiBackend::draw(
            driver.terminal.borrow_mut().backend_mut(),
            std::iter::once((0u16, 0u16, &stale)),
        )
        .expect("TestBackend draw is infallible");
        assert!(
            driver.screen_contains("X"),
            "sanity: the injected stale glyph must be visible before either render"
        );

        // A plain redraw with nothing pending: ratatui's diff still
        // believes this cell is unchanged (blank), so the stale glyph
        // survives.
        driver.render();
        assert!(
            driver.screen_contains("X"),
            "a redraw with no full-repaint request pending must not touch \
             cells the diff cache believes are unchanged"
        );

        // Now request a full repaint and redraw again: `render` must
        // consume the request by calling `Terminal::clear()` before
        // painting, which resets the diff cache so every cell —
        // including the stale one the app's own content never wrote to
        // this frame — repaints unconditionally back to blank.
        driver.core.backend_mut().request_full_repaint();
        driver.render();
        assert!(
            !driver.screen_contains("X"),
            "render() must actually call Terminal::clear() when a full \
             repaint was requested, not just consume the flag — the stale \
             glyph should be gone once every cell repaints unconditionally"
        );
    }

    /// `setup()` must observe the driver's real terminal dimensions, not
    /// the default 80×24 viewport. An app that sizes a side effect from the
    /// setup-time viewport (e.g. PTY initialization) would under-fill the
    /// pane until first interaction.
    #[test]
    fn setup_sees_real_viewport_not_default() {
        let seen = Rc::new(Cell::new(None));
        let app = SetupViewportRecorder { seen: seen.clone() };
        // Deliberately not 80×24 so a regression to the default is visible.
        let _driver = TuiDriver::new(app, 120, 40);

        let vp = seen.get().expect("setup() should have run");
        assert_eq!(
            (vp.width, vp.height),
            (120.0, 40.0),
            "setup() must see the driver's real size, not Viewport::default() (80×24)"
        );
    }

    use crate::primitives::status_bar::{StatusBar, StatusBarSegment};
    use crate::types::{Color, WidgetId};

    /// Paints one status-bar line whose text is given verbatim (no
    /// automatic padding), so a test can control exactly which glyphs are
    /// adjacent — needed to exercise the double-width continuation-cell
    /// case `find`/`find_bounds` must handle correctly.
    struct OneLineApp {
        text: &'static str,
    }

    impl AppLogic for OneLineApp {
        type AreaId = ();

        fn render(&self, backend: &mut dyn Backend, _area: ()) {
            backend.draw_status_bar_interactive(
                Rect::new(0.0, 0.0, 30.0, 1.0),
                &StatusBar {
                    id: WidgetId::new("status"),
                    left_segments: vec![StatusBarSegment {
                        text: self.text.to_string(),
                        fg: Color::rgb(255, 255, 255),
                        bg: Color::rgb(0, 0, 0),
                        bold: false,
                        action_id: None,
                    }],
                    right_segments: vec![],
                },
                &crate::InteractionState::new(),
            );
        }

        fn handle(&mut self, _event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
            Reaction::Continue
        }
    }

    /// Regression guard: two adjacent double-width (CJK) glyphs must be
    /// found as one 4-cell-wide span, not silently unmatched because
    /// ratatui wedges a blank continuation cell between them that isn't a
    /// real space.
    #[test]
    fn find_bounds_is_wide_char_aware_for_adjacent_cjk_glyphs() {
        let driver = TuiDriver::new(
            OneLineApp {
                text: "你好 world"
            },
            30,
            3,
        );

        let cjk = driver.find_bounds("你好").expect(
            "adjacent double-width glyphs should match as one span, not be split by a \
             spurious blank continuation cell",
        );
        assert_eq!(
            (cjk.x, cjk.width),
            (0.0, 4.0),
            "two double-width glyphs occupy 4 cells total"
        );

        // `find` returns the first cell's center, not the span's midpoint,
        // which preserves earlier behaviour where a click there always lands
        // inside the match regardless of span width.
        let (x, y) = driver.find("你好").expect("find should also locate it");
        assert_eq!((x, y), (0.5, 0.5));

        // "world" is offset past the 4-cell CJK run and the separating
        // space — proves the continuation-cell fix didn't just get the
        // *first* match right by accident.
        let world = driver
            .find_bounds("world")
            .expect("world should be found after the CJK run");
        assert_eq!(world.x, cjk.x + cjk.width + 1.0);
    }

    /// Regression guard: adjacent double-width glyphs must read back as a
    /// contiguous substring, with no phantom space inserted for the wide
    /// glyph's (always-blank) continuation cell — the same needle
    /// [`find_bounds`] above already located as one 4-cell span. Before
    /// this fix `screen()` walked one buffer column per iteration, so
    /// `screen_contains`/`screen_has` (the direct backer of the
    /// conformance suite's `assert_screen_has` step) disagreed with
    /// `find_bounds`/`inventory` on the exact same frame.
    #[test]
    fn screen_is_wide_char_aware_for_adjacent_cjk_glyphs() {
        let driver = TuiDriver::new(
            OneLineApp {
                text: "你好 world"
            },
            30,
            3,
        );

        assert!(
            driver.screen_contains("你好"),
            "screen() must not insert a phantom space inside a contiguous \
             double-width run:\n{}",
            driver.screen()
        );
        assert!(
            driver.screen_contains("你好 world"),
            "the whole line must read back exactly as painted:\n{}",
            driver.screen()
        );
    }

    /// `ConformanceDriver` smoke test for the TUI impl: `new_fixture` (the
    /// `LogicalViewport`-aligned constructor), `scroll_at`, and
    /// `inventory` all round-trip through the promoted trait.
    #[test]
    fn conformance_driver_new_fixture_scroll_at_and_inventory_round_trip() {
        let driver: TuiDriver<OneLineApp> = ConformanceDriver::new_fixture(
            OneLineApp {
                text: "你好 world"
            },
            LogicalViewport::new(30, 3),
        );
        assert_eq!(
            (
                driver.backend().viewport().width,
                driver.backend().viewport().height
            ),
            (30.0, 3.0),
            "new_fixture's LogicalViewport should map straight through to TUI cells"
        );

        let inv = ConformanceDriver::inventory(&driver);
        let texts: Vec<&str> = inv.text_runs().iter().map(|t| t.text.as_str()).collect();
        assert!(
            texts.contains(&"你好") && texts.contains(&"world"),
            "inventory() should synthesize a TextRun per whitespace-separated \
             run on the cell grid, wide-char aware: {texts:?}"
        );

        // scroll_at must not panic when the target text exists — the
        // dispatched Scroll event's downstream handling is exercised by
        // primitive-level tests; this just confirms the driver-level
        // find-then-dispatch plumbing works.
        let mut driver = driver;
        driver.scroll_at("world", 1);
    }

    /// Records every `UiEvent` the app's `handle()` receives, verbatim —
    /// lets a test assert exactly what reached the app (button, modifiers,
    /// `DoubleClick` vs `MouseDown`) without screen-scraping.
    #[derive(Default)]
    struct EventRecorder {
        events: Rc<RefCell<Vec<UiEvent>>>,
    }

    impl AppLogic for EventRecorder {
        type AreaId = ();

        fn render(&self, _backend: &mut dyn Backend, _area: ()) {}

        fn handle(&mut self, event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
            self.events.borrow_mut().push(event);
            Reaction::Continue
        }
    }

    /// `double_click` must deliver exactly one `UiEvent::DoubleClick` at
    /// the given position, with no prior `MouseDown`, and do so
    /// identically whether it's the 1st or 1000th call — the deterministic
    /// alternative to two `click()`s racing `DoubleClickDetector`'s 400ms
    /// wall-clock window.
    #[test]
    fn double_click_is_deterministic_across_many_calls() {
        let events = Rc::new(RefCell::new(Vec::new()));
        let app = EventRecorder {
            events: events.clone(),
        };
        let mut driver = TuiDriver::new(app, 20, 5);

        for i in 0..1000 {
            events.borrow_mut().clear();
            driver.double_click(3.0, 2.0);
            let recorded = events.borrow();
            assert_eq!(
                recorded.len(),
                1,
                "call {i}: double_click should deliver exactly one event, got {recorded:?}"
            );
            assert_eq!(
                recorded[0],
                UiEvent::DoubleClick {
                    widget: None,
                    position: Point::new(3.0, 2.0),
                },
                "call {i}: expected a single DoubleClick with no prior MouseDown"
            );
        }
    }

    /// `middle_click` delivers `MouseDown { button: MouseButton::Middle, .. }`.
    #[test]
    fn middle_click_delivers_middle_mouse_down() {
        let events = Rc::new(RefCell::new(Vec::new()));
        let app = EventRecorder {
            events: events.clone(),
        };
        let mut driver = TuiDriver::new(app, 20, 5);

        driver.middle_click(4.0, 1.0);

        let recorded = events.borrow();
        assert_eq!(recorded.len(), 1);
        assert_eq!(
            recorded[0],
            UiEvent::MouseDown {
                widget: None,
                button: MouseButton::Middle,
                position: Point::new(4.0, 1.0),
                modifiers: Modifiers::default(),
            }
        );
    }

    /// `right_click` delivers `MouseDown { button: MouseButton::Right, .. }`.
    #[test]
    fn right_click_delivers_right_mouse_down() {
        let events = Rc::new(RefCell::new(Vec::new()));
        let app = EventRecorder {
            events: events.clone(),
        };
        let mut driver = TuiDriver::new(app, 20, 5);

        driver.right_click(4.0, 1.0);

        let recorded = events.borrow();
        assert_eq!(recorded.len(), 1);
        assert_eq!(
            recorded[0],
            UiEvent::MouseDown {
                widget: None,
                button: MouseButton::Right,
                position: Point::new(4.0, 1.0),
                modifiers: Modifiers::default(),
            }
        );
    }

    /// `click_with` threads an arbitrary button + modifiers through to the
    /// app, e.g. a Ctrl-held left click.
    #[test]
    fn click_with_delivers_button_and_modifiers() {
        let events = Rc::new(RefCell::new(Vec::new()));
        let app = EventRecorder {
            events: events.clone(),
        };
        let mut driver = TuiDriver::new(app, 20, 5);

        let ctrl = Modifiers {
            ctrl: true,
            ..Modifiers::default()
        };
        driver.click_with(MouseButton::Left, ctrl, 2.0, 3.0);

        let recorded = events.borrow();
        assert_eq!(recorded.len(), 1);
        assert_eq!(
            recorded[0],
            UiEvent::MouseDown {
                widget: None,
                button: MouseButton::Left,
                position: Point::new(2.0, 3.0),
                modifiers: ctrl,
            }
        );
    }

    /// With folding disabled, two `click()` calls in immediate succession
    /// (well inside `DoubleClickDetector`'s 400ms/1.5-cell window) must
    /// deliver two `MouseDown` events and zero `DoubleClick` — proving the
    /// toggle actually suppresses folding rather than just being ignored.
    #[test]
    fn folding_disabled_keeps_two_clicks_separate() {
        let events = Rc::new(RefCell::new(Vec::new()));
        let app = EventRecorder {
            events: events.clone(),
        };
        let mut driver = TuiDriver::new(app, 20, 5);
        driver.set_double_click_folding(false);

        driver.click(5.0, 5.0);
        driver.click(5.0, 5.0);

        let recorded = events.borrow();
        let mouse_downs = recorded
            .iter()
            .filter(|e| matches!(e, UiEvent::MouseDown { .. }))
            .count();
        let double_clicks = recorded
            .iter()
            .filter(|e| matches!(e, UiEvent::DoubleClick { .. }))
            .count();
        assert_eq!(
            (mouse_downs, double_clicks),
            (2, 0),
            "folding disabled should yield two MouseDowns and no DoubleClick, got {recorded:?}"
        );
    }

    /// Sanity check for the *default* (folding enabled) behaviour this
    /// issue must not regress: two `click()`s at the same position can
    /// still fold into a `DoubleClick` via the real detector when a test
    /// wants that (contrast the deterministic `double_click` helper above,
    /// which needs no timing at all).
    #[test]
    fn folding_enabled_by_default_still_folds_two_clicks() {
        let events = Rc::new(RefCell::new(Vec::new()));
        let app = EventRecorder {
            events: events.clone(),
        };
        let mut driver = TuiDriver::new(app, 20, 5);

        driver.click(5.0, 5.0);
        driver.click(5.0, 5.0);

        let recorded = events.borrow();
        let double_clicks = recorded
            .iter()
            .filter(|e| matches!(e, UiEvent::DoubleClick { .. }))
            .count();
        assert_eq!(
            double_clicks, 1,
            "default folding should still fold two same-position clicks: {recorded:?}"
        );
    }

    use crate::primitives::tab_bar::{TabBar, TabItem};
    use crate::theme::Theme;
    use crate::types::WidgetId as QWidgetId;

    /// Paints a two-tab `TabBar` — one permanent, one preview — so a test
    /// can assert `style_at`/`styled_row` distinguish them. Mirrors the
    /// `OneLineApp` pattern above but drives `draw_tab_bar` instead of
    /// `draw_status_bar`.
    struct TabBarApp {
        theme: Theme,
    }

    impl AppLogic for TabBarApp {
        type AreaId = ();

        fn render(&self, backend: &mut dyn Backend, _area: ()) {
            backend.set_theme(self.theme);
            backend.draw_tab_bar(
                Rect::new(0.0, 0.0, 20.0, 1.0),
                &TabBar {
                    id: QWidgetId::new("tabs"),
                    tabs: vec![
                        TabItem {
                            label: "perm".to_string(),
                            is_active: false,
                            is_dirty: false,
                            is_preview: false,
                            is_closable: false,
                        },
                        TabItem {
                            label: "prev".to_string(),
                            is_active: false,
                            is_dirty: false,
                            is_preview: true,
                            is_closable: false,
                        },
                    ],
                    scroll_offset: 0,
                    right_segments: vec![],
                    active_accent: None,
                    show_tab_close: false,
                    compact: false,
                },
                None,
            );
        }

        fn handle(&mut self, _event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
            Reaction::Continue
        }
    }

    /// Acceptance criterion: `style_at` distinguishes a preview tab from a
    /// permanent one by `Modifier::ITALIC` and by the theme's
    /// `tab_preview_inactive_fg` vs `tab_inactive_fg` foreground — neither
    /// of which `screen()` can see, since both tabs stringify identically
    #[test]
    fn style_at_distinguishes_preview_tab_from_permanent_tab() {
        let theme = Theme::default();
        let driver = TuiDriver::new(TabBarApp { theme }, 20, 1);

        // Neither tab reserves a close button (`is_closable: false` on
        // both), so each gets a trailing `TAB_SEPARATOR_COLS` column
        // instead: "perm" occupies cells 0..5 ("perm" + separator at 4),
        // "prev" occupies cells 5..10 ("prev" + separator at 9); the rest
        // of the 20-cell bar is blank fill.
        assert!(driver.screen_contains("perm│prev│"));

        let perm_style = driver
            .style_at(0, 0)
            .expect("(0, 0) is inside the 20x1 buffer");
        let preview_style = driver
            .style_at(5, 0)
            .expect("(5, 0) is inside the 20x1 buffer");

        assert!(
            !perm_style.modifiers.contains(Modifier::ITALIC),
            "permanent tab must not be italic: {perm_style:?}"
        );
        assert!(
            preview_style.modifiers.contains(Modifier::ITALIC),
            "preview tab must be italic: {preview_style:?}"
        );

        assert_eq!(
            perm_style.fg,
            crate::tui::ratatui_color(theme.tab_inactive_fg),
            "permanent tab's fg should be the theme's tab_inactive_fg token"
        );
        assert_eq!(
            preview_style.fg,
            crate::tui::ratatui_color(theme.tab_preview_inactive_fg),
            "preview tab's fg should be the theme's tab_preview_inactive_fg token"
        );
    }

    /// `style_at` outside the buffer returns `None` rather than panicking
    /// (acceptance criterion) — both past the right/bottom edge and on the
    /// exact boundary row/column, which is the first out-of-range value.
    #[test]
    fn style_at_out_of_bounds_returns_none() {
        let driver = TuiDriver::new(
            TabBarApp {
                theme: Theme::default(),
            },
            20,
            1,
        );

        assert!(
            driver.style_at(20, 0).is_none(),
            "x == width is out of range"
        );
        assert!(
            driver.style_at(0, 1).is_none(),
            "y == height is out of range"
        );
        assert!(
            driver.style_at(100, 100).is_none(),
            "far outside is out of range"
        );
        assert!(
            driver.style_at(19, 0).is_some(),
            "x == width - 1 is the last valid column"
        );
    }

    /// `styled_row(y).len()` equals the buffer width for any in-range `y`
    /// (acceptance criterion), and is empty for an out-of-range row rather
    /// than panicking.
    #[test]
    fn styled_row_length_matches_buffer_width() {
        let driver = TuiDriver::new(
            TabBarApp {
                theme: Theme::default(),
            },
            20,
            1,
        );

        let row = driver.styled_row(0);
        assert_eq!(row.len(), 20, "row length should equal buffer width");
        assert_eq!(
            row.iter().map(|(ch, _)| *ch).collect::<String>(),
            // 10 chars of content ("perm" + "│" + "prev" + "│") + 10
            // spaces of blank fill = 20 chars. Not byte-sliced like the
            // old all-ASCII literal: "│" is multi-byte in UTF-8, so a
            // byte-index slice would land mid-codepoint.
            "perm│prev│          ",
            "styled_row's chars should match screen()'s glyphs left to right"
        );
        // Same per-cell distinction as style_at, reachable via styled_row.
        // Column 4 is the separator after "perm", not part of either tab's
        // label — the preview tab's own first cell is column 5.
        assert!(!row[0].1.modifiers.contains(Modifier::ITALIC));
        assert!(row[5].1.modifiers.contains(Modifier::ITALIC));

        assert!(
            driver.styled_row(1).is_empty(),
            "out-of-range row should be empty, not panic"
        );
    }

    /// A compact tab bar with no close buttons (`show_tab_close: false`).
    /// Drives the real `TuiBackend::draw_tab_bar`/`tab_bar_layout`
    /// measurer end to end — not a hand-rolled `TabMeasure` — so a
    /// regression in any of the backend's own measurer call sites breaks
    /// here, not only in `tab_bar.rs`'s rasteriser-level unit test.
    struct NoCloseTabBarApp {
        active: usize,
    }

    impl NoCloseTabBarApp {
        const RECT: Rect = Rect::new(0.0, 0.0, 20.0, 1.0);

        fn bar(&self) -> TabBar {
            TabBar {
                id: QWidgetId::new("tabs"),
                tabs: vec![
                    TabItem {
                        label: "Problems".into(),
                        is_active: self.active == 0,
                        is_dirty: false,
                        is_preview: false,
                        is_closable: false,
                    },
                    TabItem {
                        label: "Output".into(),
                        is_active: self.active == 1,
                        is_dirty: false,
                        is_preview: false,
                        is_closable: false,
                    },
                ],
                scroll_offset: 0,
                right_segments: vec![],
                active_accent: None,
                show_tab_close: false,
                compact: true,
            }
        }
    }

    impl AppLogic for NoCloseTabBarApp {
        type AreaId = ();

        #[allow(deprecated)] // `Backend::draw_tab_bar` returns `TabBarHits` — issue #823
        fn render(&self, backend: &mut dyn Backend, _area: ()) {
            backend.draw_tab_bar(Self::RECT, &self.bar(), None);
        }

        #[allow(deprecated)] // `Backend::tab_bar_layout` returns `TabBarHits` — issue #823
        fn handle(&mut self, event: UiEvent, backend: &mut dyn Backend) -> Reaction {
            let UiEvent::MouseDown { position, .. } = event else {
                return Reaction::Continue;
            };
            let hits = backend.tab_bar_layout(Self::RECT, &self.bar());
            let x = position.x as f64;
            for (i, (sx, ex)) in hits.slot_positions.iter().enumerate() {
                if x >= *sx && x < *ex {
                    self.active = i;
                    return Reaction::Redraw;
                }
            }
            Reaction::Continue
        }
    }

    /// Acceptance criterion for quadraui's compact-tab-bar separator: the
    /// backend's own measurer (not a test's hand-rolled `TabMeasure`)
    /// reserves a `TAB_SEPARATOR_CHAR` column after each no-close tab, and
    /// that column stays part of the tab it follows rather than becoming a
    /// dead click zone.
    #[test]
    fn no_close_tab_bar_separator_click_through_backend_measurer_activates_its_tab() {
        let app = NoCloseTabBarApp { active: 1 };
        let mut driver = TuiDriver::new(app, 20, 1);

        assert!(
            driver.screen_contains("Problems│Output│"),
            "the real backend measurer should reserve a separator column after each no-close tab"
        );

        let (sep_x, sep_y) = driver
            .find("│")
            .expect("separator glyph should be visible on the 20-cell bar");
        driver.click(sep_x, sep_y);
        assert_eq!(
            driver.app().active,
            0,
            "clicking the separator painted right after tab 0's label should activate tab 0, \
             not fall through to a dead zone"
        );
    }

    // ─── quadraui#594 ────────────────────────────────────────────────────

    /// Three closable tabs on a 20-cell bar. `handle()` hit-tests raw
    /// `MouseDown` clicks against the *live*, non-painting
    /// [`crate::Backend::tab_bar_layout`] query (mirrors the "cached
    /// layout hit-test pattern" `gtk/testing.rs`'s `ToggleStatusBarApp`
    /// uses) — close regions win over tab bodies, matching
    /// `TabBarLayout::hit_regions`' close-before-body ordering. Exercises
    /// `TuiDriver::tab_center`/`tab_close_center` end-to-end: the driver
    /// locates a specific tab's click target with no hardcoded
    /// coordinates, and the resulting click reaches the app through the
    /// ordinary event path.
    struct InteractiveTabBarApp {
        active: usize,
        closed_idx: Option<usize>,
    }

    impl InteractiveTabBarApp {
        const RECT: Rect = Rect::new(0.0, 0.0, 20.0, 1.0);

        fn bar(&self) -> TabBar {
            TabBar {
                id: QWidgetId::new("tabs"),
                tabs: (0..3)
                    .map(|i| TabItem {
                        label: format!("tab{i}"),
                        is_active: i == self.active,
                        is_dirty: false,
                        is_preview: false,
                        is_closable: true,
                    })
                    .collect(),
                scroll_offset: 0,
                right_segments: vec![],
                active_accent: None,
                show_tab_close: true,
                compact: false,
            }
        }
    }

    impl AppLogic for InteractiveTabBarApp {
        type AreaId = ();

        #[allow(deprecated)] // `Backend::draw_tab_bar` returns `TabBarHits` — issue #823
        fn render(&self, backend: &mut dyn Backend, _area: ()) {
            backend.draw_tab_bar(Self::RECT, &self.bar(), None);
        }

        #[allow(deprecated)] // `Backend::tab_bar_layout` returns `TabBarHits` — issue #823
        fn handle(&mut self, event: UiEvent, backend: &mut dyn Backend) -> Reaction {
            let UiEvent::MouseDown { position, .. } = event else {
                return Reaction::Continue;
            };
            let hits = backend.tab_bar_layout(Self::RECT, &self.bar());
            let x = position.x as f64;
            // Close regions before tab bodies — mirrors
            // `TabBarLayout::hit_regions`' ordering (close-before-body).
            for (i, close) in hits.close_bounds.iter().enumerate() {
                if let Some((sx, ex)) = close {
                    if x >= *sx && x < *ex {
                        self.closed_idx = Some(i);
                        return Reaction::Redraw;
                    }
                }
            }
            for (i, (sx, ex)) in hits.slot_positions.iter().enumerate() {
                if x >= *sx && x < *ex {
                    self.active = i;
                    return Reaction::Redraw;
                }
            }
            Reaction::Continue
        }
    }

    /// Acceptance criterion: with a 3-tab bar rendered,
    /// `driver.click(tab_center(&bar, 1))` activates tab 1.
    #[test]
    fn tab_center_click_activates_target_tab() {
        let app = InteractiveTabBarApp {
            active: 0,
            closed_idx: None,
        };
        let mut driver = TuiDriver::new(app, 20, 1);
        let bar_id = QWidgetId::new("tabs");

        assert_eq!(driver.app().active, 0);
        let (x, y) = driver
            .tab_center(&bar_id, 1)
            .expect("tab 1 should be visible on a 20-cell bar with 3 short tabs");
        driver.click(x, y);

        assert_eq!(
            driver.app().active,
            1,
            "clicking tab 1's center should activate it"
        );
    }

    /// Acceptance criterion: `driver.click(tab_close_center(&bar, 1))`
    /// closes tab 1 and does **not** merely activate it.
    #[test]
    fn tab_close_center_click_closes_target_tab_not_just_activates() {
        let app = InteractiveTabBarApp {
            active: 0,
            closed_idx: None,
        };
        let mut driver = TuiDriver::new(app, 20, 1);
        let bar_id = QWidgetId::new("tabs");

        let (x, y) = driver
            .tab_close_center(&bar_id, 1)
            .expect("tab 1 is closable and should have a close button");
        driver.click(x, y);

        assert_eq!(
            driver.app().closed_idx,
            Some(1),
            "clicking tab 1's close button should close it"
        );
        assert_ne!(
            driver.app().active,
            1,
            "closing tab 1 must not merely activate it — active should stay at its prior value"
        );
    }

    /// The rect a consumer hit-tests against must be the *same* rect
    /// `draw_tab_bar` painted. `tab_close_center` resolves against the
    /// [`crate::TabBarLayout`] `TuiBackend` cached at paint time; this test
    /// takes that exact point and runs it back through the authoritative
    /// no-paint accessor, [`crate::Backend::resolve_tab_bar_layout`] +
    /// [`crate::TabBarLayout::hit_test`] — not the deprecated
    /// `TabBarHits`/`tab_bar_layout` pair — and asserts it resolves to
    /// `TabBarHit::TabClose(1)`, not a plain tab-select. If this is green,
    /// the TUI backend's paint and hit-test rects agree.
    #[test]
    fn tab_close_center_resolves_to_authoritative_tab_close_hit() {
        use crate::primitives::tab_bar::TabBarHit;

        let app = InteractiveTabBarApp {
            active: 0,
            closed_idx: None,
        };
        let mut driver = TuiDriver::new(app, 20, 1);
        let bar_id = QWidgetId::new("tabs");
        let bar = driver.app().bar();

        let (x, y) = driver
            .tab_close_center(&bar_id, 1)
            .expect("tab 1 is closable and should have a close button");

        let resolved = crate::Backend::resolve_tab_bar_layout(
            driver.core.backend_mut(),
            InteractiveTabBarApp::RECT,
            &bar,
        );
        // `resolve_tab_bar_layout` is bar-relative (see its doc), while
        // `tab_close_center` returns absolute driver/screen coordinates —
        // undo the `rect.x`/`rect.y` shift `TuiDriver::tab_close_center`
        // applied before handing the point to `hit_test`.
        let local_x = x - InteractiveTabBarApp::RECT.x;
        let local_y = y - InteractiveTabBarApp::RECT.y;

        assert_eq!(
            resolved.hit_test(local_x, local_y),
            TabBarHit::TabClose(1),
            "the close-glyph rect `draw_tab_bar` painted must be the same \
             rect a consumer hit-tests against"
        );
    }

    /// Acceptance criterion: `tab_close_center` returns `None` for a tab
    /// rendered with `is_closable: false`.
    #[test]
    fn tab_close_center_none_when_tab_not_closable() {
        struct NonClosableTabBarApp;

        impl AppLogic for NonClosableTabBarApp {
            type AreaId = ();

            fn render(&self, backend: &mut dyn Backend, _area: ()) {
                backend.draw_tab_bar(
                    Rect::new(0.0, 0.0, 20.0, 1.0),
                    &TabBar {
                        id: QWidgetId::new("tabs"),
                        tabs: vec![TabItem {
                            label: "a".to_string(),
                            is_active: true,
                            is_dirty: false,
                            is_preview: false,
                            is_closable: false,
                        }],
                        scroll_offset: 0,
                        right_segments: vec![],
                        active_accent: None,
                        show_tab_close: true,
                        compact: false,
                    },
                    None,
                );
            }

            fn handle(&mut self, _event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
                Reaction::Continue
            }
        }

        let driver = TuiDriver::new(NonClosableTabBarApp, 20, 1);
        let bar_id = QWidgetId::new("tabs");

        assert!(
            driver.tab_center(&bar_id, 0).is_some(),
            "the tab itself is visible"
        );
        assert!(
            driver.tab_close_center(&bar_id, 0).is_none(),
            "a non-closable tab drew no close button, so its center must be None"
        );
    }

    /// Acceptance criterion: `tab_center` returns `None` for a tab hidden
    /// behind the bar's `scroll_offset`.
    #[test]
    fn tab_center_none_when_scrolled_out_of_view() {
        struct ScrolledTabBarApp;

        impl AppLogic for ScrolledTabBarApp {
            type AreaId = ();

            fn render(&self, backend: &mut dyn Backend, _area: ()) {
                backend.draw_tab_bar(
                    Rect::new(0.0, 0.0, 5.0, 1.0),
                    &TabBar {
                        id: QWidgetId::new("tabs"),
                        tabs: vec![
                            TabItem {
                                label: "a".to_string(),
                                is_active: false,
                                is_dirty: false,
                                is_preview: false,
                                is_closable: true,
                            },
                            TabItem {
                                label: "b".to_string(),
                                is_active: true,
                                is_dirty: false,
                                is_preview: false,
                                is_closable: true,
                            },
                            TabItem {
                                label: "c".to_string(),
                                is_active: false,
                                is_dirty: false,
                                is_preview: false,
                                is_closable: true,
                            },
                        ],
                        // Bar is far too narrow (5 cells) for all 3 tabs
                        // (each ~3 cells with a close button); TUI honours
                        // this caller-supplied offset directly rather than
                        // computing its own (no scroll arrows in TUI).
                        scroll_offset: 1,
                        right_segments: vec![],
                        active_accent: None,
                        show_tab_close: true,
                        compact: false,
                    },
                    None,
                );
            }

            fn handle(&mut self, _event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
                Reaction::Continue
            }
        }

        let driver = TuiDriver::new(ScrolledTabBarApp, 5, 1);
        let bar_id = QWidgetId::new("tabs");

        assert!(
            driver.tab_center(&bar_id, 0).is_none(),
            "tab 0 is scrolled out of view behind scroll_offset=1"
        );
        assert!(driver.tab_close_center(&bar_id, 0).is_none());
        assert!(
            driver.tab_center(&bar_id, 1).is_some(),
            "tab 1 (the scroll target) should still be visible"
        );
    }

    // ── Background-thread wake ──────────────────────────────────────────
    //
    // Before `Backend::waker` existed, there was no `Send`-safe way to get
    // a value from a background thread into the app at all — every
    // runner was poll-only (grep any `run.rs` for `mpsc`/`Waker`/
    // `channel(`: zero hits). These tests are the driver-tier proof this
    // is fixed for TUI: a real `std::thread::spawn`'d thread calls the
    // closure `Backend::waker` hands out, and the payload it carries
    // reaches `AppLogic::handle` and changes what's rendered — the same
    // production `dispatch_event` pipeline every other driver test in this
    // module exercises, not a bypass.

    /// Renders whatever string the most recent `UiEvent::User` carried, or
    /// "waiting" if none has arrived yet — so the test can assert on a
    /// *rendered* screen change, not just that `handle` was called.
    struct BackgroundResultApp {
        last: String,
    }

    impl BackgroundResultApp {
        fn new() -> Self {
            Self {
                last: "waiting".to_string(),
            }
        }
    }

    impl AppLogic for BackgroundResultApp {
        type AreaId = ();

        fn render(&self, backend: &mut dyn Backend, _area: ()) {
            backend.draw_text_display(
                Rect::new(0.0, 0.0, 40.0, 1.0),
                &crate::TextDisplay {
                    id: QWidgetId::new("result"),
                    lines: vec![crate::TextDisplayLine {
                        spans: vec![crate::types::StyledSpan::plain(self.last.clone())],
                        decoration: Default::default(),
                        timestamp: None,
                    }],
                    scroll_offset: 0,
                    auto_scroll: true,
                    max_lines: 0,
                    has_focus: false,
                    title: None,
                    show_scrollbar: false,
                },
            );
        }

        fn handle(&mut self, event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
            match event {
                UiEvent::User(payload) => {
                    if let Some(text) = payload.downcast_ref::<String>() {
                        self.last = text.clone();
                        Reaction::Redraw
                    } else {
                        Reaction::Continue
                    }
                }
                _ => Reaction::Continue,
            }
        }
    }

    /// Calling the closure `Backend::waker()` returns from another thread
    /// delivers a `UiEvent::User` that reaches `AppLogic::handle` and
    /// produces a rendered change.
    #[test]
    fn waker_delivers_background_thread_result_to_rendered_output() {
        let mut driver = TuiDriver::new(BackgroundResultApp::new(), 40, 3);
        assert!(
            driver.screen_contains("waiting"),
            "initial render should show the placeholder"
        );

        let waker = driver.backend().waker();
        let handle = std::thread::spawn(move || {
            waker(crate::UserPayload::new("done from background".to_string()));
        });
        handle.join().expect("background thread must not panic");

        let reaction = driver.pump_user_events();
        assert_eq!(
            reaction,
            Reaction::Redraw,
            "delivering the queued UiEvent::User must trigger a redraw"
        );
        assert!(
            driver.screen_contains("done from background"),
            "the background thread's payload must reach rendered output"
        );
        assert!(
            !driver.screen_contains("waiting"),
            "the placeholder must be gone once the real result renders"
        );
    }

    /// The closure `waker()` returns is reusable and thread-agnostic: two
    /// separate background threads can each call it once, and both
    /// payloads are delivered in the order they were pushed.
    #[test]
    fn waker_delivers_multiple_background_payloads_in_order() {
        let mut driver = TuiDriver::new(BackgroundResultApp::new(), 40, 3);

        let waker1 = driver.backend().waker();
        let waker2 = driver.backend().waker();
        let t1 = std::thread::spawn(move || {
            waker1(crate::UserPayload::new("first".to_string()));
        });
        t1.join().unwrap();
        let t2 = std::thread::spawn(move || {
            waker2(crate::UserPayload::new("second".to_string()));
        });
        t2.join().unwrap();

        driver.pump_user_events();
        assert!(
            driver.screen_contains("second"),
            "the later payload must win — both were delivered in push order"
        );
    }

    use crate::compose::app_shell::{AppShellLayout, PanelDefinition};
    use crate::shell::ShellContext;
    use crate::types::Icon;

    /// Minimal `ShellApp` that flips `nerd_fonts_enabled` once in `setup()`
    /// — the pattern `Backend::set_nerd_fonts`'s own doc recommends for a
    /// flag that's static for the process lifetime.
    struct NerdFontsToggleApp {
        nerd_fonts: bool,
    }

    impl ShellApp for NerdFontsToggleApp {
        fn render_content(&self, _backend: &mut dyn Backend, _layout: &AppShellLayout) {}

        fn handle(
            &mut self,
            _event: UiEvent,
            _backend: &mut dyn Backend,
            _ctx: &ShellContext,
        ) -> Reaction {
            Reaction::Continue
        }

        fn setup(&mut self, backend: &mut dyn Backend) {
            backend.set_nerd_fonts(self.nerd_fonts);
        }
    }

    /// The `ShellConfig` used by acceptance tests: one top panel and one
    /// bottom item, each carrying a `with_panel_icon` override whose
    /// glyph/fallback halves are unmistakable non-ASCII symbols — chosen so
    /// they can't collide with any chrome text (titles, tooltips) the shell
    /// itself paints.
    fn nerd_fonts_toggle_config() -> ShellConfig {
        let panel_id = WidgetId::new("panel:explorer");
        let bottom_id = WidgetId::new("panel:settings");
        ShellConfig::new(
            "Demo",
            vec![PanelDefinition {
                id: panel_id.clone(),
                icon: "X".to_string(),
                tooltip: "Explorer".to_string(),
                title: "EXPLORER".to_string(),
            }],
        )
        .with_bottom_items(vec![PanelDefinition {
            id: bottom_id.clone(),
            icon: "Y".to_string(),
            tooltip: "Settings".to_string(),
            title: "SETTINGS".to_string(),
        }])
        .with_panel_icon(panel_id, Icon::new("\u{f07c}", "\u{25c6}"))
        .with_panel_icon(bottom_id, Icon::new("\u{f013}", "\u{25a0}"))
    }

    /// A `ShellConfig` panel-icon override, rendered through
    /// `driver_with_shell` — the consumer path a real `ShellApp` takes —
    /// with `nerd_fonts_enabled` off, paints the fallback.
    #[test]
    fn shell_config_panel_icon_paints_fallback_when_nerd_fonts_off() {
        let driver = driver_with_shell(
            NerdFontsToggleApp { nerd_fonts: false },
            nerd_fonts_toggle_config(),
            40,
            10,
        );
        assert!(
            driver.screen_contains("\u{25c6}"),
            "nerd_fonts off must paint the top panel's fallback glyph"
        );
        assert!(
            !driver.screen_contains("\u{f07c}"),
            "nerd_fonts off must not paint the top panel's Nerd Font glyph"
        );
    }

    /// The same config with `nerd_fonts_enabled` on paints the glyph.
    #[test]
    fn shell_config_panel_icon_paints_glyph_when_nerd_fonts_on() {
        let driver = driver_with_shell(
            NerdFontsToggleApp { nerd_fonts: true },
            nerd_fonts_toggle_config(),
            40,
            10,
        );
        assert!(
            driver.screen_contains("\u{f07c}"),
            "nerd_fonts on must paint the top panel's Nerd Font glyph"
        );
        assert!(
            !driver.screen_contains("\u{25c6}"),
            "nerd_fonts on must not paint the top panel's fallback glyph"
        );
    }

    /// Bottom-item half: fallback when nerd_fonts is off — pins that the
    /// override reaches `bottom_items`, not just `panels`.
    #[test]
    fn shell_config_panel_icon_paints_fallback_for_bottom_item_when_nerd_fonts_off() {
        let driver = driver_with_shell(
            NerdFontsToggleApp { nerd_fonts: false },
            nerd_fonts_toggle_config(),
            40,
            10,
        );
        assert!(
            driver.screen_contains("\u{25a0}"),
            "nerd_fonts off must paint the bottom item's fallback glyph"
        );
        assert!(
            !driver.screen_contains("\u{f013}"),
            "nerd_fonts off must not paint the bottom item's Nerd Font glyph"
        );
    }

    /// Bottom-item half: glyph when nerd_fonts is on.
    #[test]
    fn shell_config_panel_icon_paints_glyph_for_bottom_item_when_nerd_fonts_on() {
        let driver = driver_with_shell(
            NerdFontsToggleApp { nerd_fonts: true },
            nerd_fonts_toggle_config(),
            40,
            10,
        );
        assert!(
            driver.screen_contains("\u{f013}"),
            "nerd_fonts on must paint the bottom item's Nerd Font glyph"
        );
        assert!(
            !driver.screen_contains("\u{25a0}"),
            "nerd_fonts on must not paint the bottom item's fallback glyph"
        );
    }

    /// `resize` must shrink the physical `TestBackend` buffer immediately,
    /// but leave `TuiBackend`'s cached viewport exactly as it was after the
    /// last `render()` — the stale-layout-vs-shrunk-buffer condition,
    /// reproducible from a driver test instead of only a hand-built
    /// `Buffer`/`Rect` pair.
    #[test]
    fn resize_shrinks_buffer_without_touching_cached_viewport() {
        let mut driver = TuiDriver::new(
            OneLineApp {
                text: "hello resize world",
            },
            30,
            3,
        );
        assert_eq!(
            (
                driver.backend().viewport().width,
                driver.backend().viewport().height
            ),
            (30.0, 3.0),
            "sanity: TuiBackend's viewport should start matching the driver's initial size"
        );

        driver.resize(5, 1);

        // The physical buffer shrank immediately...
        let area = driver.terminal.borrow().backend().buffer().area;
        assert_eq!(
            (area.width, area.height),
            (5, 1),
            "resize() must shrink the TestBackend's real cell buffer right away"
        );

        // ...but TuiBackend's cached viewport must NOT have moved: `resize`
        // never reaches into `TuiBackend` at all, only `render()` does.
        assert_eq!(
            (
                driver.backend().viewport().width,
                driver.backend().viewport().height
            ),
            (30.0, 3.0),
            "resize() must not touch TuiBackend's cached viewport — it should stay stale \
             at the pre-resize size until the next render()"
        );

        // Driving a repaint against a buffer now far smaller than the
        // app's content assumes must not panic — the stale-layout-vs-shrunk-
        // buffer condition, reproduced here at driver tier rather than by
        // hand-building a `Buffer`/`Rect` pair.
        driver.render();

        // render()'s autoresize rebases TuiBackend's viewport to
        // the new, smaller size before `app.render()` runs, so it's back
        // in sync afterward.
        assert_eq!(
            (
                driver.backend().viewport().width,
                driver.backend().viewport().height
            ),
            (5.0, 1.0),
            "render() after resize() must resync TuiBackend's viewport to the new size"
        );
    }
}