mermaid-cli 0.17.0

Open-source AI pair programmer with agentic capabilities. Local-first with Ollama, native tool calling, and beautiful TUI.
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
use std::hash::{Hash, Hasher};

use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Paragraph, StatefulWidget, Widget},
};
use rustc_hash::FxHashMap;
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

use crate::domain::{
    ActionDetails, ActionDisplay, ActionResult, QuestionAnswer, ToolMetadata, format_compact_count,
};
use crate::models::ChatMessageKind;
use crate::models::{ChatMessage, MessageRole};
use crate::render::diff::{DiffLineKind, parse_diff_line};
use crate::render::markdown::parse_markdown;
use crate::render::theme::Theme;
use crate::utils::format_relative_timestamp;

/// Entry in the click map: maps a content line to an image in chat history
#[derive(Debug, Clone)]
pub struct ImageClickTarget {
    /// Index into the DISPLAY message slice this frame rendered. The display
    /// slice can diverge from committed history (the continuation stitch hides
    /// nudges and merges bubbles), so this is only a fallback locator — prefer
    /// `image_number`.
    pub message_index: usize,
    /// Index into that display message's images vec
    pub image_index: usize,
    /// The image's stable global `[Image #N]` number, when it has one.
    /// Position-independent, so the reducer can resolve the click against
    /// committed history no matter how the display transcript was stitched.
    pub image_number: Option<u64>,
}

/// State for the chat widget
#[derive(Debug, Clone)]
pub struct ChatState {
    /// Manual scroll offset (only used when is_user_scrolling = true)
    scroll_offset: u16,
    /// Whether user is manually scrolling (not following bottom)
    is_user_scrolling: bool,
    /// Click map: content line number → image target (rebuilt every render)
    pub image_click_map: Vec<(u16, ImageClickTarget)>,
    /// Scroll position used in last render (for coordinate mapping)
    pub last_scroll_position: u16,
    /// Chat area rect from last render
    pub last_chat_area: Option<(u16, u16, u16, u16)>, // (x, y, width, height)
    /// Active drag-selection in CONTENT coordinates: `(anchor, cursor)` where
    /// each is `(content_line, col_cells)`. Highlight + copy derive from it.
    selection: Option<((usize, usize), (usize, usize))>,
    /// Plain text of each rendered content row, captured every frame so the
    /// selection can be extracted by display-cell range. Indexed by content
    /// line (the same index the selection uses).
    last_rendered_rows: Vec<String>,
    /// Memoized full-frame assembly (F31): the wrapped lines and image click
    /// map produced by the per-message render loop, keyed by a fingerprint of
    /// every input that determines them (message set, theme, width, reasoning
    /// toggle, day). An unchanged scrollback reuses this across frames instead
    /// of re-parsing, re-wrapping, and rebuilding the click map every frame.
    /// Replaced whenever the fingerprint changes.
    frame_memo: Option<FrameMemo>,
}

/// One memoized chat-frame assembly (see `ChatState::frame_memo`). Holds the
/// lines *before* the per-frame selection highlight (which is selection-
/// dependent and applied to a clone each frame) plus the image click map, so a
/// frame whose inputs are unchanged skips the whole per-message render loop
/// (F31). Cloning is `O(total lines)`, but it replaces the markdown parse +
/// wrap + click-map rebuild the loop would otherwise redo every frame.
#[derive(Debug, Clone)]
struct FrameMemo {
    /// Fingerprint of the inputs that produced `lines` + `click_map`.
    key: u64,
    /// Assembled wrapped lines, before the per-frame selection highlight.
    lines: Vec<Line<'static>>,
    /// Image click map captured alongside `lines`.
    click_map: Vec<(u16, ImageClickTarget)>,
}

impl ChatState {
    /// Create a new chat state (starts in auto-follow mode)
    pub fn new() -> Self {
        Self {
            scroll_offset: 0,
            is_user_scrolling: false,
            image_click_map: Vec::new(),
            last_scroll_position: 0,
            last_chat_area: None,
            selection: None,
            last_rendered_rows: Vec::new(),
            frame_memo: None,
        }
    }

    /// Get the scroll position for rendering
    /// scroll_offset represents distance from bottom, convert to ratatui scroll position
    pub fn get_scroll_position(&self, content_height: u16, viewport_height: u16) -> u16 {
        let max_scroll = content_height.saturating_sub(viewport_height);
        if self.is_user_scrolling {
            // Manual scroll: convert "distance from bottom" to scroll position
            // scroll_offset=0 → show bottom (max_scroll), scroll_offset=max → show top (0)
            let capped_offset = self.scroll_offset.min(max_scroll);
            max_scroll.saturating_sub(capped_offset)
        } else {
            // Auto-scroll: show bottom of content
            max_scroll
        }
    }

    /// Scroll viewport up (shows older messages further from bottom)
    pub fn scroll_up(&mut self, amount: u16) {
        self.is_user_scrolling = true;
        self.scroll_offset = self.scroll_offset.saturating_add(amount);
        // A selection's content-line anchors don't track scrolling; drop it
        // rather than leave a highlight stranded on the wrong rows.
        self.selection = None;
    }

    /// Scroll viewport down (shows newer messages closer to bottom)
    /// Automatically resumes auto-scroll when reaching the bottom
    pub fn scroll_down(&mut self, amount: u16) {
        self.scroll_offset = self.scroll_offset.saturating_sub(amount);
        if self.scroll_offset == 0 {
            // Reached bottom — resume auto-follow mode
            self.is_user_scrolling = false;
        }
        self.selection = None;
    }

    /// Force resume auto-scroll mode (jump to bottom)
    pub fn resume_auto_scroll(&mut self) {
        self.is_user_scrolling = false;
        self.scroll_offset = 0;
    }

    /// Check if user is manually scrolling (not following bottom)
    pub fn is_manually_scrolling(&self) -> bool {
        self.is_user_scrolling
    }

    /// Find an image click target at the given screen coordinates.
    /// Returns Some((message_index, image_index)) if an image indicator was clicked.
    pub fn find_image_at_screen_pos(&self, screen_row: u16) -> Option<&ImageClickTarget> {
        let (_, area_y, _, area_height) = self.last_chat_area?;

        // Check if click is within chat area
        if screen_row < area_y || screen_row >= area_y + area_height {
            return None;
        }

        // Convert screen row to content line
        let viewport_row = screen_row - area_y;
        let content_line = viewport_row + self.last_scroll_position;

        // Look up in click map
        self.image_click_map
            .iter()
            .find(|(line, _)| *line == content_line)
            .map(|(_, target)| target)
    }

    /// Map a screen `(row, col)` to content `(line, col_cells)`, or `None`
    /// when the point is outside the chat area. `col` is clamped to the chat
    /// area's left edge so a drag past the gutter still maps to column 0.
    fn screen_to_content(&self, screen_row: u16, screen_col: u16) -> Option<(usize, usize)> {
        let (area_x, area_y, _, area_height) = self.last_chat_area?;
        if screen_row < area_y || screen_row >= area_y + area_height {
            return None;
        }
        let content_line = (screen_row - area_y) as usize + self.last_scroll_position as usize;
        let col = screen_col.saturating_sub(area_x) as usize;
        Some((content_line, col))
    }

    /// Begin a drag selection at the given screen position (mouse-down).
    /// Anchors and cursor both start here; a plain click with no drag selects
    /// nothing.
    pub fn begin_selection(&mut self, screen_row: u16, screen_col: u16) {
        self.selection = self
            .screen_to_content(screen_row, screen_col)
            .map(|p| (p, p));
    }

    /// Extend the in-progress selection to the given screen position (drag).
    pub fn update_selection(&mut self, screen_row: u16, screen_col: u16) {
        if let Some((anchor, _)) = self.selection
            && let Some(cursor) = self.screen_to_content(screen_row, screen_col)
        {
            self.selection = Some((anchor, cursor));
        }
    }

    /// Drop any active selection (and its highlight).
    pub fn clear_selection(&mut self) {
        self.selection = None;
    }

    /// Extract the currently-selected text from the last rendered frame, or
    /// `None` if there's no selection or it's empty (e.g. a plain click).
    /// Walks the retained per-row text and slices each row by display cells so
    /// CJK / wide glyphs are never split mid-cell.
    pub fn selected_text(&self) -> Option<String> {
        let (a, b) = self.selection?;
        let (start, end) = if a <= b { (a, b) } else { (b, a) };
        if self.last_rendered_rows.is_empty() {
            return None;
        }
        let last = self.last_rendered_rows.len() - 1;
        let (start_line, start_col) = (start.0.min(last), start.1);
        let (end_line, end_col) = (end.0.min(last), end.1);

        let mut out = String::new();
        for line in start_line..=end_line {
            let row = &self.last_rendered_rows[line];
            let c0 = if line == start_line { start_col } else { 0 };
            let c1 = if line == end_line {
                end_col
            } else {
                usize::MAX
            };
            let mut piece = slice_by_cells(row, c0, c1).to_string();
            // Drop the rendered left margin (the "● "/"  " role/continuation
            // prefix — up to SELECT_MARGIN_CELLS cells of spaces) so copied
            // text is clean. Only spaces inside the margin zone [c0, MARGIN)
            // are removed, so a code line's own indentation is preserved.
            let mut margin = SELECT_MARGIN_CELLS.saturating_sub(c0);
            while margin > 0 && piece.starts_with(' ') {
                piece.remove(0);
                margin -= 1;
            }
            out.push_str(piece.trim_end());
            if line != end_line {
                out.push('\n');
            }
        }
        if out.is_empty() { None } else { Some(out) }
    }
}

/// Display-cell width of the role/continuation left margin ("● " or "  ")
/// that the renderer prepends to chat content lines. Stripped from copied
/// selections so the clipboard gets clean text.
const SELECT_MARGIN_CELLS: usize = 2;

/// Hard-wrap a pre-formatted (code) line at `width` display cells, preserving
/// every glyph (including whitespace) and each span's style. Continuation rows
/// get a `indent`-space hanging indent. Unlike `wrap_styled_line` this never
/// collapses runs of spaces, so code indentation and alignment survive.
fn wrap_preformatted(line: Line<'static>, width: usize, indent: usize) -> Vec<Line<'static>> {
    if width == 0 {
        return vec![line];
    }
    let total: usize = line.spans.iter().map(|s| s.content.width()).sum();
    if total <= width {
        return vec![line];
    }

    let base = line.style;
    let mut out: Vec<Line<'static>> = Vec::new();
    let mut cur: Vec<Span<'static>> = Vec::new();
    let mut cur_w = 0usize;
    let mut on_first = true;

    for span in line.spans {
        let style = span.style;
        let mut buf = String::new();
        for ch in span.content.chars() {
            let cw = ch.width().unwrap_or(0);
            // Break before this char if it would overflow and the current row
            // already holds real content (beyond the continuation indent).
            let floor = if on_first { 0 } else { indent };
            if cur_w + cw > width && cur_w > floor {
                if !buf.is_empty() {
                    cur.push(Span::styled(std::mem::take(&mut buf), style));
                }
                out.push(Line::from(std::mem::take(&mut cur)).style(base));
                on_first = false;
                cur.push(Span::styled(" ".repeat(indent), base));
                cur_w = indent;
            }
            buf.push(ch);
            cur_w += cw;
        }
        if !buf.is_empty() {
            cur.push(Span::styled(buf, style));
        }
    }
    if !cur.is_empty() {
        out.push(Line::from(cur).style(base));
    }
    if out.is_empty() {
        vec![Line::from("").style(base)]
    } else {
        out
    }
}

/// Byte offset in `s` at the start of display-cell `target` (clamped to
/// `s.len()`). A wide glyph straddling `target` is kept whole on the right
/// side, so slicing never lands mid-character.
fn byte_at_cell(s: &str, target: usize) -> usize {
    if target == 0 {
        return 0;
    }
    let mut width = 0usize;
    for (idx, ch) in s.char_indices() {
        if width >= target {
            return idx;
        }
        width += ch.width().unwrap_or(0);
    }
    s.len()
}

/// Slice `s` to the display-cell range `[c0, c1)`.
fn slice_by_cells(s: &str, c0: usize, c1: usize) -> &str {
    let start = byte_at_cell(s, c0);
    let end = byte_at_cell(s, c1).max(start);
    &s[start..end]
}

/// Pad `s` on the right with spaces until it spans `cells` display columns,
/// measured with `UnicodeWidthStr::width` (not chars/bytes) so a CJK/emoji row's
/// background bar fills to the true visual edge instead of falling short (#101).
/// Never truncates — an already-too-wide `s` is returned unchanged.
fn pad_to_cells(s: &str, cells: usize) -> String {
    let w = s.width();
    if w >= cells {
        return s.to_string();
    }
    let mut out = String::with_capacity(s.len() + (cells - w));
    out.push_str(s);
    out.push_str(&" ".repeat(cells - w));
    out
}

/// First-line spacing for a user message: the run of spaces before the
/// right-aligned timestamp. All inputs are display-cell widths so CJK/emoji
/// align correctly (#104). Returns `min_gap` plus whatever slack remains to
/// push the timestamp to `content_width`'s right edge.
fn user_timestamp_padding(
    role_prefix_width: usize,
    text_width: usize,
    timestamp_width: usize,
    min_gap: usize,
    content_width: usize,
) -> usize {
    let total_used = role_prefix_width + text_width + min_gap + timestamp_width;
    min_gap + content_width.saturating_sub(total_used)
}

/// The plain text of a rendered line (spans concatenated, styles dropped).
fn line_plain_text(line: &Line) -> String {
    line.spans.iter().map(|s| s.content.as_ref()).collect()
}

/// Saturating cast from a `usize` line counter to the `u16` ratatui scroll /
/// click-map coordinate. A scrollback longer than `u16::MAX` rows clamps to the
/// last addressable row instead of wrapping the index modulo 65536 (which a
/// plain `as u16` would do, corrupting both the scroll position and the image
/// click-map on a very long session) (F32).
fn clamp_to_u16(n: usize) -> u16 {
    u16::try_from(n).unwrap_or(u16::MAX)
}

/// Apply `hl` (merged onto each span's existing style) to display cells
/// `[c0, c1)` of `line`, splitting spans at the selection boundaries so the
/// highlight lands on exactly the selected glyphs.
fn highlight_line_cells(line: &mut Line<'static>, c0: usize, c1: usize, hl: Style) {
    let mut new_spans: Vec<Span<'static>> = Vec::with_capacity(line.spans.len() + 2);
    let mut width = 0usize;
    for span in line.spans.drain(..) {
        let span_w = span.content.width();
        let (span_start, span_end) = (width, width + span_w);
        width = span_end;

        let ov0 = c0.max(span_start);
        let ov1 = c1.min(span_end);
        if ov1 <= ov0 {
            new_spans.push(span); // no overlap with the selection
            continue;
        }

        let s = span.content.as_ref();
        let b0 = byte_at_cell(s, ov0 - span_start);
        let b1 = byte_at_cell(s, ov1 - span_start);
        if b0 > 0 {
            new_spans.push(Span::styled(s[..b0].to_string(), span.style));
        }
        new_spans.push(Span::styled(s[b0..b1].to_string(), span.style.patch(hl)));
        if b1 < s.len() {
            new_spans.push(Span::styled(s[b1..].to_string(), span.style));
        }
    }
    line.spans = new_spans;
}

impl Default for ChatState {
    fn default() -> Self {
        Self::new()
    }
}

/// Props for ChatWidget
pub struct ChatWidget<'a> {
    pub messages: &'a [ChatMessage],
    pub theme: &'a Theme,
    /// Shared render cache: `(content, theme, width)` hash → fully wrapped,
    /// role-prefixed assistant lines. Caching the WRAPPED output (not just the
    /// markdown parse) keeps a committed message from being re-parsed *and*
    /// re-wrapped every frame — it's cloned from here instead (#134).
    pub wrapped_line_cache: &'a mut FxHashMap<u64, Vec<Line<'static>>>,
    pub show_reasoning: bool,
    /// Blink phase for in-flight (`ActionResult::Running`) action headers,
    /// derived from `state.now` by the compose function. Ignored — including
    /// by the frame memo — when no message carries a running action, so idle
    /// frames don't reassemble twice a second.
    pub blink_on: bool,
}

