quadraui 0.6.1

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
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
//! `ChatController` — composed chat overlay controller.
//!
//! Owns all interaction state for a chat overlay: a scrollable transcript,
//! a multi-line input box with history navigation, and a status strip.
//!
//! Apps push transcript turns per frame via
//! [`ChatController::set_transcript`], call
//! [`ChatController::render`] + [`ChatController::handle`], and match on
//! [`ChatControllerEvent`] for semantic actions.
//!
//! # Keyboard behaviour
//!
//! By default (`submit_on_enter == false`, see
//! [`set_submit_on_enter`](ChatController::set_submit_on_enter)):
//!
//! - `Ctrl+S`, `Alt+Enter`, or `Ctrl+Enter` — submit the current input.
//!   `Ctrl+S` and `Alt+Enter` work on most terminals; `Ctrl+Enter` requires Kitty
//!   keyboard protocol (supported by kitty, Alacritty ≥0.12, WezTerm, foot).
//!   **Note**: `Ctrl+S` is the XON/XOFF flow-control suspend key in some
//!   terminal configurations (`stty -ixon` disables it). If `Ctrl+S` appears
//!   to freeze the terminal, run `stty -ixon` or use `Alt+Enter` instead.
//! - `Enter` — insert a newline in the input.
//!
//! When `submit_on_enter == true` (Enter sends by default):
//!
//! - `Enter` (no modifiers) — submit the current input.
//! - `Shift+Enter` — insert a newline. `Alt+Enter` is accepted as a
//!   fallback for terminals that cannot report `Shift+Enter`.
//! - `Ctrl+S` / `Ctrl+Enter` still submit, same as the default mode.
//!
//! In both modes:
//!
//! - `Esc` — emit [`ChatControllerEvent::Cancelled`]; the app decides
//!   whether to close the overlay.
//! - The input soft-wraps long lines to fit the box, and `↑`/`↓`
//!   move by **visual** row, not logical line — see this module's *Input
//!   soft-wrap and auto-grow* section on [`ChatController`].
//! - `↑` (when the cursor is on the first visual row of the whole
//!   buffer) — navigate to the previous history entry.
//! - `↓` (when the cursor is on the last visual row of the whole buffer)
//!   — navigate to the next history entry or restore the saved input.
//! - `PageUp` / `PageDown` — scroll the transcript.
//! - `↑` / `↓` when the cursor is not on the first/last visual row — move
//!   the cursor within the input (by visual row, so it can move within a
//!   single wrapped logical line).
//! - `Ctrl+A` — move the cursor to the beginning of the current line
//!   (readline convention).
//! - `Ctrl+E` — move the cursor to the end of the current line
//!   (readline convention).
//!
//! # Scroll behaviour
//!
//! Mouse-wheel events (positive `delta.y` = scroll up) scroll the
//! transcript by 3 rows per tick. Backends normalise their native
//! scroll direction before emitting [`crate::UiEvent::Scroll`].
//!
//! # Send / Stop segment
//!
//! A clickable segment is painted at the right of the input row —
//! reusing [`crate::Form`]'s existing `FieldKind::Button` rasteriser so no
//! new [`Backend`] trait method is needed, same rationale as
//! [`render`](Self::render)'s doc. It reads **Send** normally and **Stop**
//! while [`set_busy`](Self::set_busy)`(true)` is in effect. Clicking it:
//!
//! - while idle — behaves exactly like a keyboard submit (same
//!   history-push and [`ChatControllerEvent::Submit`] emission), or is
//!   ignored when the input is empty;
//! - while busy — emits [`ChatControllerEvent::StopRequested`] instead
//!   of touching the input buffer at all.
//!
//! The segment is omitted (and the `TextInput` takes the full row width)
//! when the row is too narrow to fit both.
//!
//! # Persistent hint line
//!
//! [`set_hint`](Self::set_hint) configures an optional one-row hint
//! painted directly above the input box. Unlike the `TextInput`
//! placeholder (which only shows while the buffer is empty and vanishes
//! on the first keystroke), the hint stays visible while typing — the
//! spot for a persistent "Enter to send, Shift+Enter for newline" style
//! affordance. `None` (default) omits the row entirely, so the layout is
//! unchanged for callers that don't opt in.
//!
//! # Collapsible turns and per-turn hit regions
//!
//! Per-turn collapsed/summary state lives on **`ChatController`**, keyed by
//! transcript index — not as fields on [`ChatTurn`] itself. Both downstream
//! consumers construct `ChatTurn` via exhaustive struct literals, so adding
//! public fields to that struct is a breaking change with no in-repo
//! migration path; keeping the state on the controller instead means
//! `ChatTurn`'s field set (and every existing constructor) is untouched by
//! this feature. See [`is_turn_collapsed`](Self::is_turn_collapsed),
//! [`set_turn_collapsed`](Self::set_turn_collapsed),
//! [`toggle_turn_collapsed`](Self::toggle_turn_collapsed),
//! [`set_turn_summary`](Self::set_turn_summary), and
//! [`turn_summary_line`](Self::turn_summary_line). A collapsed turn paints
//! as a one-line card — the role header (with a `▸` fold indicator) plus
//! [`turn_summary_line`](Self::turn_summary_line) — instead of its full
//! body. Every turn starts expanded, so existing callers are visually
//! unchanged.
//!
//! A click anywhere in the transcript resolves to the turn and in-turn row
//! it landed on: [`handle`](Self::handle) returns
//! [`ChatControllerEvent::TurnClicked`]`{ turn_idx, row_in_turn }`, and also
//! moves [`focused_turn`](Self::focused_turn) to `Some(turn_idx)` so a
//! following keyboard `Enter` acts on the same turn the mouse just landed
//! on. **Caveat:** each turn's row block ends with the blank inter-turn
//! separator row, which is folded into the *preceding* turn — for a
//! single-line turn, `row_in_turn == 0` is the header, `1` is the body, and
//! `2` is that trailing blank separator, all attributed to that turn. A
//! consumer resolving `row_in_turn > 0` to a `path:line` location should
//! account for this rather than assume every `row_in_turn` maps to real
//! content. The controller does not itself toggle `collapsed` on click —
//! that decision (fold the card vs. jump to a `path:line` location inside
//! it) is app/consumer-specific — but
//! [`toggle_turn_collapsed`](Self::toggle_turn_collapsed) /
//! [`set_turn_collapsed`](Self::set_turn_collapsed) are there to act on it.
//!
//! [`focused_turn`](Self::focused_turn) is a keyboard cursor into the
//! transcript: `Tab` (and `Shift+Tab` / `BackTab`) cycle it through
//! `None` (input has focus) → turn `0` → … → the last turn → back to
//! `None`. While a turn is focused, plain `Enter` toggles that turn's
//! collapsed state instead of submitting or inserting a newline — so
//! the whole interaction works without a mouse. Typing a character (or
//! pasting) always returns focus to the input, regardless of where `Tab`
//! or a transcript click last parked the cursor.

use crate::compose::markdown::render_markdown_to_styled;
use crate::primitives::scrollbar::{scroll_by_clamped, wheel_row_delta, PressZone, ThumbDrag};
use crate::text_util::{
    next_char_boundary, prev_char_boundary, safe_prefix, snap_to_char_boundary, wrap_spans,
    WrapPolicy,
};
use crate::theme::Theme;
use crate::types::StyledSpan;
use crate::{
    Backend, ButtonMask, Color, FieldKind, Form, FormField, Key, MessageList, MessageListHit,
    MessageListMeasure, MessageRow, Modifiers, MouseButton, NamedKey, Point, Rect, Scrollbar,
    Spinner, StyledText, TextInput, TextInputHit, UiEvent, WidgetId,
};
use serde::{Deserialize, Serialize};
use std::cell::Cell;
use std::collections::{HashMap, HashSet};

/// Transcript rows moved by one notch of a classic mouse wheel
/// (`ScrollDelta::y == ±1.0`). A finer-grained trackpad delta scrolls
/// proportionally less, a coarser one proportionally more.
const TRANSCRIPT_ROWS_PER_NOTCH: f32 = 3.0;

// ── Public types ───────────────────────────────────────────────────────────────

/// Role of a chat participant.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ChatRole {
    /// A message from the end-user.
    User,
    /// A message from the AI assistant.
    Assistant,
    /// An informational system message (seed prompt label, tool output, etc.).
    System,
}

/// A single turn in the chat transcript.
///
/// `text` is a [`StyledText`] so rich markdown-derived colouring can be added
/// in a future pass. When `line_scales` is non-empty (turns created via
/// [`ChatController::push_turn_markdown`]), the transcript renderer builds
/// styled [`MessageRow`]s with per-span fg/bold/italic and per-line heading
/// scale; otherwise it falls back to concatenating span text (the flat path).
///
/// **Collapsed/summary state deliberately lives on
/// [`ChatController`], not here.** Both downstream consumers construct
/// `ChatTurn` via exhaustive struct literals (no `..Default::default()`),
/// so adding fields to this struct is a hard breaking change with no
/// migration path available from within this repo — see
/// [`ChatController::is_turn_collapsed`], [`ChatController::set_turn_collapsed`],
/// and [`ChatController::turn_summary_line`] for the equivalent per-turn
/// state, keyed by transcript index instead of carried on the turn value
/// itself.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatTurn {
    pub role: ChatRole,
    pub text: StyledText,
    /// Unix epoch seconds; `None` when not recorded.
    pub timestamp_unix: Option<f64>,
    /// Per-line font-scale factors, parallel to the logical lines in `text`.
    ///
    /// Non-empty only for turns created by [`ChatController::push_turn_markdown`]
    /// (where the markdown adapter supplies one scale per input line).  `1.0` for
    /// body lines; `2.0` / `1.5` / `1.2` for H1 / H2 / H3 headings.
    ///
    /// When empty the transcript renderer uses the flat (legacy) path so that
    /// turns created via [`ChatController::push_turn`] or
    /// [`ChatController::set_transcript`] are visually unchanged.
    #[serde(default)]
    pub line_scales: Vec<f32>,
}

/// Events emitted by [`ChatController::handle`].
#[derive(Debug, Clone, PartialEq)]
pub enum ChatControllerEvent {
    /// User submitted a message (`Ctrl+S`, `Alt+Enter`, or `Ctrl+Enter`). Contains the full input text
    /// (with embedded `\n` for multi-line messages). Apps should:
    /// 1. Append the text as a `User` turn to their own transcript.
    /// 2. Call [`ChatController::clear_input`].
    /// 3. Start their backend session continuation (subprocess, API call, etc.).
    Submit { text: String },
    /// Stream chunk (reserved for the backend-push path; apps that own
    /// the session pipe call [`ChatController::set_transcript`] directly).
    StreamChunk { text: String },
    /// User pressed `Esc`. The app decides whether to close the overlay,
    /// show a confirmation dialog, or ignore it.
    Cancelled,
    /// User clicked the Send/Stop segment while [`ChatController::set_busy`]
    /// was `true`. Distinct from [`Cancelled`](Self::Cancelled),
    /// which is about closing the overlay — this is about interrupting an
    /// in-flight generation. The app should stop its backend session
    /// continuation (kill the subprocess, cancel the API call, etc.); the
    /// input buffer is left untouched.
    StopRequested,
    /// A key press that the chat controller did not consume. Apps can
    /// bind hotkeys here (e.g. `'c'` to copy the last assistant turn).
    KeyPressed { key: String, modifiers: Modifiers },
    /// A click landed on a transcript row belonging to `turn_idx`, at
    /// `row_in_turn` rows into that turn's block (`0` = the role header
    /// row). Also moves [`ChatController::focused_turn`] to
    /// `Some(turn_idx)`, so a keyboard `Enter` right after the click acts on
    /// the same turn. The controller does not itself toggle the turn's
    /// collapsed state on click — apps decide what a click means (toggle
    /// the card when `row_in_turn == 0`, resolve a `path:line` location
    /// elsewhere in the body, etc.) and call
    /// [`ChatController::toggle_turn_collapsed`] /
    /// [`ChatController::set_turn_collapsed`] themselves.
    ///
    /// **`row_in_turn` includes the trailing blank separator row** between
    /// this turn and the next, attributed to *this* turn (e.g. for a
    /// 1-line turn, `0` = header, `1` = body, `2` = the blank separator) —
    /// see this module's *Collapsible turns and per-turn hit regions*
    /// section.
    TurnClicked { turn_idx: usize, row_in_turn: usize },
    /// Event was consumed (state changed, caller should redraw).
    Consumed,
    /// Event was not handled by the controller.
    Ignored,
}

// ── Internal types ─────────────────────────────────────────────────────────────

/// Pre-computed rect zones for one render/handle pass.
struct ChatLayout {
    status: Rect,
    transcript: Rect,
    scrollbar: Option<Rect>,
    /// Spinner rect within the status strip (rightmost `line_height` px).
    spinner: Option<Rect>,
    /// Persistent hint row directly above the input box. `None`
    /// when [`ChatController::set_hint`] hasn't been called.
    hint: Option<Rect>,
    input: Rect,
    /// Clickable Send/Stop segment at the right of the input row.
    /// `None` when the row is too narrow to fit both it and the
    /// `TextInput`.
    send: Option<Rect>,
}

// ── Controller ─────────────────────────────────────────────────────────────────

/// Cross-backend compose controller for a chat overlay.
///
/// Renders a 3-zone modal over its host rect: a 1-row status strip at the top,
/// a scrollable transcript in the middle, and a multi-line `TextInput` at the
/// bottom. All rendering is delegated to existing [`Backend`] trait methods —
/// `draw_message_list`, `draw_scrollbar`, `draw_text_input`, `draw_spinner` —
/// so no new trait method is needed.
///
/// State ownership follows the [`TreeController`](super::tree_controller::TreeController)
/// pattern: the app pushes transcript turns per frame via
/// [`set_transcript`](Self::set_transcript), and the controller owns only
/// interaction state (scroll position, input buffer, history ring).
///
/// # Wrapping
///
/// Plain-text turns (from [`push_turn`](Self::push_turn) /
/// [`set_transcript`](Self::set_transcript)) are **word-wrapped** via
/// [`crate::text_util::word_wrap`]: rows break at whitespace where
/// possible, and only a single word wider than the column budget falls
/// back to a mid-word hard break (e.g. with a 10-column budget
/// `"implementation"` becomes `"implementa"` + `"tion"`).
///
/// Styled turns (from [`push_turn_markdown`](Self::push_turn_markdown))
/// wrap per-span at exactly the display-width budget, ignoring word
/// boundaries — [`crate::text_util::wrap_spans`] with
/// [`crate::text_util::WrapPolicy::Char`]. `Word` wrapping is available
/// on the same function (markdown rendering uses it — see
/// [`crate::compose::markdown`]) but is intentionally not used here yet.
///
/// # Input soft-wrap and auto-grow
///
/// The input box's `TextInput` is built from the *wrapped* buffer, not the
/// raw one: [`build_text_input`](Self::build_text_input) soft-wraps
/// `input_buf` to [`TextInput::content_cols`] before handing it to the
/// primitive, so long lines wrap inside the box instead of scrolling
/// horizontally. Wrapping is exact — a visual row is always a contiguous
/// byte range of its logical line, with no whitespace collapsed or
/// dropped (unlike [`crate::text_util::word_wrap`]'s transcript wrapping,
/// which *is* lossy at wrap points) — so cursor positions map losslessly
/// between logical `(line, byte offset)` space (what `input_buf`/
/// `input_cursor` store) and visual `(row, char column)` space (what the
/// painted `TextInput` shows).
///
/// `↑`/`↓` move the cursor by **visual** row, not logical line: pressing
/// `↑` partway through a wrapped paragraph moves to the previous visual
/// row within it; history recall only triggers at the *first* / *last*
/// visual row of the whole buffer (see the `Key::Named(NamedKey::Up)` /
/// `Down` arms of [`Self::handle_key`]).
///
/// The input box's painted height auto-grows with content: it's the
/// wrapped visual row count, clamped to
/// [`input_min_rows`, `input_max_rows`](Self::set_input_height_range)
/// (default `1..=8`). Once the row count exceeds `input_max_rows` the box
/// stops growing and [`TextInput::layout`]'s own vertical auto-scroll
/// keeps the cursor in view, same as any other overflowing `TextInput`.
pub struct ChatController {
    id: WidgetId,
    // ── Per-frame data pushed by the app ──────────────────────────────
    transcript: Vec<ChatTurn>,
    status_label: StyledText,
    busy: bool,
    model_label: String,
    spinner_frame: usize,
    // ── Input buffer ─────────────────────────────────────────────────
    /// Raw text with embedded `\n` separating logical lines.
    input_buf: String,
    /// Byte offset of the cursor inside `input_buf`.
    input_cursor: usize,
    /// Vertical scroll offset forwarded to [`TextInput::scroll_offset`].
    input_scroll_offset: usize,
    /// Whether the input has keyboard focus (controls cursor visibility).
    input_has_focus: bool,
    // ── Input history ─────────────────────────────────────────────────
    /// Past submitted messages (most-recent last).
    history: Vec<String>,
    /// Position in `history` when navigating, or `None` when not in
    /// history navigation mode.
    history_pos: Option<usize>,
    /// Input state saved when the user first pressed `↑` to enter history
    /// navigation. Restored on `↓` past the newest history entry.
    saved_input: Option<(String, usize)>,
    // ── Transcript scroll ─────────────────────────────────────────────
    /// First visible wrapped row.
    ///
    /// Stored in a [`Cell`] so that [`render`](Self::render) (which takes
    /// `&self` to satisfy the [`AppLogic`] trait contract) can update the
    /// position when follow-tail is engaged — without requiring the caller to
    /// hold a `&mut` reference.
    transcript_scroll_top: Cell<usize>,
    transcript_drag: Option<ThumbDrag>,
    /// When `true` the viewport is pinned to the tail: each [`render`] call
    /// drives `transcript_scroll_top` to `total_rows − visible_rows` so
    /// freshly-appended content stays visible.
    ///
    /// Starts `true` on construction.  Disengaged whenever the user scrolls
    /// up (via wheel, PageUp, or scrollbar drag); re-engaged whenever the
    /// user scrolls back down to the bottom row.
    ///
    /// [`render`]: Self::render
    stuck_to_bottom: bool,
    /// Keyboard cursor into the transcript: `Some(turn_idx)` when
    /// `Tab`/`Shift+Tab` (or a transcript click) has moved focus off the
    /// input and onto a turn, so `Enter` toggles that turn's collapsed
    /// state instead of submitting/inserting a newline. `None` means the
    /// input has focus (the default). See
    /// [`focus_next_turn`](Self::focus_next_turn).
    focused_turn: Option<usize>,
    /// Per-turn collapsed state, keyed by transcript index —
    /// deliberately *not* a field on [`ChatTurn`] itself; see this
    /// struct's *Collapsible turns and per-turn hit regions* doc section
    /// for why. Absence means expanded (the default). Entries are not
    /// remapped when [`set_transcript`](Self::set_transcript) replaces the
    /// transcript with turns in a different order — see
    /// [`is_turn_collapsed`](Self::is_turn_collapsed).
    turn_collapsed: HashSet<usize>,
    /// Per-turn summary-line override, keyed the same way as
    /// `turn_collapsed`. See
    /// [`turn_summary_line`](Self::turn_summary_line).
    turn_summary: HashMap<usize, String>,
    // ── Config ────────────────────────────────────────────────────────
    /// Auto-grow floor: the input area is never shorter than this many
    /// rows, even when empty. Default: `1`. See
    /// [`set_input_height_range`](Self::set_input_height_range).
    input_min_rows: usize,
    /// Auto-grow ceiling: the input area stops growing at this many rows;
    /// beyond it, content scrolls inside a fixed-height box instead.
    /// Default: `8`. See
    /// [`set_input_height_range`](Self::set_input_height_range).
    input_max_rows: usize,
    /// Fixed scrollbar track width in surface units, or `None` to use
    /// `backend.line_height()` (same convention as `TreeController`).
    scrollbar_width: Option<f32>,
    /// When `true`, `Enter` submits and `Shift+Enter` (or `Alt+Enter` as a
    /// fallback) inserts a newline. Default `false` — `Enter` always inserts
    /// a newline. See [`set_submit_on_enter`](Self::set_submit_on_enter).
    submit_on_enter: bool,
    /// Persistent hint row painted above the input box, or `None` to omit
    /// it. See [`set_hint`](Self::set_hint).
    hint: Option<StyledText>,
}

