shuvarie 0.1.1

Blazingly fast AI coding TUI for chivalrous people
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
use std::cell::{Cell, RefCell};
use std::collections::{BTreeMap, BTreeSet};
use std::time::{Duration, Instant};

use ratatui::prelude::*;
use serde_json::Value;
use shuvarie_core::tool_record::ToolRecord;
use shuvarie_core::{DiagnosticInfo, Role};
use shuvarie_db::{ReasoningSegment, StoredScroll, TextSegment};
use shuvarie_llm::{FileChange, ShellStreams};
use unicode_width::UnicodeWidthStr;

use super::MouseKind;
use super::blocks::{
    Block, BlockMessage, ChatEnv, ContextBlock, ReasoningBlock, SteeredPrompt, SystemText,
    TextBlock, ToolBlock, ToolMessage, UserPrompt,
};
use super::segment::{BlockAddr, ResolvedRow, slice_visual, visual_row_text};
use super::virtualizer::{TurnData, TurnEst, TurnFlags, locate, paint_turn};
use crate::tui::theme;

/// Selection column bounds of one wrapped row.
type WrapBounds = (Option<u16>, Option<u16>);

/// One logical source row under the selection: which turn/segment/source
/// row it came from, the wrapped rows it covers with their selection column
/// bounds, and the resolved handle for extraction.
struct CopyGroup {
    key: (usize, usize, u32),
    wraps: Vec<(u32, WrapBounds)>,
    resolved: ResolvedRow,
}

/// Drop selection column bounds that touch a row's text edges: a selection
/// starting at the text's first column or ending past its last column still
/// copies the whole logical row cleanly.
fn normalize_cols(
    resolved: &ResolvedRow,
    from: Option<u16>,
    to: Option<u16>,
) -> (Option<u16>, Option<u16>) {
    let end = resolved.pad_x.saturating_add(resolved.text_width);
    (
        from.filter(|c| *c > resolved.pad_x),
        to.filter(|c| *c < end),
    )
}

impl CopyGroup {
    fn flush(self, out: &mut Vec<Option<String>>) {
        let total = self.resolved.wrap_total as usize;
        let full = self.wraps.len() == total
            && self.wraps.iter().enumerate().all(|(i, (w, bounds))| {
                *w as usize == i && bounds.0.is_none() && bounds.1.is_none()
            });
        if full {
            out.push(Some(self.resolved.copy_text()));
            return;
        }
        let line = self.resolved.line();
        for (w, (from, to)) in &self.wraps {
            let text = visual_row_text(&line, self.resolved.text_width, self.resolved.trim, *w);
            let text = if from.is_some() || to.is_some() {
                let a = from.map_or(0, |c| usize::from(c.saturating_sub(self.resolved.pad_x)));
                let b = to.map_or(usize::MAX, |c| {
                    usize::from(c.saturating_sub(self.resolved.pad_x))
                });
                slice_visual(&text, a, b)
            } else {
                text
            };
            out.push(Some(text));
        }
    }
}

/// Selection columns of one content row: boundary rows span from the
/// selection's content column, interior rows the full content width.
fn sel_columns(
    turn: usize,
    row: u32,
    start: &SelPos,
    end: &SelPos,
    content_width: u16,
) -> (u16, u16) {
    let from = (turn == start.turn && start.row == row).then_some(start.col);
    let to = (turn == end.turn && end.row == row).then_some(end.col);
    let x0 = from.map_or(0, |c| c.min(content_width));
    let x1 = to.map_or(content_width, |c| c.min(content_width));
    (x0, x1)
}

/// Paint the selection background over content-space `[x0, x1)` of one row,
/// translated into screen space, extending a boundary by one cell when a wide
/// glyph straddles it.
fn tint_row(buf: &mut Buffer, clip: Rect, content_width: u16, y: u16, mut x0: u16, mut x1: u16) {
    let right = clip.x.saturating_add(content_width);
    x0 = clip.x.saturating_add(x0.min(content_width));
    x1 = clip.x.saturating_add(x1.min(content_width));
    if x0 >= x1 {
        return;
    }
    if x0 > clip.x && buf[(x0 - 1, y)].symbol().width() == 2 {
        x0 -= 1;
    }
    if x1 < right && buf[(x1 - 1, y)].symbol().width() == 2 {
        x1 += 1;
    }
    for x in x0..x1 {
        if let Some(cell) = buf.cell_mut((x, y)) {
            cell.set_bg(theme::selection());
        }
    }
}

pub enum ChatMessage {
    BeginUserTurn {
        content: String,
    },
    TokenReceived {
        content: String,
    },
    ReasoningReceived {
        content: String,
    },
    ContextLoaded {
        paths: Vec<String>,
    },
    ToolStarted {
        name: String,
        args: Value,
        worker: Option<String>,
        call_id: Option<String>,
    },
    ToolFinished {
        name: String,
        ok: bool,
        output: String,
        worker: Option<String>,
        file_change: Option<FileChange>,
        streams: Option<ShellStreams>,
        duration_ms: u64,
        call_id: Option<String>,
    },
    ToolOutput {
        tool: String,
        worker: Option<String>,
        /// The call id the core resolved for this streamed chunk (the shell
        /// call it was produced by); `None` when ambiguous, in which case the
        /// name+worker fallback routes it.
        call_id: Option<String>,
        stdout: String,
        stderr: String,
    },
    WorkerStarted {
        name: String,
        args: Value,
        call_id: Option<String>,
    },
    WorkerFinished {
        name: String,
        ok: bool,
        output: String,
        duration_ms: u64,
        call_id: Option<String>,
    },
    StreamDone,
    StreamError {
        error: String,
    },
    StreamCancelled,
    Load {
        session: shuvarie_core::Session,
    },
    Forked {
        session: shuvarie_core::Session,
    },
    Reset,
    LspDiagnostics {
        path: String,
        diagnostics: Vec<DiagnosticInfo>,
    },
    ScrollUp,
    ScrollDown,
    /// Left-button mouse activity at a terminal cell inside the history
    /// pane: down starts a selection, drag extends it, up finalizes — or
    /// toggles the block under a click (movement under the drag slop).
    Mouse {
        kind: super::MouseKind,
        column: u16,
        row: u16,
    },
    Wheel {
        up: bool,
        column: u16,
        row: u16,
    },
    ToggleLastTool,
    /// A prompt was queued (steered) while the agent works.
    SteeredQueued {
        content: String,
    },
    /// The first queued prompt was dispatched as a new user turn.
    SteeredDispatched,
    /// The most recently queued prompt was recalled into the input area.
    SteeredRecalled,
    /// The queue was wiped by a session-level transition.
    SteeredCleared,
    /// The render loop's spinner wake: the turns that can hold animated
    /// blocks — the in-flight turn and a committed turn with a late
    /// still-running `ToolFinished` straggler — repaint their spinner-bearing
    /// segments in place without invalidating their caches.
    SpinnerUpdate,
}

/// Viewport-relative scroll position. `sticky_bottom` tracks the streaming
/// follow state: pinned to the bottom while true, released by any upward
/// scroll and re-engaged when scrolling back down to the last row. `anchor`
/// is the content-space position the last frame held the viewport top at
/// (re-derived from `offset` every frame); it is what gets persisted for a
/// session. `pending_anchor` holds a restored anchor awaiting its first
/// frame, where it resolves into an `offset`.
#[derive(Debug, Default, Clone, Copy)]
struct Scroll {
    offset: u32,
    sticky_bottom: bool,
    anchor: Option<(usize, u32)>,
    pending_anchor: Option<(usize, u32)>,
}

/// How [`Chat::apply_session`] seeds the viewport scroll: restore the
/// persisted position (session load) or keep the current viewport (forks —
/// the live sticky flag and content anchor carry over: the retained path
/// prefix is unchanged, so the anchor still names the same content, and an
/// anchor beyond the shortened tail clamps to the bottom on the next paint).
enum ScrollInit {
    Restore,
    Keep,
}

/// A selection endpoint in content space: turn index (same space as
/// [`BlockAddr::turn`]), the wrapped row within that turn, and the column
/// within the content width. Anchored, so it survives scrolling.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct SelPos {
    turn: usize,
    row: u32,
    col: u16,
}

/// A drag selection: the fixed anchor and the moving head.
#[derive(Debug, Clone, Copy)]
struct SelRange {
    anchor: SelPos,
    head: SelPos,
}

/// Movement under this many cells (rows + columns) counts as a click, not a
/// drag, and toggles the block under the cursor on mouse-up.
const CLICK_SLOP: u32 = 3;

/// Clicks within this window at the same cell escalate: double selects the
/// word, triple the whole logical row.
const MULTI_CLICK_WINDOW: Duration = Duration::from_millis(500);

impl SelRange {
    /// The endpoints ordered ascending; `None` for a collapsed (zero-width)
    /// selection.
    fn ordered(&self) -> Option<(SelPos, SelPos)> {
        let (a, b) = if (self.anchor.turn, self.anchor.row, self.anchor.col)
            <= (self.head.turn, self.head.row, self.head.col)
        {
            (self.anchor, self.head)
        } else {
            (self.head, self.anchor)
        };
        let collapsed = a.turn == b.turn && a.row == b.row && a.col >= b.col;
        (!collapsed).then_some((a, b))
    }

    /// Drag distance in content cells: rows plus columns; a cross-turn head
    /// is always a drag.
    fn drag_distance(&self) -> u32 {
        if self.anchor.turn != self.head.turn {
            return u32::MAX;
        }
        self.anchor
            .row
            .abs_diff(self.head.row)
            .saturating_add(u32::from(self.anchor.col.abs_diff(self.head.col)))
    }
}

/// The chat history pane: committed turns (lazily materialized TEA block
/// lists backed by the stored session), the in-flight streaming turn, and the
/// windowed scroll engine. Only turns intersecting the viewport (plus an
/// overscan band) render their segments; far-away turns are evicted back to
/// estimated lazy slots so long sessions scroll without full-content
/// rebuilds. Scroll position and the scrollbar derive from mixed exact and
/// estimated row heights.
pub struct Chat {
    turns: RefCell<Vec<TurnData>>,
    in_flight: RefCell<Option<TurnData>>,
    /// Queued (steered) prompts waiting to take over at the agent's next
    /// completed action (tool call, thinking, or text segment). Rendered as
    /// pseudo-turns pinned after the in-flight turn.
    steered: RefCell<Vec<TurnData>>,
    streaming: bool,
    interrupted: bool,
    lsp_diagnostics: BTreeMap<String, Vec<DiagnosticInfo>>,
    stored: Option<shuvarie_core::Session>,
    stored_len: usize,
    scroll: RefCell<Scroll>,
    width: Cell<u16>,
    env_rev: u64,
    toggled: BTreeSet<(usize, usize)>,
    /// Live drag selection in content space; survives scrolling.
    selection: RefCell<Option<SelRange>>,
    /// A mouse button is down inside the history pane.
    dragging: Cell<bool>,
    /// Last click for double/triple-click escalation: position, time, count.
    last_click: RefCell<Option<(SelPos, Instant, u8)>>,
    /// Set when mouse-up finalized a non-empty selection, for the
    /// copy-on-select hook the session consumes.
    pending_copy: Cell<bool>,
    history_rect: Cell<Rect>,
}

impl Chat {
    pub fn new() -> Self {
        Self {
            turns: RefCell::new(Vec::new()),
            in_flight: RefCell::new(None),
            steered: RefCell::new(Vec::new()),
            streaming: false,
            interrupted: false,
            lsp_diagnostics: BTreeMap::new(),
            stored: None,
            stored_len: 0,
            scroll: RefCell::new(Scroll {
                sticky_bottom: true,
                ..Scroll::default()
            }),
            width: Cell::new(0),
            env_rev: 0,
            toggled: BTreeSet::new(),
            selection: RefCell::new(None),
            dragging: Cell::new(false),
            last_click: RefCell::new(None),
            pending_copy: Cell::new(false),
            history_rect: Cell::new(Rect::default()),
        }
    }

    pub fn is_streaming(&self) -> bool {
        self.streaming
    }

    /// Whether any steered prompts are queued (drives the recall help hint).
    pub fn has_steered(&self) -> bool {
        !self.steered.borrow().is_empty()
    }

    pub fn has_messages(&self) -> bool {
        !self.turns.borrow().is_empty()
    }

    /// Whether any tool block is still animating: live blocks in the
    /// in-flight turn or a straggler in the last committed turn. Only those
    /// turns can hold running blocks — committed turns are built from
    /// in-flight data or stored records, neither of which animates.
    pub fn has_running_tool_blocks(&self) -> bool {
        self.in_flight
            .borrow()
            .as_ref()
            .is_some_and(Self::turn_has_running_tool)
            || self
                .turns
                .borrow()
                .last()
                .is_some_and(Self::turn_has_running_tool)
    }

    fn turn_has_running_tool(turn: &TurnData) -> bool {
        turn.blocks
            .as_deref()
            .is_some_and(|blocks| blocks.iter().any(|block| block.tool_is_running()))
    }