/// Render assistant message content (markdown) into wrapped, role-prefixed
/// display lines.
///
/// Pure in its inputs — `(content, width, role prefix/color, theme)` — which is
/// exactly what lets the result be cached per message and reused across frames
/// without re-parsing or re-wrapping (#134). The cache key folds in content,
/// theme, and width; role prefix/color are constant on this (assistant-only)
/// path, so they need not be keyed.
fn wrap_assistant_content(
    content: &str,
    content_width: u16,
    role_prefix: &str,
    role_color: ratatui::style::Color,
    theme: &Theme,
) -> Vec<Line<'static>> {
    // Markdown content sits after the 2-cell message gutter.
    let md_width = (content_width as usize).saturating_sub(2);
    let parsed = parse_markdown(content, theme, md_width);

    let mut out: Vec<Line<'static>> = Vec::new();
    for (line_idx, parsed_line) in parsed.into_iter().enumerate() {
        // Code-block lines are tagged with the code background on their base
        // style (see markdown::parse_markdown). They're pre-formatted: don't
        // word-wrap (that collapses indentation) — let the Paragraph clip
        // overflow instead.
        let preformatted = parsed_line.preformatted;
        let base_style = parsed_line.line.style;

        // Continuation indent for wrapping: the 2-cell message gutter every line
        // carries, plus this line's own content-start column so a wrapped list
        // item's continuations hang under its text (after the marker) instead of
        // snapping back to the gutter.
        let continuation = if preformatted {
            2
        } else {
            2 + crate::render::markdown::line_hanging_indent(&parsed_line.line, theme)
        };

        // Add role indicator to first line or 2-space margin to others.
        let mut spans = if line_idx == 0 {
            vec![Span::styled(
                format!("{} ", role_prefix),
                Style::new().fg(role_color).bold(),
            )]
        } else {
            vec![Span::raw("  ")]
        };
        spans.extend(parsed_line.line.spans);
        let new_line = Line::from(spans).style(base_style);

        if preformatted {
            // Code: hard-wrap preserving indentation (don't word-collapse) so
            // wide lines stay readable.
            out.extend(wrap_preformatted(new_line, content_width as usize, 2));
        } else {
            out.extend(wrap_styled_line(
                new_line,
                content_width as usize,
                continuation,
            ));
        }
    }
    out
}

/// `std::fmt::Write` shim that streams a value's formatted bytes straight into
/// a hasher, so a `Debug`/`Display` value can be folded into a fingerprint
/// without allocating an intermediate `String`.
struct HashWrite<'a, H: Hasher>(&'a mut H);

impl<H: Hasher> std::fmt::Write for HashWrite<'_, H> {
    fn write_str(&mut self, s: &str) -> std::fmt::Result {
        self.0.write(s.as_bytes());
        Ok(())
    }
}

/// Fingerprint every input that determines the assembled chat lines + image
/// click map: the message set (role, kind, content, thinking, actions, image
/// count, timestamp, metadata), the theme identity, the content width, the
/// reasoning toggle, and today's date — the only clock-dependent input, since a
/// user timestamp renders as "Today"/"Yesterday"/an absolute date relative to it.
///
/// Two frames with the same fingerprint assemble byte-identical lines, so the
/// result can be memoized across frames (F31). Uses the same 64-bit-hash-keyed
/// caching the per-message #134 cache already relies on; the complex non-`Hash`
/// fields (`metadata`, `actions`) are folded in via their `Debug` form so no
/// rendered field is silently missed.
fn frame_fingerprint(
    messages: &[ChatMessage],
    theme_seed: u64,
    content_width: u16,
    show_reasoning: bool,
    blink_on: bool,
) -> u64 {
    use std::fmt::Write as _;
    let mut h = rustc_hash::FxHasher::default();
    theme_seed.hash(&mut h);
    content_width.hash(&mut h);
    show_reasoning.hash(&mut h);
    // The day-relative label ("Today"/"Yesterday"/date) on user timestamps
    // changes only at midnight; fold today's date in so the memo refreshes then.
    chrono::Local::now().date_naive().hash(&mut h);
    // The blink phase only affects frames that actually paint a running
    // action's header dot; folding it in unconditionally would invalidate the
    // memo twice a second on every idle frame.
    if messages.iter().any(|m| {
        m.actions
            .iter()
            .any(|a| matches!(a.result, ActionResult::Running))
    }) {
        blink_on.hash(&mut h);
    }
    messages.len().hash(&mut h);
    for msg in messages {
        msg.content.hash(&mut h);
        msg.thinking.hash(&mut h);
        // The instant fully determines `format_time(msg.timestamp)`; the
        // day-relative label is covered by today's date above.
        msg.timestamp.timestamp().hash(&mut h);
        msg.images
            .as_ref()
            .map_or(0, |imgs| imgs.len())
            .hash(&mut h);
        let mut hw = HashWrite(&mut h);
        let _ = write!(
            hw,
            "{:?}|{:?}|{:?}|{:?}",
            msg.role, msg.kind, msg.metadata, msg.actions
        );
    }
    h.finish()
}

impl<'a> StatefulWidget for ChatWidget<'a> {
    type State = ChatState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        // Code-block lines are tagged with this background; computed once so
        // the markdown cache key can use it.
        let code_bg = self.theme.colors.code_background.to_color();
        let theme_seed = {
            let mut h = rustc_hash::FxHasher::default();
            self.theme.colors.foreground.to_color().hash(&mut h);
            code_bg.hash(&mut h);
            self.theme.colors.header.to_color().hash(&mut h);
            h.finish()
        };

        // Content spans the full width — there is no scrollbar gutter.
        let content_width = area.width;
        let content_area = area;

        state.last_chat_area = Some((area.x, area.y, area.width, area.height));

        // F31: skip the whole per-message assembly when nothing that affects it
        // changed. The fingerprint folds in every render input, so a reused
        // frame is byte-identical to a fresh one. Scrolling and drag-selection
        // don't touch these inputs, so the common case (a static scrollback)
        // reuses the memo instead of re-parsing and re-wrapping every message.
        let frame_key = frame_fingerprint(
            self.messages,
            theme_seed,
            content_width,
            self.show_reasoning,
            self.blink_on,
        );
        // Type is inferred from the map below (the frame_memo struct names the
        // fields); an explicit annotation would just be a clippy::type_complexity.
        let memo_hit = state
            .frame_memo
            .as_ref()
            .filter(|m| m.key == frame_key)
            .map(|m| (m.lines.clone(), m.click_map.clone()));