impl ChatController {
    /// Create a new controller. `id` is used to namespace widget IDs for all
    /// sub-primitives (transcript, scrollbar, input, spinner).
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: WidgetId::new(id),
            transcript: Vec::new(),
            status_label: StyledText::plain(""),
            busy: false,
            model_label: String::new(),
            spinner_frame: 0,
            input_buf: String::new(),
            input_cursor: 0,
            input_scroll_offset: 0,
            input_has_focus: true,
            history: Vec::new(),
            history_pos: None,
            saved_input: None,
            transcript_scroll_top: Cell::new(0),
            transcript_drag: None,
            stuck_to_bottom: true,
            focused_turn: None,
            turn_collapsed: HashSet::new(),
            turn_summary: HashMap::new(),
            input_min_rows: 1,
            input_max_rows: 8,
            scrollbar_width: None,
            submit_on_enter: false,
            hint: None,
        }
    }

    // ── Per-frame data setters ────────────────────────────────────────

    /// Replace the transcript for the next render pass.
    ///
    /// This is the primary streaming hook: the app calls this on every
    /// chunk received from the assistant and then triggers a redraw.
    /// The controller does not hold a reference to the app's turns —
    /// it re-renders from the fresh slice each frame.
    pub fn set_transcript(&mut self, turns: Vec<ChatTurn>) {
        self.transcript = turns;
    }

    /// Set the status-strip context label (e.g. `"Refining issue #N"`).
    pub fn set_status(&mut self, label: StyledText) {
        self.status_label = label;
    }

    /// Enable or disable the busy spinner in the status strip.
    pub fn set_busy(&mut self, busy: bool) {
        self.busy = busy;
    }

    /// Set the model chip label in the status strip (e.g. `"claude-opus-4-5"`).
    pub fn set_model_label(&mut self, label: &str) {
        self.model_label = label.to_string();
    }

    /// Advance the spinner animation frame. Apps increment this on their own
    /// ticker (~100 ms per frame for a braille-style spinner).
    pub fn set_spinner_frame(&mut self, frame: usize) {
        self.spinner_frame = frame;
    }

    // ── Input accessors ───────────────────────────────────────────────

    /// The current input buffer text, with `\n` separating lines.
    pub fn input_text(&self) -> &str {
        &self.input_buf
    }

    /// Clear the input buffer and reset cursor + scroll state.
    ///
    /// Apps call this after handling a [`ChatControllerEvent::Submit`].
    pub fn clear_input(&mut self) {
        self.input_buf.clear();
        self.input_cursor = 0;
        self.input_scroll_offset = 0;
        self.history_pos = None;
        self.saved_input = None;
    }

    /// Whether the input area currently has keyboard focus.
    pub fn input_has_focus(&self) -> bool {
        self.input_has_focus
    }

    /// Set keyboard focus on the input area.
    pub fn set_input_has_focus(&mut self, focus: bool) {
        self.input_has_focus = focus;
    }

    /// Configure the input area's auto-grow row-count clamp.
    ///
    /// The input box's painted height is the wrapped visual row count of
    /// the current buffer, clamped to `[min, max]`, plus the fixed 2-row
    /// border (see [`Self::compute_layout`]). `min` is floored to `1`
    /// (the box never fully collapses); `max` is floored to `min`.
    /// Default: `1..=8`.
    pub fn set_input_height_range(&mut self, min: usize, max: usize) {
        let min = min.max(1);
        let max = max.max(min);
        self.input_min_rows = min;
        self.input_max_rows = max;
    }

    /// Override the scrollbar track width.
    ///
    /// Pass `Some(8.0)` for GTK, `Some(1.0)` for TUI (matching MSV).
    /// `None` (default) falls back to `backend.line_height()`.
    pub fn set_scrollbar_width(&mut self, width: Option<f32>) {
        self.scrollbar_width = width;
    }

    /// Toggle Zed-style "Enter to send" behaviour.
    ///
    /// `true` — `Enter` submits, `Shift+Enter`/`Alt+Enter` insert a
    /// newline. `false` (default) — `Enter` always inserts a newline;
    /// submit is `Ctrl+S` / `Alt+Enter` / `Ctrl+Enter`.
    pub fn set_submit_on_enter(&mut self, submit_on_enter: bool) {
        self.submit_on_enter = submit_on_enter;
    }

    /// Whether `Enter` currently submits (`true`) or inserts a newline
    /// (`false`). See [`set_submit_on_enter`](Self::set_submit_on_enter).
    pub fn submit_on_enter(&self) -> bool {
        self.submit_on_enter
    }

    /// Set (or clear) the persistent hint row painted above the input box.
    /// Pass `None` to omit the row (default).
    ///
    /// Unlike the `TextInput` placeholder, this stays visible while
    /// typing — see this struct's *Persistent hint line* doc section.
    pub fn set_hint(&mut self, hint: Option<StyledText>) {
        self.hint = hint;
    }

    // ── Transcript push helpers ───────────────────────────────────────

    /// Append a pre-styled turn to the controller's internal transcript.
    ///
    /// This is an alternative to [`set_transcript`] for apps that build the
    /// transcript incrementally rather than replacing it each frame.  Do not
    /// mix `push_turn` and `set_transcript` on the same controller — use one
    /// model consistently.
    ///
    /// For markdown-formatted assistant messages, prefer
    /// [`push_turn_markdown`].
    pub fn push_turn(&mut self, role: ChatRole, text: StyledText) {
        self.transcript.push(ChatTurn {
            role,
            text,
            timestamp_unix: None,
            line_scales: Vec::new(),
        });
    }

    /// Append a turn whose body is markdown text.
    ///
    /// This is the **recommended API for assistant-role messages**.  The
    /// markdown adapter ([`render_markdown_to_styled`]) converts headings,
    /// bold, italic, inline code, bulleted and numbered lists, blockquotes,
    /// links, and fenced code blocks to a [`StyledText`] with colours and
    /// decorations baked in.  The resulting [`ChatTurn`] is appended to the
    /// controller's internal transcript.
    ///
    /// Use [`set_transcript`] instead if your app maintains its own
    /// transcript vector and passes it each frame.  Do not mix `push_turn*`
    /// and `set_transcript` on the same controller.
    ///
    /// Markdown lines are interleaved into a single [`StyledText`] with
    /// `'\n'` separator spans so the transcript renderer can split them for
    /// wrapping, preserving the structure produced by the adapter (list
    /// markers, blockquote rules, etc.) as plain-text cues.
    pub fn push_turn_markdown(&mut self, role: ChatRole, markdown: &str, theme: &Theme) {
        let rendered = render_markdown_to_styled(markdown, theme);
        // Preserve line-scale metadata so the transcript renderer can build
        // styled rows with heading sizes.
        let line_scales = rendered.line_scales.clone();
        let mut spans: Vec<StyledSpan> = Vec::new();
        for (i, line) in rendered.lines.into_iter().enumerate() {
            if i > 0 {
                spans.push(StyledSpan::plain("\n"));
            }
            spans.extend(line.spans);
        }
        self.transcript.push(ChatTurn {
            role,
            text: StyledText { spans },
            timestamp_unix: None,
            line_scales,
        });
    }

    /// Current transcript scroll offset (first visible wrapped row).
    ///
    /// After [`render`](Self::render) runs with follow-tail engaged, this
    /// reflects the position that was actually painted (tail row).
    pub fn transcript_scroll_top(&self) -> usize {
        self.transcript_scroll_top.get()
    }

    /// Programmatically override the transcript scroll position.
    ///
    /// This does **not** change the [`stuck_to_bottom`](Self) flag.  If you
    /// want to re-engage follow-tail, call
    /// [`scroll_transcript_by`](Self::scroll_transcript_by) with a large
    /// positive delta so the flag is recomputed against a known `total_rows`
    /// and `visible_rows`.
    pub fn set_transcript_scroll_top(&mut self, top: usize) {
        self.transcript_scroll_top.set(top);
    }

    // ── Collapsible turns ───────────────────────────────────────────────
    //
    // Collapsed/summary state is kept on the controller (`turn_collapsed` /
    // `turn_summary`, keyed by transcript index) rather than as fields on
    // `ChatTurn` — see the module doc's *Collapsible turns and per-turn hit
    // regions* section for why.

    /// Whether `transcript[turn_idx]` is currently rendered collapsed.
    /// `false` (including out-of-range `turn_idx`) when there is no such
    /// turn.
    pub fn is_turn_collapsed(&self, turn_idx: usize) -> bool {
        turn_idx < self.transcript.len() && self.turn_collapsed.contains(&turn_idx)
    }

    /// Set `transcript[turn_idx]`'s collapsed state directly. A no-op if
    /// `turn_idx` is out of range.
    pub fn set_turn_collapsed(&mut self, turn_idx: usize, collapsed: bool) {
        if turn_idx >= self.transcript.len() {
            return;
        }
        if collapsed {
            self.turn_collapsed.insert(turn_idx);
        } else {
            self.turn_collapsed.remove(&turn_idx);
        }
    }

    /// Flip `transcript[turn_idx]`'s collapsed state. A no-op if `turn_idx`
    /// is out of range.
    ///
    /// Apps call this in response to a [`ChatControllerEvent::TurnClicked`]
    /// (typically when `row_in_turn == 0`, the role header row) or to
    /// mirror the keyboard toggle described on [`focused_turn`](Self::focused_turn).
    pub fn toggle_turn_collapsed(&mut self, turn_idx: usize) {
        if turn_idx >= self.transcript.len() {
            return;
        }
        if !self.turn_collapsed.insert(turn_idx) {
            self.turn_collapsed.remove(&turn_idx);
        }
    }

    /// Override `transcript[turn_idx]`'s summary line — see
    /// [`turn_summary_line`](Self::turn_summary_line). Pass `None` to fall
    /// back to the turn's first non-blank content line. A no-op (but not an
    /// error) if `turn_idx` is currently out of range — e.g. an app may set
    /// this ahead of a [`set_transcript`](Self::set_transcript) call that
    /// grows the transcript to include it.
    pub fn set_turn_summary(&mut self, turn_idx: usize, summary: Option<String>) {
        match summary {
            Some(s) => {
                self.turn_summary.insert(turn_idx, s);
            }
            None => {
                self.turn_summary.remove(&turn_idx);
            }
        }
    }

    /// The line shown when `transcript[turn_idx]` is
    /// [collapsed](Self::is_turn_collapsed): the
    /// [`set_turn_summary`](Self::set_turn_summary) override if set,
    /// otherwise the first non-blank line of the turn's plain text. Empty
    /// string for an out-of-range `turn_idx` or a turn with no content.
    pub fn turn_summary_line(&self, turn_idx: usize) -> String {
        if let Some(s) = self.turn_summary.get(&turn_idx) {
            return s.clone();
        }
        let Some(turn) = self.transcript.get(turn_idx) else {
            return String::new();
        };
        let plain: String = turn.text.spans.iter().map(|s| s.text.as_str()).collect();
        plain
            .lines()
            .find(|line| !line.trim().is_empty())
            .unwrap_or("")
            .to_string()
    }

    /// The transcript's keyboard focus cursor: `Some(turn_idx)`
    /// when `Tab`/`Shift+Tab` has moved focus onto a turn (so `Enter`
    /// toggles its collapsed state instead of acting on the input),
    /// `None` when the input has focus (the default).
    pub fn focused_turn(&self) -> Option<usize> {
        self.focused_turn
    }

    /// Programmatically set the transcript's keyboard focus cursor. Pass
    /// `None` to return focus to the input.
    pub fn set_focused_turn(&mut self, turn: Option<usize>) {
        self.focused_turn = turn;
        if turn.is_some() {
            self.input_has_focus = false;
        }
    }

    // ── Render ────────────────────────────────────────────────────────

    /// Paint all three zones into `rect` using `backend`.
    ///
    /// Call this inside [`crate::AppLogic::render`] after resolving the
    /// overlay rect. The controller calls `begin_frame` / `end_frame`
    /// _around_ the draw calls if your app's render path wraps frames
    /// inside the overlay rect — otherwise just call it inline.
    pub fn render(&self, backend: &mut dyn Backend, rect: Rect) {
        let layout = self.compute_layout(backend, rect);

        // ── 1. Status strip ───────────────────────────────────────────
        let status_rows = self.build_status_rows();
        let status_list = MessageList {
            id: WidgetId::new(format!("{}-status", self.id)),
            rows: status_rows,
            scroll_top: 0,
        };
        backend.draw_message_list(layout.status, &status_list);

        // ── 2. Spinner (overlaid at the right end of the status strip) ─
        if self.busy {
            if let Some(sp_rect) = layout.spinner {
                let spinner = Spinner {
                    id: WidgetId::new(format!("{}-spinner", self.id)),
                    label: String::new(),
                    frame_idx: self.spinner_frame,
                    accent: None,
                };
                backend.draw_spinner(sp_rect, &spinner);
            }
        }

        // ── 3. Transcript ─────────────────────────────────────────────
        let col_budget = self.transcript_col_budget(backend.char_width(), layout.transcript);
        let wrapped_rows = self.build_transcript_rows(col_budget);
        let total_rows = wrapped_rows.len();
        // Hoist visible_rows so follow-tail can use it before building MessageList.
        let visible_rows =
            Self::transcript_visible_rows_for(backend.line_height(), layout.transcript);

        // Follow-tail: if stuck to the bottom, pin scroll_top to the last page
        // so newly-appended rows are always visible.  This is a no-op when the
        // content fits entirely in the viewport (total ≤ visible → max = 0).
        // `transcript_scroll_top` is a `Cell<usize>` so we can update it here
        // while `render` takes `&self` (required by the `AppLogic` trait).
        if self.stuck_to_bottom {
            self.transcript_scroll_top
                .set(total_rows.saturating_sub(visible_rows));
        }

        let list = MessageList {
            id: WidgetId::new(format!("{}-transcript", self.id)),
            rows: wrapped_rows,
            scroll_top: self.transcript_scroll_top.get(),
        };
        backend.draw_message_list(layout.transcript, &list);

        // ── 4. Scrollbar ──────────────────────────────────────────────
        if let Some(sb_rect) = layout.scrollbar {
            let track_w = self.scrollbar_track_width(backend.line_height());
            let sb = build_scrollbar(
                format!("{}-sb", self.id),
                sb_rect,
                self.transcript_scroll_top.get(),
                total_rows,
                visible_rows,
                self.transcript_drag.is_some(),
                track_w.max(1.0),
            );
            backend.draw_scrollbar(sb_rect, &sb);
        }

        // ── 5. Hint row ──────────────────────────────────────────────────
        if let Some(hint_rect) = layout.hint {
            let hint_text: String = self
                .hint
                .as_ref()
                .map(|h| h.spans.iter().map(|s| s.text.as_str()).collect())
                .unwrap_or_default();
            let hint_list = MessageList {
                id: WidgetId::new(format!("{}-hint", self.id)),
                rows: vec![MessageRow::new(hint_text, Color::rgb(140, 140, 140), 0.0)],
                scroll_top: 0,
            };
            backend.draw_message_list(hint_rect, &hint_list);
        }

        // ── 6. Text input ─────────────────────────────────────────────
        let col_budget = TextInput::content_cols(layout.input.width, backend.char_width());
        let ti = self.build_text_input(col_budget);
        backend.draw_text_input(layout.input, &ti);

        // ── 7. Send / Stop segment ───────────────────────────────────────
        if let Some(send_rect) = layout.send {
            backend.draw_form(send_rect, &self.build_send_form());
        }
    }

    // ── Handle ────────────────────────────────────────────────────────

    /// Dispatch a [`UiEvent`] to the controller.
    ///
    /// Keyboard events mutate the input buffer; scroll events mutate the
    /// transcript scroll position. Returns a semantic
    /// [`ChatControllerEvent`] for the app to act on.
    ///
    /// `backend` is used only for layout measurements (line_height,
    /// char_width, text_input_layout) — no drawing happens here.
    pub fn handle(
        &mut self,
        event: &UiEvent,
        backend: &dyn Backend,
        rect: Rect,
    ) -> ChatControllerEvent {
        let layout = self.compute_layout(backend, rect);
        match event {
            UiEvent::CharTyped(ch) => {
                self.focus_input();
                self.input_insert_char(*ch);
                ChatControllerEvent::Consumed
            }

            UiEvent::ClipboardPaste(text) => {
                self.focus_input();
                self.input_insert_str(text);
                ChatControllerEvent::Consumed
            }

            UiEvent::KeyPressed { key, modifiers, .. } => {
                self.handle_key(key, modifiers, backend, &layout)
            }

            UiEvent::Scroll { delta, .. } => {
                let visible =
                    Self::transcript_visible_rows_for(backend.line_height(), layout.transcript);
                let col_budget =
                    self.transcript_col_budget(backend.char_width(), layout.transcript);
                let total = self.build_transcript_rows(col_budget).len();
                // Three rows per wheel notch; a larger trackpad delta
                // scrolls proportionally further.
                let rows = wheel_row_delta(delta.y, TRANSCRIPT_ROWS_PER_NOTCH);
                self.scroll_transcript_by(rows, total, visible);
                ChatControllerEvent::Consumed
            }

            UiEvent::MouseDown {
                button: MouseButton::Left,
                position,
                ..
            } => self.handle_click(backend, &layout, position.x, position.y),

            UiEvent::MouseMoved {
                position,
                buttons: ButtonMask { left: true, .. },
            } => self.handle_drag(position.y),

            UiEvent::MouseUp {
                button: MouseButton::Left,
                ..
            } => {
                self.transcript_drag = None;
                ChatControllerEvent::Ignored
            }

            _ => ChatControllerEvent::Ignored,
        }
    }

    // ── Transcript scroll (pub for external use) ───────────────────────

    /// Scroll the transcript by `delta` wrapped rows, clamped to valid range.
    ///
    /// Exposed so callers can drive transcript scrolling without synthesising
    /// a [`UiEvent::Scroll`].
    ///
    /// After clamping, [`stuck_to_bottom`](Self) is recomputed: scrolling up
    /// disengages follow-tail; scrolling back to the last page re-engages it.
    pub fn scroll_transcript_by(&mut self, delta: isize, total_rows: usize, visible_rows: usize) {
        let max = total_rows.saturating_sub(visible_rows);
        let new = scroll_by_clamped(self.transcript_scroll_top.get(), delta, max);
        self.transcript_scroll_top.set(new);
        // Re-engage follow-tail when scrolled to (or past) the last page;
        // disengage it when scrolled up from there.
        self.stuck_to_bottom =
            self.transcript_scroll_top.get() >= total_rows.saturating_sub(visible_rows);
    }

    // ── Focused-turn cursor ─────────────────────────────────────────────

    /// Advance the transcript's focused-turn cursor one step forward — see
    /// [`focused_turn`](Self::focused_turn)'s doc for the cycle order.
    fn focus_next_turn(&mut self) {
        if self.transcript.is_empty() {
            self.focused_turn = None;
            self.input_has_focus = true;
            return;
        }
        self.focused_turn = match self.focused_turn {
            None => Some(0),
            Some(i) if i + 1 < self.transcript.len() => Some(i + 1),
            Some(_) => None,
        };
        self.input_has_focus = self.focused_turn.is_none();
    }

    /// Retreat the transcript's focused-turn cursor one step — the inverse
    /// of [`focus_next_turn`](Self::focus_next_turn).
    fn focus_prev_turn(&mut self) {
        if self.transcript.is_empty() {
            self.focused_turn = None;
            self.input_has_focus = true;
            return;
        }
        self.focused_turn = match self.focused_turn {
            None => Some(self.transcript.len() - 1),
            Some(0) => None,
            Some(i) => Some(i - 1),
        };
        self.input_has_focus = self.focused_turn.is_none();
    }

    /// Return keyboard focus to the input, clearing the focused-turn
    /// cursor. Called whenever the user edits the input buffer, so typing
    /// always means "I'm back in the input" regardless of where `Tab` had
    /// last parked the cursor.
    fn focus_input(&mut self) {
        self.focused_turn = None;
        self.input_has_focus = true;
    }

    // ── Internal helpers ──────────────────────────────────────────────

    fn compute_layout(&self, backend: &dyn Backend, rect: Rect) -> ChatLayout {
        let lh = backend.line_height().max(1.0);
        let status_h = lh;

        // Send/Stop segment: reserve a fixed-width column at the
        // right of the input row when there's room for it alongside a
        // usable `TextInput`.
        let send_w = self.send_segment_width(backend.char_width());
        let show_send = rect.width > send_w * 2.0;
        let input_row_w = if show_send {
            rect.width - send_w
        } else {
            rect.width
        };

        // Auto-grow: height tracks the wrapped visual row count of
        // the current buffer, clamped to [input_min_rows, input_max_rows].
        // TextInput draws a 1-unit border on top and bottom plus content
        // rows. Wraps against `input_row_w`, not the full row width, so
        // auto-grow accounts for the Send/Stop segment eating into it.
        let col_budget = TextInput::content_cols(input_row_w, backend.char_width());
        let visual_rows = wrap_input_rows(&self.input_buf, col_budget).len().max(1);
        let input_rows = visual_rows.clamp(self.input_min_rows, self.input_max_rows);
        let input_h = input_rows as f32 * lh + 2.0;

        // Persistent hint row: a fixed one-row strip directly
        // above the input box, present only when `set_hint` was called.
        let hint_h = if self.hint.is_some() { lh } else { 0.0 };

        let middle_h = (rect.height - status_h - input_h - hint_h).max(0.0);

        let status = Rect::new(rect.x, rect.y, rect.width, status_h);
        let input_y = rect.y + rect.height - input_h;
        let input = Rect::new(rect.x, input_y, input_row_w, input_h);
        let send = if show_send {
            Some(Rect::new(rect.x + input_row_w, input_y, send_w, input_h))
        } else {
            None
        };
        let hint = if hint_h > 0.0 {
            Some(Rect::new(rect.x, input_y - hint_h, rect.width, hint_h))
        } else {
            None
        };

        // Spinner rect: rightmost `lh × lh` square inside the status strip.
        let spinner = if self.busy && rect.width > lh {
            Some(Rect::new(rect.x + rect.width - lh, rect.y, lh, status_h))
        } else {
            None
        };

        // Show scrollbar when transcript has any content and there is room.
        let track_w = self.scrollbar_track_width(backend.line_height());
        let (transcript, scrollbar) = if !self.transcript.is_empty() && rect.width > track_w {
            let t = Rect::new(rect.x, rect.y + status_h, rect.width - track_w, middle_h);
            let s = Rect::new(
                rect.x + rect.width - track_w,
                rect.y + status_h,
                track_w,
                middle_h,
            );
            (t, Some(s))
        } else {
            let t = Rect::new(rect.x, rect.y + status_h, rect.width, middle_h);
            (t, None)
        };

        ChatLayout {
            status,
            transcript,
            scrollbar,
            spinner,
            hint,
            input,
            send,
        }
    }

    fn scrollbar_track_width(&self, line_height: f32) -> f32 {
        self.scrollbar_width.unwrap_or(line_height)
    }

    /// Width of the Send/Stop segment reserved at the right of the input
    /// row. 8 columns comfortably fits either "Send" or "Stop"
    /// plus padding on every backend's default font.
    fn send_segment_width(&self, char_width: f32) -> f32 {
        const SEND_SEGMENT_COLS: f32 = 8.0;
        SEND_SEGMENT_COLS * char_width.max(1.0)
    }

    /// Build the single-button [`Form`] painted into the Send/Stop segment.
    /// Reuses `FieldKind::Button`'s existing cross-backend
    /// rasteriser — see this struct's *Send / Stop segment* doc section.
    fn build_send_form(&self) -> Form {
        let disabled = !self.busy && self.input_buf.trim().is_empty();
        Form {
            id: WidgetId::new(format!("{}-send-form", self.id)),
            fields: vec![FormField {
                id: WidgetId::new(format!("{}-send-btn", self.id)),
                label: StyledText::plain(if self.busy { "Stop" } else { "Send" }),
                kind: FieldKind::Button,
                hint: StyledText::plain(""),
                disabled,
                validation: None,
            }],
            focused_field: None,
            scroll_offset: 0,
            has_focus: false,
        }
    }

    fn transcript_visible_rows_for(line_height: f32, rect: Rect) -> usize {
        if line_height <= 0.0 {
            0
        } else {
            (rect.height / line_height).floor() as usize
        }
    }

    fn transcript_col_budget(&self, char_width: f32, rect: Rect) -> usize {
        if char_width <= 0.0 {
            80
        } else {
            ((rect.width / char_width).floor() as usize).max(1)
        }
    }

    fn build_status_rows(&self) -> Vec<MessageRow> {
        let label: String = self
            .status_label
            .spans
            .iter()
            .map(|s| s.text.as_str())
            .collect();
        let text = if self.model_label.is_empty() {
            label
        } else {
            format!("{label}  [{}]", self.model_label)
        };
        vec![MessageRow::new(text, Color::rgb(180, 180, 180), 0.0)]
    }

    fn build_transcript_rows(&self, col_budget: usize) -> Vec<MessageRow> {
        self.build_transcript_rows_indexed(col_budget).0
    }

    /// Same rows as [`Self::build_transcript_rows`], plus — for each
    /// `self.transcript` turn, in order — the row index where that turn's
    /// block begins. `turn_starts[i]..turn_starts.get(i + 1)`
    /// (or the end of `rows` for the last turn) is turn `i`'s row range;
    /// `row_idx - turn_starts[i]` is that row's `row_in_turn`.
    ///
    /// [`Self::handle_click`] uses this to map a clicked transcript row
    /// back to `(turn_idx, row_in_turn)` for
    /// [`ChatControllerEvent::TurnClicked`].
    fn build_transcript_rows_indexed(&self, col_budget: usize) -> (Vec<MessageRow>, Vec<usize>) {
        let mut rows = Vec::new();
        let mut turn_starts = Vec::with_capacity(self.transcript.len());
        for (idx, turn) in self.transcript.iter().enumerate() {
            turn_starts.push(rows.len());

            let (role_label, role_fg, content_fg) = match turn.role {
                ChatRole::User => ("You", Color::rgb(100, 180, 255), Color::rgb(220, 220, 220)),
                ChatRole::Assistant => ("AI", Color::rgb(120, 220, 120), Color::rgb(210, 210, 210)),
                ChatRole::System => (
                    "System",
                    Color::rgb(200, 160, 80),
                    Color::rgb(190, 190, 190),
                ),
            };

            let collapsed = self.is_turn_collapsed(idx);

            // Role header row (no indent). Collapsed turns get a
            // fold indicator appended so the card reads as expandable.
            let header = if collapsed {
                format!("{role_label} \u{25b8}")
            } else {
                role_label.to_string()
            };
            rows.push(MessageRow::new(header, role_fg, 0.0));

            if collapsed {
                // ── Collapsed path ───────────────────────────────────────
                // Render exactly one summary row instead of the full body.
                rows.push(MessageRow::new(
                    self.turn_summary_line(idx),
                    content_fg,
                    2.0,
                ));
            } else {
                let content_budget = col_budget.saturating_sub(2);

                if !turn.line_scales.is_empty() {
                    // ── Styled path ──────────────────────────────────────
                    // Turns created by `push_turn_markdown` carry per-line
                    // span lists (separated by plain `\n` spans) and
                    // matching scale factors.  Build styled MessageRows so
                    // rasterisers can apply per-span fg/bold/italic and
                    // heading font sizes.
                    let lines_spans = split_spans_by_newline(&turn.text.spans);
                    for (i, line_spans) in lines_spans.iter().enumerate() {
                        let scale = turn.line_scales.get(i).copied().unwrap_or(1.0);
                        let wrapped_groups =
                            wrap_spans(line_spans, content_budget, WrapPolicy::Char);
                        for group in wrapped_groups {
                            let text: String = group.iter().map(|s| s.text.as_str()).collect();
                            rows.push(MessageRow {
                                text,
                                fg: content_fg,
                                indent: 2.0,
                                spans: group,
                                scale,
                            });
                        }
                    }
                } else {
                    // ── Flat path (unchanged) ─────────────────────────────
                    // Turns created by `push_turn` or `set_transcript` have
                    // empty `line_scales`.  Output is byte-for-byte
                    // identical to the pre-styled-row behaviour — existing
                    // callers (vimcode debug / AI sidebar) are visually
                    // unchanged.
                    let plain: String = turn.text.spans.iter().map(|s| s.text.as_str()).collect();
                    for raw_line in plain.split('\n') {
                        for wrapped in wrap_text(raw_line, content_budget) {
                            rows.push(MessageRow::new(wrapped, content_fg, 2.0));
                        }
                    }
                }
            }

            // Blank separator between turns.
            rows.push(MessageRow::new("", Color::rgb(50, 50, 50), 0.0));
        }
        (rows, turn_starts)
    }

    /// Soft-wrap `input_buf` to `col_budget` and build the `TextInput` the
    /// rasterisers paint — see this struct's *Input soft-wrap and
    /// auto-grow* doc section.
    fn build_text_input(&self, col_budget: usize) -> TextInput {
        let rows = wrap_input_rows(&self.input_buf, col_budget);
        self.text_input_from_rows(&rows)
    }

    /// Build the paint-time `TextInput` from an already-wrapped `rows`
    /// (shared by [`Self::build_text_input`] and
    /// [`Self::handle_click`], which both need the same wrap pass — the
    /// click handler additionally uses `rows` to map the click back to a
    /// buffer byte offset).
    fn text_input_from_rows(&self, rows: &[InputRow]) -> TextInput {
        let lines: Vec<String> = rows.iter().map(|r| r.text.clone()).collect();
        let (logical_line, logical_col) =
            cursor_byte_to_line_col(&self.input_buf, self.input_cursor);
        let (visual_row, visual_col) = input_logical_to_visual(rows, logical_line, logical_col);
        let mut ti = TextInput::new(WidgetId::new(format!("{}-input", self.id)));
        ti.lines = lines;
        ti.cursor_line = visual_row;
        ti.cursor_col = visual_col;
        // The placeholder advertises the *live* submit binding: in
        // `submit_on_enter` mode plain `Enter` sends and
        // `Shift+Enter` breaks the line, so the default hint would tell
        // the user the exact opposite of what the keymap does.
        ti.placeholder = Some(
            if self.submit_on_enter {
                "Type a message\u{2026} (Enter to send, Shift+Enter for newline, Esc to cancel)"
            } else {
                "Type a message\u{2026} (Ctrl+S or Alt+Enter to send, Enter for newline, Esc to cancel)"
            }
            .into(),
        );
        ti.scroll_offset = self.input_scroll_offset;
        // No horizontal scroll: `rows` is already wrapped to fit the box's
        // width, so every visual row fits within `col_budget` columns.
        ti.scroll_col = 0;
        ti.has_focus = self.input_has_focus;
        ti
    }

    // ── Key handling ──────────────────────────────────────────────────

    fn handle_key(
        &mut self,
        key: &Key,
        modifiers: &Modifiers,
        backend: &dyn Backend,
        layout: &ChatLayout,
    ) -> ChatControllerEvent {
        match key {
            // Cycle order: input focus (`None`) → turn 0 → turn 1 → … →
            // last turn → back to input focus. No-op when the transcript is empty.
            Key::Named(NamedKey::Tab) if !modifiers.ctrl && !modifiers.alt && !modifiers.shift => {
                self.focus_next_turn();
                ChatControllerEvent::Consumed
            }
            Key::Named(NamedKey::Tab) if !modifiers.ctrl && !modifiers.alt && modifiers.shift => {
                self.focus_prev_turn();
                ChatControllerEvent::Consumed
            }
            Key::Named(NamedKey::BackTab) if !modifiers.ctrl && !modifiers.alt => {
                self.focus_prev_turn();
                ChatControllerEvent::Consumed
            }

            // ── Enter while a turn (not the input) has keyboard focus:
            //    toggle its collapsed state instead of submitting/
            //    inserting a newline. Excludes `Ctrl+Enter` so the
            //    universal submit chord still works even while a turn is
            //    focused.
            Key::Named(NamedKey::Enter)
                if !modifiers.ctrl && self.focused_turn.is_some() && !self.input_has_focus =>
            {
                if let Some(idx) = self.focused_turn {
                    self.toggle_turn_collapsed(idx);
                }
                ChatControllerEvent::Consumed
            }

            // ── Submit: Ctrl+S ──────────────────────────────────────────
            // Works on all terminals in both `submit_on_enter` modes; see
            // this arm's note on `stty -ixon` in the module doc.
            Key::Char('s') if modifiers.ctrl => self.try_submit(),

            // `Ctrl+Enter` always submits. `Alt+Enter` submits in default mode
            // (`submit_on_enter == false`); in `submit_on_enter == true` mode,
            // `Shift+Enter` inserts a newline, with `Alt+Enter` as a fallback for
            // terminals that can't report `Shift+Enter`. Plain `Enter` means newline
            // in default mode, submit in `submit_on_enter == true` mode.
            Key::Named(NamedKey::Enter) if modifiers.ctrl => self.try_submit(),
            Key::Named(NamedKey::Enter)
                if self.submit_on_enter && (modifiers.shift || modifiers.alt) =>
            {
                self.input_insert_char('\n');
                self.history_pos = None;
                self.saved_input = None;
                ChatControllerEvent::Consumed
            }
            Key::Named(NamedKey::Enter) if !self.submit_on_enter && modifiers.alt => {
                self.try_submit()
            }
            Key::Named(NamedKey::Enter) if self.submit_on_enter => self.try_submit(),

            // ── Cancel: Esc ────────────────────────────────────────────
            Key::Named(NamedKey::Escape) => ChatControllerEvent::Cancelled,

            // Plain `Enter` when `submit_on_enter == false` inserts a newline
            Key::Named(NamedKey::Enter) => {
                self.input_insert_char('\n');
                // Typing resets history navigation.
                self.history_pos = None;
                self.saved_input = None;
                ChatControllerEvent::Consumed
            }

            // ── Backspace ──────────────────────────────────────────────
            Key::Named(NamedKey::Backspace) => {
                self.input_backspace();
                ChatControllerEvent::Consumed
            }

            // ── Delete ─────────────────────────────────────────────────
            Key::Named(NamedKey::Delete) => {
                self.input_delete();
                ChatControllerEvent::Consumed
            }

            // ── Cursor movement ────────────────────────────────────────
            Key::Named(NamedKey::Left) => {
                self.input_move_left();
                ChatControllerEvent::Consumed
            }
            Key::Named(NamedKey::Right) => {
                self.input_move_right();
                ChatControllerEvent::Consumed
            }
            Key::Named(NamedKey::Home) => {
                self.input_move_home();
                ChatControllerEvent::Consumed
            }
            Key::Named(NamedKey::End) => {
                self.input_move_end();
                ChatControllerEvent::Consumed
            }

            // ── Up: history navigation or cursor up (by VISUAL row —
            //    A wrapped paragraph's interior rows move the
            //    cursor; history recall only fires on the first visual
            //    row of the whole buffer) ─────────────────────────────
            Key::Named(NamedKey::Up) => {
                let col_budget = TextInput::content_cols(layout.input.width, backend.char_width());
                let rows = wrap_input_rows(&self.input_buf, col_budget);
                let (logical_line, logical_col) =
                    cursor_byte_to_line_col(&self.input_buf, self.input_cursor);
                let (row_idx, col) = input_logical_to_visual(&rows, logical_line, logical_col);
                if row_idx == 0 {
                    self.history_prev()
                } else {
                    self.input_cursor =
                        input_visual_to_byte(&self.input_buf, &rows, row_idx - 1, col);
                    ChatControllerEvent::Consumed
                }
            }

            // ── Down: history navigation or cursor down (by VISUAL row —
            //    see the `Up` arm above) ─────────────────────────────────
            Key::Named(NamedKey::Down) => {
                let col_budget = TextInput::content_cols(layout.input.width, backend.char_width());
                let rows = wrap_input_rows(&self.input_buf, col_budget);
                let (logical_line, logical_col) =
                    cursor_byte_to_line_col(&self.input_buf, self.input_cursor);
                let (row_idx, col) = input_logical_to_visual(&rows, logical_line, logical_col);
                if row_idx + 1 >= rows.len() {
                    self.history_next()
                } else {
                    self.input_cursor =
                        input_visual_to_byte(&self.input_buf, &rows, row_idx + 1, col);
                    ChatControllerEvent::Consumed
                }
            }

            // ── PageUp / PageDown: scroll transcript ───────────────────
            Key::Named(NamedKey::PageUp) => {
                let visible =
                    Self::transcript_visible_rows_for(backend.line_height(), layout.transcript);
                let col_budget =
                    self.transcript_col_budget(backend.char_width(), layout.transcript);
                let total = self.build_transcript_rows(col_budget).len();
                let jump = (visible.max(1) - 1).max(1) as isize;
                self.scroll_transcript_by(-jump, total, visible);
                ChatControllerEvent::Consumed
            }
            Key::Named(NamedKey::PageDown) => {
                let visible =
                    Self::transcript_visible_rows_for(backend.line_height(), layout.transcript);
                let col_budget =
                    self.transcript_col_budget(backend.char_width(), layout.transcript);
                let total = self.build_transcript_rows(col_budget).len();
                let jump = (visible.max(1) - 1).max(1) as isize;
                self.scroll_transcript_by(jump, total, visible);
                ChatControllerEvent::Consumed
            }

            // ── Ctrl+A: move cursor to beginning of line (readline) ────
            Key::Char('a') if modifiers.ctrl => {
                self.input_move_home();
                ChatControllerEvent::Consumed
            }

            // ── Ctrl+E: move cursor to end of line (readline) ──────────
            Key::Char('e') if modifiers.ctrl => {
                self.input_move_end();
                ChatControllerEvent::Consumed
            }

            // ── Regular char: insert (no ctrl/alt) ────────────────────
            Key::Char(c) if !modifiers.ctrl && !modifiers.alt => {
                self.focus_input();
                self.input_insert_char(*c);
                // Any typing resets history navigation.
                self.history_pos = None;
                self.saved_input = None;
                ChatControllerEvent::Consumed
            }

            // ── Anything else: pass to app ─────────────────────────────
            _ => ChatControllerEvent::KeyPressed {
                key: format!("{key:?}"),
                modifiers: *modifiers,
            },
        }
    }

    /// Shared submit path for every submit trigger — `Ctrl+S`, `Alt+Enter`
    /// / `Ctrl+Enter` / plain `Enter` (depending on
    /// [`submit_on_enter`](Self::submit_on_enter)), and a click on the
    /// Send segment while idle. Pushes the current input to
    /// history (skipping empty/duplicate entries) and resets history
    /// navigation state; ignores the request when the input is empty.
    fn try_submit(&mut self) -> ChatControllerEvent {
        if self.input_buf.is_empty() {
            return ChatControllerEvent::Ignored;
        }
        let text = self.input_buf.clone();
        if !text.trim().is_empty() && self.history.last() != Some(&text) {
            self.history.push(text.clone());
        }
        self.history_pos = None;
        self.saved_input = None;
        ChatControllerEvent::Submit { text }
    }

    // ── History navigation ────────────────────────────────────────────

    fn history_prev(&mut self) -> ChatControllerEvent {
        if self.history.is_empty() {
            return ChatControllerEvent::Ignored;
        }
        match self.history_pos {
            None => {
                // Enter history: save current input, show newest history entry.
                self.saved_input = Some((self.input_buf.clone(), self.input_cursor));
                let idx = self.history.len() - 1;
                self.history_pos = Some(idx);
                let entry = self.history[idx].clone();
                self.input_cursor = entry.len();
                self.input_buf = entry;
                ChatControllerEvent::Consumed
            }
            Some(pos) if pos > 0 => {
                let idx = pos - 1;
                self.history_pos = Some(idx);
                let entry = self.history[idx].clone();
                self.input_cursor = entry.len();
                self.input_buf = entry;
                ChatControllerEvent::Consumed
            }
            Some(_) => {
                // Already at the oldest entry — do nothing.
                ChatControllerEvent::Consumed
            }
        }
    }

    fn history_next(&mut self) -> ChatControllerEvent {
        match self.history_pos {
            None => ChatControllerEvent::Ignored,
            Some(pos) => {
                if pos + 1 < self.history.len() {
                    let idx = pos + 1;
                    self.history_pos = Some(idx);
                    let entry = self.history[idx].clone();
                    self.input_cursor = entry.len();
                    self.input_buf = entry;
                } else {
                    // Restore saved input and exit history navigation.
                    let (text, cursor) = self.saved_input.take().unwrap_or_default();
                    self.input_buf = text;
                    self.input_cursor = cursor;
                    self.history_pos = None;
                }
                ChatControllerEvent::Consumed
            }
        }
    }

    // ── Mouse click / drag ────────────────────────────────────────────

    fn handle_click(
        &mut self,
        backend: &dyn Backend,
        layout: &ChatLayout,
        x: f32,
        y: f32,
    ) -> ChatControllerEvent {
        // Send/Stop segment click? — see this struct's *Send / Stop
        // segment* doc section for the idle-vs-busy split.
        if let Some(send_rect) = layout.send {
            if send_rect.contains(Point::new(x, y)) {
                return self.click_send();
            }
        }

        // Scrollbar click?
        if let Some(sb_rect) = layout.scrollbar {
            if sb_rect.contains(Point::new(x, y)) {
                return self.click_scrollbar(backend, layout, sb_rect, y);
            }
        }

        // Transcript area click? Hit-test against the same rows the last
        // render painted — a hit on a turn's rows emits
        // `TurnClicked` so the app can toggle collapse / resolve a
        // `path:line` location; a miss (blank tail below the last row)
        // just absorbs the click.
        if layout.transcript.contains(Point::new(x, y)) {
            let col_budget = self.transcript_col_budget(backend.char_width(), layout.transcript);
            let (rows, turn_starts) = self.build_transcript_rows_indexed(col_budget);
            let list = MessageList {
                id: WidgetId::new(format!("{}-transcript", self.id)),
                rows,
                scroll_top: self.transcript_scroll_top.get(),
            };
            let measure = MessageListMeasure::new(backend.line_height());
            return match list.hit_test(layout.transcript, measure, x, y) {
                MessageListHit::Row(row_idx) => {
                    // `turn_starts` is non-empty here: a `Row` hit means
                    // `list.rows` is non-empty, which only happens when
                    // `self.transcript` produced at least one turn.
                    let turn_idx = match turn_starts.binary_search(&row_idx) {
                        Ok(i) => i,
                        Err(i) => i.saturating_sub(1),
                    };
                    let row_in_turn = row_idx - turn_starts[turn_idx];
                    // Move the keyboard cursor to the clicked turn so mouse
                    // and keyboard stay in sync: a following `Enter`
                    // acts on the same turn the click just landed on.
                    self.set_focused_turn(Some(turn_idx));
                    ChatControllerEvent::TurnClicked {
                        turn_idx,
                        row_in_turn,
                    }
                }
                MessageListHit::Empty => ChatControllerEvent::Consumed,
            };
        }

        // Input area click?
        if layout.input.contains(Point::new(x, y)) {
            self.focus_input();
            let col_budget = TextInput::content_cols(layout.input.width, backend.char_width());
            let rows = wrap_input_rows(&self.input_buf, col_budget);
            let ti = self.text_input_from_rows(&rows);
            let til = backend.text_input_layout(layout.input, &ti);
            // Find the clicked visible line and update the cursor.
            // `line_idx` here is a VISUAL row index (into `rows`), not a
            // logical line — map it back through `rows`.
            let local_y = y - layout.input.y;
            for (r, hit) in &til.hit_regions {
                if local_y >= r.y && local_y < r.y + r.height {
                    if let TextInputHit::Line { line_idx } = hit {
                        let cw = backend.char_width().max(1.0);
                        let local_x = (x - layout.input.x - r.x).max(0.0);
                        let col = (local_x / cw).floor() as usize;
                        self.input_cursor =
                            input_visual_to_byte(&self.input_buf, &rows, *line_idx, col);
                    }
                    break;
                }
            }
            return ChatControllerEvent::Consumed;
        }

        ChatControllerEvent::Ignored
    }

    /// Handle a click anywhere in the Send/Stop segment. The
    /// segment always paints a single button filling the whole zone, so
    /// no finer-grained hit-test is needed — any click inside it hits the
    /// button.
    fn click_send(&mut self) -> ChatControllerEvent {
        if self.busy {
            ChatControllerEvent::StopRequested
        } else {
            self.try_submit()
        }
    }

    fn click_scrollbar(
        &mut self,
        backend: &dyn Backend,
        layout: &ChatLayout,
        sb_rect: Rect,
        y: f32,
    ) -> ChatControllerEvent {
        let visible = Self::transcript_visible_rows_for(backend.line_height(), layout.transcript);
        let col_budget = self.transcript_col_budget(backend.char_width(), layout.transcript);
        let total = self.build_transcript_rows(col_budget).len();
        let max_offset = total.saturating_sub(visible);
        if max_offset == 0 {
            return ChatControllerEvent::Ignored;
        }

        let track_w = self.scrollbar_track_width(backend.line_height());
        let sb = build_scrollbar(
            format!("{}-sb", self.id),
            sb_rect,
            self.transcript_scroll_top.get(),
            total,
            visible,
            false,
            track_w.max(1.0),
        );
        match sb.press_zone(y) {
            PressZone::Thumb => {
                self.transcript_drag = Some(ThumbDrag::begin(
                    y,
                    self.transcript_scroll_top.get() as f32,
                    sb.travel(),
                    max_offset as f32,
                ));
                ChatControllerEvent::Consumed
            }
            PressZone::Before => {
                self.scroll_transcript_by(-(visible as isize), total, visible);
                ChatControllerEvent::Consumed
            }
            PressZone::After => {
                self.scroll_transcript_by(visible as isize, total, visible);
                ChatControllerEvent::Consumed
            }
        }
    }

    fn handle_drag(&mut self, y: f32) -> ChatControllerEvent {
        let Some(drag) = &self.transcript_drag else {
            return ChatControllerEvent::Ignored;
        };
        let Some(new) = drag.offset_at(y) else {
            return ChatControllerEvent::Ignored;
        };
        let new = new.round() as usize;
        // Copy max_offset before the immutable borrow of `drag` ends so we can
        // use it when updating `stuck_to_bottom` after mutating `self`.
        let max_offset = drag.max_offset() as usize;
        if new == self.transcript_scroll_top.get() {
            return ChatControllerEvent::Ignored;
        }
        self.transcript_scroll_top.set(new);
        self.stuck_to_bottom = new >= max_offset;
        ChatControllerEvent::Consumed
    }

    // ── Input text buffer manipulation ────────────────────────────────

    /// Insert a single character at the cursor.  Also used by `CharTyped`.
    pub fn input_insert_char(&mut self, ch: char) {
        let cursor = snap_to_char_boundary(&self.input_buf, self.input_cursor);
        self.input_buf.insert(cursor, ch);
        self.input_cursor = cursor + ch.len_utf8();
    }

    /// Insert a string at the cursor (e.g. for clipboard paste).
    pub fn input_insert_str(&mut self, s: &str) {
        let cursor = snap_to_char_boundary(&self.input_buf, self.input_cursor);
        self.input_buf.insert_str(cursor, s);
        self.input_cursor = cursor + s.len();
    }

    fn input_backspace(&mut self) {
        if self.input_cursor == 0 {
            return;
        }
        let prev = prev_char_boundary(&self.input_buf, self.input_cursor);
        self.input_buf.replace_range(prev..self.input_cursor, "");
        self.input_cursor = prev;
    }

    fn input_delete(&mut self) {
        if self.input_cursor >= self.input_buf.len() {
            return;
        }
        let next = next_char_boundary(&self.input_buf, self.input_cursor);
        self.input_buf.replace_range(self.input_cursor..next, "");
    }

    fn input_move_left(&mut self) {
        self.input_cursor = prev_char_boundary(&self.input_buf, self.input_cursor);
    }

    fn input_move_right(&mut self) {
        self.input_cursor = next_char_boundary(&self.input_buf, self.input_cursor);
    }

    fn input_move_home(&mut self) {
        let before = &self.input_buf[..self.input_cursor];
        let line_start = before.rfind('\n').map(|i| i + 1).unwrap_or(0);
        self.input_cursor = line_start;
    }

    fn input_move_end(&mut self) {
        let after = &self.input_buf[self.input_cursor..];
        let line_end = after
            .find('\n')
            .map(|i| self.input_cursor + i)
            .unwrap_or(self.input_buf.len());
        self.input_cursor = line_end;
    }
}