    pub fn update(&mut self, msg: ChatMessage) {
        match msg {
            ChatMessage::BeginUserTurn { content } => {
                if self.in_flight.borrow().is_some() {
                    self.clear_selection_from(self.turns.borrow().len());
                }
                let mut turn = TurnData::new(Role::User);
                turn.set_blocks(vec![Block::User(UserPrompt::new(content))], false);
                self.turns.borrow_mut().push(turn);
            }
            ChatMessage::TokenReceived { content } => {
                self.streaming = true;
                let mut in_flight = self.in_flight.borrow_mut();
                let turn = in_flight.get_or_insert_with(|| TurnData::new(Role::Assistant));
                turn.append_text(content);
            }
            ChatMessage::ReasoningReceived { content } => {
                self.streaming = true;
                let mut in_flight = self.in_flight.borrow_mut();
                let turn = in_flight.get_or_insert_with(|| TurnData::new(Role::Assistant));
                turn.append_reasoning(content);
            }
            ChatMessage::ContextLoaded { paths } => {
                self.streaming = true;
                let mut in_flight = self.in_flight.borrow_mut();
                let turn = in_flight.get_or_insert_with(|| TurnData::new(Role::Assistant));
                turn.push_block(Block::Context(ContextBlock::new(paths)));
            }
            ChatMessage::ToolStarted {
                name,
                args,
                worker,
                call_id,
            } => {
                self.streaming = true;
                let mut in_flight = self.in_flight.borrow_mut();
                let turn = in_flight.get_or_insert_with(|| TurnData::new(Role::Assistant));
                turn.push_block(Block::Tool(Box::new(ToolBlock::new(
                    name,
                    args.to_string(),
                    worker,
                    call_id,
                ))));
            }
            ChatMessage::ToolFinished {
                name,
                ok,
                output,
                worker,
                file_change,
                streams,
                duration_ms,
                call_id,
            } => {
                let (display_output, display_stderr) = match streams {
                    Some(streams) => (streams.stdout, streams.stderr),
                    None => (output, String::new()),
                };
                self.with_running_tool(&name, &worker, call_id.as_deref(), |block| {
                    block.update(BlockMessage::Tool(ToolMessage::Finish {
                        ok,
                        output: display_output,
                        stderr: display_stderr,
                        file_change,
                        duration_ms,
                    }))
                });
                self.touch_in_flight();
            }
            ChatMessage::ToolOutput {
                tool,
                worker,
                call_id,
                stdout,
                stderr,
            } => {
                let updated = self.with_running_tool(&tool, &worker, call_id.as_deref(), |block| {
                    block.update(BlockMessage::Tool(ToolMessage::Output { stdout, stderr }))
                });
                if updated {
                    self.touch_in_flight();
                }
            }
            ChatMessage::WorkerStarted {
                name,
                args,
                call_id,
            } => {
                self.streaming = true;
                let mut in_flight = self.in_flight.borrow_mut();
                let turn = in_flight.get_or_insert_with(|| TurnData::new(Role::Assistant));
                turn.push_block(Block::Tool(Box::new(ToolBlock::new(
                    name,
                    args.to_string(),
                    Some(String::new()),
                    call_id,
                ))));
            }
            ChatMessage::WorkerFinished {
                name,
                ok,
                output,
                duration_ms,
                call_id,
            } => {
                self.with_running_tool(&name, &Some(String::new()), call_id.as_deref(), |block| {
                    block.update(BlockMessage::Tool(ToolMessage::Finish {
                        ok,
                        output,
                        stderr: String::new(),
                        file_change: None,
                        duration_ms,
                    }))
                });
                self.touch_in_flight();
            }
            ChatMessage::StreamDone => self.commit_done(),
            ChatMessage::StreamError { .. } | ChatMessage::StreamCancelled => {
                self.commit_interrupted()
            }
            ChatMessage::Load { session } => self.apply_session(session, ScrollInit::Restore),
            ChatMessage::Forked { session } => self.apply_session(session, ScrollInit::Keep),
            ChatMessage::Reset => {
                *self.turns.borrow_mut() = Vec::new();
                *self.in_flight.borrow_mut() = None;
                self.steered.borrow_mut().clear();
                self.stored = None;
                self.stored_len = 0;
                self.streaming = false;
                self.interrupted = false;
                self.toggled.clear();
                self.clear_selection();
                let mut scroll = self.scroll.borrow_mut();
                scroll.offset = 0;
                scroll.sticky_bottom = true;
                scroll.pending_anchor = None;
                scroll.anchor = None;
            }
            ChatMessage::LspDiagnostics { path, diagnostics } => {
                if diagnostics.is_empty() {
                    self.lsp_diagnostics.remove(&path);
                } else {
                    self.lsp_diagnostics.insert(path, diagnostics);
                }
                self.env_rev += 1;
            }
            ChatMessage::ScrollUp => {
                let mut scroll = self.scroll.borrow_mut();
                scroll.offset = scroll.offset.saturating_sub(1);
                scroll.sticky_bottom = false;
            }
            ChatMessage::ScrollDown => {
                let mut scroll = self.scroll.borrow_mut();
                scroll.offset = scroll.offset.saturating_add(1);
            }
            ChatMessage::Mouse { kind, column, row } => {
                self.handle_mouse(kind, column, row);
            }
            ChatMessage::Wheel { up, column, row } => {
                if self.in_history(column, row) {
                    let mut scroll = self.scroll.borrow_mut();
                    for _ in 0..3 {
                        if up {
                            scroll.offset = scroll.offset.saturating_sub(1);
                            scroll.sticky_bottom = false;
                        } else {
                            scroll.offset = scroll.offset.saturating_add(1);
                        }
                    }
                }
            }
            ChatMessage::ToggleLastTool => self.toggle_last_tool(),
            ChatMessage::SteeredQueued { content } => {
                let mut turn = TurnData::new(Role::User);
                turn.set_blocks(vec![Block::Steered(SteeredPrompt::new(content))], false);
                self.steered.borrow_mut().push(turn);
            }
            ChatMessage::SteeredDispatched => {
                let mut steered = self.steered.borrow_mut();
                if !steered.is_empty() {
                    steered.remove(0);
                    drop(steered);
                    self.remap_after_steered_removed();
                }
            }
            ChatMessage::SteeredRecalled => {
                self.steered.borrow_mut().pop();
                let removed = self.turns.borrow().len() + 1 + self.steered.borrow().len();
                self.clear_selection_from(removed);
            }
            ChatMessage::SteeredCleared => {
                self.steered.borrow_mut().clear();
                let from = self.turns.borrow().len() + 1;
                self.clear_selection_from(from);
            }
            ChatMessage::SpinnerUpdate => {
                let env = ChatEnv {
                    lsp_diagnostics: &self.lsp_diagnostics,
                    rev: self.env_rev,
                };
                if let Some(turn) = self.in_flight.get_mut() {
                    turn.refresh_spinners(&env);
                }
                if let Some(turn) = self.turns.get_mut().last_mut()
                    && turn.has_running_tool()
                {
                    turn.refresh_spinners(&env);
                }
            }
        }
    }

    pub fn view(&self, frame: &mut Frame<'_>, area: Rect) {
        self.history_rect.set(area);
        let content_width = area.width.saturating_sub(1);
        if content_width == 0 || area.height == 0 {
            return;
        }
        let viewport = u32::from(area.height);
        let mut turns = self.turns.borrow_mut();
        let mut in_flight = self.in_flight.borrow_mut();

        if self.width.get() != content_width {
            self.width.set(content_width);
            self.clear_selection();
            for slot in turns.iter_mut() {
                slot.cache = None;
            }
            if let Some(turn) = in_flight.as_mut() {
                turn.cache = None;
            }
        }

        let env = ChatEnv {
            lsp_diagnostics: &self.lsp_diagnostics,
            rev: self.env_rev,
        };
        let env_rev = self.env_rev;
        let streaming = self.streaming;
        let interrupted = self.interrupted;
        let turns_len = turns.len();

        let mut heights: Vec<u32> = turns
            .iter()
            .map(|slot| slot.height(content_width, env_rev))
            .collect();
        heights.push(
            in_flight
                .as_ref()
                .map_or(0, |turn| turn.height(content_width, env_rev)),
        );
        {
            let steered = self.steered.borrow();
            for slot in steered.iter() {
                heights.push(slot.height(content_width, env_rev));
            }
        }

        let sticky = self.scroll.borrow().sticky_bottom;
        let pending = self.scroll.borrow_mut().pending_anchor.take();
        let anchor = (!sticky)
            .then(|| pending.unwrap_or_else(|| locate(&heights, self.scroll.borrow().offset)));

        let offset = self.scroll.borrow().offset;
        let overscan = viewport;
        let lo = offset.saturating_sub(overscan);
        let hi = offset + viewport + overscan;

        {
            let stored = self.stored.as_ref();
            let toggled = &self.toggled;
            let mut y = 0u32;
            for (i, slot) in turns.iter_mut().enumerate() {
                let h = heights[i];
                if y + h > lo && y < hi {
                    let marker = interrupted && !streaming && i + 1 == turns_len;
                    if slot.blocks.is_none() {
                        let session = stored.expect("lazy turn without stored session");
                        slot.materialize(|| materialize_blocks(session, i), toggled, i, marker);
                    }
                    slot.ensure_cache(
                        i,
                        content_width,
                        &env,
                        env_rev,
                        TurnFlags {
                            in_flight: false,
                            interrupted_marker: marker,
                        },
                    );
                    heights[i] = slot.height(content_width, env_rev);
                }
                y += h;
            }
            if let Some(turn) = in_flight.as_mut() {
                let h = heights[turns_len];
                if y + h > lo && y < hi {
                    turn.ensure_cache(
                        turns_len,
                        content_width,
                        &env,
                        env_rev,
                        TurnFlags {
                            in_flight: true,
                            interrupted_marker: false,
                        },
                    );
                    heights[turns_len] = turn.height(content_width, env_rev);
                }
            }
            y += heights[turns_len];
            let mut steered = self.steered.borrow_mut();
            for (i, slot) in steered.iter_mut().enumerate() {
                let idx = turns_len + 1 + i;
                let h = heights[idx];
                if y + h > lo && y < hi {
                    slot.ensure_cache(
                        idx,
                        content_width,
                        &env,
                        env_rev,
                        TurnFlags {
                            in_flight: false,
                            interrupted_marker: false,
                        },
                    );
                    heights[idx] = slot.height(content_width, env_rev);
                }
                y += h;
            }
        }

        let total: u32 = heights.iter().sum();
        {
            let mut scroll = self.scroll.borrow_mut();
            if scroll.sticky_bottom {
                scroll.offset = total.saturating_sub(viewport);
            } else if let Some((turn_idx, intra)) = anchor {
                let start: u32 = heights.iter().take(turn_idx).sum();
                let h = heights.get(turn_idx).copied().unwrap_or(0);
                scroll.offset = start
                    .saturating_add(intra.min(h.saturating_sub(1)))
                    .min(total.saturating_sub(viewport));
            } else {
                scroll.offset = scroll.offset.min(total.saturating_sub(viewport));
            }
            scroll.sticky_bottom = scroll.offset >= total.saturating_sub(viewport);
            scroll.anchor = if scroll.sticky_bottom { None } else { anchor };
        }
        let scroll_y = self.scroll.borrow().offset;

        {
            let buf = frame.buffer_mut();
            let stored = self.stored.as_ref();
            let toggled = &self.toggled;
            let mut y = 0u32;
            for (i, slot) in turns.iter_mut().enumerate() {
                let mut h = heights[i];
                if y + h > scroll_y && y < scroll_y + viewport {
                    if slot.blocks.is_none() {
                        let session = stored.expect("lazy turn without stored session");
                        slot.materialize(
                            || materialize_blocks(session, i),
                            toggled,
                            i,
                            interrupted && !streaming && i + 1 == turns_len,
                        );
                    }
                    slot.ensure_cache(
                        i,
                        content_width,
                        &env,
                        env_rev,
                        TurnFlags {
                            in_flight: false,
                            interrupted_marker: interrupted && !streaming && i + 1 == turns_len,
                        },
                    );
                    h = slot.height(content_width, env_rev);
                    heights[i] = h;
                    if let Some(cache) = slot.cache() {
                        paint_turn(cache, y, scroll_y, area, content_width, buf);
                    }
                }
                y += h;
            }
            let in_flight_h = if let Some(turn) = in_flight.as_mut() {
                let h = turn.height(content_width, env_rev);
                if y + h > scroll_y && y < scroll_y + viewport {
                    turn.ensure_cache(
                        turns_len,
                        content_width,
                        &env,
                        env_rev,
                        TurnFlags {
                            in_flight: true,
                            interrupted_marker: false,
                        },
                    );
                    if let Some(cache) = turn.cache() {
                        paint_turn(cache, y, scroll_y, area, content_width, buf);
                    }
                }
                Some(h)
            } else {
                None
            };
            y += in_flight_h.unwrap_or(0);
            let mut steered = self.steered.borrow_mut();
            for (i, slot) in steered.iter_mut().enumerate() {
                let idx = turns_len + 1 + i;
                let mut h = slot.height(content_width, env_rev);
                if y + h > scroll_y && y < scroll_y + viewport {
                    slot.ensure_cache(
                        idx,
                        content_width,
                        &env,
                        env_rev,
                        TurnFlags {
                            in_flight: false,
                            interrupted_marker: false,
                        },
                    );
                    h = slot.height(content_width, env_rev);
                    if let Some(cache) = slot.cache() {
                        paint_turn(cache, y, scroll_y, area, content_width, buf);
                    }
                }
                y += h;
            }

            if self.selection.borrow().is_some() {
                self.paint_selection_overlay(
                    &turns,
                    &in_flight,
                    &steered,
                    &heights,
                    turns_len,
                    scroll_y,
                    area,
                    content_width,
                    buf,
                );
            }
        }

        self.render_scrollbar(frame, area, scroll_y, total);
        self.evict(&mut turns, scroll_y, viewport);
    }

    /// Tint the selected content rows after the paint pass. Geometry-only:
    /// interior rows tint the full content width, boundary rows from the
    /// selection's column, snapped outward around wide glyphs.
    #[allow(clippy::too_many_arguments)]
    fn paint_selection_overlay(
        &self,
        turns: &[TurnData],
        in_flight: &Option<TurnData>,
        steered: &[TurnData],
        heights: &[u32],
        turns_len: usize,
        scroll_y: u32,
        clip: Rect,
        content_width: u16,
        buf: &mut Buffer,
    ) {
        let sel = *self.selection.borrow();
        let Some((start, end)) = sel.as_ref().and_then(SelRange::ordered) else {
            return;
        };
        let viewport = u32::from(clip.height);
        let mut y = 0u32;
        for (i, h) in heights.iter().enumerate() {
            let cache = if i < turns_len {
                turns.get(i).and_then(|slot| slot.cache.as_ref())
            } else if i == turns_len {
                in_flight.as_ref().and_then(|slot| slot.cache.as_ref())
            } else {
                steered
                    .get(i - turns_len - 1)
                    .and_then(|slot| slot.cache.as_ref())
            };
            let turn_idx = i;
            let h = *h;
            if turn_idx < start.turn || turn_idx > end.turn {
                y += h;
                continue;
            }
            let lo = if turn_idx == start.turn {
                start.row.min(h.saturating_sub(1))
            } else {
                0
            };
            let hi = if turn_idx == end.turn {
                end.row.saturating_add(1).min(h)
            } else {
                h
            };
            if lo >= hi {
                y += h;
                continue;
            }
            if let Some(cache) = cache {
                for seg in &cache.segs {
                    let seg_lo = seg.start.max(lo).max(scroll_y.saturating_sub(y));
                    let seg_hi = (seg.start + seg.height)
                        .min(hi)
                        .min((scroll_y + viewport).saturating_sub(y));
                    if seg_lo >= seg_hi {
                        continue;
                    }
                    for row in seg_lo..seg_hi {
                        let global = y + row;
                        let (x0, x1) = sel_columns(turn_idx, row, &start, &end, content_width);
                        if x0 >= x1 {
                            continue;
                        }
                        let screen_y =
                            clip.y + u16::try_from(global - scroll_y).unwrap_or(u16::MAX);
                        tint_row(buf, clip, content_width, screen_y, x0, x1);
                    }
                }
            }
            y += h;
        }
    }

    /// Borrow a turn slot by selection-space index: committed turns, then
    /// the in-flight turn, then the steered queue.
    fn with_turn<R>(&self, turn_idx: usize, f: impl FnOnce(&TurnData) -> R) -> Option<R> {
        let turns_len = self.turns.borrow().len();
        if turn_idx < turns_len {
            let turns = self.turns.borrow();
            return turns.get(turn_idx).map(f);
        }
        if turn_idx == turns_len {
            let in_flight = self.in_flight.borrow();
            return in_flight.as_ref().map(f);
        }
        let steered = self.steered.borrow();
        steered.get(turn_idx.checked_sub(turns_len + 1)?).map(f)
    }

    fn turn_count(&self) -> usize {
        self.turns.borrow().len()
            + usize::from(self.in_flight.borrow().is_some())
            + self.steered.borrow().len()
    }