        let mut lines = if let Some((cached_lines, cached_click_map)) = memo_hit {
            // Memo hit: reuse the assembled lines; restore the click map that
            // was captured alongside them.
            state.image_click_map = cached_click_map;
            cached_lines
        } else {
            // Memo miss: assemble fresh, then memoize for the next frame.
            let mut lines: Vec<Line<'static>> = Vec::new();

            // Clear click map for this render pass
            state.image_click_map.clear();

            for (idx, msg) in self.messages.iter().enumerate() {
                // Skip Tool messages - they're internal to the agent loop and their
                // content is already displayed inline in the assistant's action blocks
                if matches!(msg.role, MessageRole::Tool) {
                    continue;
                }

                if matches!(msg.kind, ChatMessageKind::ContextCheckpoint) {
                    if let Some(event_lines) =
                        render_context_checkpoint_event(msg, self.theme, content_width as usize)
                    {
                        lines.extend(event_lines);
                        lines.push(Line::from(""));
                    }
                    continue;
                }

                // Run summary ("Worked for … · used … tokens"): a muted gray line where
                // the spinner was — dimmer than the assistant's text (same gray as the
                // timestamp), not italic. Display-only — excluded from the model context
                // by build_chat_request, so it never accumulates as conversation.
                if matches!(msg.kind, ChatMessageKind::RunSummary) {
                    lines.push(Line::from(Span::styled(
                        format!("  {}", msg.content),
                        Style::new().fg(self.theme.colors.text_meta.to_color()),
                    )));
                    lines.push(Line::from(""));
                    continue;
                }

                // A recovery nudge is a one-shot model instruction, not user
                // content — the stitch pre-pass hides committed ones, and this
                // guard keeps a still-live one (mid-recovery) invisible too.
                if matches!(msg.kind, ChatMessageKind::RecoveryNudge) {
                    continue;
                }

                // System notices (warnings, agent completions, command
                // replies): muted meta text — no bullet, no timestamp. The
                // same gray as the run summary, so transcript furniture never
                // competes with the conversation.
                if matches!(msg.role, MessageRole::System) {
                    let meta = Style::new().fg(self.theme.colors.text_meta.to_color());
                    for wrapped_line in
                        wrap_text_with_indent(&msg.content, content_width as usize, 2, 2)
                    {
                        lines.push(Line::from(Span::styled(wrapped_line, meta)));
                    }
                    lines.push(Line::from(""));
                    continue;
                }

                // Auto-continue stitch, streaming half: a `Continuation`
                // extending a mergeable assistant bubble draws as that
                // bubble's tail — no fresh `●`, no blank separator — so the
                // reply reads as one message *while it streams*, not only
                // after commit (committed halves are merged upstream in
                // `stitch_committed`). An unmergeable predecessor (e.g. a
                // compaction checkpoint) falls through to a normal bubble.
                let stitch_onto_prev = matches!(msg.kind, ChatMessageKind::Continuation)
                    && self.messages[..idx]
                        .iter()
                        .rev()
                        .find(|m| !matches!(m.role, MessageRole::Tool))
                        .is_some_and(crate::render::mergeable_into);
                if stitch_onto_prev && lines.last().is_some_and(|l| line_plain_text(l).is_empty()) {
                    lines.pop();
                }

                let (role_prefix, role_color) = match msg.role {
                    MessageRole::User => (">", self.theme.colors.text_primary.to_color()),
                    MessageRole::Assistant => ("", self.theme.colors.text_primary.to_color()),
                    MessageRole::System | MessageRole::Tool => {
                        unreachable!("System and Tool messages handled above")
                    },
                };
                // A stitched continuation keeps the 2-cell gutter but no
                // bullet: a single space prefix renders as the same margin
                // the bubble's wrapped lines already use.
                let role_prefix = if stitch_onto_prev { " " } else { role_prefix };

                if matches!(msg.role, MessageRole::Assistant) {
                    // Render thinking block if present
                    if let Some(ref thinking) = msg.thinking {
                        // Skip rendering if thinking content is empty or literal "None"
                        let thinking_trimmed = thinking.trim();
                        if thinking_trimmed.is_empty()
                            || thinking_trimmed == "None"
                            || thinking_trimmed == "none"
                        {
                            // Don't render empty/null thinking blocks
                        } else if self.show_reasoning {
                            // Add "Thinking..." header in italic and dimmed with grayed white dot
                            lines.push(Line::from(vec![
                                Span::styled(
                                    "",
                                    Style::new().fg(self.theme.colors.text_disabled.to_color()),
                                ),
                                Span::styled(
                                    "Thinking...",
                                    Style::new()
                                        .fg(self.theme.colors.text_secondary.to_color())
                                        .italic()
                                        .dim(),
                                ),
                            ]));

                            // Render thinking content with proper wrapping (2-space hanging indent)
                            let wrapped = wrap_text_with_indent(
                                thinking,
                                content_width as usize,
                                2, // first line indent (2 spaces)
                                2, // continuation indent (2 spaces)
                            );
                            for wrapped_line in wrapped {
                                lines.push(Line::from(Span::styled(
                                    wrapped_line,
                                    Style::new()
                                        .fg(self.theme.colors.text_secondary.to_color())
                                        .italic()
                                        .dim(),
                                )));
                            }

                            // Add blank line after thinking block
                            lines.push(Line::from(""));
                        } else if msg.content.trim().is_empty() && msg.actions.is_empty() {
                            // Reasoning is hidden and there's nothing else in this turn —
                            // skip it entirely rather than render an empty bullet. No
                            // "reasoning hidden" placeholder: /visible-reasoning controls
                            // whether the thinking shows, silently.
                            continue;
                        }
                    }

                    // Assistant prose is the bulk of the scrollback. Its wrapped,
                    // role-prefixed lines are a pure function of (content, theme,
                    // width) — exactly this key — so cache the WRAPPED output, not
                    // just the parse: a committed message is then cloned, never
                    // re-parsed or re-wrapped, each frame (#134). Theme is folded in
                    // so a theme switch can't serve stale-colored lines; width is in
                    // the key because tables wrap to the viewport.
                    let mut hasher = rustc_hash::FxHasher::default();
                    msg.content.hash(&mut hasher);
                    theme_seed.hash(&mut hasher);
                    content_width.hash(&mut hasher);
                    // A stitched continuation renders prefix-less; keep its
                    // cached lines distinct from a same-content bubble.
                    stitch_onto_prev.hash(&mut hasher);
                    let cache_key = hasher.finish();

                    let wrapped = if let Some(cached) = self.wrapped_line_cache.get(&cache_key) {
                        cached.clone()
                    } else {
                        let block = wrap_assistant_content(
                            &msg.content,
                            content_width,
                            role_prefix,
                            role_color,
                            self.theme,
                        );
                        self.wrapped_line_cache.insert(cache_key, block.clone());
                        if self.wrapped_line_cache.len()
                            > crate::constants::MARKDOWN_CACHE_MAX_ENTRIES
                        {
                            // Evict down to the cap rather than clearing the whole
                            // cache — a wholesale clear re-rendered every message each
                            // frame once a conversation exceeded the cap. Keep the
                            // entry just inserted.
                            let overflow = self.wrapped_line_cache.len()
                                - crate::constants::MARKDOWN_CACHE_MAX_ENTRIES;
                            let stale: Vec<u64> = self
                                .wrapped_line_cache
                                .keys()
                                .copied()
                                .filter(|&k| k != cache_key)
                                .take(overflow)
                                .collect();
                            for k in stale {
                                self.wrapped_line_cache.remove(&k);
                            }
                        }
                        block
                    };
                    lines.extend(wrapped);

                    // Render all actions at the end of the message
                    if !msg.actions.is_empty() {
                        // Add blank line between text content and actions
                        if !msg.content.trim().is_empty() {
                            lines.push(Line::from(""));
                        }
                        render_actions(
                            &msg.actions,
                            &mut lines,
                            self.theme,
                            content_width as usize,
                            self.blink_on,
                        );
                    }
                } else {
                    // For User messages: format timestamp and display on right edge
                    let formatted_timestamp = format_relative_timestamp(msg.timestamp);
                    // Display cells, not bytes — a CJK/emoji timestamp (or message)
                    // would otherwise mis-reserve space and push the right-aligned
                    // timestamp off its column (#104).
                    let timestamp_width = formatted_timestamp.width();
                    let min_gap = 3; // minimum spaces between text and timestamp

                    // Content is clean — timestamps are injected at API call time only
                    let cleaned_content = &msg.content;

                    // Reserve space on the first line for role prefix + gap + timestamp
                    // so text wraps early enough to not overlap the timestamp
                    let role_prefix_width = role_prefix.width() + 1; // "You " = prefix + space
                    let first_line_reserved = role_prefix_width + min_gap + timestamp_width;

                    // Manually wrap the user message with hanging indent (2 spaces)
                    let wrapped = wrap_text_with_indent(
                        cleaned_content,
                        content_width as usize,
                        first_line_reserved, // reserve space for prefix + gap + timestamp on first line
                        2,                   // continuation indent
                    );

                    let band_start = lines.len();
                    for (line_idx, wrapped_line) in wrapped.iter().enumerate() {
                        if line_idx == 0 {
                            // First line: add role prefix and timestamp on right
                            let text_content = wrapped_line.trim_start(); // Remove the indent we added
                            let text_width = text_content.width();

                            let mut spans = vec![
                                Span::styled(
                                    format!("{} ", role_prefix),
                                    Style::new().fg(role_color).bold(),
                                ),
                                Span::raw(text_content.to_string()),
                            ];

                            // Always add at least min_gap spaces, plus any extra from word-boundary slack.
                            // Align the timestamp to the content's right edge.
                            let pad = user_timestamp_padding(
                                role_prefix_width,
                                text_width,
                                timestamp_width,
                                min_gap,
                                content_width as usize,
                            );
                            spans.push(Span::raw(" ".repeat(pad)));
                            spans.push(Span::styled(
                                formatted_timestamp.clone(),
                                Style::new().fg(self.theme.colors.text_meta.to_color()),
                            ));

                            lines.push(Line::from(spans));
                        } else {
                            // Continuation lines: already have 2-space margin from wrap_text_with_indent
                            lines.push(Line::from(wrapped_line.clone()));
                        }
                    }

                    // Claude-Code-style highlight band: paint a subtle full-width
                    // background behind every line of the user's submitted prompt. The
                    // ">" marker, text, and timestamp keep their own foreground colors;
                    // only the row background is added.
                    if matches!(msg.role, MessageRole::User) {
                        let user_bg = self.theme.colors.user_message_background.to_color();
                        let cw = content_width as usize;
                        for line in &mut lines[band_start..] {
                            let used: usize = line.spans.iter().map(|s| s.content.width()).sum();
                            if used < cw {
                                line.spans.push(Span::raw(" ".repeat(cw - used)));
                            }
                            line.style = line.style.bg(user_bg);
                        }
                    }
                }

                // Show image indicators under user and assistant messages.
                // User images come from clipboard paste (`Attachment`); assistant
                // images come from tool executions that emitted `ProgressEvent::
                // Artifact` during their run — screenshot captures, inline
                // previews from computer-use, etc. Both land in `msg.images` as
                // base64 strings and render the same way.
                if matches!(msg.role, MessageRole::User | MessageRole::Assistant)
                    && let Some(ref images) = msg.images
                    && !images.is_empty()
                {
                    for (i, _) in images.iter().enumerate() {
                        // Record this line in the click map before pushing.
                        // `lines.len()` is usize; clamp to the u16 click-map/scroll
                        // coordinate with a saturating cast at this boundary so a
                        // scrollback past u16::MAX rows clamps instead of wrapping a
                        // stale line index into the map (F32).
                        let content_line = lines.len();
                        let image_number =
                            msg.image_numbers.as_ref().and_then(|v| v.get(i)).copied();
                        state.image_click_map.push((
                            clamp_to_u16(content_line),
                            ImageClickTarget {
                                message_index: idx,
                                image_index: i,
                                image_number,
                            },
                        ));
                        // Prefer the stable global number stored with the
                        // message; fall back to a positional index for sessions
                        // saved before image numbering (and assistant/tool
                        // images, which carry no global number).
                        let label = image_number
                            .map(|n| format!("[Image #{n}]"))
                            .unwrap_or_else(|| format!("[Image #{}]", i + 1));
                        lines.push(Line::from(vec![
                            Span::styled(
                                "",
                                Style::new().fg(self.theme.colors.info.to_color()),
                            ),
                            Span::styled(
                                label,
                                Style::new().fg(self.theme.colors.info.to_color()).italic(),
                            ),
                        ]));
                    }
                }

                lines.push(Line::from(""));
            }

            // Capture the plain text of each rendered row for selection
            // extraction (before the per-frame highlight, which changes only
            // styling, not text). Recomputed only on a miss: a memo hit means
            // unchanged content, so the rows from the miss that built the memo
            // stay valid — this skips an O(total) re-collect every frame (F31).
            state.last_rendered_rows = lines.iter().map(line_plain_text).collect();

            // F31: memoize this assembly so an unchanged next frame reuses it
            // instead of re-running the loop above. Store the lines *before* the
            // selection highlight (applied per-frame below), so the cache stays
            // selection-independent.
            state.frame_memo = Some(FrameMemo {
                key: frame_key,
                lines: lines.clone(),
                click_map: state.image_click_map.clone(),
            });
            lines
        };

        // NOTE: The response buffer is NOT rendered during streaming (buffering mode).
        // The response is buffered invisibly and only shown when generation is complete.
        // This provides a Claude Code-like experience where the complete response
        // appears instantly instead of streaming character-by-character.
        //
        // The status line shows progress: "↑ Sending..." → "↓ Streaming..." with timer

        // NOTE: `state.last_rendered_rows` (used by selection extraction) is
        // refreshed inside the memo-miss branch above, not here — a memo hit
        // keeps the rows from the miss that built it (content is unchanged on a
        // hit), so they need not be re-collected every frame (F31).

        // Paint the active drag selection (reverse video over the selected
        // cells). Selection lines are content indices, matching `lines`.
        if let Some((a, b)) = state.selection
            && !lines.is_empty()
        {
            let (start, end) = if a <= b { (a, b) } else { (b, a) };
            let sel_style = Style::new().add_modifier(Modifier::REVERSED);
            let last_line = lines.len() - 1;
            for (line_idx, line) in lines
                .iter_mut()
                .enumerate()
                .take(end.0.min(last_line) + 1)
                .skip(start.0)
            {
                let c0 = if line_idx == start.0 { start.1 } else { 0 };
                let c1 = if line_idx == end.0 { end.1 } else { usize::MAX };
                if c1 > c0 {
                    highlight_line_cells(line, c0, c1, sel_style);
                }
            }
        }

        // NOTE: Wrapping is disabled because we handle it manually with hanging indents
        // Calculate content height and viewport for proper scroll clamping.
        // `lines.len()` is usize; convert to the u16 ratatui scroll type with a
        // saturating cast so a scrollback longer than u16::MAX rows clamps the
        // scroll position instead of wrapping it (F32).
        let content_height = lines.len();
        let viewport_height = area.height;

        let scroll_pos = state.get_scroll_position(clamp_to_u16(content_height), viewport_height);
        state.last_scroll_position = scroll_pos;

        let paragraph = Paragraph::new(lines)
            .block(Block::default())
            .scroll((scroll_pos, 0));

        paragraph.render(content_area, buf);
    }
}

fn render_context_checkpoint_event(
    msg: &ChatMessage,
    theme: &Theme,
    viewport_width: usize,
) -> Option<Vec<Line<'static>>> {
    if !matches!(msg.role, MessageRole::User) {
        return None;
    }

    let metadata = msg.metadata.as_ref();
    let trigger = metadata
        .and_then(|value| value.get("trigger"))
        .and_then(|value| value.as_str())
        .unwrap_or("manual");
    let before_tokens = metadata.and_then(|value| metadata_usize(value, "before_tokens"));
    let after_tokens = metadata.and_then(|value| metadata_usize(value, "after_tokens"));
    let archived_messages =
        metadata.and_then(|value| metadata_usize(value, "archived_message_count"));
    let preserved_messages =
        metadata.and_then(|value| metadata_usize(value, "preserved_message_count"));
    let duration_secs = metadata
        .and_then(|value| value.get("duration_secs"))
        .and_then(|value| value.as_f64());
    let review_status = metadata
        .and_then(|value| value.get("review_status"))
        .and_then(|value| value.as_str());
    let review_error = metadata
        .and_then(|value| value.get("review_error"))
        .and_then(|value| value.as_str());

    let action_color = theme.colors.info.to_color();
    let mut result = match (before_tokens, after_tokens) {
        (Some(before), Some(after)) => {
            format!(
                "{} -> {} tokens",
                format_compact_count(before),
                format_compact_count(after)
            )
        },
        _ => "Context compacted".to_string(),
    };

    if let Some(count) = archived_messages {
        result.push_str(&format!(
            ", archived {} {}",
            count,
            if count == 1 { "message" } else { "messages" }
        ));
    }
    if let Some(count) = preserved_messages {
        result.push_str(&format!(
            ", preserved {} {}",
            count,
            if count == 1 { "message" } else { "messages" }
        ));
    }
    if let Some(status) = review_status {
        match status {
            "reviewed" => result.push_str(", reviewed"),
            "draft_validated" => result.push_str(", validated draft"),
            _ => {},
        }
    }
    result = append_action_duration(result, duration_secs);

    let mut lines = vec![Line::from(vec![
        Span::styled("", Style::new().fg(action_color).bold()),
        Span::styled("Compact(", Style::new().fg(action_color).bold()),
        Span::styled(
            trigger.to_string(),
            Style::new().fg(theme.colors.text_secondary.to_color()),
        ),
        Span::styled(")", Style::new().fg(action_color).bold()),
    ])];
    lines.extend(wrap_styled_line(
        Line::from(vec![
            Span::styled("", Style::new().fg(action_color)),
            Span::styled(
                result,
                Style::new().fg(theme.colors.text_secondary.to_color()),
            ),
        ]),
        viewport_width,
        4,
    ));

    if let Some(error) = review_error.filter(|error| !error.trim().is_empty()) {
        lines.extend(wrap_styled_line(
            Line::from(vec![
                Span::styled("    ", Style::new().fg(action_color)),
                Span::styled(
                    format!("review: {}", compact_inline_error(error, 180)),
                    Style::new().fg(theme.colors.warning.to_color()),
                ),
            ]),
            viewport_width,
            4,
        ));
    }

    Some(lines)
}