// ── Module-level helpers ───────────────────────────────────────────────────────

fn build_scrollbar(
    id: String,
    rect: Rect,
    scroll_top: usize,
    total_rows: usize,
    visible_rows: usize,
    is_dragging: bool,
    min_thumb: f32,
) -> Scrollbar {
    let mut sb = Scrollbar::vertical(
        id,
        rect,
        scroll_top as f32,
        total_rows as f32,
        visible_rows as f32,
        min_thumb,
    );
    sb.dragging = is_dragging;
    sb
}

/// Word-aware soft-wrap of `text` to `col_budget` characters per row.
///
/// Uses [`crate::text_util::word_wrap`] to break at whitespace where possible.
/// Only a single word wider than `col_budget` hard-breaks mid-word (there is
/// no other way to fit it); everything else wraps at word boundaries.
fn wrap_text(text: &str, col_budget: usize) -> Vec<String> {
    crate::text_util::word_wrap(text, col_budget)
}

/// Split a flat span list (where `\n`-only spans act as line delimiters)
/// into per-logical-line span lists.
///
/// This is the inverse of the encoding used by
/// [`ChatController::push_turn_markdown`], which concatenates per-line
/// span vecs with [`StyledSpan::plain`]`("\n")` separators.  The
/// resulting `Vec<Vec<StyledSpan>>` has one entry per logical line
/// (including an empty entry for blank lines).
fn split_spans_by_newline(spans: &[StyledSpan]) -> Vec<Vec<StyledSpan>> {
    let mut lines: Vec<Vec<StyledSpan>> = Vec::new();
    let mut current: Vec<StyledSpan> = Vec::new();
    for span in spans {
        if span.text == "\n" {
            lines.push(std::mem::take(&mut current));
        } else {
            current.push(span.clone());
        }
    }
    lines.push(current);
    lines
}