    fn turn_height(&self, turn_idx: usize, width: u16) -> u32 {
        self.with_turn(turn_idx, |turn| turn.height(width, self.env_rev))
            .unwrap_or(0)
    }

    /// The content-space position under a terminal cell, `None` outside the
    /// history pane or past the last turn.
    fn sel_pos_at(&self, column: u16, row: u16) -> Option<SelPos> {
        if !self.in_history(column, row) {
            return None;
        }
        let rect = self.history_rect.get();
        let content_y = self.scroll.borrow().offset + u32::from(row - rect.y);
        let width = self.width.get();
        if width == 0 {
            return None;
        }
        let mut start = 0u32;
        for i in 0..self.turn_count() {
            let h = self.turn_height(i, width);
            if content_y < start + h {
                return Some(SelPos {
                    turn: i,
                    row: content_y - start,
                    col: column - rect.x,
                });
            }
            start += h;
        }
        None
    }

    fn handle_mouse(&mut self, kind: MouseKind, column: u16, row: u16) {
        match kind {
            MouseKind::Down => {
                self.clear_selection();
                self.dragging.set(false);
                let Some(pos) = self.sel_pos_at(column, row) else {
                    return;
                };
                if self.escalated_click(pos) {
                    return;
                }
                *self.selection.borrow_mut() = Some(SelRange {
                    anchor: pos,
                    head: pos,
                });
                self.dragging.set(true);
            }
            MouseKind::Drag => {
                if !self.dragging.get() {
                    return;
                }
                if let Some(pos) = self.sel_pos_at(column, row)
                    && let Some(sel) = self.selection.borrow_mut().as_mut()
                {
                    sel.head = pos;
                }
                self.drag_auto_scroll(row);
            }
            MouseKind::Up => {
                if !self.dragging.get() {
                    return;
                }
                self.dragging.set(false);
                let range = *self.selection.borrow();
                let Some(range) = range else { return };
                if range.drag_distance() < CLICK_SLOP {
                    self.clear_selection();
                    self.handle_click(column, row);
                } else if range.ordered().is_some() {
                    self.pending_copy.set(true);
                }
            }
        }
    }

    /// One row of auto-scroll when a drag reaches a viewport edge; the
    /// sticky-bottom state re-engages at the bottom through the next view.
    fn drag_auto_scroll(&self, row: u16) {
        let rect = self.history_rect.get();
        if rect.height == 0 {
            return;
        }
        let mut scroll = self.scroll.borrow_mut();
        if row <= rect.y {
            scroll.offset = scroll.offset.saturating_sub(1);
            scroll.sticky_bottom = false;
        } else if row + 1 >= rect.y + rect.height {
            scroll.offset = scroll.offset.saturating_add(1);
        }
    }

    fn clear_selection(&self) {
        *self.selection.borrow_mut() = None;
        self.pending_copy.set(false);
    }

    /// Escalate a same-cell click inside [`MULTI_CLICK_WINDOW`]: double
    /// selects the word, triple the whole logical row. The selection is
    /// final (dragging stays disarmed, copy is flagged); `true` when the
    /// click was consumed, so a failed resolve falls through to point start.
    fn escalated_click(&self, pos: SelPos) -> bool {
        let now = Instant::now();
        let count = match *self.last_click.borrow() {
            Some((last, at, count))
                if last == pos && now.duration_since(at) <= MULTI_CLICK_WINDOW =>
            {
                (count % 3) + 1
            }
            _ => 1,
        };
        *self.last_click.borrow_mut() = Some((pos, now, count));
        if count == 1 {
            return false;
        }
        let width = self.width.get();
        if width == 0 {
            return false;
        }
        let span = if count >= 3 {
            self.logical_row_range(pos, width)
        } else {
            self.word_range(pos)
        };
        let Some((anchor, head)) = span else {
            return false;
        };
        *self.selection.borrow_mut() = Some(SelRange { anchor, head });
        self.pending_copy.set(true);
        true
    }

    /// Resolve the visual row under `pos` for word/row picking.
    fn resolved_visual_row(&self, pos: SelPos) -> Option<ResolvedRow> {
        let width = self.width.get();
        self.with_turn(pos.turn, |slot| {
            let cache = slot.cache.as_ref()?;
            for seg in &cache.segs {
                if pos.row >= seg.start && pos.row < seg.start + seg.height {
                    return seg.segment.locate_row(pos.row - seg.start, width);
                }
            }
            None
        })
        .flatten()
    }

    /// The whitespace-delimited run of the visual row under `pos`.
    fn word_range(&self, pos: SelPos) -> Option<(SelPos, SelPos)> {
        let resolved = self.resolved_visual_row(pos)?;
        let text = visual_row_text(
            &resolved.line(),
            resolved.text_width,
            resolved.trim,
            resolved.wrap_index,
        );
        let text_col = usize::from(pos.col.saturating_sub(resolved.pad_x));
        let mut hit: Option<(usize, usize)> = None;
        let mut run_start: Option<usize> = None;
        let mut x = 0usize;
        for c in text.chars() {
            let w = unicode_width::UnicodeWidthChar::width(c).unwrap_or(0);
            if c.is_whitespace() {
                if let Some(s) = run_start.take()
                    && text_col >= s
                    && text_col < x
                {
                    hit = Some((s, x));
                    break;
                }
            } else {
                run_start.get_or_insert(x);
            }
            x += w;
        }
        if hit.is_none()
            && let Some(s) = run_start
        {
            hit = Some((s, x));
        }
        let (start, end) = hit?;
        if start >= end {
            return None;
        }
        let anchor = SelPos {
            turn: pos.turn,
            row: pos.row,
            col: resolved.pad_x.saturating_add(start as u16),
        };
        let head = SelPos {
            turn: pos.turn,
            row: pos.row,
            col: resolved.pad_x.saturating_add(end as u16),
        };
        Some((anchor, head))
    }

    /// The full logical row (all wraps) under `pos`, spanning the row's
    /// content range so copy emits the clean logical text.
    fn logical_row_range(&self, pos: SelPos, width: u16) -> Option<(SelPos, SelPos)> {
        let resolved = self.resolved_visual_row(pos)?;
        let first = pos.row.saturating_sub(resolved.wrap_index);
        let last = pos.row.saturating_add(
            resolved
                .wrap_total
                .saturating_sub(1)
                .saturating_sub(resolved.wrap_index),
        );
        let anchor = SelPos {
            turn: pos.turn,
            row: first,
            col: 0,
        };
        let head = SelPos {
            turn: pos.turn,
            row: last,
            col: width,
        };
        Some((anchor, head))
    }

    /// Re-address the selection after the in-flight turn committed: its
    /// index now addresses the committed turn; steered turns shift by one.
    fn remap_after_commit(&self) {
        let in_flight_idx = self.turns.borrow().len().saturating_sub(1);
        if let Some(sel) = self.selection.borrow_mut().as_mut() {
            for pos in [&mut sel.anchor, &mut sel.head] {
                if pos.turn > in_flight_idx {
                    pos.turn += 1;
                }
            }
        }
    }

    /// Re-address the selection after steered[0] was dispatched: turns at
    /// its old index are gone, later steered turns shift down by one.
    fn remap_after_steered_removed(&self) {
        let removed = self.turns.borrow().len() + 1;
        if let Some(sel) = self.selection.borrow_mut().as_mut() {
            for pos in [&mut sel.anchor, &mut sel.head] {
                if pos.turn > removed {
                    pos.turn -= 1;
                }
            }
        }
        self.clear_selection_from(removed);
    }

    /// Drop the selection when it references a turn at or past `from`
    /// (removed steered turn, wiped in-flight, session replacement).
    fn clear_selection_from(&self, from: usize) {
        if self
            .selection
            .borrow()
            .as_ref()
            .is_some_and(|sel| sel.anchor.turn >= from || sel.head.turn >= from)
        {
            self.clear_selection();
        }
    }

    /// Materialize + render a turn on demand from `update` paths (toggle,
    /// click) outside the render loop.
    fn ensure_materialized(&mut self, turn_idx: usize) {
        let marker = {
            let turns = self.turns.borrow();
            match turns.get(turn_idx) {
                Some(slot) if slot.blocks.is_some() => return,
                _ => self.interrupted && !self.streaming && turn_idx + 1 == turns.len(),
            }
        };
        let mut turns = self.turns.borrow_mut();
        let Some(slot) = turns.get_mut(turn_idx) else {
            return;
        };
        if slot.blocks.is_some() {
            return;
        }
        let Some(session) = self.stored.as_ref() else {
            return;
        };
        slot.materialize(
            || materialize_blocks(session, turn_idx),
            &self.toggled,
            turn_idx,
            marker,
        );
    }

    /// Find the still-running block a finish or streamed shell chunk belongs
    /// to and apply it. Both carry the provider's call id when the core could
    /// resolve it, so batched calls of one tool (all `Running` at once — and
    /// their streamed shell output) each land on their own block; the
    /// name+worker match is only a fallback for events without an id.
    fn with_running_tool(
        &mut self,
        name: &str,
        worker: &Option<String>,
        call_id: Option<&str>,
        apply: impl FnOnce(&mut Block) -> bool,
    ) -> bool {
        let is_match = |block: &Block| {
            if !block.tool_is_running() {
                return false;
            }
            let own = block.tool_call_id().unwrap_or_default();
            match call_id.filter(|id| !id.is_empty()) {
                Some(id) if !own.is_empty() => id == own,
                _ => block.tool_matches(name, worker),
            }
        };
        let mut in_flight = self.in_flight.borrow_mut();
        if let Some(turn) = in_flight.as_mut()
            && let Some(blocks) = turn.blocks.as_mut()
            && let Some(block) = blocks.iter_mut().rev().find(|block| is_match(block))
        {
            return apply(block);
        }
        // A finish that arrives after the turn was committed (a worker
        // straggler drained late) still lands on its block in the committed
        // turn; the rev bump forces the cached render to rebuild.
        let mut turns = self.turns.borrow_mut();
        for turn in turns.iter_mut().rev() {
            let Some(blocks) = turn.blocks.as_mut() else {
                continue;
            };
            let Some(block) = blocks.iter_mut().rev().find(|block| is_match(block)) else {
                continue;
            };
            let updated = apply(block);
            if updated {
                turn.rev += 1;
                turn.refresh_est(false);
            }
            return updated;
        }
        false
    }

    fn touch_in_flight(&mut self) {
        if let Some(turn) = self.in_flight.borrow_mut().as_mut() {
            turn.rev += 1;
            turn.refresh_est(false);
        }
    }

    fn commit_done(&mut self) {
        if let Some(mut turn) = self.in_flight.borrow_mut().take() {
            turn.finish_thinking();
            turn.rev += 1;
            turn.refresh_est(false);
            self.turns.borrow_mut().push(turn);
            self.interrupted = false;
            self.remap_after_commit();
        }
        self.streaming = false;
    }

    fn commit_interrupted(&mut self) {
        if let Some(mut turn) = self.in_flight.borrow_mut().take() {
            turn.finish_thinking();
            turn.kill_running_tools();
            let has_content = turn.blocks.as_ref().is_some_and(|blocks| {
                blocks.iter().any(|block| {
                    block.is_text() || matches!(block, Block::Reasoning(_) | Block::Tool(_))
                })
            });
            if has_content {
                self.interrupted = true;
                turn.rev += 1;
                turn.refresh_est(true);
                self.turns.borrow_mut().push(turn);
                self.remap_after_commit();
            } else {
                self.clear_selection_from(self.turns.borrow().len());
            }
        }
        self.streaming = false;
    }

    fn apply_session(&mut self, session: shuvarie_core::Session, scroll: ScrollInit) {
        self.clear_selection();
        let interrupted = session.last_assistant_interrupted();
        let ests = build_turn_ests(&session, interrupted);
        let len = ests.len();
        *self.turns.borrow_mut() = session
            .messages
            .iter()
            .map(|message| message.role)
            .zip(ests)
            .map(|(role, est)| TurnData::lazy(role, est))
            .collect();
        *self.in_flight.borrow_mut() = None;
        let saved_scroll = session.scroll;
        self.stored = Some(session);
        self.stored_len = len;
        self.streaming = false;
        self.interrupted = interrupted;
        self.toggled.clear();
        let mut scroll_state = self.scroll.borrow_mut();
        match scroll {
            ScrollInit::Restore => {
                scroll_state.pending_anchor = None;
                scroll_state.anchor = None;
                scroll_state.sticky_bottom = saved_scroll.sticky;
                if !saved_scroll.sticky {
                    scroll_state.pending_anchor = saved_scroll
                        .anchor
                        .map(|(turn, row)| (turn as usize, row as u32));
                }
            }
            ScrollInit::Keep => {
                if !scroll_state.sticky_bottom {
                    scroll_state.pending_anchor = scroll_state.anchor;
                }
            }
        }
    }

    /// The scroll position to persist when this session is left: the sticky
    /// bottom flag plus, when released from the bottom, the content anchor
    /// the viewport top was last held at (from the most recent frame).
    pub fn scroll_save(&self) -> StoredScroll {
        let scroll = self.scroll.borrow();
        StoredScroll {
            sticky: scroll.sticky_bottom,
            anchor: scroll
                .anchor
                .map(|(turn, row)| (turn as u64, u64::from(row))),
        }
    }

    /// Whether a chat selection is live.
    pub fn has_selection(&self) -> bool {
        self.selection.borrow().is_some()
    }

    /// Text of the active chat selection, copied on demand; `None` when no
    /// selection is live. Fully covered logical rows copy clean logical
    /// text (gutterless code, decorated tool rows); boundary rows copy the
    /// visual fragment the pixels show.
    pub fn selected_text(&self) -> Option<String> {
        let (start, end) = (*self.selection.borrow()).and_then(|r| r.ordered())?;
        let width = self.width.get();
        if width == 0 {
            return None;
        }
        let last = self.turn_count().saturating_sub(1);
        if start.turn > last {
            return None;
        }
        let end_turn = end.turn.min(last);

        let mut out: Vec<Option<String>> = Vec::new();
        let mut group: Option<CopyGroup> = None;
        for turn in start.turn..=end_turn {
            let turn_h = self.turn_height(turn, width);
            if turn_h == 0 {
                continue;
            }
            let lo = if turn == start.turn {
                start.row.min(turn_h - 1)
            } else {
                0
            };
            let hi = if turn == end_turn {
                end.row.min(turn_h - 1)
            } else {
                turn_h - 1
            };
            if lo > hi {
                continue;
            }
            for row in lo..=hi {
                let hit = self.with_turn(turn, |slot| {
                    let cache = slot.cache.as_ref()?;
                    for (seg_idx, seg) in cache.segs.iter().enumerate() {
                        if row >= seg.start && row < seg.start + seg.height {
                            return seg
                                .segment
                                .locate_row(row - seg.start, width)
                                .map(|resolved| (seg_idx, resolved));
                        }
                    }
                    None
                });
                let from = (turn == start.turn && row == start.row).then_some(start.col);
                let to = (turn == end_turn && row == end.row).then_some(end.col);
                let hit = hit.flatten();
                let cols = hit.as_ref().map(|(_, r)| normalize_cols(r, from, to));
                match hit {
                    Some((seg_idx, resolved)) => {
                        let key = (turn, seg_idx, resolved.source_row);
                        let bounds = cols.expect("resolved row carries normalized bounds");
                        match &mut group {
                            Some(g) if g.key == key => g.wraps.push((resolved.wrap_index, bounds)),
                            _ => {
                                if let Some(done) = group.take() {
                                    done.flush(&mut out);
                                }
                                group = Some(CopyGroup {
                                    key,
                                    wraps: vec![(resolved.wrap_index, bounds)],
                                    resolved,
                                });
                            }
                        }
                    }
                    None => {
                        if let Some(done) = group.take() {
                            done.flush(&mut out);
                        }
                        out.push(None);
                    }
                }
            }
        }
        if let Some(done) = group.take() {
            done.flush(&mut out);
        }

        let mut rows: Vec<String> = Vec::new();
        let mut blanks = 0usize;
        for entry in out {
            match entry {
                Some(text) => {
                    for _ in 0..blanks {
                        rows.push(String::new());
                    }
                    blanks = 0;
                    rows.push(text);
                }
                None => blanks += 1,
            }
        }
        if rows.is_empty() {
            None
        } else {
            Some(rows.join("\n"))
        }
    }