fn metadata_usize(value: &serde_json::Value, key: &str) -> Option<usize> {
    value
        .get(key)?
        .as_u64()
        .and_then(|value| usize::try_from(value).ok())
}

fn compact_inline_error(text: &str, max_chars: usize) -> String {
    let text = text.trim();
    if text.chars().count() <= max_chars {
        return text.to_string();
    }
    let keep = max_chars.saturating_sub(3);
    let mut out: String = text.chars().take(keep).collect();
    out.push_str("...");
    out
}

/// Render actions in Claude Code style
/// Expand tab characters to spaces on 4-column tab stops.
///
/// Tabs paint as zero cells in the terminal buffer, so a line containing them
/// has a char count larger than its painted width. Any width math done by char
/// count (e.g. padding a diff line so its background bar spans the row) would
/// then come up short by one column per tab. Expanding here keeps indentation
/// visible and makes char count match painted width.
fn expand_tabs(s: &str) -> String {
    const TAB_WIDTH: usize = 4;
    if !s.contains('\t') {
        return s.to_string();
    }
    let mut out = String::with_capacity(s.len() + TAB_WIDTH);
    let mut col = 0usize;
    for ch in s.chars() {
        if ch == '\t' {
            let n = TAB_WIDTH - (col % TAB_WIDTH);
            for _ in 0..n {
                out.push(' ');
            }
            col += n;
        } else {
            out.push(ch);
            col += UnicodeWidthChar::width(ch).unwrap_or(0);
        }
    }
    out
}

fn render_actions(
    actions: &[ActionDisplay],
    lines: &mut Vec<Line>,
    theme: &Theme,
    viewport_width: usize,
    blink_on: bool,
) {
    for (action_idx, action) in actions.iter().enumerate() {
        if action_idx > 0 {
            lines.push(Line::from(""));
        }
        // An answered `ask_user_question` renders as its own block — the
        // user's answers ARE the outcome, so the transcript shows each
        // question → answer pair instead of the generic `name(target)`
        // header over a bare duration.
        if let Some(meta) = &action.metadata
            && let ToolMetadata::Questions {
                answers,
                remembered,
            } = &meta.detail
            && matches!(action.result, ActionResult::Success { .. })
        {
            render_question_answers(answers, *remembered, lines, theme, viewport_width);
            continue;
        }
        // An approved plan (`exit_plan_mode`) renders as its own block: the
        // plan body IS the outcome, shown as markdown under a header naming
        // the saved plan file.
        if let Some(meta) = &action.metadata
            && let ToolMetadata::Plan { path, body, .. } = &meta.detail
            && matches!(action.result, ActionResult::Success { .. })
        {
            render_plan_approved(path, body, lines, theme, viewport_width);
            continue;
        }
        let action_color = match action.action_type.as_str() {
            "Write" | "Update" => theme.colors.success.to_color(),
            "Delete" => theme.colors.warning.to_color(),
            _ => theme.colors.info.to_color(),
        };

        // Header: ● Type(target) — the target (a command, query, path…) wraps
        // instead of clipping at the viewport edge. Its own newlines are kept
        // as rows and overlong rows word-wrap with a hanging indent; a huge
        // target (e.g. a heredoc script) is capped so one Bash call can't
        // flood the transcript — the cap row ends in "…)" like a truncation.
        // An in-flight call's dot blinks (accent ↔ faded) as the live "this
        // one is still running" indicator; the rest of the header stays put.
        let dot_style = if matches!(action.result, ActionResult::Running) && !blink_on {
            Style::new()
                .fg(theme.colors.text_disabled.to_color())
                .bold()
        } else {
            Style::new().fg(action_color).bold()
        };
        push_action_header(
            lines,
            action,
            action_color,
            dot_style,
            theme,
            viewport_width,
        );

        match &action.result {
            // In flight: the header row (with its blinking dot) is the whole
            // display — the result elbow arrives with the outcome.
            ActionResult::Running => {},
            ActionResult::Success { .. } => {
                // Result summary from details enum
                let result_msg = match &action.details {
                    ActionDetails::FileContent { line_count, .. } => {
                        let base = format!(
                            "{} {} written",
                            line_count,
                            if *line_count == 1 { "line" } else { "lines" }
                        );
                        append_action_duration(base, action.duration_seconds)
                    },
                    ActionDetails::Diff { summary, .. } => summary.clone(),
                    ActionDetails::Preview { text, .. } => text.clone(),
                    // Success is already implied (an error renders differently),
                    // so a plain success needs no label — the header shows the
                    // action + target; the line just carries the timing.
                    ActionDetails::Simple => {
                        append_action_duration(String::new(), action.duration_seconds)
                    },
                };

                for (idx, line) in result_msg.lines().enumerate() {
                    let prefix = if idx == 0 { "" } else { "    " };
                    // Word-wrap the result row (4-space hanging indent) so a
                    // long summary is readable instead of clipped.
                    lines.extend(wrap_styled_line(
                        Line::from(vec![
                            Span::styled(prefix, Style::new().fg(action_color)),
                            Span::styled(
                                line.to_string(),
                                Style::new().fg(theme.colors.text_secondary.to_color()),
                            ),
                        ]),
                        viewport_width,
                        4,
                    ));
                }

                // Write: syntax-highlighted file preview
                if let ActionDetails::FileContent {
                    content,
                    line_count,
                } = &action.details
                {
                    let preview_lines: Vec<&str> = content.lines().take(10).collect();
                    if !preview_lines.is_empty() {
                        lines.push(Line::from(vec![Span::styled(
                            "    ",
                            Style::new().fg(action_color),
                        )]));

                        let preview_content = preview_lines.join("\n");
                        let mut parsed = parse_markdown(
                            &format!("```\n{}\n```", preview_content),
                            theme,
                            viewport_width.saturating_sub(4),
                        );
                        for parsed_line in parsed.iter_mut() {
                            let mut new_spans =
                                vec![Span::styled("    ", Style::new().fg(action_color))];
                            new_spans.append(&mut parsed_line.line.spans);
                            parsed_line.line.spans = new_spans;
                        }
                        // Hard-wrap (not word-wrap) so code indentation and
                        // alignment survive; overlong rows continue with a
                        // 6-space hanging indent instead of clipping.
                        lines.extend(
                            parsed
                                .into_iter()
                                .flat_map(|ml| wrap_preformatted(ml.line, viewport_width, 6)),
                        );

                        if *line_count > 10 {
                            lines.push(Line::from(vec![
                                Span::styled("    ", Style::new().fg(action_color)),
                                Span::styled(
                                    format!("... ({} more lines)", line_count - 10),
                                    Style::new()
                                        .fg(theme.colors.text_disabled.to_color())
                                        .italic(),
                                ),
                            ]));
                        }
                    }
                }

                // Edit: color-coded diff
                if let ActionDetails::Diff { diff, .. } = &action.details {
                    let diff_lines: Vec<&str> = diff.lines().collect();
                    let display_lines: Vec<&str> = diff_lines.iter().take(80).copied().collect();

                    if !display_lines.is_empty() {
                        let removed_bg = theme.colors.diff_removed_bg.to_color();
                        let added_bg = theme.colors.diff_added_bg.to_color();

                        for diff_line in &display_lines {
                            // Expand tabs first: the TUI paints a tab as zero
                            // cells, so a tab-bearing line's char count exceeds
                            // its painted width and the char-count pad below
                            // would leave the background bar short — a ragged
                            // "staircase" down the right edge. Expanding also
                            // makes tab indentation actually visible.
                            let diff_line = expand_tabs(diff_line);
                            // Delegate the producer-format awareness to
                            // `parse_diff_line`, which lives next to the
                            // marker constants and stays in lockstep with
                            // any future format change.
                            match parse_diff_line(&diff_line) {
                                DiffLineKind::Removed => {
                                    push_wrapped_diff_rows(
                                        lines,
                                        format!("    {}", diff_line),
                                        Style::new()
                                            .fg(theme.colors.error.to_color())
                                            .bg(removed_bg),
                                        viewport_width,
                                    );
                                },
                                DiffLineKind::Added => {
                                    push_wrapped_diff_rows(
                                        lines,
                                        format!("    {}", diff_line),
                                        Style::new()
                                            .fg(theme.colors.success.to_color())
                                            .bg(added_bg),
                                        viewport_width,
                                    );
                                },
                                DiffLineKind::Context => {
                                    // Hard-wrap like the colored rows so an
                                    // overlong context line isn't clipped.
                                    lines.extend(wrap_preformatted(
                                        Line::from(vec![
                                            Span::styled("    ", Style::new().fg(action_color)),
                                            Span::styled(
                                                diff_line,
                                                Style::new()
                                                    .fg(theme.colors.text_secondary.to_color()),
                                            ),
                                        ]),
                                        viewport_width,
                                        6,
                                    ));
                                },
                            }
                        }

                        let remaining = diff_lines.len().saturating_sub(display_lines.len());
                        if remaining > 0 {
                            lines.push(Line::from(vec![
                                Span::styled("    ", Style::new().fg(action_color)),
                                Span::styled(
                                    format!("... ({} more lines)", remaining),
                                    Style::new()
                                        .fg(theme.colors.text_disabled.to_color())
                                        .italic(),
                                ),
                            ]));
                        }
                    }
                }
            },
            ActionResult::Error { error } => {
                let error =
                    append_action_duration(format!("Error: {}", error), action.duration_seconds);
                // Word-wrap so the full error body (an HTTP error JSON can run
                // hundreds of cells) is readable instead of clipped at the
                // viewport edge. Multi-line errors keep their own rows.
                for (idx, err_line) in error.lines().enumerate() {
                    let prefix = if idx == 0 { "" } else { "    " };
                    lines.extend(wrap_styled_line(
                        Line::from(vec![
                            Span::styled(prefix, Style::new().fg(theme.colors.error.to_color())),
                            Span::styled(
                                err_line.to_string(),
                                Style::new().fg(theme.colors.error.to_color()),
                            ),
                        ]),
                        viewport_width,
                        4,
                    ));
                }
            },
        }
    }
}

/// Record of an approved plan (`exit_plan_mode`): a header bullet naming the
/// plan file, then the plan body rendered as markdown under the elbow gutter
/// — the transcript keeps the exact text the user approved.
fn render_plan_approved(
    path: &str,
    body: &str,
    lines: &mut Vec<Line>,
    theme: &Theme,
    viewport_width: usize,
) {
    lines.push(Line::from(Span::styled(
        format!("● User approved the plan — {path}"),
        Style::new().fg(theme.colors.success.to_color()),
    )));
    let gutter_style = Style::new().fg(theme.colors.text_secondary.to_color());
    // The 4-cell gutter comes off the markdown wrap budget, matching the
    // question→answer block above.
    let parsed = parse_markdown(body, theme, viewport_width.saturating_sub(4));
    let mut first_row = true;
    for mut parsed_line in parsed {
        let gutter = if first_row { "" } else { "    " };
        first_row = false;
        let mut spans = vec![Span::styled(gutter, gutter_style)];
        spans.append(&mut parsed_line.line.spans);
        lines.push(Line::from(spans));
    }
}

/// Claude-Code-style record of an answered `ask_user_question` call: a plain
/// header bullet plus one `· question → answer` line per question, so the
/// transcript preserves what the user chose (not just how long it took).
fn render_question_answers(
    answers: &[QuestionAnswer],
    remembered: bool,
    lines: &mut Vec<Line>,
    theme: &Theme,
    viewport_width: usize,
) {
    let header = if remembered {
        "User answered the model's questions (remembered):"
    } else {
        "User answered the model's questions:"
    };
    lines.push(Line::from(Span::styled(
        format!("{header}"),
        Style::new().fg(theme.colors.text_primary.to_color()),
    )));

    let gutter_style = Style::new().fg(theme.colors.text_secondary.to_color());
    let text_style = Style::new().fg(theme.colors.text_secondary.to_color());
    let note_style = Style::new()
        .fg(theme.colors.text_disabled.to_color())
        .italic();
    // The 4-cell gutter ("  ⎿ " on the first row, "    " after) comes off the
    // wrap budget; continuations hang 2 cells so wrapped text aligns under
    // the question, not the `·`.
    let wrap_width = viewport_width.saturating_sub(4);
    let mut first_row = true;
    for answer in answers {
        let value = if answer.selected.is_empty() {
            "(no selection)".to_string()
        } else {
            answer.selected.join(", ")
        };
        let entry = format!("· {}{}", answer.question, value);
        let mut rows: Vec<(String, Style)> = wrap_text_with_indent(&entry, wrap_width, 0, 2)
            .into_iter()
            .map(|row| (row, text_style))
            .collect();
        if let Some(note) = &answer.note {
            rows.extend(
                wrap_text_with_indent(&format!("(note: {note})"), wrap_width, 2, 4)
                    .into_iter()
                    .map(|row| (row, note_style)),
            );
        }
        for (row, style) in rows {
            let gutter = if first_row { "" } else { "    " };
            first_row = false;
            lines.push(Line::from(vec![
                Span::styled(gutter, gutter_style),
                Span::styled(row, style),
            ]));
        }
    }
}

/// Cap on wrapped action-header rows: a long target (a Bash heredoc, a huge
/// query) wraps for readability, but past this many rows it truncates with
/// "…)" so a single tool call can't flood the transcript.
const MAX_ACTION_HEADER_ROWS: usize = 4;