/// Convert a byte offset in `text` to `(line, char_col)`.
fn cursor_byte_to_line_col(text: &str, cursor: usize) -> (usize, usize) {
    let before = safe_prefix(text, cursor);
    let line = before.bytes().filter(|&b| b == b'\n').count();
    let col_start = before.rfind('\n').map(|i| i + 1).unwrap_or(0);
    let col = before[col_start..].chars().count();
    (line, col)
}

/// Convert `(line, char_col)` back to a byte offset in `text`.
///
/// Clamps to the end of the line if `target_col` exceeds the line length.
/// Clamps to `text.len()` if `target_line` doesn't exist.
fn line_col_to_byte(text: &str, target_line: usize, target_col: usize) -> usize {
    let mut current_line = 0usize;
    let mut line_start = 0usize;

    for (i, ch) in text.char_indices() {
        if current_line == target_line {
            // We're on the right line — scan forward `target_col` chars.
            let segment = &text[i..];
            let col_byte = segment
                .char_indices()
                .nth(target_col)
                .map(|(b, _)| b)
                .unwrap_or_else(|| {
                    // Clamp to end of this line (before the '\n').
                    segment.find('\n').unwrap_or(segment.len())
                });
            return i + col_byte;
        }
        if ch == '\n' {
            current_line += 1;
            line_start = i + 1;
        }
    }

    // Handle the case where we're at line 0 of an empty string, or
    // the target line is the last line (no trailing \n yet).
    if current_line == target_line {
        let segment = &text[line_start..];
        let col_byte = segment
            .char_indices()
            .nth(target_col)
            .map(|(b, _)| b)
            .unwrap_or_else(|| segment.find('\n').unwrap_or(segment.len()));
        return line_start + col_byte;
    }

    // Target line doesn't exist — clamp to end of text.
    text.len()
}

// ── Input soft-wrap ─────────────────────────────────────────────────────

/// One soft-wrapped visual row of the chat input buffer.
///
/// Wrapping here is deliberately **exact** — a row's `text` is always a
/// contiguous char range of its owning logical line, with no whitespace
/// collapsed or dropped (unlike [`crate::text_util::word_wrap`]'s
/// transcript wrapping, which *is* lossy at wrap points). Concatenating
/// every row for a given `logical_line`, in order, reconstructs that
/// line's text byte-for-byte. That's what lets
/// [`input_logical_to_visual`] / [`input_visual_to_byte`] round-trip
/// cursor positions losslessly between logical (buffer byte offset) and
/// visual (row, char column) space.
struct InputRow {
    /// Index into the logical (`\n`-separated) lines of the buffer.
    logical_line: usize,
    /// Char-column offset into `logical_line` where this row starts.
    col_offset: usize,
    /// This row's text — a char-exact slice of `logical_line`.
    text: String,
}

/// Soft-wrap `text` (the whole input buffer, `\n`-separated logical
/// lines) to `col_budget` char columns per visual row. See [`InputRow`]
/// for the exactness guarantee that makes cursor-position round-tripping
/// possible.
///
/// Always returns at least one row per logical line (an empty logical
/// line yields one empty row), so `rows.len() >= 1` for any input,
/// including `""`.
fn wrap_input_rows(text: &str, col_budget: usize) -> Vec<InputRow> {
    let mut rows = Vec::new();
    for (logical_line, line) in text.split('\n').enumerate() {
        for (col_offset, row_text) in wrap_line_exact(line, col_budget) {
            rows.push(InputRow {
                logical_line,
                col_offset,
                text: row_text,
            });
        }
    }
    rows
}