    /// Copy-on-select hook: the selection's text once, right after a drag
    /// finalized it, then cleared.
    pub fn take_pending_copy(&self) -> Option<String> {
        if !self.pending_copy.replace(false) {
            return None;
        }
        self.selected_text()
    }

    fn in_history(&self, column: u16, row: u16) -> bool {
        let rect = self.history_rect.get();
        rect.width > 0
            && rect.height > 0
            && column >= rect.x
            && column < rect.x + rect.width
            && row >= rect.y
            && row < rect.y + rect.height
    }

    fn handle_click(&mut self, column: u16, row: u16) {
        if !self.in_history(column, row) {
            return;
        }
        let rect = self.history_rect.get();
        let content_y = self.scroll.borrow().offset + u32::from(row - rect.y);
        let width = self.width.get();
        let env_rev = self.env_rev;
        let mut start = 0u32;
        let mut target = None;
        {
            let turns = self.turns.borrow();
            for slot in turns.iter() {
                let h = slot.height(width, env_rev);
                if content_y < start + h {
                    if let Some(cache) = slot.cache() {
                        let local = content_y - start;
                        target = cache
                            .hits
                            .iter()
                            .find(|region| local >= region.start && local < region.end)
                            .map(|region| region.addr.clone());
                    }
                    break;
                }
                start += h;
            }
        }
        if target.is_none() {
            let in_flight = self.in_flight.borrow();
            if let Some(turn) = in_flight.as_ref() {
                let h = turn.height(width, env_rev);
                if content_y < start + h
                    && let Some(cache) = turn.cache()
                {
                    let local = content_y - start;
                    target = cache
                        .hits
                        .iter()
                        .find(|region| local >= region.start && local < region.end)
                        .map(|region| region.addr.clone());
                }
            }
        }
        if target.is_none() {
            let in_flight_h = self
                .in_flight
                .borrow()
                .as_ref()
                .map_or(0, |turn| turn.height(width, env_rev));
            start += in_flight_h;
            let steered = self.steered.borrow();
            for turn in steered.iter() {
                let h = turn.height(width, env_rev);
                if content_y < start + h {
                    if let Some(cache) = turn.cache() {
                        let local = content_y - start;
                        target = cache
                            .hits
                            .iter()
                            .find(|region| local >= region.start && local < region.end)
                            .map(|region| region.addr.clone());
                    }
                    break;
                }
                start += h;
            }
        }
        if let Some(addr) = target {
            self.toggle_block(addr);
        }
    }

    fn toggle_block(&mut self, addr: BlockAddr) {
        self.clear_selection();
        let turns_len = self.turns.borrow().len();
        if addr.turn < turns_len {
            self.ensure_materialized(addr.turn);
            let mut turns = self.turns.borrow_mut();
            let Some(slot) = turns.get_mut(addr.turn) else {
                return;
            };
            let changed = slot
                .blocks
                .as_mut()
                .and_then(|blocks| blocks.get_mut(addr.block))
                .is_some_and(|block| block.update(BlockMessage::Toggle));
            if changed {
                let expanded = slot
                    .blocks
                    .as_ref()
                    .and_then(|blocks| blocks.get(addr.block))
                    .is_some_and(Block::is_expanded);
                if expanded {
                    self.toggled.insert((addr.turn, addr.block));
                } else {
                    self.toggled.remove(&(addr.turn, addr.block));
                }
                slot.rev += 1;
                slot.refresh_est(self.interrupted && !self.streaming && addr.turn + 1 == turns_len);
            }
        } else if addr.turn == turns_len {
            let mut in_flight = self.in_flight.borrow_mut();
            let Some(turn) = in_flight.as_mut() else {
                return;
            };
            let changed = turn
                .blocks
                .as_mut()
                .and_then(|blocks| blocks.get_mut(addr.block))
                .is_some_and(|block| block.update(BlockMessage::Toggle));
            if changed {
                let expanded = turn
                    .blocks
                    .as_ref()
                    .and_then(|blocks| blocks.get(addr.block))
                    .is_some_and(Block::is_expanded);
                if expanded {
                    self.toggled.insert((addr.turn, addr.block));
                } else {
                    self.toggled.remove(&(addr.turn, addr.block));
                }
                turn.rev += 1;
                turn.refresh_est(false);
            }
        }
    }

    fn toggle_last_tool(&mut self) {
        let turns_len = self.turns.borrow().len();
        let in_flight_tool = {
            let in_flight = self.in_flight.borrow();
            in_flight.as_ref().and_then(|turn| {
                turn.blocks
                    .as_ref()
                    .and_then(|blocks| blocks.iter().rposition(Block::is_tool))
            })
        };
        if let Some(block) = in_flight_tool {
            let addr = BlockAddr {
                turn: turns_len,
                block,
            };
            self.toggle_block(addr);
            return;
        }
        for turn_idx in (0..turns_len).rev() {
            {
                let turns = self.turns.borrow();
                let slot = &turns[turn_idx];
                if slot.blocks.is_none() && slot.est.tool_count == 0 {
                    continue;
                }
            }
            self.ensure_materialized(turn_idx);
            let found = self.turns.borrow()[turn_idx]
                .blocks
                .as_ref()
                .and_then(|blocks| blocks.iter().rposition(Block::is_tool));
            if let Some(block) = found {
                self.toggle_block(BlockAddr {
                    turn: turn_idx,
                    block,
                });
                return;
            }
        }
    }

    /// Evict rendered state for turns far outside the viewport: lazy-backed
    /// turns drop their block models too (re-materializable from the stored
    /// session); live turns keep blocks but drop the render cache.
    fn evict(&self, turns: &mut [TurnData], scroll_y: u32, viewport: u32) {
        let margin = 3 * viewport.max(1);
        let lo = scroll_y.saturating_sub(margin);
        let hi = scroll_y + viewport + margin;
        let width = self.width.get();
        let env_rev = self.env_rev;
        let mut y = 0u32;
        for (i, slot) in turns.iter_mut().enumerate() {
            let h = slot.height(width, env_rev);
            if y + h <= lo || y >= hi {
                if i < self.stored_len {
                    slot.blocks = None;
                }
                slot.cache = None;
            }
            y += h;
        }
    }

    fn render_scrollbar(
        &self,
        frame: &mut Frame<'_>,
        area: Rect,
        scroll_y: u32,
        content_height: u32,
    ) {
        let track_len = area.height as usize;
        if track_len < 2 || content_height <= u32::from(area.height) {
            return;
        }
        let content_len = content_height as usize;
        let viewport_len = area.height as usize;
        let offset = scroll_y as usize;
        let max_offset = content_len - viewport_len;
        let thumb_len = (track_len * viewport_len / content_len).clamp(1, track_len);
        let max_start = track_len - thumb_len;
        let thumb_start = (max_start * offset)
            .checked_div(max_offset)
            .unwrap_or(0)
            .min(max_start);
        let bar_x = area.right().saturating_sub(1);
        let buf = frame.buffer_mut();
        for row in area.top()..area.bottom() {
            let y = row as usize;
            let (symbol, style) = if (thumb_start..thumb_start + thumb_len).contains(&y) {
                ("", theme::accent())
            } else {
                (" ", theme::text_muted())
            };
            let cell = buf.cell_mut((bar_x, row)).expect("bar_x in bounds");
            cell.set_symbol(symbol);
            cell.set_style(Style::new().fg(style));
        }
    }
}

/// Rebuild the turns of a stored session: user/system messages become their
/// single blocks, assistant messages assemble reasoning and text runs at the
/// tool-call positions they streamed at (`after_tool`), the summary marker,
/// and the tool blocks in record order.
fn materialize_blocks(session: &shuvarie_core::Session, idx: usize) -> Vec<Block> {
    let message = &session.messages[idx];
    let mut blocks = Vec::new();
    match message.role {
        Role::User => blocks.push(Block::User(UserPrompt::new(message.content.clone()))),
        Role::System => blocks.push(Block::System(SystemText::new(message.content.clone()))),
        Role::Assistant => {
            let segments: &[ReasoningSegment] = session
                .reasoning
                .get(&(idx as u64))
                .map(Vec::as_slice)
                .unwrap_or_default();
            let text_runs: &[TextSegment] = session
                .text_segments
                .get(&(idx as u64))
                .map(Vec::as_slice)
                .unwrap_or_default();
            let mut seg_i = 0usize;
            let drain_reasoning =
                |blocks: &mut Vec<Block>, seg_i: &mut usize, tools_done: usize| {
                    while let Some(seg) = segments.get(*seg_i)
                        && (seg.after_tool as usize) <= tools_done
                    {
                        blocks.push(Block::Reasoning(ReasoningBlock::finished(
                            seg.text.clone(),
                            seg.duration_ms,
                        )));
                        *seg_i += 1;
                    }
                };
            let mut run_i = 0usize;
            let drain_text = |blocks: &mut Vec<Block>, run_i: &mut usize, tools_done: usize| {
                while let Some(run) = text_runs.get(*run_i)
                    && (run.after_tool as usize) <= tools_done
                {
                    if !run.text.is_empty() {
                        blocks.push(Block::Text(TextBlock::new(run.text.clone())));
                    }
                    *run_i += 1;
                }
            };
            drain_reasoning(&mut blocks, &mut seg_i, 0);
            drain_text(&mut blocks, &mut run_i, 0);
            if session.summaries.contains(&(idx as u64)) {
                blocks.push(Block::Summary);
            }
            for (count, record) in session
                .tool_records
                .iter()
                .filter(|record| record.message_seq as usize == idx)
                .enumerate()
            {
                blocks.push(Block::Tool(Box::new(ToolBlock::from_record(record))));
                drain_reasoning(&mut blocks, &mut seg_i, count + 1);
                drain_text(&mut blocks, &mut run_i, count + 1);
            }
            drain_reasoning(&mut blocks, &mut seg_i, usize::MAX);
            drain_text(&mut blocks, &mut run_i, usize::MAX);
            if text_runs.is_empty() && !message.content.is_empty() {
                blocks.push(Block::Text(TextBlock::new(message.content.clone())));
            }
        }
    }
    blocks
}