/// Push the "● Type(target)" action header, wrapping the target across rows
/// instead of letting an over-wide one clip at the viewport edge.
///
/// The target's own newlines are preserved as row breaks; overlong rows
/// word-wrap with a 4-space hanging indent (an unbroken token hard-breaks).
/// Two cells are reserved so the closing ")" — and the "…" a capped header
/// gains — never overflow the last row.
fn push_action_header(
    lines: &mut Vec<Line>,
    action: &ActionDisplay,
    action_color: Color,
    dot_style: Style,
    theme: &Theme,
    viewport_width: usize,
) {
    let bold = Style::new().fg(action_color).bold();
    let secondary = Style::new().fg(theme.colors.text_secondary.to_color());
    if action.target.is_empty() {
        lines.push(Line::from(vec![
            Span::styled("", dot_style),
            Span::styled(format!("{}()", action.action_type), bold),
        ]));
        return;
    }

    let open = format!("{}(", action.action_type);
    // The first row's indent stands in for the 2-cell "● " plus the opening
    // "Type(" so wrapping accounts for them; it is stripped and replaced with
    // the real styled spans below.
    let first_indent = 2 + open.width();
    let wrap_width = viewport_width.saturating_sub(2).max(first_indent + 1);
    let mut rows = wrap_text_with_indent(&action.target, wrap_width, first_indent, 4);
    let truncated = rows.len() > MAX_ACTION_HEADER_ROWS;
    rows.truncate(MAX_ACTION_HEADER_ROWS);

    let last = rows.len().saturating_sub(1);
    for (i, row) in rows.into_iter().enumerate() {
        let mut spans = if i == 0 {
            vec![
                Span::styled("", dot_style),
                Span::styled(open.clone(), bold),
                Span::styled(row.trim_start().to_string(), secondary),
            ]
        } else {
            vec![Span::styled(row, secondary)]
        };
        if i == last {
            if truncated {
                spans.push(Span::styled(
                    "",
                    Style::new().fg(theme.colors.text_disabled.to_color()),
                ));
            }
            spans.push(Span::styled(")", bold));
        }
        lines.push(Line::from(spans));
    }
}

/// Push one colored diff row, hard-wrapped at the viewport width and padded so
/// every produced row carries the full-width background bar (no unfilled
/// column on a diff row — the "staircase" invariant).
fn push_wrapped_diff_rows(lines: &mut Vec<Line>, text: String, style: Style, width: usize) {
    for row in wrap_preformatted(Line::from(Span::raw(text)), width, 6) {
        let padded = pad_to_cells(&line_plain_text(&row), width);
        lines.push(Line::from(Span::styled(padded, style)));
    }
}

fn append_action_duration(mut text: String, duration_seconds: Option<f64>) -> String {
    if let Some(seconds) = duration_seconds {
        // An empty base (a plain success with no detail) becomes just
        // "took Xms" — no leading comma.
        if !text.is_empty() {
            text.push_str(", ");
        }
        text.push_str("took ");
        text.push_str(&format_action_duration(seconds));
    }
    text
}

fn format_action_duration(seconds: f64) -> String {
    if seconds < 1.0 {
        format!("{}ms", (seconds * 1000.0).round().max(1.0) as u64)
    } else if seconds < 10.0 {
        format!("{:.1}s", seconds)
    } else {
        format!("{}s", seconds.round() as u64)
    }
}

/// Hard-break a single over-long token into the plain-text line accumulator,
/// splitting at char boundaries (UTF-8-safe, display-cell aware) so a giant
/// unbroken token (e.g. a 5000-char URL) wraps across lines instead of
/// overflowing the viewport and being clipped (F33).
///
/// Mirrors the accumulation `wrap_text_with_indent` does for normal words:
/// `current_line`/`current_length` carry the in-progress line (its indent
/// already pushed into `current_line`, not counted in `current_length`),
/// finished lines are pushed to `out`, and each new line gets a
/// `continuation_indent`-space hanging indent. `initial_budget` is the content
/// width available on the line the token starts on (the caller's per-line
/// `available_width`); subsequent lines use `width - continuation_indent`.
fn hard_break_plain_token(
    token: &str,
    out: &mut Vec<String>,
    current_line: &mut String,
    current_length: &mut usize,
    width: usize,
    continuation_indent: usize,
    initial_budget: usize,
) {
    let cont_budget = width.saturating_sub(continuation_indent).max(1);
    let mut line_budget = initial_budget.max(1);

    // If the current line already holds content, flush it so the token starts
    // fresh on a continuation line; otherwise break onto the current (indent-
    // only) line directly.
    if *current_length > 0 {
        out.push(std::mem::take(current_line));
        current_line.push_str(&" ".repeat(continuation_indent));
        *current_length = 0;
        line_budget = cont_budget;
    }

    for ch in token.chars() {
        let cw = ch.width().unwrap_or(0);
        // Break before this char if it would overflow and the line already
        // holds at least one glyph (so a single too-wide glyph never loops).
        if *current_length + cw > line_budget && *current_length > 0 {
            out.push(std::mem::take(current_line));
            current_line.push_str(&" ".repeat(continuation_indent));
            *current_length = 0;
            line_budget = cont_budget;
        }
        current_line.push(ch);
        *current_length += cw;
    }
}

/// Wrap text with hanging indent support.
///
/// `width`, `first_line_indent`, and `continuation_indent` are all measured
/// in **display cells**, not bytes. Word lengths are also measured in cells
/// via `UnicodeWidthStr::width` so CJK / emoji wrap at the visual edge —
/// previously a CJK paragraph would wrap after ~1/3 of the line because
/// `word.len()` (bytes) is roughly 3× `word.width()` (cells) for 3-byte
/// codepoints.
fn wrap_text_with_indent(
    text: &str,
    width: usize,
    first_line_indent: usize,
    continuation_indent: usize,
) -> Vec<String> {
    let mut wrapped_lines = Vec::new();

    for (line_idx, line) in text.lines().enumerate() {
        if line.is_empty() {
            wrapped_lines.push(String::new());
            continue;
        }

        let current_indent = if line_idx == 0 {
            first_line_indent
        } else {
            continuation_indent
        };
        let available_width = width.saturating_sub(current_indent);

        if available_width == 0 {
            wrapped_lines.push(" ".repeat(current_indent));
            continue;
        }

        let words: Vec<&str> = line.split_whitespace().collect();
        if words.is_empty() {
            wrapped_lines.push(" ".repeat(current_indent));
            continue;
        }

        let mut current_line = String::with_capacity(width);
        current_line.push_str(&" ".repeat(current_indent));
        // Display-cell widths: indent is ASCII spaces (1 cell each), so
        // start fresh and let words contribute their own cell widths.
        let mut current_length = 0;

        for (word_idx, word) in words.iter().enumerate() {
            let word_width = word.width();

            if word_idx == 0 {
                if word_width <= available_width {
                    // First word fits on the line
                    current_line.push_str(word);
                    current_length = word_width;
                } else {
                    // A single token wider than the whole line (e.g. a long
                    // URL): hard-break it at width boundaries so it wraps
                    // instead of overflowing the viewport and being clipped
                    // (F33).
                    hard_break_plain_token(
                        word,
                        &mut wrapped_lines,
                        &mut current_line,
                        &mut current_length,
                        width,
                        continuation_indent,
                        available_width,
                    );
                }
            } else if current_length + 1 + word_width <= available_width {
                // Word fits on current line (the +1 accounts for the
                // separator space, which is 1 cell)
                current_line.push(' ');
                current_line.push_str(word);
                current_length += 1 + word_width;
            } else if word_width <= available_width {
                // Word doesn't fit, start a new line
                wrapped_lines.push(current_line);
                current_line = String::with_capacity(width);
                current_line.push_str(&" ".repeat(continuation_indent));
                current_line.push_str(word);
                current_length = word_width;
            } else {
                // Over-long token mid-paragraph: flush the current line, then
                // hard-break the token across continuation lines (F33).
                hard_break_plain_token(
                    word,
                    &mut wrapped_lines,
                    &mut current_line,
                    &mut current_length,
                    width,
                    continuation_indent,
                    available_width,
                );
            }
        }

        // Add the last line
        if !current_line.trim().is_empty() {
            wrapped_lines.push(current_line);
        }
    }

    wrapped_lines
}

/// Hard-break a single over-long word into the styled line accumulator,
/// splitting at char boundaries (UTF-8-safe, display-cell aware) and keeping
/// each fragment's own style on every produced piece, so a giant unbroken
/// token (e.g. a long URL) wraps across rows instead of overflowing the
/// viewport and being clipped (F33). The styled counterpart of
/// `hard_break_plain_token`. The word arrives as styled fragments (see the
/// flattening pass in `wrap_styled_line`) because a token can change style
/// mid-word (`**bold**suffix`); the break must not flatten that to one style.
///
/// `current_line_spans`/`current_line_width` carry the in-progress row;
/// finished rows are pushed to `result_lines`; each new row opens with a
/// `continuation_indent`-space span. `line_capacity` is the width budget for
/// the row the token starts on (the first row counts its leading indent in
/// `current_line_width`, so its budget is the full `width`); wrapped rows use
/// `continuation_capacity` (the caller's `available_width`, with the indent in
/// a separate span and not counted).
#[allow(clippy::too_many_arguments)]
fn hard_break_styled_word(
    fragments: &[(String, Style)],
    result_lines: &mut Vec<Line<'static>>,
    current_line_spans: &mut Vec<Span<'static>>,
    current_line_width: &mut usize,
    continuation_indent: usize,
    continuation_capacity: usize,
    mut line_capacity: usize,
) {
    for (text, style) in fragments {
        let mut buf = String::new();
        for ch in text.chars() {
            let cw = ch.width().unwrap_or(0);
            // Break before this char if it would overflow and the row already
            // holds at least one glyph (so a single too-wide glyph never loops).
            if *current_line_width + cw > line_capacity && *current_line_width > 0 {
                if !buf.is_empty() {
                    current_line_spans.push(Span::styled(std::mem::take(&mut buf), *style));
                }
                result_lines.push(Line::from(std::mem::take(current_line_spans)));
                current_line_spans.push(Span::raw(" ".repeat(continuation_indent)));
                *current_line_width = 0;
                line_capacity = continuation_capacity.max(1);
            }
            buf.push(ch);
            *current_line_width += cw;
        }
        if !buf.is_empty() {
            current_line_spans.push(Span::styled(buf, *style));
        }
    }
}