/// Break one logical `line` (no `\n`) into `(col_offset, text)` visual
/// rows of at most `col_budget` char columns, breaking after the last
/// space at or before the budget where possible (an unbroken run longer
/// than `col_budget` hard-breaks at the budget). Never collapses or
/// drops characters — see [`InputRow`].
///
/// `col_budget == 0` or a line that already fits returns the line
/// unmodified as a single row, matching
/// [`crate::text_util::word_wrap`]'s convention.
fn wrap_line_exact(line: &str, col_budget: usize) -> Vec<(usize, String)> {
    let chars: Vec<char> = line.chars().collect();
    if col_budget == 0 || chars.len() <= col_budget {
        return vec![(0, line.to_string())];
    }
    let mut rows = Vec::new();
    let mut start = 0usize;
    while start < chars.len() {
        let mut end = (start + col_budget).min(chars.len());
        if end < chars.len() {
            if let Some(space_rel) = chars[start..end].iter().rposition(|&c| c == ' ') {
                let space_idx = start + space_rel;
                if space_idx > start {
                    // Break just after the space so it stays with this
                    // row (matching normal word-wrap convention) rather
                    // than becoming a leading space on the next row.
                    end = space_idx + 1;
                }
            }
        }
        rows.push((start, chars[start..end].iter().collect()));
        start = end;
    }
    rows
}

/// Map a logical `(line, char_col)` cursor position (as produced by
/// [`cursor_byte_to_line_col`]) to `(visual_row_idx, visual_col)` within
/// `rows` — the inverse of [`input_visual_to_byte`].
fn input_logical_to_visual(rows: &[InputRow], line: usize, col: usize) -> (usize, usize) {
    let mut last_for_line: Option<usize> = None;
    for (i, r) in rows.iter().enumerate() {
        if r.logical_line != line {
            continue;
        }
        last_for_line = Some(i);
        let len = r.text.chars().count();
        if col >= r.col_offset && col < r.col_offset + len {
            return (i, col - r.col_offset);
        }
    }
    // `col` is at (or past) the end of the logical line — land on the end
    // of its last visual row.
    match last_for_line {
        Some(i) => {
            let r = &rows[i];
            let len = r.text.chars().count();
            (i, col.saturating_sub(r.col_offset).min(len))
        }
        None => (0, 0),
    }
}

/// Map a `(visual_row_idx, visual_col)` position within `rows` back to a
/// byte offset in `text` (the whole input buffer) — the inverse of
/// [`input_logical_to_visual`]. Both indices are clamped, so this never
/// panics on an out-of-range row or column; `rows` empty returns `0`.
fn input_visual_to_byte(text: &str, rows: &[InputRow], row_idx: usize, col: usize) -> usize {
    let Some(last) = rows.len().checked_sub(1) else {
        return 0;
    };
    let r = &rows[row_idx.min(last)];
    let len = r.text.chars().count();
    line_col_to_byte(text, r.logical_line, r.col_offset + col.min(len))
}