/// Precompute the lazy-turn height estimates of a stored session in one pass:
/// tool records are grouped per message so the walk stays linear.
fn build_turn_ests(session: &shuvarie_core::Session, interrupted: bool) -> Vec<TurnEst> {
    let mut by_msg: BTreeMap<u64, Vec<&ToolRecord>> = BTreeMap::new();
    for record in &session.tool_records {
        by_msg.entry(record.message_seq).or_default().push(record);
    }
    let last = session.messages.len().saturating_sub(1);
    session
        .messages
        .iter()
        .enumerate()
        .map(|(idx, message)| {
            let tools: Vec<&ToolRecord> = by_msg.get(&(idx as u64)).cloned().unwrap_or_default();
            let reasoning_count = session.reasoning.get(&(idx as u64)).map_or(0, Vec::len);
            let text_runs: &[TextSegment] = session
                .text_segments
                .get(&(idx as u64))
                .map(Vec::as_slice)
                .unwrap_or_default();
            let summary = session.summaries.contains(&(idx as u64));
            TurnEst::from_session_parts(
                message.role,
                &message.content,
                &tools,
                reasoning_count,
                text_runs,
                summary,
                interrupted && idx == last && message.role == Role::Assistant,
            )
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;
    use shuvarie_core::tool_record::ToolRecord;

    use crate::tui::session::blocks::ReasoningMessage;
    use crate::tui::session::segment::{BLOCK_PADDING, TEXT_PADDING};
    use crate::tui::session::virtualizer::render_turn_cache;

    fn header_text(block: &Block) -> String {
        let Block::Reasoning(reasoning) = block else {
            panic!("not a reasoning block");
        };
        reasoning
            .view(80)
            .first()
            .and_then(|segment| segment.flattened().into_iter().next())
            .map(|line| {
                line.spans
                    .iter()
                    .map(|span| span.content.clone())
                    .collect::<String>()
            })
            .unwrap_or_default()
    }

    fn block_tags(blocks: &[Block]) -> Vec<&'static str> {
        blocks
            .iter()
            .map(|block| match block {
                Block::Reasoning(_) => "R",
                Block::Tool(_) => "T",
                Block::Text(_) => "X",
                Block::User(_) => "U",
                _ => "?",
            })
            .collect()
    }

    fn tool_record(seq: u64) -> ToolRecord {
        ToolRecord {
            name: "read_file".to_string(),
            args_json: "{}".to_string(),
            output: String::new(),
            stderr: String::new(),
            ok: true,
            killed: false,
            worker: None,
            message_id: 1,
            message_seq: seq,
            file_change: None,
            original_content: None,
            new_content: None,
            duration_ms: 0,
        }
    }

    fn draw(chat: &Chat, width: u16, height: u16) -> ratatui::buffer::Buffer {
        draw_at(chat, Rect::new(0, 0, width, height))
    }

    fn draw_at(chat: &Chat, area: Rect) -> ratatui::buffer::Buffer {
        let backend = TestBackend::new(
            area.x.saturating_add(area.width),
            area.y.saturating_add(area.height),
        );
        let mut terminal = Terminal::new(backend).unwrap();
        terminal.draw(|frame| chat.view(frame, area)).unwrap();
        terminal.backend().buffer().clone()
    }

    fn render_turn_lines(chat: &Chat, turn_idx: Option<usize>, width: u16) -> Option<String> {
        let diags = BTreeMap::new();
        let env = ChatEnv {
            lsp_diagnostics: &diags,
            rev: 0,
        };
        let cache = match turn_idx {
            Some(idx) => {
                let turns = chat.turns.borrow();
                let slot = turns.get(idx)?;
                render_turn_cache(
                    slot,
                    idx,
                    TurnFlags {
                        in_flight: false,
                        interrupted_marker: false,
                    },
                    width,
                    &env,
                    0,
                )?
            }
            None => {
                let turn = chat.in_flight.borrow();
                let turn = turn.as_ref()?;
                render_turn_cache(
                    turn,
                    chat.turns.borrow().len(),
                    TurnFlags {
                        in_flight: true,
                        interrupted_marker: false,
                    },
                    width,
                    &env,
                    0,
                )?
            }
        };
        Some(
            cache
                .segs
                .iter()
                .flat_map(|seg| {
                    seg.segment
                        .flattened()
                        .iter()
                        .map(|line| {
                            line.spans
                                .iter()
                                .map(|span| span.content.clone())
                                .collect::<String>()
                        })
                        .collect::<Vec<_>>()
                })
                .collect::<Vec<_>>()
                .join("\n"),
        )
    }

    #[test]
    fn working_placeholder_hidden_while_thinking() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::ReasoningReceived {
            content: "hmm".into(),
        });
        let thinking = render_turn_lines(&chat, None, 80).unwrap();
        assert!(thinking.contains("Thinking..."));
        assert!(
            !thinking.contains("(Working...)"),
            "no placeholder while thinking"
        );

        chat.update(ChatMessage::ToolStarted {
            name: "read_file".into(),
            args: serde_json::json!({}),
            worker: None,
            call_id: None,
        });
        let tool_only = render_turn_lines(&chat, None, 80).unwrap();
        assert!(tool_only.contains("(Working...)"));
    }

    #[test]
    fn thinking_header_shows_spinner_then_thought() {
        let block = ReasoningBlock::new("hmm");
        let thinking = header_text(&Block::Reasoning(block));
        assert!(thinking.contains("Thinking..."), "header: {thinking}");
        assert!(!thinking.contains("Thought"));

        let mut block = ReasoningBlock::new("hmm");
        assert!(block.update(ReasoningMessage::Finish));
        let done = header_text(&Block::Reasoning(block));
        assert!(done.contains("Thought"), "header: {done}");

        let done = header_text(&Block::Reasoning(ReasoningBlock::finished("hmm", 0)));
        assert!(done.contains("Thought"), "reloaded header: {done}");

        let done = header_text(&Block::Reasoning(ReasoningBlock::finished("hmm", 10_300)));
        assert!(done.contains("Thought 10.3s"), "reloaded header: {done}");
    }

    #[test]
    fn text_and_tools_finish_thinking() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::ReasoningReceived {
            content: "first".into(),
        });
        chat.update(ChatMessage::TokenReceived {
            content: "answer".into(),
        });
        let inspect = |chat: &Chat| {
            let in_flight = chat.in_flight.borrow();
            let blocks = in_flight.as_ref().unwrap().blocks.as_deref().unwrap();
            let headers: Vec<String> = blocks
                .iter()
                .filter(|block| matches!(block, Block::Reasoning(_)))
                .map(header_text)
                .collect();
            (block_tags(blocks), headers)
        };
        let (tags, headers) = inspect(&chat);
        assert_eq!(tags, vec!["R", "X"]);
        assert!(headers[0].contains("Thought"));

        chat.update(ChatMessage::ReasoningReceived {
            content: "more".into(),
        });
        chat.update(ChatMessage::ToolStarted {
            name: "read_file".into(),
            args: serde_json::json!({}),
            worker: None,
            call_id: None,
        });
        chat.update(ChatMessage::ReasoningReceived {
            content: "again".into(),
        });
        let (tags, headers) = inspect(&chat);
        assert_eq!(tags, vec!["R", "X", "R", "T", "R"]);
        assert!(headers[0].contains("Thought"));
        assert!(headers[1].contains("Thought"));
        assert!(headers[2].contains("Thinking..."));
    }

    #[test]
    #[ignore]
    fn render_perf_probe() {
        let unit = "## Section\n\nSome prose explaining the next steps in detail.\n\n```rust\nfn main() {\n    let x = compute(42);\n    println!(\"{x}\");\n}\n```\n\n";
        for &text_units in &[10usize, 40, 160] {
            let mut chat = Chat::new();
            chat.update(ChatMessage::BeginUserTurn {
                content: "go".into(),
            });
            for i in 0..40 {
                chat.update(ChatMessage::ToolStarted {
                    name: "read_file".into(),
                    args: serde_json::json!({"path": format!("src/a/long/path/file_{i}.rs")}),
                    worker: Some("explore".into()),
                    call_id: None,
                });
                chat.update(ChatMessage::TokenReceived {
                    content: unit.repeat(2),
                });
                chat.update(ChatMessage::ToolFinished {
                    name: "read_file".into(),
                    ok: true,
                    output: "ok line\n".repeat(400),
                    worker: Some("explore".into()),
                    file_change: None,
                    streams: None,
                    duration_ms: 120,
                    call_id: None,
                });
            }
            chat.update(ChatMessage::TokenReceived {
                content: unit.repeat(text_units),
            });
            let t0 = std::time::Instant::now();
            draw(&chat, 100, 40);
            let cold = t0.elapsed();
            let mut worst = std::time::Duration::ZERO;
            for _ in 0..5 {
                let t1 = std::time::Instant::now();
                chat.update(ChatMessage::SpinnerUpdate);
                draw(&chat, 100, 40);
                worst = worst.max(t1.elapsed());
            }
            eprintln!(
                "text_units={text_units} cold={cold:?} spinner_rebuild_worst={warm:?}",
                warm = worst
            );
        }
    }

    #[test]
    fn commit_done_keeps_running_worker_tool_block() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "go".into(),
        });
        chat.update(ChatMessage::WorkerStarted {
            name: "explore".into(),
            args: serde_json::json!("find it"),
            call_id: None,
        });
        chat.update(ChatMessage::ToolStarted {
            name: "read_file".into(),
            args: serde_json::json!({"path": "x"}),
            worker: Some("explore".into()),
            call_id: None,
        });
        chat.update(ChatMessage::StreamDone);
        assert!(chat.in_flight.borrow().is_none());
        let turns = chat.turns.borrow();
        let blocks = turns.last().unwrap().blocks.as_deref().unwrap();
        let running: Vec<_> = blocks
            .iter()
            .filter(|block| {
                let Block::Tool(tool) = block else {
                    return false;
                };
                tool.is_running()
            })
            .collect();
        assert_eq!(
            running.len(),
            2,
            "running blocks leaked into a committed turn"
        );
    }

    #[test]
    fn late_tool_started_reopens_in_flight_turn() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "go".into(),
        });
        chat.update(ChatMessage::StreamDone);
        assert!(chat.in_flight.borrow().is_none());
        chat.update(ChatMessage::ToolStarted {
            name: "grep".into(),
            args: serde_json::json!({}),
            worker: Some("explore".into()),
            call_id: None,
        });
        assert!(
            chat.in_flight.borrow().is_some(),
            "a late ToolStarted re-created an in-flight turn after commit"
        );
    }

    #[test]
    fn late_tool_finished_finishes_committed_block() {
        // A worker straggler drained after `StreamDone`: the running block
        // lives in the committed turn and must still be finished there.
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "go".into(),
        });
        chat.update(ChatMessage::WorkerStarted {
            name: "explore".into(),
            args: serde_json::json!("find it"),
            call_id: None,
        });
        chat.update(ChatMessage::ToolStarted {
            name: "read_file".into(),
            args: serde_json::json!({"path": "x"}),
            worker: Some("explore".into()),
            call_id: None,
        });
        chat.update(ChatMessage::StreamDone);
        assert!(chat.has_running_tool_blocks());

        let turns = chat.turns.borrow();
        let rev_before = turns.last().unwrap().rev;
        drop(turns);

        chat.update(ChatMessage::ToolFinished {
            name: "read_file".into(),
            ok: true,
            output: "contents".into(),
            worker: Some("explore".into()),
            file_change: None,
            streams: None,
            duration_ms: 120,
            call_id: None,
        });
        assert!(
            chat.has_running_tool_blocks(),
            "the worker call itself is still running"
        );
        let turns = chat.turns.borrow();
        let turn = turns.last().unwrap();
        assert!(
            turn.rev > rev_before,
            "committed turn cache must rebuild after a late finish"
        );
        let blocks = turn.blocks.as_deref().unwrap();
        let Block::Tool(tool) = blocks.last().unwrap() else {
            panic!("expected tool block")
        };
        assert!(!tool.is_running());
    }

    #[test]
    fn running_committed_block_keeps_wake_armed() {
        // The render loop's spinner wake comes from `has_running_tool_blocks`
        // when `busy` is false, so a committed straggler keeps animating.
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "go".into(),
        });
        chat.update(ChatMessage::ToolStarted {
            name: "grep".into(),
            args: serde_json::json!({}),
            worker: None,
            call_id: None,
        });
        assert!(chat.has_running_tool_blocks());
        chat.update(ChatMessage::StreamDone);
        assert!(chat.has_running_tool_blocks(), "straggler stays armed");
        chat.update(ChatMessage::ToolFinished {
            name: "grep".into(),
            ok: true,
            output: "out".into(),
            worker: None,
            file_change: None,
            streams: None,
            duration_ms: 5,
            call_id: None,
        });
        assert!(!chat.has_running_tool_blocks());
        chat.update(ChatMessage::ToolFinished {
            name: "grep".into(),
            ok: true,
            output: "out".into(),
            worker: None,
            file_change: None,
            streams: None,
            duration_ms: 5,
            call_id: None,
        });
        assert!(!chat.has_running_tool_blocks(), "stale finish is a no-op");
    }

    #[test]
    fn batched_same_tool_finishes_land_on_their_own_blocks() {
        // A model can batch several calls of one tool in a single response:
        // rig streams every call's start before any result, so all blocks are
        // running at once. Each finish must land on the block of its own
        // call id — matching by name alone reverses the outputs onto the
        // sibling blocks (the first block would show the newest list).
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "go".into(),
        });
        chat.update(ChatMessage::ToolStarted {
            name: "todo".into(),
            args: serde_json::json!({ "op": "add", "text": "first" }),
            worker: None,
            call_id: Some("call-1".into()),
        });
        chat.update(ChatMessage::ToolStarted {
            name: "todo".into(),
            args: serde_json::json!({ "op": "add", "text": "second" }),
            worker: None,
            call_id: Some("call-2".into()),
        });
        chat.update(ChatMessage::ToolFinished {
            name: "todo".into(),
            ok: true,
            output: "Todos (0/1 done)\n  #1 [ ] first".into(),
            worker: None,
            file_change: None,
            streams: None,
            duration_ms: 1,
            call_id: Some("call-1".into()),
        });
        chat.update(ChatMessage::ToolFinished {
            name: "todo".into(),
            ok: true,
            output: "Todos (0/2 done)\n  #1 [ ] first\n  #2 [ ] second".into(),
            worker: None,
            file_change: None,
            streams: None,
            duration_ms: 1,
            call_id: Some("call-2".into()),
        });
        let text = render_turn_lines(&chat, None, 80).unwrap();
        let first_header = text.find("todo + \"first\"").expect("first header");
        let second_header = text.find("todo + \"second\"").expect("second header");
        assert!(
            first_header < second_header,
            "blocks stay in call order: {text}"
        );
        let one_done = text.find("0/1 done").expect("first list count");
        let two_done = text.find("0/2 done").expect("second list count");
        assert!(
            one_done < two_done,
            "each block shows its own call's snapshot: {text}"
        );
        assert!(
            one_done < second_header,
            "the first block's body precedes the second block: {text}"
        );
    }

    #[test]
    fn concurrent_shell_chunks_stream_into_their_own_blocks() {
        // One agent (here the run_tests worker) runs two `run_shell` calls in
        // one batch: streamed output chunks carry the call id the core
        // resolved, so each lands on its own block — the name+worker match
        // alone would route every chunk to the last-created block.
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "go".into(),
        });
        chat.update(ChatMessage::WorkerStarted {
            name: "run_tests".into(),
            args: serde_json::json!({ "task": "verify" }),
            call_id: Some("w1".into()),
        });
        chat.update(ChatMessage::ToolStarted {
            name: "run_shell".into(),
            args: serde_json::json!({ "command": "cargo test" }),
            worker: Some("run_tests".into()),
            call_id: Some("s1".into()),
        });
        chat.update(ChatMessage::ToolStarted {
            name: "run_shell".into(),
            args: serde_json::json!({ "command": "cargo clippy" }),
            worker: Some("run_tests".into()),
            call_id: Some("s2".into()),
        });
        chat.update(ChatMessage::ToolOutput {
            tool: "run_shell".into(),
            worker: Some("run_tests".into()),
            call_id: Some("s2".into()),
            stdout: "clippy tail".into(),
            stderr: String::new(),
        });
        chat.update(ChatMessage::ToolOutput {
            tool: "run_shell".into(),
            worker: Some("run_tests".into()),
            call_id: Some("s1".into()),
            stdout: "test tail".into(),
            stderr: String::new(),
        });
        let text = render_turn_lines(&chat, None, 80).unwrap();
        let test_block = text
            .find("test tail")
            .expect("the first block got its chunk");
        let clippy_block = text
            .find("clippy tail")
            .expect("the second block got its chunk");
        let test_header = text.find("cargo test").expect("first shell header");
        let clippy_header = text.find("cargo clippy").expect("second shell header");
        assert!(
            test_header < test_block,
            "the first block streams its own output: {text}"
        );
        assert!(
            clippy_header < clippy_block && test_block < clippy_header,
            "the second block streams its own output below the first: {text}"
        );
    }

    #[test]
    fn finish_without_call_id_falls_back_to_name_and_worker() {
        // Shell-output paths (and legacy flows) have no call id; they match
        // by name + worker as before.
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "go".into(),
        });
        chat.update(ChatMessage::ToolStarted {
            name: "run_shell".into(),
            args: serde_json::json!({"command": "ls"}),
            worker: None,
            call_id: None,
        });
        chat.update(ChatMessage::ToolFinished {
            name: "run_shell".into(),
            ok: true,
            output: "exit 0\nout".into(),
            worker: None,
            file_change: None,
            streams: None,
            duration_ms: 3,
            call_id: None,
        });
        let text = render_turn_lines(&chat, None, 80).unwrap();
        assert!(text.contains("out"), "finish landed on the block: {text}");
        assert!(
            text.contains("Took"),
            "finished blocks show the took meta row: {text}"
        );
    }

    #[test]
    fn commit_finishes_thinking() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::ReasoningReceived {
            content: "only thoughts".into(),
        });
        chat.update(ChatMessage::StreamDone);
        let turns = chat.turns.borrow();
        let blocks = turns.last().unwrap().blocks.as_deref().unwrap();
        assert_eq!(block_tags(blocks), vec!["R"]);
        assert!(header_text(&blocks[0]).contains("Thought"));
    }

    #[test]
    fn reload_interleaves_reasoning_between_tool_records() {
        let mut session = shuvarie_core::Session::new();
        session.push_user("do it");
        session.push_assistant("done");
        session.reasoning.insert(
            1,
            vec![
                ReasoningSegment {
                    after_tool: 0,
                    text: "start".to_string(),
                    duration_ms: 0,
                },
                ReasoningSegment {
                    after_tool: 2,
                    text: "after two tools".to_string(),
                    duration_ms: 0,
                },
                ReasoningSegment {
                    after_tool: 9,
                    text: "beyond records".to_string(),
                    duration_ms: 0,
                },
            ],
        );
        session.tool_records = vec![tool_record(1), tool_record(1)];

        let blocks = materialize_blocks(&session, 1);
        assert_eq!(block_tags(&blocks), vec!["R", "T", "T", "R", "R", "X"]);
        assert!(header_text(&blocks[0]).contains("Thought"));
    }

    #[test]
    fn reload_interleaves_text_between_tool_records() {
        let mut session = shuvarie_core::Session::new();
        session.push_user("do it");
        session.push_assistant("start\n\nmid");
        session.text_segments.insert(
            1,
            vec![
                TextSegment {
                    after_tool: 0,
                    text: "start".to_string(),
                },
                TextSegment {
                    after_tool: 2,
                    text: "\n\nmid".to_string(),
                },
            ],
        );
        session.tool_records = vec![tool_record(1), tool_record(1)];

        let blocks = materialize_blocks(&session, 1);
        assert_eq!(
            block_tags(&blocks),
            vec!["X", "T", "T", "X"],
            "text runs sit at their tool gaps; no trailing duplicate"
        );
        assert!(matches!(blocks.last().unwrap(), Block::Text(_)));
    }

    #[test]
    fn reload_keeps_trailing_text_without_segments() {
        let mut session = shuvarie_core::Session::new();
        session.push_user("do it");
        session.push_assistant("all at the end");
        session.tool_records = vec![tool_record(1)];

        let blocks = materialize_blocks(&session, 1);
        assert_eq!(block_tags(&blocks), vec!["T", "X"]);
    }

    #[test]
    fn est_walk_interleaves_text_between_tools() {
        let tools = [tool_record(1), tool_record(1)];
        let runs = [
            TextSegment {
                after_tool: 0,
                text: "before".to_string(),
            },
            TextSegment {
                after_tool: 2,
                text: "between".to_string(),
            },
            TextSegment {
                after_tool: 2,
                text: "after".to_string(),
            },
        ];
        let est = TurnEst::from_session_parts(
            Role::Assistant,
            "before\n\nbetween\n\nafter",
            &tools.iter().collect::<Vec<_>>(),
            0,
            &runs,
            false,
            false,
        );
        assert_eq!(est.tool_count, 2);
        assert_eq!(est.text_lines, 3, "one line per run");
        assert_eq!(
            est.padding_rows,
            2 * 3 * u32::from(TEXT_PADDING.1) + 2 * 2 * u32::from(BLOCK_PADDING.1),
            "padding per text run plus per tool"
        );
    }

    #[test]
    fn est_walk_without_runs_counts_one_text_block() {
        let tools = [tool_record(1)];
        let est = TurnEst::from_session_parts(
            Role::Assistant,
            "reply",
            &tools.iter().collect::<Vec<_>>(),
            0,
            &[],
            false,
            false,
        );
        assert_eq!(est.text_lines, 1);
        assert_eq!(
            est.padding_rows,
            2 * u32::from(TEXT_PADDING.1) + 2 * u32::from(BLOCK_PADDING.1)
        );
    }

    #[test]
    fn diagnostics_only_invalidate_tool_turns() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "check".into(),
        });
        chat.update(ChatMessage::ToolStarted {
            name: "edit_file".into(),
            args: serde_json::json!({}),
            worker: None,
            call_id: None,
        });
        chat.update(ChatMessage::ToolFinished {
            name: "edit_file".into(),
            ok: true,
            output: String::new(),
            worker: None,
            file_change: None,
            streams: None,
            duration_ms: 0,
            call_id: None,
        });
        chat.update(ChatMessage::StreamDone);
        chat.update(ChatMessage::BeginUserTurn {
            content: "plain".into(),
        });
        chat.update(ChatMessage::TokenReceived {
            content: "reply".into(),
        });
        chat.update(ChatMessage::StreamDone);
        draw(&chat, 80, 20);

        chat.update(ChatMessage::LspDiagnostics {
            path: "src/lib.rs".into(),
            diagnostics: vec![],
        });

        let turns = chat.turns.borrow();
        let tool_turn = &turns[1];
        let text_turn = &turns[3];
        assert!(tool_turn.env_relevant);
        assert!(!text_turn.env_relevant);
        assert!(
            !tool_turn.cache.as_ref().unwrap().matches(
                79,
                tool_turn.rev,
                tool_turn.env_relevant,
                chat.env_rev
            ),
            "tool turn cache invalidated by env bump"
        );
        assert!(
            text_turn.cache.as_ref().unwrap().matches(
                79,
                text_turn.rev,
                text_turn.env_relevant,
                chat.env_rev
            ),
            "text turn cache survives env bump"
        );
    }

    #[test]
    fn in_flight_rerender_is_stable() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "make it so".into(),
        });
        chat.update(ChatMessage::TokenReceived {
            content: "hello".into(),
        });
        let first = render_turn_lines(&chat, None, 80).unwrap();

        chat.update(ChatMessage::TokenReceived {
            content: " world".into(),
        });
        let second = render_turn_lines(&chat, None, 80).unwrap();
        assert_ne!(first, second);

        let again = render_turn_lines(&chat, None, 80).unwrap();
        assert_eq!(second, again, "same state renders identically");
    }

    /// A session whose turns render much taller than their O(1) estimates:
    /// single-line tool outputs that wrap over many rows and long reasoning
    /// paragraphs. This is the shape that made estimate↔exact height flapping
    /// visible as scroll jitter.
    fn est_hostile_session(turns: usize) -> shuvarie_core::Session {
        let mut session = shuvarie_core::Session::new();
        for i in 0..turns {
            session.push_user(format!("do task {i}"));
            session.push_assistant(format!("done task {i}"));
            let idx = session.messages.len() as u64 - 1;
            session.reasoning.insert(
                idx,
                vec![ReasoningSegment {
                    after_tool: 0,
                    text: format!("thinking about task {i} ") + &"y".repeat(600),
                    duration_ms: 0,
                }],
            );
            session.tool_records.push(ToolRecord {
                name: "run_shell".to_string(),
                args_json: format!("{{\"command\":\"{}\"}}", "c".repeat(290)),
                output: "x".repeat(1200),
                stderr: String::new(),
                ok: true,
                killed: false,
                worker: None,
                message_id: i as u64,
                message_seq: idx,
                file_change: None,
                original_content: None,
                new_content: None,
                duration_ms: 0,
            });
        }
        session
    }

    #[test]
    fn turn_height_stays_measured_when_cache_invalidated() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::Load {
            session: est_hostile_session(6),
        });
        draw(&chat, 80, 20);
        let measured = chat.turns.borrow()[1].height(79, chat.env_rev);
        let est = chat.turns.borrow()[1].est.height(79);
        assert_ne!(
            measured, est,
            "session must be estimate-hostile for this test"
        );

        chat.update(ChatMessage::LspDiagnostics {
            path: "src/main.rs".into(),
            diagnostics: vec![],
        });
        assert_eq!(
            chat.turns.borrow()[1].height(79, chat.env_rev),
            measured,
            "env bump must not flip the layout height back to the estimate"
        );

        chat.turns.borrow_mut()[1].rev += 1;
        assert_eq!(
            chat.turns.borrow()[1].height(79, chat.env_rev),
            measured,
            "rev bump must not flip the layout height back to the estimate"
        );
    }

    #[test]
    fn wheel_scrolls_only_within_the_history_pane() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::TokenReceived {
            content: "hello".into(),
        });
        draw(&chat, 80, 20);
        let rect = chat.history_rect.get();
        assert!(rect.height > 0, "the history pane is laid out");

        chat.update(ChatMessage::Wheel {
            up: false,
            column: rect.x + 1,
            row: rect.y + 1,
        });
        assert_eq!(chat.scroll.borrow().offset, 3, "wheel-down scrolls 3 rows");

        chat.update(ChatMessage::Wheel {
            up: true,
            column: rect.x + 1,
            row: rect.y + 1,
        });
        assert_eq!(chat.scroll.borrow().offset, 0);
        assert!(
            !chat.scroll.borrow().sticky_bottom,
            "wheel-up disengages sticky like ScrollUp"
        );

        chat.update(ChatMessage::Wheel {
            up: false,
            column: rect.x + rect.width,
            row: rect.y,
        });
        assert_eq!(
            chat.scroll.borrow().offset,
            0,
            "a wheel outside the history pane does not scroll"
        );
    }

    #[test]
    fn scroll_up_sticks_and_anchor_holds_while_streaming() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::Load {
            session: est_hostile_session(30),
        });
        for _ in 0..3000 {
            chat.update(ChatMessage::ScrollDown);
        }
        draw(&chat, 80, 20);
        for _ in 0..10 {
            chat.update(ChatMessage::ScrollUp);
        }
        draw(&chat, 80, 20);
        assert!(
            !chat.scroll.borrow().sticky_bottom,
            "scroll-up disengages sticky"
        );
        let held = chat.scroll.borrow().offset;

        for i in 0..30 {
            chat.update(ChatMessage::TokenReceived {
                content: format!("word{i} "),
            });
            chat.update(ChatMessage::SpinnerUpdate);
            if i % 3 == 0 {
                chat.update(ChatMessage::LspDiagnostics {
                    path: "src/main.rs".into(),
                    diagnostics: vec![],
                });
            }
            draw(&chat, 80, 20);
            let scroll = chat.scroll.borrow();
            assert_eq!(
                scroll.offset, held,
                "frame {i}: anchor must hold the viewport while streaming"
            );
            assert!(
                !scroll.sticky_bottom,
                "frame {i}: streaming must not re-engage sticky"
            );
        }

        for _ in 0..3000 {
            chat.update(ChatMessage::ScrollDown);
        }
        draw(&chat, 80, 20);
        assert!(
            chat.scroll.borrow().sticky_bottom,
            "scrolling back to the bottom re-engages sticky"
        );
    }

    #[test]
    fn scroll_save_round_trips_through_the_persisted_anchor() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::Load {
            session: est_hostile_session(30),
        });
        for _ in 0..3000 {
            chat.update(ChatMessage::ScrollDown);
        }
        draw(&chat, 80, 20);
        for _ in 0..10 {
            chat.update(ChatMessage::ScrollUp);
        }
        draw(&chat, 80, 20);
        let saved = chat.scroll_save();
        assert!(!saved.sticky, "a released viewport saves non-sticky");
        let (turn, row) = saved.anchor.expect("a released viewport saves an anchor");
        let restored_anchor = Some((turn as usize, row as u32));

        let mut reloaded = Chat::new();
        let mut session = est_hostile_session(30);
        session.scroll = StoredScroll {
            sticky: saved.sticky,
            anchor: Some((turn, row)),
        };
        reloaded.update(ChatMessage::Load { session });
        assert!(!reloaded.scroll.borrow().sticky_bottom);
        assert!(
            reloaded.scroll.borrow().anchor.is_none(),
            "loading drops the previous session's anchor"
        );
        draw(&reloaded, 80, 20);
        assert_eq!(
            reloaded.scroll.borrow().anchor,
            restored_anchor,
            "restore lands the viewport top on the saved anchor"
        );
        draw(&reloaded, 80, 20);
        assert_eq!(
            reloaded.scroll.borrow().anchor,
            restored_anchor,
            "the restored anchor holds across frames"
        );
    }

    #[test]
    fn scroll_save_round_trips_sticky_bottom() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::Load {
            session: est_hostile_session(30),
        });
        for _ in 0..10 {
            chat.update(ChatMessage::ScrollUp);
        }
        draw(&chat, 80, 20);
        for _ in 0..3000 {
            chat.update(ChatMessage::ScrollDown);
        }
        draw(&chat, 80, 20);
        let saved = chat.scroll_save();
        assert!(saved.sticky, "the bottom-pinned viewport saves sticky");
        assert!(saved.anchor.is_none());

        let mut reloaded = Chat::new();
        let mut session = est_hostile_session(30);
        session.scroll = saved;
        reloaded.update(ChatMessage::Load { session });
        draw(&reloaded, 80, 20);
        assert!(
            reloaded.scroll.borrow().sticky_bottom,
            "restore re-pins the viewport to the bottom"
        );
    }

    #[test]
    fn fork_keeps_the_scrolled_viewport() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::Load {
            session: est_hostile_session(60),
        });
        for _ in 0..3000 {
            chat.update(ChatMessage::ScrollDown);
        }
        draw(&chat, 80, 20);
        for _ in 0..400 {
            chat.update(ChatMessage::ScrollUp);
        }
        draw(&chat, 80, 20);
        assert!(!chat.scroll.borrow().sticky_bottom);
        let held_anchor = chat.scroll.borrow().anchor;

        chat.update(ChatMessage::Forked {
            session: est_hostile_session(59),
        });
        draw(&chat, 80, 20);
        assert_eq!(
            chat.scroll.borrow().anchor,
            held_anchor,
            "undo keeps the viewport on the same content"
        );
        draw(&chat, 80, 20);
        assert_eq!(
            chat.scroll.borrow().anchor,
            held_anchor,
            "the kept anchor holds across frames"
        );
        assert!(!chat.scroll.borrow().sticky_bottom);
    }

    #[test]
    fn fork_of_the_anchored_turn_clamps_to_the_bottom() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::Load {
            session: est_hostile_session(30),
        });
        for _ in 0..3000 {
            chat.update(ChatMessage::ScrollDown);
        }
        draw(&chat, 80, 20);
        chat.update(ChatMessage::ScrollUp);
        draw(&chat, 80, 20);
        assert!(!chat.scroll.borrow().sticky_bottom);
        let (turn, _) = chat
            .scroll
            .borrow()
            .anchor
            .expect("a released viewport holds an anchor");
        assert!(
            turn >= 57,
            "one scroll-up must reach the final turns for this test"
        );

        chat.update(ChatMessage::Forked {
            session: est_hostile_session(turn / 2),
        });
        draw(&chat, 80, 20);
        assert!(
            chat.scroll.borrow().sticky_bottom,
            "an anchor in the forked-away tail lands at the bottom"
        );
    }

    #[test]
    fn fork_keeps_sticky_bottom() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::Load {
            session: est_hostile_session(30),
        });
        for _ in 0..3000 {
            chat.update(ChatMessage::ScrollDown);
        }
        draw(&chat, 80, 20);
        assert!(chat.scroll.borrow().sticky_bottom);

        chat.update(ChatMessage::Forked {
            session: est_hostile_session(29),
        });
        draw(&chat, 80, 20);
        assert!(
            chat.scroll.borrow().sticky_bottom,
            "undo at the bottom stays pinned to the shortened history"
        );
        assert!(chat.scroll.borrow().anchor.is_none());
    }

    fn session_with_user_turns(count: usize) -> shuvarie_core::Session {
        let mut session = shuvarie_core::Session::new();
        for i in 0..count {
            session.push_user(format!("prompt number {i}"));
            session.push_assistant(format!("reply number {i}"));
        }
        session
    }

    fn session_with_tool_turns(count: usize) -> shuvarie_core::Session {
        let mut session = shuvarie_core::Session::new();
        for i in 0..count {
            session.push_user(format!("do {i}"));
            session.push_assistant(format!("done {i}"));
            session.tool_records.push(ToolRecord {
                name: "read_file".to_string(),
                args_json: format!("{{\"path\":\"f{i}.rs\"}}"),
                output: (0..3)
                    .map(|l| format!("out {i}-{l}"))
                    .collect::<Vec<_>>()
                    .join("\n"),
                stderr: String::new(),
                ok: true,
                killed: false,
                worker: None,
                message_id: i as u64,
                message_seq: (2 * i + 1) as u64,
                file_change: None,
                original_content: None,
                new_content: None,
                duration_ms: 0,
            });
        }
        session
    }

    #[test]
    fn lazy_load_materializes_window_only() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::Load {
            session: session_with_user_turns(60),
        });
        draw(&chat, 80, 20);
        {
            let turns = chat.turns.borrow();
            let materialized = turns.iter().filter(|t| t.blocks.is_some()).count();
            assert!(
                materialized > 0 && materialized < 60,
                "materialized {materialized}"
            );
            assert!(turns.last().unwrap().blocks.is_none());
            assert!(turns.first().unwrap().blocks.is_some());
        }

        for _ in 0..6000 {
            chat.update(ChatMessage::ScrollDown);
        }
        draw(&chat, 80, 20);
        let turns = chat.turns.borrow();
        assert!(
            turns.first().unwrap().blocks.is_none(),
            "top turns evicted after scrolling away"
        );
        assert!(turns.last().unwrap().blocks.is_some());
    }

    #[test]
    fn sticky_bottom_follows_tokens_until_scroll_up() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "hi".into(),
        });
        for i in 0..40 {
            chat.update(ChatMessage::TokenReceived {
                content: format!("line {i}\n"),
            });
        }
        draw(&chat, 80, 10);
        assert!(chat.scroll.borrow().sticky_bottom);
        let bottom = chat.scroll.borrow().offset;
        assert!(bottom > 0, "streaming content exceeds the viewport");

        chat.update(ChatMessage::ScrollUp);
        assert!(!chat.scroll.borrow().sticky_bottom);
        chat.update(ChatMessage::TokenReceived {
            content: "more text\n".into(),
        });
        draw(&chat, 80, 10);
        assert_eq!(chat.scroll.borrow().offset, bottom - 1);
    }

    #[test]
    fn scrollbar_thumb_reaches_track_bottom_when_scrolled_to_bottom() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "hi".into(),
        });
        for i in 0..40 {
            chat.update(ChatMessage::TokenReceived {
                content: format!("line {i}\n"),
            });
        }
        let buf = draw(&chat, 80, 10);
        let bar_x = buf.area().width - 1;
        assert!(
            chat.scroll.borrow().sticky_bottom,
            "streaming keeps the view pinned to the bottom"
        );
        assert_eq!(
            buf[(bar_x, 9)].symbol(),
            "",
            "thumb covers the last track row"
        );
        assert_eq!(buf[(bar_x, 0)].symbol(), " ", "top of the track is empty");
    }

    #[test]
    fn paint_shows_first_prompt_at_top_after_load() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::Load {
            session: session_with_user_turns(10),
        });
        let buf = draw(&chat, 80, 12);
        assert!(
            buf[(0, 0)].symbol() != "",
            "no scrollbar at the top row of the track"
        );
        let row_text: String = (0..60).map(|x| buf[(x, 1)].symbol().to_string()).collect();
        assert!(
            row_text.contains("prompt number 0"),
            "top row shows the first prompt, got: {row_text:?}"
        );
    }

    #[test]
    fn width_change_re_renders_window_at_new_width() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::Load {
            session: session_with_user_turns(60),
        });
        draw(&chat, 80, 20);
        assert!(chat.turns.borrow()[0].cache.as_ref().unwrap().width == 79);
        draw(&chat, 40, 20);
        let turns = chat.turns.borrow();
        assert!(
            turns[0]
                .cache
                .as_ref()
                .is_some_and(|cache| cache.width == 39),
            "window re-rendered at the new width"
        );
        assert!(
            turns.last().unwrap().cache.is_none(),
            "far turns stay unrendered after a width change"
        );
    }

    #[test]
    fn big_expanded_tool_body_paints_visible_tail_when_scrolled() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::ToolStarted {
            name: "grep".into(),
            args: serde_json::json!({ "pattern": "x" }),
            worker: None,
            call_id: None,
        });
        let output: String = (0..500)
            .map(|i| format!("out {i}: payload {i} with filler"))
            .collect::<Vec<_>>()
            .join("\n");
        chat.update(ChatMessage::ToolFinished {
            name: "grep".into(),
            ok: true,
            output,
            worker: None,
            file_change: None,
            streams: None,
            duration_ms: 0,
            call_id: None,
        });
        chat.update(ChatMessage::ToggleLastTool);
        let buf = draw(&chat, 80, 24);
        let row_text = |y: u16| {
            (0..buf.area().width)
                .map(|x| buf[(x, y)].symbol().to_string())
                .collect::<String>()
        };
        assert!(
            (0..buf.area().height).any(|y| row_text(y).contains("out 499:")),
            "tail rows of the sliced body must paint at sticky bottom"
        );
    }

    #[test]
    fn toggle_expansion_survives_eviction() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::Load {
            session: session_with_tool_turns(30),
        });
        for _ in 0..6000 {
            chat.update(ChatMessage::ScrollDown);
        }
        draw(&chat, 80, 20);
        chat.update(ChatMessage::ToggleLastTool);
        let tool_idx = (0..chat.turns.borrow().len())
            .rev()
            .find(|i| {
                chat.turns.borrow()[*i]
                    .blocks
                    .as_ref()
                    .is_some_and(|blocks| blocks.iter().any(Block::is_tool))
            })
            .unwrap();
        let expanded = {
            let turns = chat.turns.borrow();
            let blocks = turns[tool_idx].blocks.as_ref().unwrap();
            let pos = blocks.iter().rposition(Block::is_tool).unwrap();
            blocks[pos].is_expanded()
        };
        assert!(expanded, "toggled tool block is expanded");

        for _ in 0..6000 {
            chat.update(ChatMessage::ScrollUp);
        }
        draw(&chat, 80, 20);
        assert!(
            chat.turns.borrow()[tool_idx].blocks.is_none(),
            "turn evicted while scrolled away"
        );

        for _ in 0..6000 {
            chat.update(ChatMessage::ScrollDown);
        }
        draw(&chat, 80, 20);
        let turns = chat.turns.borrow();
        let blocks = turns[tool_idx].blocks.as_ref().unwrap();
        let pos = blocks.iter().rposition(Block::is_tool).unwrap();
        assert!(
            blocks[pos].is_expanded(),
            "expansion preserved across eviction"
        );
    }

    #[test]
    fn click_toggles_tool_block() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "check".into(),
        });
        chat.update(ChatMessage::ToolStarted {
            name: "read_file".into(),
            args: serde_json::json!({}),
            worker: None,
            call_id: None,
        });
        chat.update(ChatMessage::ToolFinished {
            name: "read_file".into(),
            ok: true,
            output: String::new(),
            worker: None,
            file_change: None,
            streams: None,
            duration_ms: 0,
            call_id: None,
        });

        let buf = draw(&chat, 80, 20);
        let rect = chat.history_rect.get();
        let click_row = (1..buf.area().height).find(|row| buf[(0, *row)].bg == theme::success_bg());
        let Some(row) = click_row else {
            panic!("tool block background not found");
        };
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Down,
            column: rect.x + 5,
            row,
        });
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Up,
            column: rect.x + 5,
            row,
        });
        let expanded = chat
            .in_flight
            .borrow()
            .as_ref()
            .unwrap()
            .blocks
            .as_ref()
            .unwrap()
            .last()
            .map(Block::is_expanded);
        assert_eq!(expanded, Some(true));
    }

    /// The buffer row holding `needle`, searched left to right.
    fn row_with(buf: &ratatui::buffer::Buffer, needle: &str) -> Option<(u16, u16)> {
        for y in 0..buf.area().height {
            for x in 0..buf.area().width {
                let line: String = (x..buf.area().width)
                    .map(|cx| buf[(cx, y)].symbol().to_string())
                    .collect::<String>();
                if let Some(col) = line.find(needle) {
                    return Some((x + col as u16, y));
                }
            }
        }
        None
    }

    #[test]
    fn drag_selects_and_copies_plain_text() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "hello brave world".into(),
        });
        let buf = draw(&chat, 80, 20);
        let (col, row) = row_with(&buf, "hello").expect("prompt text on screen");
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Down,
            column: col,
            row,
        });
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Drag,
            column: col + 1,
            row,
        });
        let (end_col, _) = row_with(&buf, "world").expect("tail on screen");
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Drag,
            column: end_col + "world".len() as u16,
            row,
        });
        assert_eq!(chat.selected_text().as_deref(), Some("hello brave world"));
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Up,
            column: end_col + "world".len() as u16,
            row,
        });
        assert_eq!(chat.selected_text().as_deref(), Some("hello brave world"));
        assert!(chat.take_pending_copy().is_some(), "drag finalized");
        assert!(chat.take_pending_copy().is_none(), "consumed once");
    }

    #[test]
    fn small_drag_is_a_click_without_selection() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "check".into(),
        });
        chat.update(ChatMessage::ToolStarted {
            name: "read_file".into(),
            args: serde_json::json!({}),
            worker: None,
            call_id: None,
        });
        chat.update(ChatMessage::ToolFinished {
            name: "read_file".into(),
            ok: true,
            output: String::new(),
            worker: None,
            file_change: None,
            streams: None,
            duration_ms: 0,
            call_id: None,
        });
        let buf = draw(&chat, 80, 20);
        let Some((col, row)) = (1..buf.area().height)
            .find_map(|row| (buf[(0, row)].bg == theme::success_bg()).then_some((5, row)))
        else {
            panic!("tool block background not found");
        };
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Down,
            column: col,
            row,
        });
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Drag,
            column: col + 1,
            row,
        });
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Up,
            column: col + 1,
            row,
        });
        assert!(chat.selected_text().is_none(), "slop drag stays a click");
        let expanded = chat
            .in_flight
            .borrow()
            .as_ref()
            .unwrap()
            .blocks
            .as_ref()
            .unwrap()
            .last()
            .map(Block::is_expanded);
        assert_eq!(expanded, Some(true));
    }

    #[test]
    fn selection_cleared_on_session_load() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "hello brave world".into(),
        });
        let buf = draw(&chat, 80, 20);
        let (col, row) = row_with(&buf, "hello").expect("prompt text");
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Down,
            column: col,
            row,
        });
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Drag,
            column: col + 10,
            row,
        });
        assert!(chat.selected_text().is_some());
        chat.update(ChatMessage::Load {
            session: shuvarie_core::Session::default(),
        });
        assert!(chat.selected_text().is_none());
    }

    #[test]
    fn drag_across_wrapped_rows_copies_logical_text() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "first words here and some more words that wrap the row width\nsecond line"
                .into(),
        });
        let buf = draw(&chat, 50, 20);
        let Some((col, row)) = row_with(&buf, "first words") else {
            panic!("first line on screen");
        };
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Down,
            column: col,
            row,
        });
        let Some((end_col, end_row)) = row_with(&buf, "second line") else {
            panic!("second line on screen");
        };
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Drag,
            column: end_col + "second line".len() as u16,
            row: end_row,
        });
        assert_eq!(
            chat.selected_text().as_deref(),
            Some("first words here and some more words that wrap the row width\nsecond line")
        );
    }

    #[test]
    fn boundary_drag_copies_visual_fragment() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "alpha beta gamma".into(),
        });
        let buf = draw(&chat, 80, 20);
        let Some((col, row)) = row_with(&buf, "beta") else {
            panic!("text on screen");
        };
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Down,
            column: col,
            row,
        });
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Drag,
            column: col + 4,
            row,
        });
        assert_eq!(chat.selected_text().as_deref(), Some("beta"));
    }

    #[test]
    fn double_click_selects_word() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "alpha beta gamma".into(),
        });
        let buf = draw(&chat, 80, 20);
        let Some((col, row)) = row_with(&buf, "beta") else {
            panic!("text on screen");
        };
        for _ in 0..2 {
            chat.update(ChatMessage::Mouse {
                kind: super::MouseKind::Down,
                column: col,
                row,
            });
        }
        assert_eq!(chat.selected_text().as_deref(), Some("beta"));
    }

    #[test]
    fn triple_click_selects_logical_row() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "alpha beta gamma\nsecond row".into(),
        });
        let buf = draw(&chat, 80, 20);
        let Some((col, row)) = row_with(&buf, "beta") else {
            panic!("text on screen");
        };
        for _ in 0..3 {
            chat.update(ChatMessage::Mouse {
                kind: super::MouseKind::Down,
                column: col,
                row,
            });
        }
        assert_eq!(chat.selected_text().as_deref(), Some("alpha beta gamma"));
    }

    #[test]
    fn fourth_click_starts_a_fresh_point_selection() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "alpha beta gamma".into(),
        });
        let buf = draw(&chat, 80, 20);
        let Some((col, row)) = row_with(&buf, "beta") else {
            panic!("text on screen");
        };
        for _ in 0..4 {
            chat.update(ChatMessage::Mouse {
                kind: super::MouseKind::Down,
                column: col,
                row,
            });
        }
        assert_eq!(chat.selected_text(), None, "count wrapped to point start");
    }

    #[test]
    fn overlay_tints_boundary_row_at_screen_offset() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "alpha beta gamma".into(),
        });
        let clip = Rect::new(10, 2, 80, 20);
        let buf = draw_at(&chat, clip);
        let Some((col, row)) = row_with(&buf, "beta") else {
            panic!("text on screen");
        };
        assert!(col >= clip.x, "text right of the clip origin");
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Down,
            column: col,
            row,
        });
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Drag,
            column: col + 4,
            row,
        });
        let buf = draw_at(&chat, clip);
        let tinted: Vec<u16> = (0..buf.area().width)
            .filter(|&x| buf[(x, row)].bg == theme::selection())
            .collect();
        assert_eq!(
            tinted,
            (col..col + 4).collect::<Vec<_>>(),
            "boundary row tints exactly the selected columns on screen"
        );
    }

    #[test]
    fn overlay_tints_interior_rows_full_width_at_screen_offset() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "alpha beta gamma\nsecond row here".into(),
        });
        let clip = Rect::new(10, 2, 80, 20);
        let buf = draw_at(&chat, clip);
        let Some((col, row)) = row_with(&buf, "beta") else {
            panic!("text on screen");
        };
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Down,
            column: col,
            row,
        });
        let Some((tail_col, tail_row)) = row_with(&buf, "second") else {
            panic!("second row on screen");
        };
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Drag,
            column: tail_col + 3,
            row: tail_row,
        });
        let buf = draw_at(&chat, clip);
        let content = clip.x..clip.x + chat_width_of(clip.width);
        for row in (row + 1)..tail_row {
            for x in 0..buf.area().width {
                assert_eq!(
                    buf[(x, row)].bg == theme::selection(),
                    content.contains(&x),
                    "interior row {row} tints exactly the content width"
                );
            }
        }
    }

    fn chat_width_of(pane_width: u16) -> u16 {
        pane_width.saturating_sub(1)
    }

    #[test]
    fn overlay_tints_only_the_selected_turn() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "first turn".into(),
        });
        chat.update(ChatMessage::StreamDone);
        chat.update(ChatMessage::BeginUserTurn {
            content: "second turn".into(),
        });
        chat.update(ChatMessage::StreamDone);
        let buf = draw(&chat, 80, 20);
        let Some((col, row)) = row_with(&buf, "second") else {
            panic!("second turn on screen");
        };
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Down,
            column: col,
            row,
        });
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Drag,
            column: col + 4,
            row,
        });
        let buf = draw(&chat, 80, 20);
        let Some((_, other_row)) = row_with(&buf, "first") else {
            panic!("first turn on screen");
        };
        for x in 0..buf.area().width {
            assert_ne!(
                buf[(x, other_row)].bg,
                theme::selection(),
                "a turn outside the selection never tints"
            );
        }
    }

    #[test]
    fn overlay_tints_selection_cells() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "alpha beta gamma".into(),
        });
        let buf = draw(&chat, 80, 20);
        let Some((col, row)) = row_with(&buf, "beta") else {
            panic!("text on screen");
        };
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Down,
            column: col,
            row,
        });
        chat.update(ChatMessage::Mouse {
            kind: super::MouseKind::Drag,
            column: col + 4,
            row,
        });
        let buf = draw(&chat, 80, 20);
        let mut tinted = 0usize;
        for x in 0..buf.area().width {
            if buf[(x, row)].bg == theme::selection() {
                tinted += 1;
            }
        }
        assert_eq!(tinted, 4, "boundary row tints exactly the head cols");
    }

    #[test]
    fn bench_spinner_frame_rebuild_cost() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::TokenReceived {
            content: "Exploring the workspace now.".into(),
        });
        let big = {
            let mut s = String::new();
            for i in 0..400 {
                s.push_str(&format!("line {i}: src/module_{i}.rs:12: fn example_{i}(x: &str) -> usize {{ x.len() }}\n"));
            }
            s
        };
        for i in 0..30 {
            chat.update(ChatMessage::ToolStarted {
                name: "read_file".into(),
                args: serde_json::json!({ "path": format!("src/module_{i}.rs") }),
                worker: Some("explore_workspace".into()),
                call_id: Some(format!("call_{i}")),
            });
            chat.update(ChatMessage::ToolFinished {
                name: "read_file".into(),
                ok: true,
                output: big.clone(),
                worker: Some("explore_workspace".into()),
                file_change: None,
                streams: None,
                duration_ms: 12,
                call_id: Some(format!("call_{i}")),
            });
        }
        chat.update(ChatMessage::TokenReceived {
            content: "Here is what I found.".into(),
        });
        chat.update(ChatMessage::ToolStarted {
            name: "run_shell".into(),
            args: serde_json::json!({ "command": "cargo test" }),
            worker: None,
            call_id: Some("call_running".into()),
        });
        let diags = BTreeMap::new();
        let env_rev = 0u64;
        let turns_len = chat.turns.borrow().len();
        {
            let mut turn = chat.in_flight.borrow_mut();
            let turn = turn.as_mut().expect("in-flight turn");
            turn.ensure_cache(
                turns_len,
                100,
                &ChatEnv {
                    lsp_diagnostics: &diags,
                    rev: env_rev,
                },
                env_rev,
                TurnFlags {
                    in_flight: true,
                    interrupted_marker: false,
                },
            );
        }
        let rev_before = chat.in_flight.borrow().as_ref().expect("turn").rev;
        let started = std::time::Instant::now();
        let frames = 20;
        for _ in 0..frames {
            chat.update(ChatMessage::SpinnerUpdate);
            let mut turn = chat.in_flight.borrow_mut();
            let turn = turn.as_mut().expect("in-flight turn");
            turn.ensure_cache(
                turns_len,
                100,
                &ChatEnv {
                    lsp_diagnostics: &diags,
                    rev: env_rev,
                },
                env_rev,
                TurnFlags {
                    in_flight: true,
                    interrupted_marker: false,
                },
            );
            assert!(turn.height(100, env_rev) > 0);
        }
        assert_eq!(
            chat.in_flight.borrow().as_ref().expect("turn").rev,
            rev_before,
            "spinner frames must not invalidate the turn cache"
        );
        let per_frame = started.elapsed() / frames;
        println!("spinner-frame repaint: {per_frame:?} per frame (30 blocks x 16KB output)");
        assert!(
            per_frame < std::time::Duration::from_millis(5),
            "repaint too slow: {per_frame:?}"
        );
    }

    #[test]
    fn bench_streaming_delta_cost() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "start".into(),
        });
        chat.update(ChatMessage::TokenReceived {
            content: "Intro paragraph before the long reply.".into(),
        });
        let diags = BTreeMap::new();
        let env_rev = 0u64;
        let turns_len = 0usize;
        let delta = "some streamed prose line that wraps a couple of times at this width\n";
        let deltas = 400;
        // Realistic streaming: paragraph breaks let the markdown cache commit
        // everything before the open paragraph, so a delta re-renders only
        // that open paragraph.
        let started = std::time::Instant::now();
        for i in 0..deltas {
            let mut content = format!("line {i}: {delta}");
            if i % 4 == 3 {
                content.push('\n');
            }
            chat.update(ChatMessage::TokenReceived { content });
            let mut turn = chat.in_flight.borrow_mut();
            let turn = turn.as_mut().expect("in-flight turn");
            turn.ensure_cache(
                turns_len,
                100,
                &ChatEnv {
                    lsp_diagnostics: &diags,
                    rev: env_rev,
                },
                env_rev,
                TurnFlags {
                    in_flight: true,
                    interrupted_marker: false,
                },
            );
            assert!(turn.height(100, env_rev) > 0);
        }
        let per_delta = started.elapsed() / deltas;
        println!("streaming delta: {per_delta:?} per delta (appended + ensured cache)");
        assert!(
            per_delta < std::time::Duration::from_millis(2),
            "delta too slow: {per_delta:?}"
        );
    }

    #[test]
    fn spinner_tick_repaints_without_invalidation() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::TokenReceived {
            content: "Working on it.".into(),
        });
        chat.update(ChatMessage::ToolStarted {
            name: "run_shell".into(),
            args: serde_json::json!({ "command": "ls" }),
            worker: None,
            call_id: Some("call_1".into()),
        });
        let diags = BTreeMap::new();
        let env = ChatEnv {
            lsp_diagnostics: &diags,
            rev: 0,
        };
        {
            let mut turn = chat.in_flight.borrow_mut();
            let turn = turn.as_mut().expect("in-flight turn");
            turn.ensure_cache(
                0,
                80,
                &env,
                0,
                TurnFlags {
                    in_flight: true,
                    interrupted_marker: false,
                },
            );
        }
        let rev_before;
        let other_lines;
        let tool_line_before;
        {
            let turn = chat.in_flight.borrow();
            let turn = turn.as_ref().expect("in-flight turn");
            let cache = turn.cache().expect("cache");
            assert!(!cache.spinners.is_empty(), "running tool must hold a slot");
            rev_before = turn.rev;
            let slot = cache.spinners[0].seg;
            tool_line_before = cache.segs[slot].segment.flattened()[0]
                .spans
                .iter()
                .map(|span| span.content.clone())
                .collect::<String>();
            other_lines = (0..cache.segs.len())
                .filter(|i| *i != slot)
                .map(|i| cache.segs[i].segment.flattened().len())
                .collect::<Vec<_>>();
        }
        chat.update(ChatMessage::SpinnerUpdate);
        let turn = chat.in_flight.borrow();
        let turn = turn.as_ref().expect("in-flight turn");
        assert_eq!(turn.rev, rev_before, "spinner tick must not bump rev");
        let cache = turn.cache().expect("cache");
        let slot = cache.spinners[0].seg;
        let tool_line = cache.segs[slot].segment.flattened()[0]
            .spans
            .iter()
            .map(|span| span.content.clone())
            .collect::<String>();
        assert_eq!(
            tool_line, tool_line_before,
            "same wall-clock frame: same glyph"
        );
        let other_lines_after: Vec<usize> = (0..cache.segs.len())
            .filter(|i| *i != slot)
            .map(|i| cache.segs[i].segment.flattened().len())
            .collect();
        assert_eq!(other_lines, other_lines_after, "non-spinner segs untouched");
        let glyph = crate::tui::spinner::spinner();
        assert!(
            tool_line.starts_with(glyph.content.as_ref()),
            "tool segment must still render the current spinner glyph: {tool_line:?}"
        );
    }

    fn steered_contents(chat: &Chat) -> Vec<String> {
        chat.steered
            .borrow()
            .iter()
            .map(|turn| {
                let blocks = turn.blocks.as_deref().unwrap();
                let Block::Steered(block) = &blocks[0] else {
                    panic!("not a steered block");
                };
                block
                    .view(80)
                    .into_iter()
                    .flat_map(|segment| segment.flattened())
                    .skip(1)
                    .map(|line| {
                        line.spans
                            .iter()
                            .map(|span| span.content.clone())
                            .collect::<String>()
                    })
                    .collect::<Vec<_>>()
                    .join("\n")
            })
            .collect()
    }

    #[test]
    fn steered_queue_lifecycle() {
        let mut chat = Chat::new();
        assert!(!chat.has_steered());

        chat.update(ChatMessage::SteeredQueued {
            content: "first".into(),
        });
        chat.update(ChatMessage::SteeredQueued {
            content: "second".into(),
        });
        assert_eq!(
            steered_contents(&chat),
            vec!["first".to_string(), "second".into()]
        );

        chat.update(ChatMessage::SteeredDispatched);
        assert_eq!(steered_contents(&chat), vec!["second".to_string()]);

        chat.update(ChatMessage::SteeredRecalled);
        assert!(!chat.has_steered());

        chat.update(ChatMessage::SteeredQueued {
            content: "x".into(),
        });
        chat.update(ChatMessage::SteeredCleared);
        assert!(!chat.has_steered());
    }

    #[test]
    fn steered_entries_render_below_in_flight_turn() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "first prompt".into(),
        });
        chat.update(ChatMessage::TokenReceived {
            content: "streaming answer".into(),
        });
        chat.update(ChatMessage::SteeredQueued {
            content: "queued prompt".into(),
        });
        let buf = draw(&chat, 100, 24);
        let row_text = |y: u16| {
            (0..buf.area().width)
                .map(|x| buf[(x, y)].symbol().to_string())
                .collect::<String>()
        };
        let find = |needle: &str| {
            (0..buf.area().height)
                .map(|y| (y, row_text(y)))
                .find(|(_, text)| text.contains(needle))
                .map(|(y, _)| y)
        };
        let (header, body, stream) = (
            find("steered").expect("steered header should render"),
            find("queued prompt").expect("steered body should render"),
            find("streaming answer").expect("in-flight turn should render"),
        );
        assert!(row_text(header).contains("sends after the current action"));
        assert!(
            body > stream,
            "steered entry renders below the in-flight turn"
        );
    }

    #[test]
    fn interrupted_turn_kills_running_tool_blocks() {
        // The interrupt lands mid-tool: the block must reach a terminal state
        // (killed, keeping its streamed output) instead of vanishing, and the
        // committed turn must stop animating.
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "go".into(),
        });
        chat.update(ChatMessage::ToolStarted {
            name: "run_shell".into(),
            args: serde_json::json!({"command": "sleep 30"}),
            worker: None,
            call_id: None,
        });
        chat.update(ChatMessage::ToolOutput {
            tool: "run_shell".into(),
            worker: None,
            call_id: None,
            stdout: "partial output".into(),
            stderr: String::new(),
        });
        chat.update(ChatMessage::StreamCancelled);

        assert!(chat.in_flight.borrow().is_none());
        assert!(chat.interrupted, "turn committed as interrupted");
        assert!(!chat.has_running_tool_blocks(), "no block animates anymore");
        let turns = chat.turns.borrow();
        let turn = turns.last().unwrap();
        let blocks = turn.blocks.as_deref().unwrap();
        let Block::Tool(tool) = &blocks[0] else {
            panic!("expected the killed tool block");
        };
        assert!(!tool.is_running());
        drop(turns);

        let text = render_turn_lines(&chat, Some(1), 80).unwrap();
        assert!(text.contains(""), "killed marker in the header: {text}");
        assert!(text.contains("killed"), "killed label: {text}");
        assert!(text.contains("partial"), "streamed output kept: {text}");
        assert!(
            text.contains("Took"),
            "killed block shows its duration: {text}"
        );
        assert!(!text.contains("Elapsed "), "the run is over: {text}");
    }

    #[test]
    fn interrupted_text_turn_keeps_thinking_and_text() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "go".into(),
        });
        chat.update(ChatMessage::ReasoningReceived {
            content: "thinking".into(),
        });
        chat.update(ChatMessage::TokenReceived {
            content: "partial reply".into(),
        });
        chat.update(ChatMessage::StreamError {
            error: "boom".into(),
        });
        let text = render_turn_lines(&chat, Some(1), 80).unwrap();
        assert!(text.contains("Thought"), "thinking finalized: {text}");
        assert!(text.contains("partial reply"));
        assert!(!text.contains("Thinking..."), "no frozen thinking header");
        assert!(chat.interrupted);
    }

    #[test]
    fn timeout_killed_shell_finishes_as_killed() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "go".into(),
        });
        chat.update(ChatMessage::ToolStarted {
            name: "run_shell".into(),
            args: serde_json::json!({"command": "cargo build", "timeout_secs": 30}),
            worker: None,
            call_id: None,
        });
        chat.update(ChatMessage::ToolFinished {
            name: "run_shell".into(),
            ok: false,
            output: "timeout 30s:\nsome partial output".into(),
            worker: None,
            file_change: None,
            streams: None,
            duration_ms: 30_100,
            call_id: None,
        });
        let text = render_turn_lines(&chat, None, 80).unwrap();
        assert!(
            text.contains(""),
            "timeout kill shows the stop marker: {text}"
        );
        assert!(
            !text.contains(""),
            "a timeout kill is not a failure: {text}"
        );
        assert!(
            text.contains("timeout 30s"),
            "the timeout label stays: {text}"
        );
    }

    #[test]
    fn shell_exit_failure_stays_failed() {
        let mut chat = Chat::new();
        chat.update(ChatMessage::BeginUserTurn {
            content: "go".into(),
        });
        chat.update(ChatMessage::ToolStarted {
            name: "run_shell".into(),
            args: serde_json::json!({"command": "false"}),
            worker: None,
            call_id: None,
        });
        chat.update(ChatMessage::ToolFinished {
            name: "run_shell".into(),
            ok: false,
            output: "exit 1:\nboom".into(),
            worker: None,
            file_change: None,
            streams: None,
            duration_ms: 12,
            call_id: None,
        });
        let text = render_turn_lines(&chat, None, 80).unwrap();
        assert!(
            text.contains(""),
            "real failure keeps the error marker: {text}"
        );
        assert!(!text.contains(""), "no stop marker on a failure: {text}");
    }
}