/// Wrap a styled Line with hanging indent, preserving all span styles.
/// Returns multiple Line objects with proper indentation.
///
/// Wrapping runs over a word stream flattened ACROSS spans: a word is a run of
/// styled fragments, and a word boundary exists only where the source text has
/// whitespace. A span ending mid-word glues onto the next span's text, so
/// `**bold**suffix` stays one token and a `.` right after a link's dimmed URL
/// stays attached (no phantom space at a style boundary). Separator spaces
/// between words are re-emitted UNSTYLED so a link's underline or inline
/// code's background never paints the gap before it.
fn wrap_styled_line(
    line: Line<'static>,
    width: usize,
    continuation_indent: usize,
) -> Vec<Line<'static>> {
    // Widths are counted in display cells (via `UnicodeWidthStr`), not
    // bytes. This makes CJK double-width chars and emoji wrap at the
    // correct visual column, and avoids over-wrapping multi-byte ASCII-
    // looking glyphs.
    let total_width: usize = line.spans.iter().map(|s| s.content.width()).sum();

    // If the line fits within width, return as-is
    if total_width <= width {
        return vec![line];
    }

    // Line needs wrapping - extract all text and styles
    let mut result_lines = Vec::new();
    let mut current_line_spans: Vec<Span<'static>> = Vec::new();
    let mut current_line_width = 0usize;
    let available_width = width.saturating_sub(continuation_indent);

    // Preserve the line's existing left margin (the "  " continuation gutter the
    // caller prepends to every non-first message line) on the *first* wrapped
    // segment. The whitespace split below drops leading spaces and the "first
    // word, no indent" rule would then flush the segment to column 0 — that's the
    // recurring bug where a wrapped paragraph escapes the message gutter while its
    // own continuation lines (which get `continuation_indent`) stay aligned. A
    // non-whitespace prefix like "● " is unaffected (it survives the split).
    let leading_indent: usize = {
        let mut n = 0;
        for span in &line.spans {
            let spaces = span.content.len() - span.content.trim_start_matches(' ').len();
            n += spaces;
            if spaces < span.content.len() {
                break; // this span has non-space content, so leading run ends here
            }
        }
        n
    };

    // Flatten the spans into words: each word is a run of styled fragments.
    // Whitespace anywhere closes the current word (runs collapse to a single
    // boundary); a span ending mid-word leaves the word open so the next
    // span's text glues on — a style change is NOT a word boundary.
    let mut words: Vec<Vec<(String, Style)>> = Vec::new();
    let mut current_word: Vec<(String, Style)> = Vec::new();
    for span in &line.spans {
        let mut frag = String::new();
        for ch in span.content.chars() {
            if ch.is_whitespace() {
                if !frag.is_empty() {
                    current_word.push((std::mem::take(&mut frag), span.style));
                }
                if !current_word.is_empty() {
                    words.push(std::mem::take(&mut current_word));
                }
            } else {
                frag.push(ch);
            }
        }
        if !frag.is_empty() {
            current_word.push((frag, span.style));
        }
    }
    if !current_word.is_empty() {
        words.push(current_word);
    }

    fn emit_word(spans: &mut Vec<Span<'static>>, word: Vec<(String, Style)>) {
        for (text, style) in word {
            spans.push(Span::styled(text, style));
        }
    }

    for word in words {
        let word_width: usize = word.iter().map(|(text, _)| text.width()).sum();

        if current_line_width == 0 && result_lines.is_empty() {
            // First word of the first line: re-apply the original left margin
            // (dropped by the whitespace split) so the segment keeps the gutter
            // instead of flushing to column 0.
            if leading_indent > 0 {
                current_line_spans.push(Span::raw(" ".repeat(leading_indent)));
                current_line_width += leading_indent;
            }
            if word_width <= available_width {
                current_line_width += word_width;
                emit_word(&mut current_line_spans, word);
            } else {
                // A single token wider than the line (e.g. a long URL):
                // hard-break it at width boundaries so it wraps instead of
                // being clipped by the viewport (F33). The first row may use
                // the full `width` (its indent is already counted above);
                // continuation rows fall back to `available_width`.
                hard_break_styled_word(
                    &word,
                    &mut result_lines,
                    &mut current_line_spans,
                    &mut current_line_width,
                    continuation_indent,
                    available_width,
                    width,
                );
            }
            continue;
        }

        // Separator space before this word — only when the row already holds
        // content, and always UNSTYLED: the space between words belongs to
        // neither word's style (an underlined link must not underline the gap
        // in front of it).
        let sep = usize::from(current_line_width > 0);
        if current_line_width + sep + word_width <= available_width {
            // Word fits on current line
            if sep == 1 {
                current_line_spans.push(Span::raw(" "));
            }
            current_line_width += sep + word_width;
            emit_word(&mut current_line_spans, word);
        } else if word_width <= available_width {
            // Word doesn't fit - finish current line and start new one
            result_lines.push(Line::from(std::mem::take(&mut current_line_spans)));
            current_line_spans.push(Span::raw(" ".repeat(continuation_indent)));
            current_line_width = word_width;
            emit_word(&mut current_line_spans, word);
        } else {
            // Over-long token mid-line: finish the current line, then
            // hard-break the token across continuation rows (F33), keeping
            // each fragment's style on every produced piece.
            result_lines.push(Line::from(std::mem::take(&mut current_line_spans)));
            current_line_spans.push(Span::raw(" ".repeat(continuation_indent)));
            current_line_width = 0;
            hard_break_styled_word(
                &word,
                &mut result_lines,
                &mut current_line_spans,
                &mut current_line_width,
                continuation_indent,
                available_width,
                available_width,
            );
        }
    }

    // Add the last line if it has content
    if !current_line_spans.is_empty() {
        result_lines.push(Line::from(current_line_spans));
    }

    if result_lines.is_empty() {
        vec![line]
    } else {
        result_lines
    }
}

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

    #[test]
    fn question_answers_render_as_question_arrow_answer_block() {
        use crate::domain::{QuestionAnswer, ToolMetadata, ToolRunMetadata};

        let theme = Theme::dark();
        let answers = vec![
            QuestionAnswer {
                header: "Snack".to_string(),
                question: "Which snack fuels your next coding session?".to_string(),
                selected: vec!["Coffee (Recommended)".to_string()],
                note: None,
            },
            QuestionAnswer {
                header: "Powers".to_string(),
                question: "Which superpowers would you take?".to_string(),
                selected: vec![
                    "Read any codebase instantly".to_string(),
                    "Bugs reproduce on demand".to_string(),
                ],
                note: Some("only on weekdays".to_string()),
            },
        ];
        let action = ActionDisplay {
            action_type: "ask_user_question".to_string(),
            target: String::new(),
            result: ActionResult::Success {
                output: String::new(),
                images: None,
            },
            details: ActionDetails::Simple,
            duration_seconds: Some(93.0),
            metadata: Some(ToolRunMetadata {
                detail: ToolMetadata::Questions {
                    answers,
                    remembered: false,
                },
                ..Default::default()
            }),
        };

        let mut lines: Vec<Line> = Vec::new();
        render_actions(&[action], &mut lines, &theme, 120, true);
        let rows: Vec<String> = lines.iter().map(line_plain_text).collect();
        let all = rows.join("\n");

        assert_eq!(rows[0], "● User answered the model's questions:");
        assert!(
            rows[1].starts_with("  ⎿ · Which snack fuels your next coding session? → Coffee"),
            "got {:?}",
            rows[1]
        );
        assert!(
            all.contains(
                "· Which superpowers would you take? → Read any codebase instantly, \
                 Bugs reproduce on demand"
            ),
            "got {all}"
        );
        assert!(all.contains("(note: only on weekdays)"), "got {all}");
        // The generic `name()` header and duration line are replaced entirely.
        assert!(!all.contains("ask_user_question("), "got {all}");
        assert!(!all.contains("took"), "got {all}");
    }

    #[test]
    fn diff_background_fills_full_width_with_tabs() {
        // Regression: tab characters paint as zero cells, so char-count padding
        // left the red/green diff bar short by one column per tab — a ragged
        // "staircase" down the right edge. After expand_tabs, every column of a
        // diff row must carry the background.
        use crate::render::diff::{DIFF_ADDED_MARKER, DIFF_REMOVED_MARKER};
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let theme = Theme::dark();
        let added_bg = theme.colors.diff_added_bg.to_color();
        let removed_bg = theme.colors.diff_removed_bg.to_color();
        // Lines at increasing tab depth — the exact shape that staircased.
        let diff = format!(
            "  62{m}\tconst out = [];\n  63{p}\t\tlet fixed = false;\n  64{p}\t\t\tdeeplyNested();",
            m = DIFF_REMOVED_MARKER,
            p = DIFF_ADDED_MARKER
        );
        let action = ActionDisplay {
            action_type: "Update".to_string(),
            target: "engine.ts".to_string(),
            result: ActionResult::Success {
                output: String::new(),
                images: None,
            },
            details: ActionDetails::Diff {
                summary: "ok".to_string(),
                diff,
            },
            duration_seconds: Some(0.3),
            metadata: None,
        };

        let width: u16 = 60;
        let mut lines: Vec<Line> = Vec::new();
        render_actions(&[action], &mut lines, &theme, width as usize, true);
        let h = lines.len() as u16;
        let backend = TestBackend::new(width, h);
        let mut term = Terminal::new(backend).unwrap();
        term.draw(|f| {
            Paragraph::new(lines).render(Rect::new(0, 0, width, h), f.buffer_mut());
        })
        .unwrap();
        let buf = term.backend().buffer();

        for y in 0..h {
            let is_diff_row = (0..width).any(|x| {
                let bg = buf[(x, y)].bg;
                bg == added_bg || bg == removed_bg
            });
            if !is_diff_row {
                continue;
            }
            for x in 0..width {
                let bg = buf[(x, y)].bg;
                assert!(
                    bg == added_bg || bg == removed_bg,
                    "diff background must fill the whole row, but column {x} of row {y} is unfilled (staircase)"
                );
            }
        }
    }

    /// Every rendered action row must fit the viewport width — overlong
    /// headers, results, and errors wrap instead of clipping at the edge.
    fn assert_rows_fit(lines: &[Line], width: usize) {
        for (i, line) in lines.iter().enumerate() {
            let w: usize = line.spans.iter().map(|s| s.content.width()).sum();
            assert!(
                w <= width,
                "row {i} is {w} cells wide, exceeding the {width}-cell viewport: {:?}",
                line_plain_text(line)
            );
        }
    }

    #[test]
    fn action_header_and_error_wrap_instead_of_clipping() {
        // Regression: a long Bash command in the header and a long HTTP error
        // body in the result were painted as single over-wide rows and clipped
        // at the viewport edge instead of wrapping.
        let theme = Theme::dark();
        let action = ActionDisplay {
            action_type: "Error".to_string(),
            target: "Backend error".to_string(),
            result: ActionResult::Error {
                error: r#"HTTP error 404: {"error":{"code":"model_not_found","message":"The requested model was not found.","param":null,"type":"invalid_request_error"}}"#.to_string(),
            },
            details: ActionDetails::Simple,
            duration_seconds: None,
            metadata: None,
        };

        let width = 60usize;
        let mut lines: Vec<Line> = Vec::new();
        render_actions(&[action], &mut lines, &theme, width, true);

        assert_rows_fit(&lines, width);
        let rendered = lines
            .iter()
            .map(line_plain_text)
            .collect::<Vec<_>>()
            .join("\n");
        // The full error body must survive the wrap (word boundaries may move,
        // so check the tail token that clipping used to cut off).
        assert!(rendered.contains("invalid_request_error"));
        assert!(
            lines.len() > 2,
            "a 140-cell error at width 60 must span multiple rows"
        );
    }

    #[test]
    fn action_header_wraps_long_command_and_keeps_closing_paren() {
        let theme = Theme::dark();
        let action = ActionDisplay {
            action_type: "Bash".to_string(),
            target: "python3 -c 'print(1)' && echo a-very-long-command-line \
                     that keeps going well past the sixty cell viewport edge"
                .to_string(),
            result: ActionResult::Success {
                output: String::new(),
                images: None,
            },
            details: ActionDetails::Simple,
            duration_seconds: Some(0.1),
            metadata: None,
        };

        let width = 60usize;
        let mut lines: Vec<Line> = Vec::new();
        render_actions(&[action], &mut lines, &theme, width, true);

        assert_rows_fit(&lines, width);
        let rows: Vec<String> = lines.iter().map(line_plain_text).collect();
        assert!(rows[0].starts_with("● Bash("));
        assert!(
            rows.len() >= 2,
            "the long command must wrap the header across rows"
        );
        let last_target_row = rows
            .iter()
            .rfind(|r| r.trim_end().ends_with(')'))
            .expect("wrapped header must still close its paren");
        assert!(last_target_row.trim_end().ends_with(')'));
    }

    #[test]
    fn action_header_caps_rows_and_marks_truncation() {
        // A heredoc-sized target must not flood the transcript: the header
        // caps at MAX_ACTION_HEADER_ROWS and the last row signals "…)".
        let theme = Theme::dark();
        let action = ActionDisplay {
            action_type: "Bash".to_string(),
            target: "word ".repeat(400),
            result: ActionResult::Success {
                output: String::new(),
                images: None,
            },
            details: ActionDetails::Simple,
            duration_seconds: None,
            metadata: None,
        };

        let width = 60usize;
        let mut lines: Vec<Line> = Vec::new();
        render_actions(&[action], &mut lines, &theme, width, true);

        assert_rows_fit(&lines, width);
        let header_rows: Vec<String> = lines
            .iter()
            .map(line_plain_text)
            .take_while(|r| !r.trim_start().starts_with(''))
            .collect();
        assert_eq!(
            header_rows.len(),
            MAX_ACTION_HEADER_ROWS,
            "header must cap at MAX_ACTION_HEADER_ROWS rows"
        );
        assert!(
            header_rows.last().unwrap().trim_end().ends_with("…)"),
            "capped header must end with …) — got {:?}",
            header_rows.last().unwrap()
        );
    }

    #[test]
    fn action_header_preserves_multiline_command_rows() {
        // A multi-line command (heredoc-style) keeps its own line breaks in
        // the header instead of the old behavior where ratatui dropped the
        // newlines and glued fragments together ("'PY'from PIL import…").
        let theme = Theme::dark();
        let action = ActionDisplay {
            action_type: "Bash".to_string(),
            target: "python3 - << 'PY'\nfrom PIL import Image\nPY".to_string(),
            result: ActionResult::Success {
                output: String::new(),
                images: None,
            },
            details: ActionDetails::Simple,
            duration_seconds: None,
            metadata: None,
        };

        let mut lines: Vec<Line> = Vec::new();
        render_actions(&[action], &mut lines, &theme, 80, true);

        let rows: Vec<String> = lines.iter().map(line_plain_text).collect();
        assert!(rows[0].contains("python3 - << 'PY'"));
        assert!(rows[1].contains("from PIL import Image"));
        assert!(!rows[0].contains("'PY'from"), "newline must not be dropped");
    }

    #[test]
    fn action_result_summary_wraps_instead_of_clipping() {
        let theme = Theme::dark();
        let action = ActionDisplay {
            action_type: "Tasks".to_string(),
            target: "update 3 steps".to_string(),
            result: ActionResult::Success {
                output: String::new(),
                images: None,
            },
            details: ActionDetails::Preview {
                text: "Tasks 5/6 · User chose SKIP for domain/phone/address - \
                       placeholders kept intentionally until real data available. \
                       Task 2 and 6 deferred., to revisit later"
                    .to_string(),
                line_count: None,
            },
            duration_seconds: None,
            metadata: None,
        };

        let width = 60usize;
        let mut lines: Vec<Line> = Vec::new();
        render_actions(&[action], &mut lines, &theme, width, true);

        assert_rows_fit(&lines, width);
        let rendered = lines
            .iter()
            .map(line_plain_text)
            .collect::<Vec<_>>()
            .join("\n");
        assert!(
            rendered.contains("revisit later"),
            "the summary's tail must survive the wrap instead of being clipped"
        );
    }

    #[test]
    fn wrapped_line_cache_hit_matches_cache_miss() {
        // #134: caching the WRAPPED assistant lines must be byte-for-byte
        // identical to wrapping fresh. Render the same messages through a shared
        // cache — first call misses (populates), second hits — and assert the
        // two frame buffers are equal; then prove a cold cache renders the same
        // frame as the warm one. Assistant-only messages keep the frame free of
        // the time-relative user timestamp, so nothing here is clock-dependent.
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let theme = Theme::dark();
        let messages = vec![
            ChatMessage::assistant(
                "# Heading\n\nSome **bold** prose long enough that it has to wrap \
                 across this narrow viewport more than once.\n\n\
                 - a list item that also keeps going past the edge so it wraps too\n\
                 - second item\n\n```rust\nfn a_very_long_preformatted_code_line_that_overflows() {}\n```",
            ),
            ChatMessage::assistant("Short follow-up paragraph."),
        ];

        let (width, height): (u16, u16) = (40, 40);
        let render_once = |cache: &mut FxHashMap<u64, Vec<Line<'static>>>| {
            let mut term = Terminal::new(TestBackend::new(width, height)).unwrap();
            let mut state = ChatState::new();
            term.draw(|f| {
                let widget = ChatWidget {
                    messages: &messages,
                    theme: &theme,
                    wrapped_line_cache: cache,
                    show_reasoning: true,
                    blink_on: true,
                };
                f.render_stateful_widget(widget, Rect::new(0, 0, width, height), &mut state);
            })
            .unwrap();
            term.backend().buffer().clone()
        };

        let mut shared = FxHashMap::default();
        let miss = render_once(&mut shared);
        assert!(!shared.is_empty(), "first render must populate the cache");
        let hit = render_once(&mut shared);
        assert_eq!(miss, hit, "cache hit must render identically to cache miss");

        let mut cold_cache = FxHashMap::default();
        let cold = render_once(&mut cold_cache);
        assert_eq!(hit, cold, "warm-cache frame must equal a cold-cache frame");
    }

    #[test]
    fn system_notice_renders_as_dim_meta_text_without_bullet_or_timestamp() {
        // System notices are transcript furniture, not conversation: they must
        // render as indented muted-gray text — no role bullet, no right-aligned
        // timestamp (both belonged to the old user-layout share).
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let theme = Theme::dark();
        let messages = vec![ChatMessage::system(
            "Heads up: this model reports no vision capability",
        )];
        let (width, height): (u16, u16) = (60, 10);
        let mut term = Terminal::new(TestBackend::new(width, height)).unwrap();
        let mut state = ChatState::new();
        let mut cache = FxHashMap::default();
        term.draw(|f| {
            let widget = ChatWidget {
                messages: &messages,
                theme: &theme,
                wrapped_line_cache: &mut cache,
                show_reasoning: true,
                blink_on: true,
            };
            f.render_stateful_widget(widget, Rect::new(0, 0, width, height), &mut state);
        })
        .unwrap();
        let buf = term.backend().buffer();
        let rows: Vec<String> = (0..height)
            .map(|y| {
                (0..width)
                    .map(|x| buf[(x, y)].symbol().to_string())
                    .collect::<String>()
            })
            .collect();
        let all = rows.join("\n");
        assert!(
            !all.contains(''),
            "no role bullet on system notices: {all}"
        );
        assert!(
            !all.contains("Today at"),
            "no timestamp on system notices: {all}"
        );
        let row = rows
            .iter()
            .position(|r| r.contains("Heads up"))
            .expect("notice rendered");
        assert!(
            rows[row].starts_with("  Heads up"),
            "2-space indent, nothing in the gutter: {:?}",
            rows[row]
        );
        let col = rows[row].find("Heads up").unwrap(); // ASCII row: byte == cell
        assert_eq!(
            buf[(col as u16, row as u16)].fg,
            theme.colors.text_meta.to_color(),
            "notice text uses the muted meta gray"
        );
    }

    #[test]
    fn byte_at_cell_clamps_and_respects_cjk() {
        assert_eq!(byte_at_cell("hello", 0), 0);
        assert_eq!(byte_at_cell("hello", 3), 3);
        assert_eq!(byte_at_cell("hello", 99), 5); // clamp past end
        // "你好" = 2 chars, 3 bytes each, 2 cells each.
        assert_eq!(byte_at_cell("你好", 0), 0);
        assert_eq!(byte_at_cell("你好", 2), 3); // after first wide char
        // A cell index that lands mid-glyph keeps the glyph whole (rounds up).
        assert_eq!(byte_at_cell("你好", 1), 3);
    }

    #[test]
    fn slice_by_cells_extracts_display_range() {
        assert_eq!(slice_by_cells("hello world", 0, 5), "hello");
        assert_eq!(slice_by_cells("hello world", 6, 11), "world");
        assert_eq!(slice_by_cells("你好world", 2, 7), "好wor");
    }

    #[test]
    fn pad_to_cells_fills_to_display_width() {
        assert_eq!(pad_to_cells("ab", 5), "ab   ");
        // "你好" = 4 display cells; pad to 6 → exactly 2 trailing spaces (#101).
        assert_eq!(pad_to_cells("你好", 6), "你好  ");
        // Already wide enough → unchanged (never truncates).
        assert_eq!(pad_to_cells("你好", 3), "你好");
        assert_eq!(pad_to_cells("", 0), "");
    }

    #[test]
    fn user_timestamp_padding_aligns_on_display_cells() {
        // ASCII: prefix(4) + text(5) + gap(3) + ts(8) = 20 used; content 40.
        assert_eq!(user_timestamp_padding(4, 5, 8, 3, 40), 23);
        // A wider (CJK) message shrinks the gap but the timestamp still lands at
        // the content right edge: role + text + pad + ts == content_width (#104).
        let pad = user_timestamp_padding(4, 10, 8, 3, 40);
        assert_eq!(4 + 10 + pad + 8, 40);
        // Overflow (text wider than the line) clamps to min_gap, never underflows.
        assert_eq!(user_timestamp_padding(4, 100, 8, 3, 40), 3);
    }

    #[test]
    fn wrap_preformatted_hard_wraps_preserving_spaces() {
        // 18 cells, wraps at 10. Spaces are preserved (not collapsed) and the
        // leading indentation survives on the first row.
        let line = Line::from(vec![Span::raw("    aaaa bbbb cccc")]);
        let wrapped = wrap_preformatted(line, 10, 2);
        assert!(wrapped.len() >= 2, "wide line should wrap to multiple rows");
        let first: String = wrapped[0]
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect();
        assert!(
            first.starts_with("    aaaa"),
            "indentation must be preserved, got {first:?}"
        );
        let second: String = wrapped[1]
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect();
        assert!(
            second.starts_with("  "),
            "continuation should get the hanging indent, got {second:?}"
        );
    }

    #[test]
    fn wrap_preformatted_short_line_unchanged() {
        let line = Line::from(vec![Span::raw("    short")]);
        let wrapped = wrap_preformatted(line, 40, 2);
        assert_eq!(wrapped.len(), 1);
        let text: String = wrapped[0]
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect();
        assert_eq!(text, "    short");
    }

    /// Build a ChatState whose last frame rendered `rows`, with a selection
    /// already mapped to content coords, so `selected_text` can be tested
    /// without a real terminal.
    fn state_with_rows(rows: &[&str], sel: ((usize, usize), (usize, usize))) -> ChatState {
        let mut st = ChatState::new();
        st.last_rendered_rows = rows.iter().map(|r| r.to_string()).collect();
        st.selection = Some(sel);
        st
    }

    #[test]
    fn selected_text_single_line() {
        let st = state_with_rows(&["> hello world"], ((0, 2), (0, 7)));
        assert_eq!(st.selected_text().as_deref(), Some("hello"));
    }

    #[test]
    fn selected_text_spans_multiple_rows() {
        let st = state_with_rows(&["> first line", "  second line"], ((0, 2), (1, 8)));
        // The continuation row's "  " margin is stripped so copied text is
        // clean (the start row was sliced from the click column past "> ").
        assert_eq!(st.selected_text().as_deref(), Some("first line\nsecond"));
    }

    #[test]
    fn selected_text_strips_margin_but_keeps_code_indentation() {
        // Rendered rows: 2-cell margin + the code's own indentation. Selecting
        // from column 0 must drop only the 2-cell margin, not the code indent.
        let st = state_with_rows(
            &["  fn main() {", "      let x = 1;", "  }"],
            ((0, 0), (2, 3)),
        );
        assert_eq!(
            st.selected_text().as_deref(),
            Some("fn main() {\n    let x = 1;\n}")
        );
    }

    #[test]
    fn selected_text_normalizes_reversed_drag() {
        // Dragging bottom-up / right-to-left yields the same text.
        let st = state_with_rows(&["> hello world"], ((0, 7), (0, 2)));
        assert_eq!(st.selected_text().as_deref(), Some("hello"));
    }

    #[test]
    fn selected_text_empty_selection_is_none() {
        // A plain click (anchor == cursor) selects nothing.
        let st = state_with_rows(&["> hello"], ((0, 3), (0, 3)));
        assert_eq!(st.selected_text(), None);
    }

    #[test]
    fn highlight_line_cells_splits_spans_on_selection() {
        let mut line = Line::from(vec![Span::raw("abcdef")]);
        highlight_line_cells(
            &mut line,
            2,
            4,
            Style::new().add_modifier(Modifier::REVERSED),
        );
        // Split into "ab" | "cd"(reversed) | "ef".
        let texts: Vec<String> = line.spans.iter().map(|s| s.content.to_string()).collect();
        assert_eq!(texts, vec!["ab", "cd", "ef"]);
        assert!(
            line.spans[1]
                .style
                .add_modifier
                .contains(Modifier::REVERSED)
        );
        assert!(
            !line.spans[0]
                .style
                .add_modifier
                .contains(Modifier::REVERSED)
        );
    }

    #[test]
    fn context_checkpoint_renders_as_compact_event() {
        let mut msg = ChatMessage::user("full checkpoint summary hidden from the chat log");
        msg.kind = ChatMessageKind::ContextCheckpoint;
        msg.metadata = Some(serde_json::json!({
            "trigger": "manual",
            "before_tokens": 43_800,
            "after_tokens": 9_200,
            "archived_message_count": 18,
            "preserved_message_count": 4,
            "duration_secs": 2.4,
            "review_status": "reviewed",
        }));

        let lines =
            render_context_checkpoint_event(&msg, &Theme::dark(), 120).expect("event lines");
        let rendered = lines
            .iter()
            .map(|line| {
                line.spans
                    .iter()
                    .map(|span| span.content.as_ref())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n");

        assert!(rendered.contains("Compact(manual)"));
        assert!(rendered.contains("43.8k -> 9.2k tokens"));
        assert!(rendered.contains("archived 18 messages"));
        assert!(rendered.contains("preserved 4 messages"));
        assert!(rendered.contains("reviewed"));
        assert!(!rendered.contains("full checkpoint summary"));
    }

    #[test]
    fn context_checkpoint_renders_validated_draft() {
        let mut msg = ChatMessage::user("full checkpoint summary hidden from the chat log");
        msg.kind = ChatMessageKind::ContextCheckpoint;
        msg.metadata = Some(serde_json::json!({
            "trigger": "auto_threshold",
            "before_tokens": 43_800,
            "after_tokens": 9_200,
            "archived_message_count": 18,
            "preserved_message_count": 4,
            "duration_secs": 2.4,
            "review_status": "draft_validated",
            "review_error": "provider overloaded",
        }));

        let lines =
            render_context_checkpoint_event(&msg, &Theme::dark(), 120).expect("event lines");
        let rendered = lines
            .iter()
            .map(|line| {
                line.spans
                    .iter()
                    .map(|span| span.content.as_ref())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n");

        assert!(rendered.contains("Compact(auto_threshold)"));
        assert!(rendered.contains("validated draft"));
        assert!(rendered.contains("review: provider overloaded"));
    }

    /// CJK characters are 3 bytes but 2 display cells each. The
    /// byte-length version of `wrap_styled_line` would incorrectly
    /// over-wrap such input. This test asserts the display-width
    /// version keeps CJK-only input on a single line when the display
    /// width fits, even when the byte length exceeds the width.
    #[test]
    fn wrap_styled_line_uses_display_width_for_cjk() {
        // "你好世界" is 4 CJK chars × 3 bytes = 12 bytes, × 2 display cells = 8 cells.
        // Target width of 10: byte-length would see 12 > 10 and wrap;
        // display-width sees 8 <= 10 and keeps it on one line.
        let line = Line::from(Span::raw("你好世界".to_string()));
        let wrapped = wrap_styled_line(line, 10, 2);
        assert_eq!(
            wrapped.len(),
            1,
            "CJK input fitting in display-width should NOT be wrapped; got {} lines",
            wrapped.len()
        );
    }

    /// Sanity: ASCII wrapping still works and produces >= 2 lines when
    /// the input exceeds the width.
    #[test]
    fn wrap_styled_line_ascii_wraps_when_too_long() {
        let line = Line::from(Span::raw(
            "the quick brown fox jumps over the lazy dog".to_string(),
        ));
        let wrapped = wrap_styled_line(line, 15, 2);
        assert!(
            wrapped.len() >= 2,
            "long ASCII input should wrap to multiple lines; got {}",
            wrapped.len()
        );
    }

    fn first_segment_text(wrapped: &[Line<'static>]) -> String {
        wrapped[0]
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect()
    }

    /// Regression (recurring "paragraph escapes the gutter" bug): a non-first
    /// message line carries a 2-space gutter prefix; when it wraps, the first
    /// segment must keep that gutter, not flush to column 0. `split_whitespace`
    /// used to drop the leading spaces and the "first word, no indent" rule
    /// flushed the segment left.
    #[test]
    fn wrap_styled_line_keeps_gutter_on_wrapped_paragraph() {
        let line = Line::from(vec![
            Span::raw("  "), // the continuation gutter chat.rs prepends
            Span::raw(
                "No source files, no config, no docs, no build system and more words to wrap"
                    .to_string(),
            ),
        ]);
        let wrapped = wrap_styled_line(line, 30, 2);
        assert!(wrapped.len() >= 2, "should wrap");
        let first = first_segment_text(&wrapped);
        assert!(
            first.starts_with("  ") && first.trim_start().starts_with("No source"),
            "first wrapped segment must keep the 2-space gutter; got {first:?}"
        );
    }

    /// End-to-end: a wrapped list item keeps the bullet on the first segment and
    /// hangs its continuation lines under the item text (col 6 = 2 gutter + 2
    /// nesting indent + 2 marker), instead of snapping back to the message gutter.
    /// Exercises the same span shape chat.rs builds, with the continuation indent
    /// chat.rs derives via markdown::line_hanging_indent (4) + the gutter (2).
    #[test]
    fn wrap_styled_line_hangs_list_continuation_under_marker() {
        let line = Line::from(vec![
            Span::raw("  "), // message gutter (chat.rs)
            Span::raw("  "), // list nesting indent (markdown)
            Span::raw(""), // marker (markdown)
            Span::raw("alpha beta gamma delta epsilon zeta eta theta iota".to_string()),
        ]);
        let wrapped = wrap_styled_line(line, 24, 6);
        assert!(wrapped.len() >= 2, "should wrap");
        assert!(
            first_segment_text(&wrapped).starts_with(""),
            "first segment keeps gutter + nesting + marker"
        );
        for cont in &wrapped[1..] {
            let t: String = cont.spans.iter().map(|s| s.content.as_ref()).collect();
            assert!(
                t.starts_with("      ") && t.chars().nth(6).is_some_and(|c| c != ' '),
                "continuation hangs under the item text at col 6; got {t:?}"
            );
        }
    }

    /// The fix preserves whitespace margins only — the message bullet "● " must
    /// still sit at column 0 on the first line.
    #[test]
    fn wrap_styled_line_keeps_bullet_at_column_zero() {
        let line = Line::from(vec![
            Span::raw(""),
            Span::raw(
                "a fairly long first line of a message that definitely needs to wrap".to_string(),
            ),
        ]);
        let wrapped = wrap_styled_line(line, 25, 2);
        assert!(wrapped.len() >= 2, "should wrap");
        assert!(
            first_segment_text(&wrapped).starts_with(''),
            "bullet must stay at column 0"
        );
    }

    /// Counterpart to `wrap_styled_line_uses_display_width_for_cjk` for
    /// the plain-string wrapper used by user messages and thinking blocks.
    /// The byte-based version would wrap a 4-CJK paragraph after the second
    /// char (12 bytes > 10) even though it fits in 8 cells. Display-width
    /// version keeps it on one line.
    #[test]
    fn wrap_text_with_indent_uses_display_width_for_cjk() {
        // "你好世界" = 4 chars, 12 bytes, 8 display cells. Width 12 cells
        // with 0 indent: should fit on one line.
        let wrapped = wrap_text_with_indent("你好世界", 12, 0, 0);
        assert_eq!(
            wrapped.len(),
            1,
            "CJK paragraph fitting in display width should not wrap; got {} lines: {:?}",
            wrapped.len(),
            wrapped
        );
        assert_eq!(wrapped[0].trim_start(), "你好世界");
    }

    /// Mixed content: CJK + ASCII should still wrap correctly when the
    /// total exceeds available cells.
    #[test]
    fn wrap_text_with_indent_wraps_cjk_at_visual_edge() {
        // "你好 world 世界" = 2 + 1 + 5 + 1 + 2 = 11 cells without spaces,
        // with separators: 2 + 1 + 5 + 1 + 4 = 13 cells. Width 8 cells should
        // produce ≥ 2 lines.
        let wrapped = wrap_text_with_indent("你好 world 世界", 8, 0, 0);
        assert!(
            wrapped.len() >= 2,
            "mixed CJK+ASCII exceeding width should wrap; got {} lines: {:?}",
            wrapped.len(),
            wrapped
        );
    }

    #[test]
    fn clamp_to_u16_saturates_past_u16_max() {
        // F32: line counters past u16::MAX must clamp to the last addressable
        // row, never wrap modulo 65536 (which a plain `as u16` would do).
        assert_eq!(clamp_to_u16(0), 0);
        assert_eq!(clamp_to_u16(65_535), u16::MAX);
        assert_eq!(clamp_to_u16(65_536), u16::MAX);
        assert_eq!(clamp_to_u16(1_000_000), u16::MAX);
    }

    #[test]
    fn wrap_text_with_indent_hard_breaks_overlong_token() {
        // F33: a single unbroken token far wider than the viewport must
        // hard-break at width boundaries instead of overflowing and being
        // clipped. No internal spaces, so word-wrapping alone can't split it.
        let token = "x".repeat(100);
        let width = 20;
        let wrapped = wrap_text_with_indent(&token, width, 2, 2);
        assert!(
            wrapped.len() >= 5,
            "a 100-cell token at width 20 must span many rows; got {}",
            wrapped.len()
        );
        for line in &wrapped {
            assert!(
                line.chars().count() <= width,
                "no wrapped row may exceed the width; got {:?} ({} cells)",
                line,
                line.chars().count()
            );
        }
        // Stripping each row's hanging indent reconstructs the token intact.
        let joined: String = wrapped.iter().map(|l| l.trim_start()).collect();
        assert_eq!(
            joined, token,
            "hard-break must preserve the token's content"
        );
    }

    #[test]
    fn wrap_styled_line_hard_breaks_overlong_token() {
        // F33 (styled path): the same hard-break, preserving each piece's style.
        let token = "y".repeat(90);
        let style = Style::new().fg(ratatui::style::Color::Red);
        let line = Line::from(vec![Span::raw("  "), Span::styled(token.clone(), style)]);
        let width = 24;
        let wrapped = wrap_styled_line(line, width, 2);
        assert!(
            wrapped.len() >= 4,
            "must hard-break across rows; got {}",
            wrapped.len()
        );

        let mut reconstructed = String::new();
        for l in &wrapped {
            let row_cells: usize = l.spans.iter().map(|s| s.content.chars().count()).sum();
            assert!(
                row_cells <= width,
                "row exceeds width: {row_cells} > {width}"
            );
            for s in &l.spans {
                // Skip indent/gutter spans (whitespace only); every content
                // piece must keep the original red foreground.
                if s.content.trim().is_empty() {
                    continue;
                }
                assert_eq!(
                    s.style.fg,
                    Some(ratatui::style::Color::Red),
                    "hard-break must preserve the span style"
                );
                reconstructed.push_str(s.content.as_ref());
            }
        }
        assert_eq!(reconstructed, token, "hard-break must preserve the token");
    }

    /// The separator space re-inserted between words must be unstyled: when a
    /// wrapped line contains an underlined link span, the gap before the link
    /// used to inherit the underline (visibly underlined space in the TUI).
    #[test]
    fn wrap_styled_line_separator_before_styled_span_is_unstyled() {
        let underlined = Style::new().add_modifier(ratatui::style::Modifier::UNDERLINED);
        let line = Line::from(vec![
            Span::raw("  "),
            Span::raw("some filler words long enough to force a wrap here "),
            Span::styled("underlined-link-text", underlined),
            Span::raw(" and a bit more trailing filler after the link"),
        ]);
        let wrapped = wrap_styled_line(line, 30, 2);
        assert!(wrapped.len() >= 2, "fixture must actually wrap");
        for l in &wrapped {
            for s in &l.spans {
                if s.content.chars().all(|c| c == ' ') {
                    assert_eq!(
                        s.style,
                        Style::default(),
                        "whitespace span {:?} must be unstyled",
                        s.content
                    );
                }
            }
        }
    }

    /// A span boundary WITHOUT source whitespace is not a word boundary: the
    /// dimmed "(url)" suffix a markdown link gets, followed by a bare "." text
    /// span, must stay "(url)." — not gain a phantom space ("(url) .").
    #[test]
    fn wrap_styled_line_no_phantom_space_at_span_boundary() {
        let dim = Style::new().fg(ratatui::style::Color::DarkGray);
        let line = Line::from(vec![
            Span::raw("  "),
            Span::raw("filler text that pushes the line well past the width limit "),
            Span::styled("(https://example.com)".to_string(), dim),
            Span::raw("."),
        ]);
        let wrapped = wrap_styled_line(line, 30, 2);
        assert!(wrapped.len() >= 2, "fixture must actually wrap");
        let text: String = wrapped
            .iter()
            .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref()))
            .collect();
        assert!(
            text.contains("(https://example.com)."),
            "period must stay glued to the URL suffix; got {text:?}"
        );
        assert!(
            !text.contains("(https://example.com) ."),
            "no phantom space before the period; got {text:?}"
        );
    }

    /// A style change mid-word ("**bold**suffix") is not a word boundary: the
    /// two fragments must land on the same row as one token, each keeping its
    /// own style.
    #[test]
    fn wrap_styled_line_keeps_mid_word_style_change_glued() {
        let bold = Style::new().add_modifier(ratatui::style::Modifier::BOLD);
        let line = Line::from(vec![
            Span::raw("  "),
            Span::raw("leading filler words to force wrapping "),
            Span::styled("bold", bold),
            Span::raw("suffix"),
            Span::raw(" trailing filler words to force more wrapping"),
        ]);
        let wrapped = wrap_styled_line(line, 30, 2);
        assert!(wrapped.len() >= 2, "fixture must actually wrap");
        let rows: Vec<String> = wrapped
            .iter()
            .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
            .collect();
        assert_eq!(
            rows.iter().filter(|r| r.contains("boldsuffix")).count(),
            1,
            "glued token must land whole on exactly one row; rows: {rows:?}"
        );
        for l in &wrapped {
            for s in &l.spans {
                if s.content.as_ref() == "bold" {
                    assert_eq!(s.style, bold, "bold fragment keeps its modifier");
                }
                if s.content.as_ref() == "suffix" {
                    assert_eq!(s.style, Style::default(), "suffix fragment stays plain");
                }
            }
        }
    }

    /// An over-long glued token made of differently styled fragments must
    /// hard-break across rows with each fragment's style preserved and no
    /// content lost — it enters the break path as ONE token, not two words.
    #[test]
    fn wrap_styled_line_hard_breaks_multi_fragment_token_preserving_styles() {
        let red = Style::new().fg(ratatui::style::Color::Red);
        let blue = Style::new().fg(ratatui::style::Color::Blue);
        let line = Line::from(vec![
            Span::raw("  "),
            Span::styled("a".repeat(40), red),
            Span::styled("b".repeat(40), blue),
        ]);
        let width = 24;
        let wrapped = wrap_styled_line(line, width, 2);
        assert!(
            wrapped.len() >= 4,
            "80-cell token at width 24 must span >= 4 rows; got {}",
            wrapped.len()
        );
        let mut reconstructed = String::new();
        for l in &wrapped {
            let row_cells: usize = l.spans.iter().map(|s| s.content.width()).sum();
            assert!(
                row_cells <= width,
                "row exceeds width: {row_cells} > {width}"
            );
            for s in &l.spans {
                if s.content.trim().is_empty() {
                    continue;
                }
                let expected = if s.content.contains('a') { red } else { blue };
                assert!(
                    !(s.content.contains('a') && s.content.contains('b')),
                    "fragments must not merge across the style boundary"
                );
                assert_eq!(s.style, expected, "fragment style preserved across break");
                reconstructed.push_str(s.content.as_ref());
            }
        }
        assert_eq!(
            reconstructed,
            format!("{}{}", "a".repeat(40), "b".repeat(40)),
            "hard-break must preserve the whole glued token"
        );
    }

    /// A whitespace-only span between two text spans still separates words —
    /// gluing only happens where the source truly has no whitespace.
    #[test]
    fn wrap_styled_line_whitespace_only_span_is_word_boundary() {
        let line = Line::from(vec![
            Span::raw("  "),
            Span::raw("filler words that push this line past the wrap width "),
            Span::raw("foo"),
            Span::raw(" "),
            Span::raw("bar"),
        ]);
        let wrapped = wrap_styled_line(line, 30, 2);
        assert!(wrapped.len() >= 2, "fixture must actually wrap");
        let text: String = wrapped
            .iter()
            .map(|l| {
                l.spans
                    .iter()
                    .map(|s| s.content.as_ref())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n");
        assert!(
            text.contains("foo bar") || text.contains("foo\n  bar"),
            "whitespace-only span must keep the words apart; got {text:?}"
        );
        assert!(
            !text.contains("foobar"),
            "words must not glue; got {text:?}"
        );
    }

    #[test]
    fn frame_memo_hit_matches_miss() {
        // F31: memoizing the assembled frame must be byte-for-byte identical to
        // re-assembling it. Render the SAME state twice — the first render
        // populates the frame memo, the second reuses it — and assert the
        // buffers are equal. Assistant-only messages keep the frame free of the
        // clock-relative user timestamp, so nothing here is time-dependent.
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let theme = Theme::dark();
        let messages = vec![
            ChatMessage::assistant(
                "# Heading\n\nSome **bold** prose long enough that it wraps across \
                 this narrow viewport more than once.\n\n- a list item that also \
                 runs past the edge so it wraps\n- second item",
            ),
            ChatMessage::assistant("Short follow-up."),
        ];

        let (width, height): (u16, u16) = (34, 30);
        let mut cache = FxHashMap::default();
        let mut state = ChatState::new();

        let render = |state: &mut ChatState, cache: &mut FxHashMap<u64, Vec<Line<'static>>>| {
            let mut term = Terminal::new(TestBackend::new(width, height)).unwrap();
            term.draw(|f| {
                let widget = ChatWidget {
                    messages: &messages,
                    theme: &theme,
                    wrapped_line_cache: cache,
                    show_reasoning: true,
                    blink_on: true,
                };
                f.render_stateful_widget(widget, Rect::new(0, 0, width, height), state);
            })
            .unwrap();
            term.backend().buffer().clone()
        };

        let miss = render(&mut state, &mut cache);
        assert!(
            state.frame_memo.is_some(),
            "first render must populate the frame memo"
        );
        let hit = render(&mut state, &mut cache);
        assert_eq!(
            miss, hit,
            "frame-memo hit must render identically to the miss"
        );
        // The rows used for selection extraction are only re-collected on a
        // miss; assert the hit path left them intact (not cleared/stale) so
        // copy/selection still works on a reused frame (F31).
        assert!(
            !state.last_rendered_rows.is_empty(),
            "memo hit must preserve last_rendered_rows from the miss"
        );
    }

    #[test]
    fn append_action_duration_handles_empty_base() {
        // A plain success with no detail (e.g. the Delete line) → just "took Xms",
        // no leading comma.
        assert_eq!(
            append_action_duration(String::new(), Some(0.035)),
            "took 35ms"
        );
        // A detail line keeps its text before the timing.
        assert_eq!(
            append_action_duration("3 lines read".to_string(), Some(1.25)),
            "3 lines read, took 1.2s"
        );
        // No duration → text unchanged (empty stays empty → renders no line).
        assert_eq!(append_action_duration(String::new(), None), "");
    }
}