// ── Tests ──────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::testing::RecordingBackend;

    // Tests use `RecordingBackend` for its `draw_text_input`/`text_input_layout`
    // and `draw_spinner`/`spinner_layout` implementations, which return real layouts
    // rather than panicking, as required by click-routing and render tests.

    fn make_rect() -> Rect {
        Rect::new(0.0, 0.0, 80.0, 24.0)
    }

    fn make_turn(role: ChatRole, text: &str) -> ChatTurn {
        ChatTurn {
            role,
            text: StyledText::plain(text),
            timestamp_unix: None,
            line_scales: Vec::new(),
        }
    }

    // ── Construction ─────────────────────────────────────────────────

    #[test]
    fn new_starts_empty() {
        let cc = ChatController::new("chat");
        assert_eq!(cc.input_text(), "");
        assert_eq!(cc.transcript_scroll_top(), 0);
        assert!(cc.input_has_focus());
    }

    // ── Input insertion ───────────────────────────────────────────────

    #[test]
    fn input_insert_char_appends() {
        let mut cc = ChatController::new("c");
        cc.input_insert_char('h');
        cc.input_insert_char('i');
        assert_eq!(cc.input_text(), "hi");
    }

    #[test]
    fn input_insert_str_paste() {
        let mut cc = ChatController::new("c");
        cc.input_insert_str("hello\nworld");
        assert_eq!(cc.input_text(), "hello\nworld");
    }

    #[test]
    fn clear_input_resets_state() {
        let mut cc = ChatController::new("c");
        cc.input_insert_str("hello\nworld");
        cc.clear_input();
        assert_eq!(cc.input_text(), "");
        assert_eq!(cc.input_cursor, 0);
    }

    // ── Keyboard: submit ──────────────────────────────────────────────

    #[test]
    fn ctrl_enter_submits_and_emits_event() {
        let mut cc = ChatController::new("c");
        cc.input_insert_str("hello");
        let rect = make_rect();
        let event = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Enter),
            modifiers: Modifiers {
                ctrl: true,
                ..Default::default()
            },
            repeat: false,
        };
        let ev = cc.handle(&event, &RecordingBackend::new(), rect);
        assert_eq!(
            ev,
            ChatControllerEvent::Submit {
                text: "hello".into()
            }
        );
    }

    #[test]
    fn alt_enter_submits_and_emits_event() {
        let mut cc = ChatController::new("c");
        cc.input_insert_str("hello");
        let rect = make_rect();
        let event = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Enter),
            modifiers: Modifiers {
                alt: true,
                ..Default::default()
            },
            repeat: false,
        };
        let ev = cc.handle(&event, &RecordingBackend::new(), rect);
        assert_eq!(
            ev,
            ChatControllerEvent::Submit {
                text: "hello".into()
            }
        );
    }

    #[test]
    fn ctrl_enter_on_empty_input_ignored() {
        let mut cc = ChatController::new("c");
        let rect = make_rect();
        let event = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Enter),
            modifiers: Modifiers {
                ctrl: true,
                ..Default::default()
            },
            repeat: false,
        };
        let ev = cc.handle(&event, &RecordingBackend::new(), rect);
        assert_eq!(ev, ChatControllerEvent::Ignored);
    }

    #[test]
    fn ctrl_s_submits_and_emits_event() {
        let mut cc = ChatController::new("c");
        cc.input_insert_str("hello");
        let rect = make_rect();
        let event = UiEvent::KeyPressed {
            key: Key::Char('s'),
            modifiers: Modifiers {
                ctrl: true,
                ..Default::default()
            },
            repeat: false,
        };
        let ev = cc.handle(&event, &RecordingBackend::new(), rect);
        assert_eq!(
            ev,
            ChatControllerEvent::Submit {
                text: "hello".into()
            }
        );
    }

    #[test]
    fn ctrl_s_on_empty_input_ignored() {
        let mut cc = ChatController::new("c");
        let rect = make_rect();
        let event = UiEvent::KeyPressed {
            key: Key::Char('s'),
            modifiers: Modifiers {
                ctrl: true,
                ..Default::default()
            },
            repeat: false,
        };
        let ev = cc.handle(&event, &RecordingBackend::new(), rect);
        assert_eq!(ev, ChatControllerEvent::Ignored);
    }

    #[test]
    fn submit_adds_to_history() {
        let mut cc = ChatController::new("c");
        cc.input_insert_str("hello");
        let rect = make_rect();
        let event = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Enter),
            modifiers: Modifiers {
                ctrl: true,
                ..Default::default()
            },
            repeat: false,
        };
        cc.handle(&event, &RecordingBackend::new(), rect);
        assert_eq!(cc.history.len(), 1);
        assert_eq!(cc.history[0], "hello");
    }

    // ── Keyboard: Ctrl+A / Ctrl+E line motion ─────────────────────────

    fn ctrl_key(ch: char) -> UiEvent {
        UiEvent::KeyPressed {
            key: Key::Char(ch),
            modifiers: Modifiers {
                ctrl: true,
                ..Default::default()
            },
            repeat: false,
        }
    }

    #[test]
    fn ctrl_a_moves_cursor_to_line_start() {
        let mut cc = ChatController::new("c");
        cc.input_insert_str("hello");
        // Cursor sits at end of "hello" after insertion.
        assert_eq!(cc.input_cursor, 5);
        let ev = cc.handle(&ctrl_key('a'), &RecordingBackend::new(), make_rect());
        assert_eq!(ev, ChatControllerEvent::Consumed);
        assert_eq!(cc.input_cursor, 0);
    }

    #[test]
    fn ctrl_e_moves_cursor_to_line_end() {
        let mut cc = ChatController::new("c");
        cc.input_insert_str("hello");
        // Move to the start first so Ctrl+E has somewhere to travel.
        cc.handle(&ctrl_key('a'), &RecordingBackend::new(), make_rect());
        assert_eq!(cc.input_cursor, 0);
        let ev = cc.handle(&ctrl_key('e'), &RecordingBackend::new(), make_rect());
        assert_eq!(ev, ChatControllerEvent::Consumed);
        assert_eq!(cc.input_cursor, 5);
    }

    #[test]
    fn ctrl_a_e_respect_current_line_in_multiline() {
        let mut cc = ChatController::new("c");
        cc.input_insert_str("hello\nworld");
        // Cursor is on the second line, at its end (byte index 11).
        assert_eq!(cc.input_cursor, 11);
        // Ctrl+A moves to the start of the *current* line, not the buffer.
        cc.handle(&ctrl_key('a'), &RecordingBackend::new(), make_rect());
        // Cursor lands just after the '\n' (start of "world").
        assert_eq!(cc.input_cursor, 6);
        // Ctrl+E moves to the end of the current line (end of buffer here).
        cc.handle(&ctrl_key('e'), &RecordingBackend::new(), make_rect());
        assert_eq!(cc.input_cursor, 11);
    }

    // ── Serde round-trips ─────────────────────────────────────────────

    #[test]
    fn chat_turn_serde_roundtrip() {
        let turn = ChatTurn {
            role: ChatRole::Assistant,
            text: StyledText::colored("hi there", Color::rgb(180, 230, 180)),
            timestamp_unix: Some(1_700_000_000.0),
            line_scales: Vec::new(),
        };
        let json = serde_json::to_string(&turn).expect("serialize ChatTurn");
        let decoded: ChatTurn = serde_json::from_str(&json).expect("deserialize ChatTurn");
        assert_eq!(decoded.role, turn.role);
        assert_eq!(decoded.text, turn.text);
        assert_eq!(decoded.timestamp_unix, turn.timestamp_unix);
    }

    #[test]
    fn chat_role_serde_roundtrip() {
        for role in [ChatRole::User, ChatRole::Assistant, ChatRole::System] {
            let json = serde_json::to_string(&role).expect("serialize ChatRole");
            let decoded: ChatRole = serde_json::from_str(&json).expect("deserialize ChatRole");
            assert_eq!(decoded, role);
        }
    }

    // ── Keyboard: cancel ──────────────────────────────────────────────

    #[test]
    fn esc_emits_cancelled() {
        let mut cc = ChatController::new("c");
        let rect = make_rect();
        let event = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Escape),
            modifiers: Modifiers::default(),
            repeat: false,
        };
        let ev = cc.handle(&event, &RecordingBackend::new(), rect);
        assert_eq!(ev, ChatControllerEvent::Cancelled);
    }

    // ── Keyboard: enter inserts newline ───────────────────────────────

    #[test]
    fn plain_enter_inserts_newline() {
        let mut cc = ChatController::new("c");
        cc.input_insert_str("hello");
        let rect = make_rect();
        let event = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Enter),
            modifiers: Modifiers::default(),
            repeat: false,
        };
        let ev = cc.handle(&event, &RecordingBackend::new(), rect);
        assert_eq!(ev, ChatControllerEvent::Consumed);
        assert_eq!(cc.input_text(), "hello\n");
    }

    // ── Keyboard: submit_on_enter mode ─────────────────────────────────

    #[test]
    fn submit_on_enter_defaults_to_false() {
        let cc = ChatController::new("c");
        assert!(!cc.submit_on_enter());
    }

    #[test]
    fn submit_on_enter_plain_enter_submits() {
        let mut cc = ChatController::new("c");
        cc.set_submit_on_enter(true);
        cc.input_insert_str("hello");
        let event = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Enter),
            modifiers: Modifiers::default(),
            repeat: false,
        };
        let ev = cc.handle(&event, &RecordingBackend::new(), make_rect());
        assert_eq!(
            ev,
            ChatControllerEvent::Submit {
                text: "hello".into()
            }
        );
    }

    #[test]
    fn submit_on_enter_shift_enter_inserts_newline() {
        let mut cc = ChatController::new("c");
        cc.set_submit_on_enter(true);
        cc.input_insert_str("hello");
        let event = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Enter),
            modifiers: Modifiers {
                shift: true,
                ..Default::default()
            },
            repeat: false,
        };
        let ev = cc.handle(&event, &RecordingBackend::new(), make_rect());
        assert_eq!(ev, ChatControllerEvent::Consumed);
        assert_eq!(cc.input_text(), "hello\n");
    }

    #[test]
    fn submit_on_enter_alt_enter_inserts_newline_fallback() {
        // Alt+Enter is the fallback for terminals that can't report
        // Shift+Enter — it must insert a newline in submit_on_enter mode,
        // the opposite of its meaning in the default mode.
        let mut cc = ChatController::new("c");
        cc.set_submit_on_enter(true);
        cc.input_insert_str("hello");
        let event = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Enter),
            modifiers: Modifiers {
                alt: true,
                ..Default::default()
            },
            repeat: false,
        };
        let ev = cc.handle(&event, &RecordingBackend::new(), make_rect());
        assert_eq!(ev, ChatControllerEvent::Consumed);
        assert_eq!(cc.input_text(), "hello\n");
    }

    #[test]
    fn submit_on_enter_ctrl_enter_still_submits() {
        let mut cc = ChatController::new("c");
        cc.set_submit_on_enter(true);
        cc.input_insert_str("hello");
        let event = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Enter),
            modifiers: Modifiers {
                ctrl: true,
                ..Default::default()
            },
            repeat: false,
        };
        let ev = cc.handle(&event, &RecordingBackend::new(), make_rect());
        assert_eq!(
            ev,
            ChatControllerEvent::Submit {
                text: "hello".into()
            }
        );
    }

    #[test]
    fn submit_on_enter_plain_enter_on_empty_input_ignored() {
        let mut cc = ChatController::new("c");
        cc.set_submit_on_enter(true);
        let event = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Enter),
            modifiers: Modifiers::default(),
            repeat: false,
        };
        let ev = cc.handle(&event, &RecordingBackend::new(), make_rect());
        assert_eq!(ev, ChatControllerEvent::Ignored);
    }

    // ── History navigation ────────────────────────────────────────────

    #[test]
    fn up_on_empty_history_returns_ignored() {
        let mut cc = ChatController::new("c");
        let ev = cc.history_prev();
        assert_eq!(ev, ChatControllerEvent::Ignored);
    }

    #[test]
    fn up_enters_history_with_newest_entry() {
        let mut cc = ChatController::new("c");
        cc.history.push("first".into());
        cc.history.push("second".into());
        let ev = cc.history_prev();
        assert_eq!(ev, ChatControllerEvent::Consumed);
        assert_eq!(cc.input_text(), "second");
        assert_eq!(cc.history_pos, Some(1));
    }

    #[test]
    fn up_twice_goes_to_older_entry() {
        let mut cc = ChatController::new("c");
        cc.history.push("first".into());
        cc.history.push("second".into());
        cc.history_prev(); // → "second"
        let ev = cc.history_prev();
        assert_eq!(ev, ChatControllerEvent::Consumed);
        assert_eq!(cc.input_text(), "first");
        assert_eq!(cc.history_pos, Some(0));
    }

    #[test]
    fn up_at_oldest_entry_stays() {
        let mut cc = ChatController::new("c");
        cc.history.push("only".into());
        cc.history_prev(); // at idx 0
        let ev = cc.history_prev(); // already at oldest
        assert_eq!(ev, ChatControllerEvent::Consumed);
        assert_eq!(cc.input_text(), "only"); // unchanged
    }

    #[test]
    fn down_after_history_nav_restores_saved_input() {
        let mut cc = ChatController::new("c");
        cc.input_insert_str("draft");
        cc.history.push("first".into());
        cc.history.push("second".into());
        cc.history_prev(); // → "second"
        cc.history_prev(); // → "first"
        cc.history_next(); // → "second"
        let ev = cc.history_next(); // → restore "draft"
        assert_eq!(ev, ChatControllerEvent::Consumed);
        assert_eq!(cc.input_text(), "draft");
        assert_eq!(cc.history_pos, None);
    }

    #[test]
    fn down_when_not_navigating_returns_ignored() {
        let mut cc = ChatController::new("c");
        let ev = cc.history_next();
        assert_eq!(ev, ChatControllerEvent::Ignored);
    }

    // ── History navigation via Up key (cursor on line 0) ─────────────

    #[test]
    fn up_key_on_line_0_enters_history() {
        let mut cc = ChatController::new("c");
        cc.history.push("prev".into());
        let rect = make_rect();
        let event = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Up),
            modifiers: Modifiers::default(),
            repeat: false,
        };
        let ev = cc.handle(&event, &RecordingBackend::new(), rect);
        assert_eq!(ev, ChatControllerEvent::Consumed);
        assert_eq!(cc.input_text(), "prev");
    }

    #[test]
    fn up_key_on_line_1_moves_cursor_up() {
        let mut cc = ChatController::new("c");
        cc.input_insert_str("line0\nline1");
        // Cursor is on line 1 after insert.
        let (line, _) = cursor_byte_to_line_col(cc.input_text(), cc.input_cursor);
        assert_eq!(line, 1);
        let rect = make_rect();
        let event = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Up),
            modifiers: Modifiers::default(),
            repeat: false,
        };
        let ev = cc.handle(&event, &RecordingBackend::new(), rect);
        assert_eq!(ev, ChatControllerEvent::Consumed);
        let (new_line, _) = cursor_byte_to_line_col(cc.input_text(), cc.input_cursor);
        assert_eq!(new_line, 0);
        // History should NOT have been entered.
        assert_eq!(cc.history_pos, None);
    }

    // ── Transcript scroll ─────────────────────────────────────────────

    #[test]
    fn scroll_transcript_clamps_to_bounds() {
        let mut cc = ChatController::new("c");
        cc.scroll_transcript_by(100, 10, 5); // total=10, visible=5, max=5
        assert_eq!(cc.transcript_scroll_top(), 5);
        cc.scroll_transcript_by(-100, 10, 5);
        assert_eq!(cc.transcript_scroll_top(), 0);
    }

    #[test]
    fn page_up_scrolls_transcript() {
        let mut cc = ChatController::new("c");
        cc.set_transcript_scroll_top(10);
        cc.scroll_transcript_by(-5, 20, 5);
        assert_eq!(cc.transcript_scroll_top(), 5);
    }

    /// A two-notch wheel gesture scrolls twice as far as a one-notch one:
    /// the handler consumes the delta's magnitude, not only its sign.
    #[test]
    fn wheel_scroll_consumes_the_delta_magnitude_not_just_its_sign() {
        let mut cc = ChatController::new("c");
        cc.set_transcript(
            (0..60)
                .map(|i| make_turn(ChatRole::User, &format!("line {i}")))
                .collect(),
        );
        cc.set_transcript_scroll_top(40);

        let ev = UiEvent::Scroll {
            widget: None,
            delta: crate::ScrollDelta::new(0.0, 2.0),
            position: crate::Point::new(5.0, 5.0),
        };
        assert_eq!(
            cc.handle(&ev, &RecordingBackend::new(), make_rect()),
            ChatControllerEvent::Consumed
        );
        assert_eq!(
            cc.transcript_scroll_top(),
            40 - 2 * TRANSCRIPT_ROWS_PER_NOTCH as usize,
            "two notches move two notches' worth of rows"
        );
    }

    /// A fractional trackpad delta still moves the transcript: rounding the
    /// magnitude must never swallow a slow gesture entirely.
    #[test]
    fn wheel_scroll_still_moves_for_a_sub_notch_gesture() {
        let mut cc = ChatController::new("c");
        cc.set_transcript(
            (0..60)
                .map(|i| make_turn(ChatRole::User, &format!("line {i}")))
                .collect(),
        );
        cc.set_transcript_scroll_top(40);

        let ev = UiEvent::Scroll {
            widget: None,
            delta: crate::ScrollDelta::new(0.0, 0.1),
            position: crate::Point::new(5.0, 5.0),
        };
        cc.handle(&ev, &RecordingBackend::new(), make_rect());
        assert!(
            cc.transcript_scroll_top() < 40,
            "a sub-notch gesture still scrolls at least one row"
        );
    }

    // ── Follow-tail (stick-to-bottom) ─────────────────────────────────

    /// A brand-new controller must start stuck to the bottom so the first
    /// streamed reply is visible without the user having to scroll.
    #[test]
    fn new_controller_is_stuck_to_bottom() {
        let cc = ChatController::new("c");
        assert!(
            cc.stuck_to_bottom,
            "new controller must start stuck_to_bottom=true"
        );
    }

    /// When `stuck_to_bottom` is true and new turns push the total row-count
    /// beyond the visible window, `render()` must advance `transcript_scroll_top`
    /// so the newest rows are visible.
    ///
    /// Geometry with `RecordingBackend` (line_height=1, char_width=1) + `make_rect`
    /// (80 × 24):
    ///   status_h = 1, input_h = 4×1+2 = 6, middle_h = 17,
    ///   scrollbar_width = 1  →  transcript_rect = 79 × 17,
    ///   visible_rows = 17, col_budget = 79.
    ///
    /// Each plain turn → 1 header + 1 content + 1 blank = 3 rows.
    /// 7 turns → 21 rows.  max_scroll = 21 − 17 = 4.
    #[test]
    fn follow_tail_advances_scroll_top_on_new_content() {
        let mut cc = ChatController::new("c");
        for i in 0..7 {
            cc.push_turn(ChatRole::User, StyledText::plain(&format!("m{i}")));
        }
        assert_eq!(cc.transcript_scroll_top(), 0, "scroll_top must start at 0");
        cc.render(&mut RecordingBackend::new(), make_rect());
        assert!(
            cc.transcript_scroll_top() > 0,
            "follow-tail must advance scroll_top when content exceeds the visible window; \
             scroll_top={}",
            cc.transcript_scroll_top()
        );
    }

    /// When the user has scrolled up (disengaging follow-tail), appending new
    /// content must NOT yank the viewport to the bottom.
    #[test]
    fn scrolled_up_position_preserved_across_new_content() {
        let mut cc = ChatController::new("c");
        // Scroll up from 0 → disengages follow-tail (max = 20−5 = 15; 0 < 15).
        cc.scroll_transcript_by(-5, 20, 5); // clamped to 0, stuck=false
                                            // Scroll to a mid position.
        cc.scroll_transcript_by(3, 20, 5); // scroll_top=3, stuck=false
        assert!(
            !cc.stuck_to_bottom,
            "scroll_transcript_by up must disengage follow-tail"
        );
        assert_eq!(cc.transcript_scroll_top(), 3);
        // Append new content.
        cc.push_turn(ChatRole::Assistant, StyledText::plain("new reply"));
        // render() must leave scroll_top unchanged because follow-tail is off.
        cc.render(&mut RecordingBackend::new(), make_rect());
        assert_eq!(
            cc.transcript_scroll_top(),
            3,
            "scroll position must be preserved when follow-tail is disengaged; \
             scroll_top={}",
            cc.transcript_scroll_top()
        );
    }

    /// After scrolling up (disengaging follow-tail), scrolling back to the very
    /// last page must re-engage follow-tail automatically.
    #[test]
    fn scroll_to_bottom_reengages_follow_tail() {
        let mut cc = ChatController::new("c");
        // Disengage by scrolling up.
        cc.scroll_transcript_by(-5, 20, 5); // clamped to 0, max=15, stuck=false
        cc.scroll_transcript_by(3, 20, 5); // scroll_top=3, stuck=false
        assert!(!cc.stuck_to_bottom);
        // Scroll to the bottom (max = 20−5 = 15).
        cc.scroll_transcript_by(100, 20, 5); // clamped to 15, stuck=(15≥15)=true
        assert!(
            cc.stuck_to_bottom,
            "scrolling back to the last page must re-engage follow-tail"
        );
    }

    // ── push_turn / push_turn_markdown ───────────────────────────────

    #[test]
    fn push_turn_appends_turn_to_transcript() {
        let mut cc = ChatController::new("c");
        cc.push_turn(ChatRole::User, StyledText::plain("hello"));
        assert_eq!(cc.transcript.len(), 1);
        assert_eq!(cc.transcript[0].role, ChatRole::User);
        let text: String = cc.transcript[0]
            .text
            .spans
            .iter()
            .map(|s| s.text.as_str())
            .collect();
        assert_eq!(text, "hello");
    }

    #[test]
    fn push_turn_multiple_turns_accumulate() {
        let mut cc = ChatController::new("c");
        cc.push_turn(ChatRole::User, StyledText::plain("first"));
        cc.push_turn(ChatRole::Assistant, StyledText::plain("second"));
        assert_eq!(cc.transcript.len(), 2);
        assert_eq!(cc.transcript[0].role, ChatRole::User);
        assert_eq!(cc.transcript[1].role, ChatRole::Assistant);
    }

    #[test]
    fn push_turn_markdown_joins_lines_with_newline() {
        let mut cc = ChatController::new("c");
        let theme = crate::Theme::default();
        cc.push_turn_markdown(ChatRole::Assistant, "line one\nline two", &theme);
        assert_eq!(cc.transcript.len(), 1);
        assert_eq!(cc.transcript[0].role, ChatRole::Assistant);
        // Span texts joined must contain both lines with a '\n' separator.
        let text: String = cc.transcript[0]
            .text
            .spans
            .iter()
            .map(|s| s.text.as_str())
            .collect();
        assert!(
            text.contains("line one"),
            "first line must be present; got: {text:?}"
        );
        assert!(
            text.contains("line two"),
            "second line must be present; got: {text:?}"
        );
        assert!(
            text.contains('\n'),
            "lines must be joined with a newline separator; got: {text:?}"
        );
    }

    #[test]
    fn push_turn_markdown_structural_glyphs_survive_in_plain_text() {
        // The ChatController renders transcript rows by concatenating span
        // text — structural glyphs (bullets, blockquote bars) must survive
        // so they appear as text cues in the rendered transcript.
        let mut cc = ChatController::new("c");
        let theme = crate::Theme::default();
        cc.push_turn_markdown(ChatRole::Assistant, "- item one\n- item two", &theme);
        let text: String = cc.transcript[0]
            .text
            .spans
            .iter()
            .map(|s| s.text.as_str())
            .collect();
        assert!(
            text.contains('\u{2022}'),
            "bullet glyph must survive as a structural text cue; got: {text:?}"
        );
        assert!(
            text.contains("item one"),
            "first item content must be present; got: {text:?}"
        );
    }

    #[test]
    fn push_turn_markdown_empty_string_produces_one_turn_no_panic() {
        let mut cc = ChatController::new("c");
        let theme = crate::Theme::default();
        // Empty markdown must not panic and must append exactly one turn.
        cc.push_turn_markdown(ChatRole::System, "", &theme);
        assert_eq!(cc.transcript.len(), 1);
    }

    // ── Transcript row building ───────────────────────────────────────

    #[test]
    fn build_transcript_rows_includes_role_header() {
        let mut cc = ChatController::new("c");
        cc.set_transcript(vec![make_turn(ChatRole::User, "hi")]);
        let rows = cc.build_transcript_rows(80);
        // Should have: role header ("You"), content row ("hi"), blank separator.
        assert!(rows.len() >= 3);
        assert_eq!(rows[0].text, "You");
        assert_eq!(rows[1].text, "hi");
    }

    #[test]
    fn build_transcript_rows_wraps_long_line() {
        let mut cc = ChatController::new("c");
        // A 10-char line. col_budget=7 → effective content budget=5 (after the
        // 2-unit indent subtract) → "12345" + "67890" = 2 content rows.
        cc.set_transcript(vec![make_turn(ChatRole::Assistant, "1234567890")]);
        let rows = cc.build_transcript_rows(7);
        let content: Vec<_> = rows
            .iter()
            .filter(|r| !r.text.is_empty() && r.indent > 0.0)
            .collect();
        assert_eq!(content.len(), 2);
    }

    // ── Styled transcript rows ────────────────────────────────────────

    #[test]
    fn push_turn_markdown_stores_line_scales() {
        let mut cc = ChatController::new("c");
        let theme = crate::Theme::default();
        cc.push_turn_markdown(ChatRole::Assistant, "# Heading\nbody", &theme);
        let turn = &cc.transcript[0];
        // Markdown adapter produces 2 lines → 2 scales.
        assert_eq!(
            turn.line_scales.len(),
            2,
            "line_scales must have one entry per markdown line; got {:?}",
            turn.line_scales
        );
        // H1 → scale 2.0.
        assert!(
            (turn.line_scales[0] - 2.0).abs() < f32::EPSILON,
            "H1 line_scale must be 2.0; got {}",
            turn.line_scales[0]
        );
        // Body → scale 1.0.
        assert!(
            (turn.line_scales[1] - 1.0).abs() < f32::EPSILON,
            "body line_scale must be 1.0; got {}",
            turn.line_scales[1]
        );
    }

    #[test]
    fn push_turn_has_empty_line_scales() {
        // Turns created via push_turn must have empty line_scales so the
        // flat render path is used — invariant for existing callers.
        let mut cc = ChatController::new("c");
        cc.push_turn(ChatRole::User, StyledText::plain("plain text"));
        assert!(
            cc.transcript[0].line_scales.is_empty(),
            "push_turn must leave line_scales empty"
        );
    }

    #[test]
    fn build_transcript_rows_flat_path_unchanged() {
        // Turns with empty line_scales must produce rows with empty spans
        // — bit-for-bit identical to the pre-styled-row behaviour.
        let mut cc = ChatController::new("c");
        cc.set_transcript(vec![make_turn(ChatRole::User, "hello")]);
        let rows = cc.build_transcript_rows(80);
        // Content row at index 1 (after the "You" header).
        let content_row = rows.iter().find(|r| r.text == "hello").unwrap();
        assert!(
            content_row.spans.is_empty(),
            "flat-path rows must have empty spans; got {:?}",
            content_row.spans
        );
        assert!(
            (content_row.scale - 1.0).abs() < f32::EPSILON,
            "flat-path rows must have scale 1.0"
        );
    }

    #[test]
    fn build_transcript_rows_styled_path_produces_spans() {
        // Turns created by push_turn_markdown must produce rows with non-empty
        // spans so rasterisers can apply per-span styling.
        let mut cc = ChatController::new("c");
        let theme = crate::Theme::default();
        cc.push_turn_markdown(ChatRole::Assistant, "**bold** text", &theme);
        let rows = cc.build_transcript_rows(80);
        // Skip the "AI" role header row, find the content row.
        let content_rows: Vec<_> = rows.iter().filter(|r| r.indent > 0.0).collect();
        assert!(
            !content_rows.is_empty(),
            "expected at least one content row"
        );
        let first = &content_rows[0];
        assert!(
            !first.spans.is_empty(),
            "markdown turns must produce rows with non-empty spans; got empty"
        );
        // The bold span must appear somewhere in the row spans.
        let has_bold = first.spans.iter().any(|s| s.bold);
        assert!(
            has_bold,
            "expected a bold span in the row; spans: {:?}",
            first.spans
        );
    }

    #[test]
    fn build_transcript_rows_heading_carries_scale() {
        // H1 markdown line → content rows must have scale 2.0.
        let mut cc = ChatController::new("c");
        let theme = crate::Theme::default();
        cc.push_turn_markdown(ChatRole::Assistant, "# Title", &theme);
        let rows = cc.build_transcript_rows(80);
        let content_rows: Vec<_> = rows.iter().filter(|r| r.indent > 0.0).collect();
        assert!(!content_rows.is_empty(), "expected content rows");
        let heading_row = &content_rows[0];
        assert!(
            (heading_row.scale - 2.0).abs() < f32::EPSILON,
            "H1 content row must have scale 2.0; got {}",
            heading_row.scale
        );
    }

    #[test]
    fn build_transcript_rows_plain_role_header_has_no_spans() {
        // Role headers ("You", "AI", "System") must always be flat rows —
        // they are inserted by the controller, not from user content.
        let mut cc = ChatController::new("c");
        let theme = crate::Theme::default();
        cc.push_turn_markdown(ChatRole::User, "**bold**", &theme);
        let rows = cc.build_transcript_rows(80);
        let header = rows.iter().find(|r| r.text == "You").unwrap();
        assert!(
            header.spans.is_empty(),
            "role header must be a flat row; spans: {:?}",
            header.spans
        );
    }

    #[test]
    fn build_transcript_rows_styled_wraps_across_budget() {
        // A styled turn wider than the column budget must produce multiple rows.
        let mut cc = ChatController::new("c");
        let theme = crate::Theme::default();
        // 10 plain chars; col_budget=7 → content_budget=5 → 2 rows.
        cc.push_turn_markdown(ChatRole::Assistant, "1234567890", &theme);
        let rows = cc.build_transcript_rows(7);
        let content_rows: Vec<_> = rows.iter().filter(|r| r.indent > 0.0).collect();
        assert_eq!(
            content_rows.len(),
            2,
            "10-char styled line at budget=5 must wrap to 2 rows; got {}",
            content_rows.len()
        );
    }

    #[test]
    fn build_transcript_rows_styled_wraps_cjk_at_display_width() {
        // Styled (markdown) turns wrap via `text_util::wrap_spans` with
        // `WrapPolicy::Char`, budgeting by display width. 6 CJK
        // characters are 6 chars but 12 display cells — a
        // `chars().count()`-based budget would wrongly let them all
        // through on one row at content_budget=6; the display-width-aware
        // wrapper must split after 3 characters (6 cells).
        let mut cc = ChatController::new("c");
        let theme = crate::Theme::default();
        cc.push_turn_markdown(ChatRole::Assistant, "**中文中文中文**", &theme);
        let rows = cc.build_transcript_rows(8); // content_budget = 8 - 2 = 6
        let content_rows: Vec<_> = rows.iter().filter(|r| r.indent > 0.0).collect();
        assert_eq!(
            content_rows.len(),
            2,
            "6 CJK chars (12 cells) at a 6-cell content budget must wrap to \
             2 rows, not 1; got {}",
            content_rows.len()
        );
        for row in &content_rows {
            assert!(
                crate::text_util::display_width(&row.text) <= 6,
                "row {:?} exceeds the 6-cell budget",
                row.text
            );
        }
    }

    // ── split_spans_by_newline ────────────────────────────────────────

    #[test]
    fn split_spans_by_newline_single_line() {
        let spans = vec![StyledSpan::plain("hello")];
        let lines = split_spans_by_newline(&spans);
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].len(), 1);
        assert_eq!(lines[0][0].text, "hello");
    }

    #[test]
    fn split_spans_by_newline_two_lines() {
        let spans = vec![
            StyledSpan::plain("line1"),
            StyledSpan::plain("\n"),
            StyledSpan::plain("line2"),
        ];
        let lines = split_spans_by_newline(&spans);
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0][0].text, "line1");
        assert_eq!(lines[1][0].text, "line2");
    }

    #[test]
    fn split_spans_by_newline_empty_produces_one_empty_line() {
        let lines = split_spans_by_newline(&[]);
        assert_eq!(lines.len(), 1);
        assert!(lines[0].is_empty());
    }

    // `wrap_spans`/`WrapPolicy` are unit-tested in `text_util.rs`; this
    // module only tests the `WrapPolicy::Char` call site.

    // ── Wrap helper ───────────────────────────────────────────────────

    #[test]
    fn wrap_text_short_line_is_not_split() {
        let v = wrap_text("hello", 80);
        assert_eq!(v, vec!["hello".to_string()]);
    }

    #[test]
    fn wrap_text_splits_at_budget() {
        let v = wrap_text("abcde", 3);
        assert_eq!(v, vec!["abc", "de"]);
    }

    #[test]
    fn wrap_text_empty_returns_one_empty_row() {
        let v = wrap_text("", 80);
        assert_eq!(v, vec![String::new()]);
    }

    // ── Input soft-wrap ────────────────────────────────────────────────

    #[test]
    fn wrap_line_exact_short_line_not_split() {
        assert_eq!(wrap_line_exact("hi", 10), vec![(0, "hi".to_string())]);
    }

    #[test]
    fn wrap_line_exact_breaks_at_space() {
        // "hello world" (11 chars) at budget 7 breaks after "hello " (the
        // space stays with the first row) leaving "world" on the second.
        assert_eq!(
            wrap_line_exact("hello world", 7),
            vec![(0, "hello ".to_string()), (6, "world".to_string())]
        );
    }

    #[test]
    fn wrap_line_exact_hard_breaks_a_single_long_word() {
        assert_eq!(
            wrap_line_exact("abcdefgh", 3),
            vec![
                (0, "abc".to_string()),
                (3, "def".to_string()),
                (6, "gh".to_string())
            ]
        );
    }

    #[test]
    fn wrap_line_exact_reconstructs_original_text() {
        // The defining property: concatenating every row's text
        // reconstructs the input exactly — no whitespace collapsed or
        // dropped (unlike `word_wrap`), so cursor round-trips stay exact.
        let line = "the quick brown fox jumps over the lazy dog";
        for budget in 1..line.chars().count() + 2 {
            let rows = wrap_line_exact(line, budget);
            let joined: String = rows.iter().map(|(_, t)| t.as_str()).collect();
            assert_eq!(joined, line, "budget={budget}");
        }
    }

    #[test]
    fn wrap_input_rows_one_row_per_short_logical_line() {
        let rows = wrap_input_rows("ab\ncd", 80);
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0].logical_line, 0);
        assert_eq!(rows[1].logical_line, 1);
    }

    #[test]
    fn wrap_input_rows_empty_buffer_yields_one_empty_row() {
        let rows = wrap_input_rows("", 80);
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].text, "");
    }

    #[test]
    fn logical_to_visual_round_trips_through_visual_to_byte() {
        let text = "hello world\nsecond line";
        let rows = wrap_input_rows(text, 6); // forces "hello world" to wrap
        assert!(rows.len() > 2, "expected wrapping to produce >2 rows");

        // Cursor at byte offset 8 ("hello wo|rld...") -> logical (0, 8).
        let (line, col) = cursor_byte_to_line_col(text, 8);
        assert_eq!((line, col), (0, 8));

        let (row_idx, visual_col) = input_logical_to_visual(&rows, line, col);
        let byte = input_visual_to_byte(text, &rows, row_idx, visual_col);
        assert_eq!(byte, 8, "round trip through visual space must be lossless");
    }

    #[test]
    fn logical_to_visual_end_of_line_lands_on_last_visual_row() {
        let text = "hello world";
        let rows = wrap_input_rows(text, 6); // wraps into 2 rows
        let last_row = rows.len() - 1;
        let (line, col) = cursor_byte_to_line_col(text, text.len());
        let (row_idx, _) = input_logical_to_visual(&rows, line, col);
        assert_eq!(row_idx, last_row);
    }

    // ── Up/Down move by VISUAL row when wrapped ────────────────────────

    #[test]
    fn up_within_wrapped_paragraph_moves_cursor_not_history() {
        let mut cc = ChatController::new("c");
        cc.set_input_height_range(1, 8);
        cc.input_insert_str("hello world this wraps");
        cc.history.push("prev".into());
        // Narrow rect forces wrapping: content width well under the text length.
        let rect = Rect::new(0.0, 0.0, 12.0, 24.0);
        let event = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Up),
            modifiers: Modifiers::default(),
            repeat: false,
        };
        let ev = cc.handle(&event, &RecordingBackend::new(), rect);
        assert_eq!(ev, ChatControllerEvent::Consumed);
        // History must NOT have been entered — the cursor started on a
        // later visual row of the wrapped paragraph, not the first one.
        assert_eq!(cc.history_pos, None);
        assert_eq!(cc.input_text(), "hello world this wraps");
    }

    #[test]
    fn up_on_first_visual_row_of_wrapped_paragraph_enters_history() {
        let mut cc = ChatController::new("c");
        cc.input_insert_str("hello world this wraps");
        cc.input_cursor = 3; // still within the first wrapped row
        cc.history.push("prev".into());
        let rect = Rect::new(0.0, 0.0, 12.0, 24.0);
        let event = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Up),
            modifiers: Modifiers::default(),
            repeat: false,
        };
        let ev = cc.handle(&event, &RecordingBackend::new(), rect);
        assert_eq!(ev, ChatControllerEvent::Consumed);
        assert_eq!(cc.input_text(), "prev", "should have entered history");
    }

    #[test]
    fn down_on_last_visual_row_of_wrapped_paragraph_enters_history_next() {
        let mut cc = ChatController::new("c");
        // A wrapped paragraph sitting in `saved_input`, restored once Down
        // walks off the newest history entry.
        cc.input_insert_str("hello world this wraps");
        cc.history.push("first".into());
        cc.history.push("second".into());
        let rect = Rect::new(0.0, 0.0, 12.0, 24.0);
        // Drive `history_prev` directly (bypassing the Up key) to reach a
        // deterministic "navigating the newest entry" state.
        cc.history_prev();
        assert_eq!(cc.input_text(), "second");

        let event = UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Down),
            modifiers: Modifiers::default(),
            repeat: false,
        };
        let ev = cc.handle(&event, &RecordingBackend::new(), rect);
        assert_eq!(ev, ChatControllerEvent::Consumed);
        // "second" fits on one visual row even at width 12, so Down from
        // its only (first==last) row walks off the newest history entry
        // and restores the saved wrapped paragraph.
        assert_eq!(cc.history_pos, None);
        assert_eq!(cc.input_text(), "hello world this wraps");
    }

    // ── Cursor byte conversion helpers ────────────────────────────────

    #[test]
    fn byte_to_line_col_single_line() {
        assert_eq!(cursor_byte_to_line_col("hello", 3), (0, 3));
    }

    #[test]
    fn byte_to_line_col_multiline() {
        assert_eq!(cursor_byte_to_line_col("ab\ncd", 4), (1, 1));
    }

    /// Regression test for multibyte character handling: `cursor_byte_to_line_col`
    /// must snap a cursor byte offset to a valid char boundary, not panic when
    /// the offset lands mid-multibyte-character (inside a character like "é").
    #[test]
    fn byte_to_line_col_multibyte_mid_char_offset_does_not_panic() {
        let text = "héllo";
        assert!(!text.is_char_boundary(2)); // inside the 2-byte 'é'
        let (line, col) = cursor_byte_to_line_col(text, 2);
        assert_eq!((line, col), (0, 1));
    }

    #[test]
    fn line_col_to_byte_first_line() {
        assert_eq!(line_col_to_byte("hello", 0, 3), 3);
    }

    #[test]
    fn line_col_to_byte_second_line() {
        assert_eq!(line_col_to_byte("ab\ncd", 1, 1), 4);
    }

    #[test]
    fn line_col_to_byte_clamps_to_end_of_line() {
        // "ab\ncd" line 0 has 2 chars; col 99 should clamp to 2 (before \n).
        assert_eq!(line_col_to_byte("ab\ncd", 0, 99), 2);
    }

    #[test]
    fn line_col_to_byte_nonexistent_line_clamps_to_end() {
        assert_eq!(line_col_to_byte("ab", 5, 0), 2);
    }

    // ── Input backspace / delete ──────────────────────────────────────

    #[test]
    fn backspace_deletes_previous_char() {
        let mut cc = ChatController::new("c");
        cc.input_insert_str("hi");
        cc.input_backspace();
        assert_eq!(cc.input_text(), "h");
        assert_eq!(cc.input_cursor, 1);
    }

    #[test]
    fn backspace_at_start_is_noop() {
        let mut cc = ChatController::new("c");
        cc.input_insert_str("x");
        cc.input_cursor = 0;
        cc.input_backspace();
        assert_eq!(cc.input_text(), "x");
    }

    #[test]
    fn delete_removes_char_at_cursor() {
        let mut cc = ChatController::new("c");
        cc.input_insert_str("ab");
        cc.input_cursor = 0;
        cc.input_delete();
        assert_eq!(cc.input_text(), "b");
    }

    // ── Layout zones ─────────────────────────────────────────────────

    #[test]
    fn layout_status_at_top() {
        let cc = ChatController::new("c");
        let layout = cc.compute_layout(&RecordingBackend::new(), make_rect());
        assert_eq!(layout.status.y, 0.0);
        assert_eq!(layout.status.height, 1.0); // line_height = 1.0
    }

    #[test]
    fn layout_input_at_bottom() {
        let cc = ChatController::new("c");
        let layout = cc.compute_layout(&RecordingBackend::new(), make_rect());
        // Auto-grow: empty input wraps to 1 visual row, clamped
        // to the default input_min_rows=1. lh=1, border=2 → input_h = 3.
        let expected_input_y = make_rect().height - (1.0 * 1.0 + 2.0);
        assert_eq!(layout.input.y, expected_input_y);
    }

    #[test]
    fn layout_input_grows_with_wrapped_row_count() {
        let mut cc = ChatController::new("c");
        cc.input_insert_str("line one\nline two\nline three");
        let layout = cc.compute_layout(&RecordingBackend::new(), make_rect());
        // 3 short logical lines, wide rect → 3 visual rows, no wrapping.
        // lh=1, border=2 → input_h = 5.
        let expected_input_y = make_rect().height - (3.0 * 1.0 + 2.0);
        assert_eq!(layout.input.y, expected_input_y);
    }

    #[test]
    fn layout_input_clamps_to_max_rows() {
        let mut cc = ChatController::new("c");
        for _ in 0..20 {
            cc.input_insert_char('\n');
        }
        // 21 logical lines (20 newlines) would need 21 visual rows, but
        // the default max is 8.
        let layout = cc.compute_layout(&RecordingBackend::new(), make_rect());
        let expected_input_y = make_rect().height - (8.0 * 1.0 + 2.0);
        assert_eq!(layout.input.y, expected_input_y);
    }

    #[test]
    fn set_input_height_range_overrides_default_clamp() {
        let mut cc = ChatController::new("c");
        cc.set_input_height_range(2, 3);
        let layout = cc.compute_layout(&RecordingBackend::new(), make_rect());
        // Empty input wraps to 1 visual row, clamped up to the new min=2.
        let expected_input_y = make_rect().height - (2.0 * 1.0 + 2.0);
        assert_eq!(layout.input.y, expected_input_y);
    }

    #[test]
    fn set_input_height_range_floors_max_to_min() {
        let mut cc = ChatController::new("c");
        cc.set_input_height_range(5, 2); // max < min — max floored up to min.
        assert_eq!(cc.input_min_rows, 5);
        assert_eq!(cc.input_max_rows, 5);
    }

    #[test]
    fn layout_no_scrollbar_when_transcript_empty() {
        let cc = ChatController::new("c");
        let layout = cc.compute_layout(&RecordingBackend::new(), make_rect());
        assert!(layout.scrollbar.is_none());
    }

    #[test]
    fn layout_scrollbar_present_when_transcript_nonempty() {
        let mut cc = ChatController::new("c");
        cc.set_transcript(vec![make_turn(ChatRole::User, "hello")]);
        let layout = cc.compute_layout(&RecordingBackend::new(), make_rect());
        assert!(layout.scrollbar.is_some());
        // Transcript rect should be narrower than full width.
        assert!(layout.transcript.width < make_rect().width);
    }

    #[test]
    fn layout_spinner_present_when_busy() {
        let mut cc = ChatController::new("c");
        cc.set_busy(true);
        let layout = cc.compute_layout(&RecordingBackend::new(), make_rect());
        assert!(layout.spinner.is_some());
    }

    #[test]
    fn layout_spinner_absent_when_not_busy() {
        let cc = ChatController::new("c");
        let layout = cc.compute_layout(&RecordingBackend::new(), make_rect());
        assert!(layout.spinner.is_none());
    }

    // ── Send/Stop segment + hint layout ────────────────────────────────

    #[test]
    fn layout_send_segment_present_when_row_wide_enough() {
        let cc = ChatController::new("c");
        let layout = cc.compute_layout(&RecordingBackend::new(), make_rect());
        assert!(layout.send.is_some());
        // The TextInput's own rect should be narrower than the full row
        // to make room for the segment.
        assert!(layout.input.width < make_rect().width);
    }

    #[test]
    fn layout_send_segment_absent_when_row_too_narrow() {
        let cc = ChatController::new("c");
        let narrow = Rect::new(0.0, 0.0, 10.0, 24.0);
        let layout = cc.compute_layout(&RecordingBackend::new(), narrow);
        assert!(layout.send.is_none());
        // TextInput falls back to the full row width.
        assert_eq!(layout.input.width, narrow.width);
    }

    #[test]
    fn layout_send_segment_spans_full_input_height() {
        let cc = ChatController::new("c");
        let layout = cc.compute_layout(&RecordingBackend::new(), make_rect());
        let send = layout.send.expect("send segment present");
        assert_eq!(send.y, layout.input.y);
        assert_eq!(send.height, layout.input.height);
    }

    #[test]
    fn layout_hint_absent_by_default() {
        let cc = ChatController::new("c");
        let layout = cc.compute_layout(&RecordingBackend::new(), make_rect());
        assert!(layout.hint.is_none());
    }

    #[test]
    fn layout_hint_present_when_set() {
        let mut cc = ChatController::new("c");
        cc.set_hint(Some(StyledText::plain(
            "Enter to send, Shift+Enter for newline",
        )));
        let layout = cc.compute_layout(&RecordingBackend::new(), make_rect());
        let hint = layout.hint.expect("hint row present");
        // The hint row sits directly above the input box.
        assert_eq!(hint.y + hint.height, layout.input.y);
    }

    #[test]
    fn layout_hint_cleared_by_set_hint_none() {
        let mut cc = ChatController::new("c");
        cc.set_hint(Some(StyledText::plain("hint")));
        cc.set_hint(None);
        let layout = cc.compute_layout(&RecordingBackend::new(), make_rect());
        assert!(layout.hint.is_none());
    }

    // ── Send/Stop segment click routing ────────────────────────────────

    fn click_at(cc: &mut ChatController, rect: Rect, x: f32, y: f32) -> ChatControllerEvent {
        let event = crate::mouse_down(MouseButton::Left, x, y, Modifiers::default());
        cc.handle(&event, &RecordingBackend::new(), rect)
    }

    #[test]
    fn click_send_segment_while_idle_submits() {
        let mut cc = ChatController::new("c");
        cc.input_insert_str("hello");
        let rect = make_rect();
        let send = cc
            .compute_layout(&RecordingBackend::new(), rect)
            .send
            .expect("send segment present");
        let ev = click_at(&mut cc, rect, send.x + 1.0, send.y + 1.0);
        assert_eq!(
            ev,
            ChatControllerEvent::Submit {
                text: "hello".into()
            }
        );
    }

    #[test]
    fn click_send_segment_while_idle_and_empty_is_ignored() {
        let mut cc = ChatController::new("c");
        let rect = make_rect();
        let send = cc
            .compute_layout(&RecordingBackend::new(), rect)
            .send
            .expect("send segment present");
        let ev = click_at(&mut cc, rect, send.x + 1.0, send.y + 1.0);
        assert_eq!(ev, ChatControllerEvent::Ignored);
    }

    #[test]
    fn click_send_segment_while_busy_emits_stop_requested() {
        let mut cc = ChatController::new("c");
        cc.input_insert_str("hello");
        cc.set_busy(true);
        let rect = make_rect();
        let send = cc
            .compute_layout(&RecordingBackend::new(), rect)
            .send
            .expect("send segment present");
        let ev = click_at(&mut cc, rect, send.x + 1.0, send.y + 1.0);
        assert_eq!(ev, ChatControllerEvent::StopRequested);
        // The input buffer is left untouched by a stop request.
        assert_eq!(cc.input_text(), "hello");
    }

    // ── Collapsible turns and per-turn hit regions ──────────────────────

    #[test]
    fn turn_summary_line_defaults_to_first_nonblank_line() {
        let mut cc = ChatController::new("c");
        cc.set_transcript(vec![make_turn(
            ChatRole::Assistant,
            "\n  \nreal content\nmore",
        )]);
        assert_eq!(cc.turn_summary_line(0), "real content");
    }

    #[test]
    fn turn_summary_line_prefers_explicit_summary() {
        let mut cc = ChatController::new("c");
        cc.set_transcript(vec![make_turn(ChatRole::Assistant, "full body text")]);
        cc.set_turn_summary(0, Some("custom summary".to_string()));
        assert_eq!(cc.turn_summary_line(0), "custom summary");
    }

    #[test]
    fn turn_summary_line_empty_for_turn_with_no_content() {
        let mut cc = ChatController::new("c");
        cc.set_transcript(vec![make_turn(ChatRole::Assistant, "")]);
        assert_eq!(cc.turn_summary_line(0), "");
    }

    #[test]
    fn turn_summary_line_empty_for_out_of_range_turn_idx() {
        let cc = ChatController::new("c");
        assert_eq!(cc.turn_summary_line(0), "");
    }

    #[test]
    fn set_turn_summary_none_clears_the_override() {
        let mut cc = ChatController::new("c");
        cc.set_transcript(vec![make_turn(ChatRole::Assistant, "fallback line")]);
        cc.set_turn_summary(0, Some("override".to_string()));
        assert_eq!(cc.turn_summary_line(0), "override");
        cc.set_turn_summary(0, None);
        assert_eq!(cc.turn_summary_line(0), "fallback line");
    }

    #[test]
    fn new_turns_start_expanded() {
        let mut cc = ChatController::new("c");
        cc.set_transcript(vec![make_turn(ChatRole::User, "hi")]);
        assert!(!cc.is_turn_collapsed(0));
    }

    #[test]
    fn toggle_turn_collapsed_flips_state() {
        let mut cc = ChatController::new("c");
        cc.set_transcript(vec![make_turn(ChatRole::User, "hi")]);
        cc.toggle_turn_collapsed(0);
        assert!(cc.is_turn_collapsed(0));
        cc.toggle_turn_collapsed(0);
        assert!(!cc.is_turn_collapsed(0));
    }

    #[test]
    fn set_turn_collapsed_out_of_range_is_a_noop() {
        let mut cc = ChatController::new("c");
        cc.set_turn_collapsed(5, true);
        cc.toggle_turn_collapsed(5);
        assert!(!cc.is_turn_collapsed(5));
    }

    #[test]
    fn build_transcript_rows_collapsed_turn_emits_header_and_summary_only() {
        let mut cc = ChatController::new("c");
        cc.set_transcript(vec![make_turn(
            ChatRole::Assistant,
            "first line\nsecond line",
        )]);
        cc.set_turn_collapsed(0, true);

        let rows = cc.build_transcript_rows(80);
        // Header row + one summary row + the blank inter-turn separator —
        // not the full two-line body.
        assert_eq!(rows.len(), 3);
        assert!(
            rows[0].text.contains("AI"),
            "header row should still show the role label: {:?}",
            rows[0].text
        );
        assert_eq!(rows[1].text, "first line");
    }

    #[test]
    fn build_transcript_rows_expanded_turn_unchanged_by_collapsed_field() {
        // `collapsed` defaulting to `false` must not perturb the existing
        // flat-path row output at all.
        let mut cc = ChatController::new("c");
        cc.set_transcript(vec![make_turn(ChatRole::User, "hello")]);
        let rows = cc.build_transcript_rows(80);
        assert_eq!(rows[0].text, "You");
        assert_eq!(rows[1].text, "hello");
        assert_eq!(rows[1].indent, 2.0);
        assert_eq!(rows.len(), 3);
    }

    #[test]
    fn transcript_click_on_first_turn_header_returns_turn_clicked() {
        let mut cc = ChatController::new("c");
        cc.set_transcript(vec![
            make_turn(ChatRole::User, "Hello"),
            make_turn(ChatRole::Assistant, "Hi"),
        ]);
        let rect = make_rect();
        let t = cc.compute_layout(&RecordingBackend::new(), rect).transcript;
        // Row 0 (turn 0's header row) sits at the very top of the
        // transcript rect (line_height == 1.0 on `RecordingBackend`).
        let ev = click_at(&mut cc, rect, t.x + 1.0, t.y + 0.5);
        assert_eq!(
            ev,
            ChatControllerEvent::TurnClicked {
                turn_idx: 0,
                row_in_turn: 0
            }
        );
        // A click also moves the keyboard cursor onto the clicked turn so
        // mouse and keyboard interactions stay in sync.
        assert_eq!(cc.focused_turn(), Some(0));
    }

    #[test]
    fn transcript_click_on_second_turn_resolves_its_turn_idx() {
        let mut cc = ChatController::new("c");
        cc.set_transcript(vec![
            make_turn(ChatRole::User, "Hello"),
            make_turn(ChatRole::Assistant, "Hi"),
        ]);
        let rect = make_rect();
        let t = cc.compute_layout(&RecordingBackend::new(), rect).transcript;
        // Turn 0 occupies rows 0-2 (header, content, blank separator);
        // turn 1's header starts at row 3.
        let ev = click_at(&mut cc, rect, t.x + 1.0, t.y + 3.5);
        assert_eq!(
            ev,
            ChatControllerEvent::TurnClicked {
                turn_idx: 1,
                row_in_turn: 0
            }
        );
        assert_eq!(cc.focused_turn(), Some(1));
    }

    #[test]
    fn click_then_enter_toggles_the_clicked_turn_not_a_stale_focus() {
        // Pressing `Enter` after a mouse click must toggle the clicked turn,
        // using the focused_turn set by the click.
        let mut cc = ChatController::new("c");
        cc.set_transcript(vec![
            make_turn(ChatRole::User, "Hello"),
            make_turn(ChatRole::Assistant, "Hi"),
        ]);
        let rect = make_rect();
        let backend = RecordingBackend::new();
        let t = cc.compute_layout(&backend, rect).transcript;

        click_at(&mut cc, rect, t.x + 1.0, t.y + 3.5);
        assert_eq!(cc.focused_turn(), Some(1));
        assert!(!cc.is_turn_collapsed(1));

        let enter = key_event(Key::Named(NamedKey::Enter), Modifiers::default());
        let ev = cc.handle(&enter, &backend, rect);
        assert_eq!(ev, ChatControllerEvent::Consumed);
        assert!(cc.is_turn_collapsed(1));
        assert!(!cc.is_turn_collapsed(0));
    }

    #[test]
    fn transcript_click_below_last_row_is_consumed_not_turn_clicked() {
        let mut cc = ChatController::new("c");
        cc.set_transcript(vec![make_turn(ChatRole::User, "Hi")]);
        let rect = make_rect();
        let t = cc.compute_layout(&RecordingBackend::new(), rect).transcript;
        // Far below the 3 painted rows, but still inside the transcript
        // rect's blank tail.
        let ev = click_at(&mut cc, rect, t.x + 1.0, t.y + t.height - 0.5);
        assert_eq!(ev, ChatControllerEvent::Consumed);
    }

    // ── Focused-turn keyboard cursor ─────────────────────────────────────

    fn key_event(key: Key, modifiers: Modifiers) -> UiEvent {
        UiEvent::KeyPressed {
            key,
            modifiers,
            repeat: false,
        }
    }

    #[test]
    fn tab_cycles_focused_turn_then_back_to_input() {
        let mut cc = ChatController::new("c");
        cc.set_transcript(vec![
            make_turn(ChatRole::User, "one"),
            make_turn(ChatRole::Assistant, "two"),
        ]);
        let rect = make_rect();
        let backend = RecordingBackend::new();
        let tab = key_event(Key::Named(NamedKey::Tab), Modifiers::default());

        assert_eq!(cc.focused_turn(), None);
        assert!(cc.input_has_focus());

        cc.handle(&tab, &backend, rect);
        assert_eq!(cc.focused_turn(), Some(0));
        assert!(!cc.input_has_focus());

        cc.handle(&tab, &backend, rect);
        assert_eq!(cc.focused_turn(), Some(1));

        cc.handle(&tab, &backend, rect);
        assert_eq!(cc.focused_turn(), None);
        assert!(cc.input_has_focus());
    }

    #[test]
    fn shift_tab_cycles_focused_turn_backward() {
        let mut cc = ChatController::new("c");
        cc.set_transcript(vec![
            make_turn(ChatRole::User, "one"),
            make_turn(ChatRole::Assistant, "two"),
        ]);
        let rect = make_rect();
        let backend = RecordingBackend::new();
        let shift_tab = key_event(
            Key::Named(NamedKey::Tab),
            Modifiers {
                shift: true,
                ..Default::default()
            },
        );

        cc.handle(&shift_tab, &backend, rect);
        assert_eq!(cc.focused_turn(), Some(1));
        cc.handle(&shift_tab, &backend, rect);
        assert_eq!(cc.focused_turn(), Some(0));
        cc.handle(&shift_tab, &backend, rect);
        assert_eq!(cc.focused_turn(), None);
    }

    #[test]
    fn tab_with_empty_transcript_is_a_noop() {
        let mut cc = ChatController::new("c");
        let rect = make_rect();
        let backend = RecordingBackend::new();
        let tab = key_event(Key::Named(NamedKey::Tab), Modifiers::default());
        cc.handle(&tab, &backend, rect);
        assert_eq!(cc.focused_turn(), None);
        assert!(cc.input_has_focus());
    }

    #[test]
    fn enter_while_turn_focused_toggles_collapsed_instead_of_submitting() {
        let mut cc = ChatController::new("c");
        cc.set_transcript(vec![make_turn(ChatRole::Assistant, "body")]);
        cc.set_focused_turn(Some(0));
        let rect = make_rect();
        let backend = RecordingBackend::new();
        let enter = key_event(Key::Named(NamedKey::Enter), Modifiers::default());

        assert!(!cc.is_turn_collapsed(0));
        let ev = cc.handle(&enter, &backend, rect);
        assert_eq!(ev, ChatControllerEvent::Consumed);
        assert!(cc.is_turn_collapsed(0));

        // Pressing Enter again expands it back.
        let ev2 = cc.handle(&enter, &backend, rect);
        assert_eq!(ev2, ChatControllerEvent::Consumed);
        assert!(!cc.is_turn_collapsed(0));
    }

    #[test]
    fn ctrl_enter_still_submits_while_a_turn_is_focused() {
        let mut cc = ChatController::new("c");
        cc.set_transcript(vec![make_turn(ChatRole::Assistant, "body")]);
        cc.set_focused_turn(Some(0));
        cc.input_insert_str("hello");
        let rect = make_rect();
        let backend = RecordingBackend::new();
        let ctrl_enter = key_event(
            Key::Named(NamedKey::Enter),
            Modifiers {
                ctrl: true,
                ..Default::default()
            },
        );
        let ev = cc.handle(&ctrl_enter, &backend, rect);
        assert_eq!(
            ev,
            ChatControllerEvent::Submit {
                text: "hello".into()
            }
        );
        // The universal submit chord bypasses the toggle — the turn stays
        // expanded.
        assert!(!cc.is_turn_collapsed(0));
    }

    #[test]
    fn typing_returns_focus_to_input_from_a_focused_turn() {
        let mut cc = ChatController::new("c");
        cc.set_transcript(vec![make_turn(ChatRole::User, "one")]);
        cc.set_focused_turn(Some(0));
        assert!(!cc.input_has_focus());

        let rect = make_rect();
        let backend = RecordingBackend::new();
        cc.handle(&UiEvent::CharTyped('x'), &backend, rect);

        assert_eq!(cc.focused_turn(), None);
        assert!(cc.input_has_focus());
        assert_eq!(cc.input_text(), "x");
    }

    // ── Backend rendering tests ───────────────────────────────────────
    //
    // The tests above exercise state/layout against a `RecordingBackend` whose
    // draw calls are no-ops. These two paint the controller through the
    // real `TuiBackend` / `GtkBackend` trait impls into a backend-owned
    // headless surface (a `ratatui::Buffer` / `cairo::ImageSurface`) and
    // assert that the actual `draw_message_list` / `draw_text_input` /
    // `draw_scrollbar` / `draw_spinner` rasterisers produced output. This
    // is the golden-style coverage required by the issue acceptance
    // criteria (TESTING.md "coordinate drift" row).

    /// TUI: paint a populated controller into a `ratatui::Buffer` via the
    /// `TuiBackend` trait path and assert the painted cells contain the
    /// expected glyphs — the status label + model chip, the user role
    /// header `"You"`, an assistant content row, and the input
    /// placeholder. This proves the real TUI rasterisers ran (not a mock).
    #[cfg(feature = "tui")]
    #[test]
    fn tui_render_paints_glyphs_into_buffer() {
        use crate::tui::TuiBackend;
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        const W: u16 = 48;
        const H: u16 = 14;

        let mut cc = ChatController::new("chat");
        cc.set_status(StyledText::plain("Refining issue #264"));
        cc.set_model_label("claude-opus-4-5");
        cc.set_transcript(vec![
            make_turn(ChatRole::User, "Hello there"),
            make_turn(ChatRole::Assistant, "General Kenobi"),
        ]);

        let mut terminal = Terminal::new(TestBackend::new(W, H)).expect("construct test terminal");
        let mut backend = TuiBackend::new();
        backend.begin_frame(crate::Viewport {
            width: W as f32,
            height: H as f32,
            scale: 1.0,
        });

        let rect = Rect::new(0.0, 0.0, W as f32, H as f32);
        terminal
            .draw(|frame| {
                backend.enter_frame_scope(frame, |b| {
                    cc.render(b, rect);
                });
            })
            .expect("draw frame");

        // Flatten the painted buffer to a single string so assertions are
        // robust to exact cell coordinates.
        let buf = terminal.backend().buffer();
        let mut painted = String::new();
        for y in 0..H {
            for x in 0..W {
                painted.push(buf[(x, y)].symbol().chars().next().unwrap_or(' '));
            }
            painted.push('\n');
        }

        assert!(
            painted.contains("Refining issue #264"),
            "status label not painted:\n{painted}"
        );
        assert!(
            painted.contains("claude-opus-4-5"),
            "model chip not painted:\n{painted}"
        );
        assert!(
            painted.contains("You"),
            "user role header not painted:\n{painted}"
        );
        assert!(
            painted.contains("General Kenobi"),
            "assistant content row not painted:\n{painted}"
        );
        assert!(
            painted.contains("Type a message"),
            "input placeholder not painted:\n{painted}"
        );
    }

    /// TUI: the Send/Stop segment paints "Send" while idle and
    /// "Stop" while busy, and the persistent hint row paints its text —
    /// through the real `TuiBackend::draw_form` / `draw_message_list`
    /// rasterisers, not a mock.
    #[cfg(feature = "tui")]
    #[test]
    fn tui_render_paints_send_stop_segment_and_hint() {
        use crate::tui::TuiBackend;
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        const W: u16 = 48;
        const H: u16 = 14;

        fn paint(cc: &ChatController) -> String {
            let mut terminal =
                Terminal::new(TestBackend::new(W, H)).expect("construct test terminal");
            let mut backend = TuiBackend::new();
            backend.begin_frame(crate::Viewport {
                width: W as f32,
                height: H as f32,
                scale: 1.0,
            });
            let rect = Rect::new(0.0, 0.0, W as f32, H as f32);
            terminal
                .draw(|frame| {
                    backend.enter_frame_scope(frame, |b| {
                        cc.render(b, rect);
                    });
                })
                .expect("draw frame");
            let buf = terminal.backend().buffer();
            let mut painted = String::new();
            for y in 0..H {
                for x in 0..W {
                    painted.push(buf[(x, y)].symbol().chars().next().unwrap_or(' '));
                }
                painted.push('\n');
            }
            painted
        }

        let mut cc = ChatController::new("chat");
        cc.set_hint(Some(StyledText::plain("Enter to send")));

        let idle = paint(&cc);
        assert!(idle.contains("Send"), "Send label not painted:\n{idle}");
        assert!(
            idle.contains("Enter to send"),
            "hint row not painted:\n{idle}"
        );

        cc.set_busy(true);
        let busy = paint(&cc);
        assert!(busy.contains("Stop"), "Stop label not painted:\n{busy}");
    }

    /// TUI: the input placeholder advertises the binding that is actually live.
    ///
    /// `set_submit_on_enter(true)` inverts the meaning of `Enter` and
    /// `Shift+Enter`, so the placeholder must change to match. The default
    /// placeholder ("Alt+Enter to send, Enter for newline") would instruct the
    /// user to do the opposite of what the keymap does. Tested with the real
    /// `TuiBackend::draw_text_input` rasteriser, wide enough that the full
    /// string fits without truncation.
    #[cfg(feature = "tui")]
    #[test]
    fn tui_placeholder_tracks_submit_on_enter_mode() {
        use crate::tui::TuiBackend;
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        // Wide enough that the whole placeholder fits inside the input box
        // (box borders + the Send segment eat ~10 columns).
        const W: u16 = 110;
        const H: u16 = 14;

        fn paint(cc: &ChatController) -> String {
            let mut terminal =
                Terminal::new(TestBackend::new(W, H)).expect("construct test terminal");
            let mut backend = TuiBackend::new();
            backend.begin_frame(crate::Viewport {
                width: W as f32,
                height: H as f32,
                scale: 1.0,
            });
            let rect = Rect::new(0.0, 0.0, W as f32, H as f32);
            terminal
                .draw(|frame| {
                    backend.enter_frame_scope(frame, |b| {
                        cc.render(b, rect);
                    });
                })
                .expect("draw frame");
            let buf = terminal.backend().buffer();
            let mut painted = String::new();
            for y in 0..H {
                for x in 0..W {
                    painted.push(buf[(x, y)].symbol().chars().next().unwrap_or(' '));
                }
                painted.push('\n');
            }
            painted
        }

        // Default mode: Alt+Enter sends, plain Enter breaks the line.
        let mut cc = ChatController::new("chat");
        let default_mode = paint(&cc);
        assert!(
            default_mode.contains("Alt+Enter to send"),
            "default-mode placeholder should advertise Alt+Enter as submit:\n{default_mode}"
        );
        assert!(
            default_mode.contains("Enter for newline"),
            "default-mode placeholder should advertise plain Enter as newline:\n{default_mode}"
        );

        // submit_on_enter: the two bindings swap, and so must the hint.
        cc.set_submit_on_enter(true);
        let enter_mode = paint(&cc);
        assert!(
            enter_mode.contains("Enter to send"),
            "submit_on_enter placeholder should advertise Enter as submit:\n{enter_mode}"
        );
        assert!(
            enter_mode.contains("Shift+Enter for newline"),
            "submit_on_enter placeholder should advertise Shift+Enter as newline:\n{enter_mode}"
        );
        assert!(
            !enter_mode.contains("Alt+Enter to send"),
            "submit_on_enter placeholder must not still claim Alt+Enter submits — in this \
             mode Alt+Enter inserts a newline:\n{enter_mode}"
        );
    }

    /// GTK: paint a populated controller into a `cairo::ImageSurface` via
    /// the `GtkBackend` trait path against a white background, then assert
    /// (a) the render inked at least one non-white pixel — proving the GTK
    /// rasterisers actually drew — and (b) the backend's
    /// `text_input_layout` returns a non-empty layout for the input zone.
    #[cfg(feature = "gtk")]
    #[test]
    fn gtk_render_inks_surface_and_layout_nonempty() {
        use crate::gtk::GtkBackend;
        use pangocairo::cairo::{Context, Format, ImageSurface};

        const W: i32 = 360;
        const H: i32 = 220;

        let mut cc = ChatController::new("chat");
        cc.set_status(StyledText::plain("Plan review for #264"));
        cc.set_model_label("claude-opus-4-5");
        cc.set_transcript(vec![
            make_turn(ChatRole::User, "Hello there"),
            make_turn(ChatRole::Assistant, "General Kenobi"),
        ]);

        let mut backend = GtkBackend::new();
        // White background: any non-white pixel must have come from the
        // controller's foreground ink (text / borders / scrollbar).
        backend.set_theme(crate::Theme {
            background: crate::Color::rgb(255, 255, 255),
            ..crate::Theme::default()
        });

        let rect = Rect::new(0.0, 0.0, W as f32, H as f32);
        let mut surface = ImageSurface::create(Format::ARgb32, W, H).expect("create ImageSurface");
        {
            let cr = Context::new(&surface).expect("cairo Context");
            cr.set_source_rgb(1.0, 1.0, 1.0);
            cr.paint().expect("paint white baseline");
            let layout = pangocairo::functions::create_layout(&cr);
            backend.enter_frame_scope(&cr, &layout, |b| {
                cc.render(b, rect);
            });
        }

        // (a) The render path inked at least one non-white pixel.
        let stride = surface.stride() as usize;
        let inked = {
            let data = surface.data().expect("surface data");
            let mut found = false;
            'scan: for y in 0..H {
                for x in 0..W {
                    let off = y as usize * stride + x as usize * 4;
                    // Cairo ARGB32 on little-endian is BGRA in memory.
                    let (r, g, b) = (data[off + 2], data[off + 1], data[off]);
                    if !(r == 255 && g == 255 && b == 255) {
                        found = true;
                        break 'scan;
                    }
                }
            }
            found
        };
        assert!(
            inked,
            "controller.render painted nothing into the GTK surface"
        );

        // (b) text_input_layout for the input zone yields a usable layout.
        let mut ti = TextInput::new(WidgetId::new("probe-input"));
        ti.lines = vec!["hello".to_string()];
        ti.cursor_col = 5;
        ti.has_focus = true;
        let input_rect = Rect::new(0.0, H as f32 - 80.0, W as f32, 80.0);
        let ti_layout = backend.text_input_layout(input_rect, &ti);
        assert!(
            !ti_layout.visible_lines.is_empty(),
            "text_input_layout returned no visible lines"
        );
    }
}