lemurclaw-tui 0.0.1

Terminal UI for the lemurclaw AI coding agent
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
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
use super::*;
use crate::tui_internal::bottom_pane::goal_status_indicator_line;
use crate::tui_internal::chatwidget::rate_limits::NUDGE_MODEL_SLUG;
use crate::tui_internal::chatwidget::rate_limits::get_limits_duration;
use lemurclaw_core::app_server_protocol::SpendControlLimitSnapshot;
use pretty_assertions::assert_eq;
use ratatui::backend::TestBackend;
use serial_test::serial;

fn enable_test_ambient_pet(chat: &mut ChatWidget) {
    chat.set_pet_image_support_for_tests(crate::tui_internal::pets::PetImageSupport::Supported(
        crate::tui_internal::pets::ImageProtocol::Kitty,
    ));
    chat.install_test_ambient_pet_for_tests(/*animations_enabled*/ false);
}

fn take_workspace_headline_request_id(
    rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
) -> u64 {
    match rx.try_recv() {
        Ok(AppEvent::RefreshStatusLineWorkspaceHeadline { request_id }) => request_id,
        event => panic!("expected workspace headline refresh, got {event:?}"),
    }
}

/// Receiving a token usage update without usage clears the context indicator.
#[tokio::test]
async fn token_count_none_resets_context_indicator() {
    let (mut chat, _rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;

    let context_window = 13_000;
    let pre_compact_tokens = 12_700;

    handle_token_count(
        &mut chat,
        Some(make_token_info(pre_compact_tokens, context_window)),
    );
    assert_eq!(chat.bottom_pane.context_window_percent(), Some(30));

    handle_token_count(&mut chat, /*info*/ None);
    assert_eq!(chat.bottom_pane.context_window_percent(), None);
}

#[tokio::test]
async fn app_server_cyber_policy_error_renders_dedicated_notice() {
    let (mut chat, mut rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;

    handle_error(
        &mut chat,
        "server fallback message",
        Some(CodexErrorInfo::CyberPolicy),
    );

    let cells = drain_insert_history(&mut rx);
    assert_eq!(cells.len(), 1);
    let rendered = lines_to_single_string(&cells[0]);
    assert!(rendered.contains("This content can't be shown"));
    assert!(rendered.contains("extra caution with cybersecurity requests"));
    assert!(!rendered.contains("server fallback message"));
}

#[tokio::test]
async fn app_server_model_verification_renders_warning() {
    let (mut chat, mut rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;

    handle_model_verification(
        &mut chat,
        vec![AppServerModelVerification::TrustedAccessForCyber],
    );

    let cells = drain_insert_history(&mut rx);
    assert_eq!(cells.len(), 1);
    let rendered = lines_to_single_string(&cells[0]);
    assert!(rendered.contains("multiple flags for possible cybersecurity risk"));
    assert!(rendered.contains("extra safety checks are on"));
    assert!(rendered.contains("Trusted Access for Cyber"));
    assert!(rendered.contains("https://chatgpt.com/cyber"));
}

#[tokio::test]
async fn context_indicator_shows_used_tokens_when_window_unknown() {
    let (mut chat, _rx, _ops) = make_chatwidget_manual(Some("unknown-model")).await;

    chat.config.model_context_window = None;
    let auto_compact_limit = 200_000;
    chat.config.model_auto_compact_token_limit = Some(auto_compact_limit);

    // No model window, so the indicator should fall back to showing tokens used.
    let total_tokens = 106_000;
    let token_usage = TokenUsage {
        total_tokens,
        ..TokenUsage::default()
    };
    let token_info = TokenUsageInfo {
        total_token_usage: token_usage.clone(),
        last_token_usage: token_usage,
        model_context_window: None,
    };

    handle_token_count(&mut chat, Some(token_info));

    assert_eq!(chat.bottom_pane.context_window_percent(), None);
    assert_eq!(
        chat.bottom_pane.context_window_used_tokens(),
        Some(total_tokens)
    );
}

#[tokio::test]
async fn token_usage_update_uses_runtime_context_window() {
    let (mut chat, mut rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;

    chat.config.model_context_window = Some(1_000_000);

    handle_token_count(
        &mut chat,
        Some(make_token_info(
            /*total_tokens*/ 0, /*context_window*/ 950_000,
        )),
    );

    assert_eq!(
        chat.status_line_value_for_item(crate::tui_internal::bottom_pane::StatusLineItem::ContextWindowSize),
        Some("950K window".to_string())
    );
    assert_eq!(chat.bottom_pane.context_window_percent(), Some(100));

    chat.add_status_output(
        /*refreshing_rate_limits*/ false, /*request_id*/ None,
    );

    let cells = drain_insert_history(&mut rx);
    let context_line = cells
        .last()
        .expect("status output inserted")
        .iter()
        .map(|line| {
            line.spans
                .iter()
                .map(|span| span.content.as_ref())
                .collect::<String>()
        })
        .find(|line| line.contains("Context window"))
        .expect("context window line");

    assert!(
        context_line.contains("950K"),
        "expected /status to use runtime context window, got: {context_line}"
    );
    assert!(
        !context_line.contains("1M"),
        "expected /status to avoid raw config context window, got: {context_line}"
    );
}

#[tokio::test]
async fn status_line_git_summary_items_render_values() {
    let (mut chat, _rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.status_line_git_summary = Some(StatusLineGitSummary {
        pull_request: Some(crate::tui_internal::branch_summary::StatusLinePullRequest {
            number: 20_252,
            url: "https://github.com/openai/codex/pull/20252".to_string(),
        }),
        branch_change_stats: Some(crate::tui_internal::branch_summary::GitBranchDiffStats {
            additions: 143,
            deletions: 22,
        }),
    });

    assert_eq!(
        chat.status_line_value_for_item(crate::tui_internal::bottom_pane::StatusLineItem::PullRequestNumber),
        Some("PR #20252".to_string())
    );
    assert_eq!(
        chat.status_line_value_for_item(crate::tui_internal::bottom_pane::StatusLineItem::BranchChanges),
        Some("+143 -22".to_string())
    );
}

#[tokio::test]
async fn raw_output_status_line_value_only_shows_when_enabled() {
    let (mut chat, _rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;

    assert_eq!(
        chat.status_line_value_for_item(crate::tui_internal::bottom_pane::StatusLineItem::RawOutput),
        None
    );

    chat.set_raw_output_mode(/*enabled*/ true);

    assert_eq!(
        chat.status_line_value_for_item(crate::tui_internal::bottom_pane::StatusLineItem::RawOutput),
        Some("raw output".to_string())
    );
}

#[tokio::test]
async fn status_line_branch_changes_render_no_changes() {
    let (mut chat, _rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.status_line_git_summary = Some(StatusLineGitSummary {
        pull_request: None,
        branch_change_stats: Some(crate::tui_internal::branch_summary::GitBranchDiffStats {
            additions: 0,
            deletions: 0,
        }),
    });

    assert_eq!(
        chat.status_line_value_for_item(crate::tui_internal::bottom_pane::StatusLineItem::BranchChanges),
        Some("No changes".to_string())
    );
}

#[tokio::test]
async fn stale_status_line_git_summary_update_is_ignored() {
    let (mut chat, _rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.status_line_git_summary_cwd = Some(PathBuf::from("/expected"));
    chat.status_line_git_summary_pending = true;

    chat.set_status_line_git_summary(
        PathBuf::from("/other"),
        StatusLineGitSummary {
            pull_request: Some(crate::tui_internal::branch_summary::StatusLinePullRequest {
                number: 20_252,
                url: "https://github.com/openai/codex/pull/20252".to_string(),
            }),
            branch_change_stats: Some(crate::tui_internal::branch_summary::GitBranchDiffStats {
                additions: 143,
                deletions: 22,
            }),
        },
    );

    assert!(chat.status_line_git_summary.is_none());
    assert!(!chat.status_line_git_summary_pending);
}

#[tokio::test]
async fn raw_output_mode_can_change_without_inserting_notice() {
    let (mut chat, mut rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;

    chat.set_raw_output_mode(/*enabled*/ true);

    assert!(chat.raw_output_mode());
    assert!(drain_insert_history(&mut rx).is_empty());

    chat.set_raw_output_mode_and_notify(/*enabled*/ false);

    assert!(!chat.raw_output_mode());
    let history = drain_insert_history(&mut rx)
        .iter()
        .map(|lines| lines_to_single_string(lines))
        .collect::<Vec<_>>()
        .join("\n");
    assert!(
        history.contains("Raw output mode off: rich transcript rendering restored."),
        "expected raw output notice, got {history:?}"
    );
}

#[tokio::test]
async fn flush_answer_stream_keeps_default_reflow_for_plain_text_tail() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    let cwd = chat.config.cwd.to_path_buf();

    let mut controller = crate::tui_internal::streaming::controller::StreamController::new(
        Some(80),
        cwd.as_path(),
        HistoryRenderMode::Rich,
    );
    assert!(controller.push("plain response line\n"));
    chat.stream_controller = Some(controller);

    while rx.try_recv().is_ok() {}

    chat.flush_answer_stream_with_separator();

    let mut saw_consolidate = false;
    let mut saw_insert_history = false;
    while let Ok(event) = rx.try_recv() {
        match event {
            AppEvent::InsertHistoryCell(_) => saw_insert_history = true,
            AppEvent::ConsolidateAgentMessage {
                scrollback_reflow,
                deferred_history_cell,
                ..
            } => {
                saw_consolidate = true;
                assert_eq!(
                    scrollback_reflow,
                    crate::tui_internal::app_event::ConsolidationScrollbackReflow::IfResizeReflowRan
                );
                assert!(deferred_history_cell.is_none());
            }
            _ => {}
        }
    }

    assert!(
        saw_consolidate,
        "expected stream finalization to consolidate"
    );
    assert!(
        saw_insert_history,
        "plain text should still insert history before consolidation"
    );
}

#[tokio::test]
async fn flush_answer_stream_requests_scrollback_reflow_for_live_table_tail() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    let cwd = chat.config.cwd.to_path_buf();

    let mut controller = crate::tui_internal::streaming::controller::StreamController::new(
        Some(80),
        cwd.as_path(),
        HistoryRenderMode::Rich,
    );
    controller.push("| Name | Notes |\n");
    controller.push("| --- | --- |\n");
    controller.push("| alpha | tail held until final table render |\n");
    assert!(
        controller.has_live_tail(),
        "expected table holdback to leave a live tail for this regression",
    );
    chat.stream_controller = Some(controller);

    while rx.try_recv().is_ok() {}

    chat.flush_answer_stream_with_separator();

    let mut saw_consolidate = false;
    let mut saw_insert_history = false;
    while let Ok(event) = rx.try_recv() {
        match event {
            AppEvent::InsertHistoryCell(_) => saw_insert_history = true,
            AppEvent::ConsolidateAgentMessage {
                scrollback_reflow,
                deferred_history_cell,
                ..
            } => {
                saw_consolidate = true;
                assert_eq!(
                    scrollback_reflow,
                    crate::tui_internal::app_event::ConsolidationScrollbackReflow::Required
                );
                assert!(
                    deferred_history_cell.is_some(),
                    "live table tail should be staged for consolidation",
                );
            }
            _ => {}
        }
    }

    assert!(
        saw_consolidate,
        "expected stream finalization to consolidate"
    );
    assert!(
        !saw_insert_history,
        "live table tail should not be inserted before canonical reflow"
    );
}

#[tokio::test]
async fn completed_plan_table_tail_skips_provisional_history_insert() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    let cwd = chat.config.cwd.to_path_buf();

    let mut controller = crate::tui_internal::streaming::controller::PlanStreamController::new(
        Some(80),
        cwd.as_path(),
        HistoryRenderMode::Rich,
    );
    controller.push("| Step | Owner |\n");
    controller.push("| --- | --- |\n");
    controller.push("| Verify | Codex |\n");
    assert!(
        controller.has_live_tail(),
        "expected plan table holdback to leave a live tail",
    );
    chat.plan_stream_controller = Some(controller);
    chat.transcript.plan_delta_buffer =
        "| Step | Owner |\n| --- | --- |\n| Verify | Codex |\n".to_string();

    while rx.try_recv().is_ok() {}

    chat.on_plan_item_completed(String::new());

    let mut saw_source_backed_plan = false;
    let mut saw_stream_plan = false;
    let mut rendered_plan = String::new();
    while let Ok(event) = rx.try_recv() {
        if let AppEvent::InsertHistoryCell(cell) = event {
            if cell.as_any().is::<history_cell::ProposedPlanCell>() {
                saw_source_backed_plan = true;
                rendered_plan = lines_to_single_string(&cell.display_lines(/*width*/ 80));
            }
            saw_stream_plan |= cell.as_any().is::<history_cell::ProposedPlanStreamCell>();
        }
    }

    assert!(saw_source_backed_plan, "expected source-backed plan insert");
    assert!(
        rendered_plan.contains(''),
        "expected completed plan table to render with separators, got: {rendered_plan:?}"
    );
    assert!(
        !saw_stream_plan,
        "live plan table tail should not be inserted provisionally"
    );
}

#[tokio::test]
#[cfg_attr(target_os = "windows", ignore = "disabled on windows")]
async fn configured_pet_load_is_deferred_until_after_construction() {
    let (tx_raw, mut rx) = unbounded_channel::<AppEvent>();
    let tx = AppEventSender::new(tx_raw);
    let mut cfg = test_config().await;
    cfg.tui_pet = Some(crate::tui_internal::pets::DEFAULT_PET_ID.to_string());
    crate::tui_internal::pets::write_test_pack(&cfg.codex_home);
    let resolved_model = get_model_offline_for_tests(cfg.model.as_deref());
    let session_telemetry = test_session_telemetry(&cfg, resolved_model.as_str());
    let init = ChatWidgetInit {
        config: cfg.clone(),
        frame_requester: FrameRequester::test_dummy(),
        app_event_tx: tx,
        workspace_command_runner: None,
        initial_user_message: None,
        enhanced_keys_supported: false,
        has_chatgpt_account: false,
        has_codex_backend_auth: false,
        model_catalog: test_model_catalog(&cfg),
        feedback: lemurclaw_core::feedback::CodexFeedback::new(),
        is_first_run: true,
        status_account_display: None,
        runtime_model_provider_base_url: None,
        initial_plan_type: None,
        model: Some(resolved_model),
        startup_tooltip_override: None,
        status_line_invalid_items_warned: Arc::new(AtomicBool::new(false)),
        terminal_title_invalid_items_warned: Arc::new(AtomicBool::new(false)),
        session_telemetry,
    };

    let chat = ChatWidget::new_with_app_event(init);

    assert!(!chat.ambient_pet_image_enabled());
    let event = tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 30), rx.recv())
        .await
        .unwrap()
        .unwrap();
    assert_matches!(
        event,
        AppEvent::ConfiguredPetLoaded { pet_id, result } => {
            assert_eq!(pet_id, crate::tui_internal::pets::DEFAULT_PET_ID);
            assert!(result.unwrap().is_some());
        }
    );
}

#[tokio::test]
async fn prefetch_rate_limits_is_gated_on_chatgpt_auth_provider() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    assert!(!chat.should_prefetch_rate_limits());

    set_chatgpt_auth(&mut chat);
    assert!(chat.should_prefetch_rate_limits());

    chat.config.model_provider.requires_openai_auth = false;
    assert!(!chat.should_prefetch_rate_limits());

    chat.prefetch_rate_limits();
    assert!(!chat.should_prefetch_rate_limits());
}

#[tokio::test]
async fn rate_limit_warnings_emit_thresholds() {
    let mut state = RateLimitWarningState::default();
    let mut warnings: Vec<String> = Vec::new();

    warnings.extend(state.take_warnings(Some(10.0), Some(10079), Some(55.0), Some(299)));
    warnings.extend(state.take_warnings(Some(55.0), Some(10081), Some(10.0), Some(299)));
    warnings.extend(state.take_warnings(Some(10.0), Some(10081), Some(80.0), Some(299)));
    warnings.extend(state.take_warnings(Some(80.0), Some(10081), Some(10.0), Some(299)));
    warnings.extend(state.take_warnings(Some(10.0), Some(10081), Some(95.0), Some(299)));
    warnings.extend(state.take_warnings(Some(95.0), Some(10079), Some(10.0), Some(299)));

    assert_eq!(
        warnings,
        vec![
            String::from(
                "Heads up, you have less than 25% of your 5h limit left. Run /status for a breakdown."
            ),
            String::from(
                "Heads up, you have less than 25% of your weekly limit left. Run /status for a breakdown.",
            ),
            String::from(
                "Heads up, you have less than 5% of your 5h limit left. Run /status for a breakdown."
            ),
            String::from(
                "Heads up, you have less than 5% of your weekly limit left. Run /status for a breakdown.",
            ),
        ],
        "expected one warning per limit for the highest crossed threshold"
    );
}

#[tokio::test]
async fn test_rate_limit_warnings_monthly() {
    let mut state = RateLimitWarningState::default();
    let mut warnings: Vec<String> = Vec::new();

    warnings.extend(state.take_warnings(
        Some(75.0),
        Some(43199),
        /*primary_used_percent*/ None,
        /*primary_window_minutes*/ None,
    ));
    assert_eq!(
        warnings,
        vec![String::from(
            "Heads up, you have less than 25% of your monthly limit left. Run /status for a breakdown.",
        ),],
        "expected one warning per limit for the highest crossed threshold"
    );
}

#[test]
fn rate_limit_duration_labels_only_render_supported_windows() {
    assert_eq!(get_limits_duration(2 * 60), None);
    assert_eq!(get_limits_duration(24 * 60).as_deref(), Some("daily"));
    assert_eq!(
        get_limits_duration(365 * 24 * 60).as_deref(),
        Some("annual")
    );
}

#[tokio::test]
async fn test_rate_limit_warnings_use_generic_fallback_labels() {
    let mut state = RateLimitWarningState::default();

    assert_eq!(
        state.take_warnings(
            /*secondary_used_percent*/ Some(75.0),
            /*secondary_window_minutes*/ None,
            /*primary_used_percent*/ Some(75.0),
            /*primary_window_minutes*/ None,
        ),
        vec![
            String::from(
                "Heads up, you have less than 25% of your secondary usage limit left. Run /status for a breakdown.",
            ),
            String::from(
                "Heads up, you have less than 25% of your usage limit left. Run /status for a breakdown.",
            ),
        ],
    );
}

#[tokio::test]
async fn test_rate_limit_warnings_use_secondary_fallback_for_unsupported_window() {
    let mut state = RateLimitWarningState::default();

    assert_eq!(
        state.take_warnings(
            /*secondary_used_percent*/ Some(75.0),
            /*secondary_window_minutes*/ Some(2 * 60),
            /*primary_used_percent*/ None,
            /*primary_window_minutes*/ None,
        ),
        vec![String::from(
            "Heads up, you have less than 25% of your secondary usage limit left. Run /status for a breakdown.",
        )],
    );
}

#[tokio::test]
async fn status_line_uses_secondary_fallback_for_unsupported_window() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
        limit_id: None,
        limit_name: None,
        primary: None,
        secondary: Some(RateLimitWindow {
            used_percent: 50,
            window_duration_mins: Some(2 * 60),
            resets_at: None,
        }),
        credits: None,
        individual_limit: None,
        plan_type: None,
        spend_control_reached: None,
        rate_limit_reached_type: None,
    }));

    assert_eq!(
        chat.status_line_value_for_item(crate::tui_internal::bottom_pane::StatusLineItem::WeeklyLimit),
        Some("secondary usage 50% left".to_string())
    );
}

#[tokio::test]
async fn status_line_legacy_limit_items_prefer_matching_windows() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
        limit_id: None,
        limit_name: None,
        primary: Some(RateLimitWindow {
            used_percent: 94,
            window_duration_mins: Some(7 * 24 * 60),
            resets_at: None,
        }),
        secondary: Some(RateLimitWindow {
            used_percent: 40,
            window_duration_mins: Some(5 * 60),
            resets_at: None,
        }),
        credits: None,
        individual_limit: None,
        plan_type: None,
        spend_control_reached: None,
        rate_limit_reached_type: None,
    }));

    assert_eq!(
        chat.status_line_value_for_item(crate::tui_internal::bottom_pane::StatusLineItem::FiveHourLimit),
        Some("5h 60% left".to_string())
    );
    assert_eq!(
        chat.status_line_value_for_item(crate::tui_internal::bottom_pane::StatusLineItem::WeeklyLimit),
        Some("weekly 6% left".to_string())
    );
}

#[tokio::test]
async fn status_line_shows_secondary_non_weekly_when_primary_is_weekly() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
        limit_id: None,
        limit_name: None,
        primary: Some(RateLimitWindow {
            used_percent: 94,
            window_duration_mins: Some(7 * 24 * 60),
            resets_at: None,
        }),
        secondary: Some(RateLimitWindow {
            used_percent: 35,
            window_duration_mins: Some(30 * 24 * 60),
            resets_at: None,
        }),
        credits: None,
        individual_limit: None,
        plan_type: None,
        spend_control_reached: None,
        rate_limit_reached_type: None,
    }));

    assert_eq!(
        chat.status_line_value_for_item(crate::tui_internal::bottom_pane::StatusLineItem::FiveHourLimit),
        Some("monthly 65% left".to_string())
    );
    assert_eq!(
        chat.status_line_value_for_item(crate::tui_internal::bottom_pane::StatusLineItem::WeeklyLimit),
        Some("weekly 6% left".to_string())
    );
}

#[tokio::test]
async fn status_line_five_hour_item_omits_weekly_only_limit() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
        limit_id: None,
        limit_name: None,
        primary: Some(RateLimitWindow {
            used_percent: 9,
            window_duration_mins: Some(7 * 24 * 60),
            resets_at: None,
        }),
        secondary: None,
        credits: None,
        individual_limit: None,
        plan_type: None,
        spend_control_reached: None,
        rate_limit_reached_type: None,
    }));

    assert_eq!(
        chat.status_line_value_for_item(crate::tui_internal::bottom_pane::StatusLineItem::FiveHourLimit),
        None
    );
    assert_eq!(
        chat.status_line_value_for_item(crate::tui_internal::bottom_pane::StatusLineItem::WeeklyLimit),
        Some("weekly 91% left".to_string())
    );
}

#[tokio::test]
async fn status_line_single_monthly_primary_omits_weekly_limit_item() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
        limit_id: None,
        limit_name: None,
        primary: Some(RateLimitWindow {
            used_percent: 35,
            window_duration_mins: Some(30 * 24 * 60),
            resets_at: None,
        }),
        secondary: None,
        credits: None,
        individual_limit: None,
        plan_type: None,
        spend_control_reached: None,
        rate_limit_reached_type: None,
    }));

    assert_eq!(
        chat.status_line_value_for_item(crate::tui_internal::bottom_pane::StatusLineItem::FiveHourLimit),
        Some("monthly 65% left".to_string())
    );
    assert_eq!(
        chat.status_line_value_for_item(crate::tui_internal::bottom_pane::StatusLineItem::WeeklyLimit),
        None
    );
}

#[tokio::test]
async fn status_line_secondary_only_non_weekly_limit_omits_primary_limit_item() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
        limit_id: None,
        limit_name: None,
        primary: None,
        secondary: Some(RateLimitWindow {
            used_percent: 35,
            window_duration_mins: Some(30 * 24 * 60),
            resets_at: None,
        }),
        credits: None,
        individual_limit: None,
        plan_type: None,
        spend_control_reached: None,
        rate_limit_reached_type: None,
    }));

    assert_eq!(
        chat.status_line_value_for_item(crate::tui_internal::bottom_pane::StatusLineItem::FiveHourLimit),
        None
    );
    assert_eq!(
        chat.status_line_value_for_item(crate::tui_internal::bottom_pane::StatusLineItem::WeeklyLimit),
        Some("monthly 65% left".to_string())
    );
}

#[tokio::test]
async fn rate_limit_snapshot_keeps_prior_credits_when_missing_from_headers() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
        limit_id: None,
        limit_name: None,
        primary: None,
        secondary: None,
        credits: Some(CreditsSnapshot {
            has_credits: true,
            unlimited: false,
            balance: Some("17.5".to_string()),
        }),
        individual_limit: None,
        plan_type: None,
        spend_control_reached: None,
        rate_limit_reached_type: None,
    }));
    let initial_balance = chat
        .rate_limit_snapshots_by_limit_id
        .get("codex")
        .and_then(|snapshot| snapshot.credits.as_ref())
        .and_then(|credits| credits.balance.as_deref());
    assert_eq!(initial_balance, Some("17.5"));

    chat.on_rolling_rate_limit_snapshot(RateLimitSnapshot {
        limit_id: None,
        limit_name: None,
        primary: Some(RateLimitWindow {
            used_percent: 80,
            window_duration_mins: Some(60),
            resets_at: Some(123),
        }),
        secondary: None,
        credits: None,
        individual_limit: None,
        plan_type: None,
        spend_control_reached: None,
        rate_limit_reached_type: None,
    });

    let display = chat
        .rate_limit_snapshots_by_limit_id
        .get("codex")
        .expect("rate limits should be cached");
    let credits = display
        .credits
        .as_ref()
        .expect("credits should persist when headers omit them");

    assert_eq!(credits.balance.as_deref(), Some("17.5"));
    assert!(!credits.unlimited);
    assert_eq!(
        display.primary.as_ref().map(|window| window.used_percent),
        Some(80.0)
    );
}

#[tokio::test]
async fn rolling_rate_limit_snapshot_preserves_prior_individual_limit() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    let mut usage_limits = snapshot(/*percent*/ 10.0);
    usage_limits.individual_limit = Some(SpendControlLimitSnapshot {
        limit: "25000".to_string(),
        used: "8000".to_string(),
        remaining_percent: 68,
        resets_at: 1_800_000_000,
    });
    chat.on_rate_limit_snapshot(Some(usage_limits));

    chat.on_rolling_rate_limit_snapshot(snapshot(/*percent*/ 20.0));

    let display = chat
        .rate_limit_snapshots_by_limit_id
        .get("codex")
        .expect("rate limits should be cached");
    let individual_limit = display
        .individual_limit
        .as_ref()
        .expect("rolling updates should preserve monthly limits");
    assert_eq!(individual_limit.used, "8,000");
    assert_eq!(individual_limit.limit, "25,000");
    assert_eq!(individual_limit.percent_remaining, 68.0);

    chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 30.0)));
    let display = chat
        .rate_limit_snapshots_by_limit_id
        .get("codex")
        .expect("rate limits should be cached");
    assert!(display.individual_limit.is_none());
}

#[tokio::test]
async fn rate_limit_snapshot_updates_and_retains_plan_type() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
        limit_id: None,
        limit_name: None,
        primary: Some(RateLimitWindow {
            used_percent: 10,
            window_duration_mins: Some(60),
            resets_at: None,
        }),
        secondary: Some(RateLimitWindow {
            used_percent: 5,
            window_duration_mins: Some(300),
            resets_at: None,
        }),
        credits: None,
        individual_limit: None,
        plan_type: Some(PlanType::Plus),
        spend_control_reached: None,
        rate_limit_reached_type: None,
    }));
    assert_eq!(chat.plan_type, Some(PlanType::Plus));

    chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
        limit_id: None,
        limit_name: None,
        primary: Some(RateLimitWindow {
            used_percent: 25,
            window_duration_mins: Some(30),
            resets_at: Some(123),
        }),
        secondary: Some(RateLimitWindow {
            used_percent: 15,
            window_duration_mins: Some(300),
            resets_at: Some(234),
        }),
        credits: None,
        individual_limit: None,
        plan_type: Some(PlanType::Pro),
        spend_control_reached: None,
        rate_limit_reached_type: None,
    }));
    assert_eq!(chat.plan_type, Some(PlanType::Pro));

    chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
        limit_id: None,
        limit_name: None,
        primary: Some(RateLimitWindow {
            used_percent: 30,
            window_duration_mins: Some(60),
            resets_at: Some(456),
        }),
        secondary: Some(RateLimitWindow {
            used_percent: 18,
            window_duration_mins: Some(300),
            resets_at: Some(567),
        }),
        credits: None,
        individual_limit: None,
        plan_type: None,
        spend_control_reached: None,
        rate_limit_reached_type: None,
    }));
    assert_eq!(chat.plan_type, Some(PlanType::Pro));
}

#[tokio::test]
async fn rate_limit_snapshots_keep_separate_entries_per_limit_id() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
        limit_id: Some("codex".to_string()),
        limit_name: Some("codex".to_string()),
        primary: Some(RateLimitWindow {
            used_percent: 20,
            window_duration_mins: Some(300),
            resets_at: Some(100),
        }),
        secondary: None,
        credits: Some(CreditsSnapshot {
            has_credits: true,
            unlimited: false,
            balance: Some("5.00".to_string()),
        }),
        individual_limit: None,
        plan_type: Some(PlanType::Pro),
        spend_control_reached: None,
        rate_limit_reached_type: None,
    }));

    chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
        limit_id: Some("codex_other".to_string()),
        limit_name: Some("codex_other".to_string()),
        primary: Some(RateLimitWindow {
            used_percent: 90,
            window_duration_mins: Some(60),
            resets_at: Some(200),
        }),
        secondary: None,
        credits: None,
        individual_limit: None,
        plan_type: Some(PlanType::Pro),
        spend_control_reached: None,
        rate_limit_reached_type: None,
    }));

    let codex = chat
        .rate_limit_snapshots_by_limit_id
        .get("codex")
        .expect("codex snapshot should exist");
    let other = chat
        .rate_limit_snapshots_by_limit_id
        .get("codex_other")
        .expect("codex_other snapshot should exist");

    assert_eq!(codex.primary.as_ref().map(|w| w.used_percent), Some(20.0));
    assert_eq!(
        codex
            .credits
            .as_ref()
            .and_then(|credits| credits.balance.as_deref()),
        Some("5.00")
    );
    assert_eq!(other.primary.as_ref().map(|w| w.used_percent), Some(90.0));
    assert!(other.credits.is_none());
}

#[tokio::test]
async fn rate_limit_switch_prompt_skips_when_on_lower_cost_model() {
    let (mut chat, _, _) = make_chatwidget_manual(Some(NUDGE_MODEL_SLUG)).await;
    chat.has_chatgpt_account = true;

    chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 95.0)));

    assert!(matches!(
        chat.rate_limit_switch_prompt,
        RateLimitSwitchPromptState::Idle
    ));
}

#[tokio::test]
async fn rate_limit_switch_prompt_skips_non_codex_limit() {
    let (mut chat, _, _) = make_chatwidget_manual(Some("gpt-5")).await;
    chat.has_chatgpt_account = true;

    chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
        limit_id: Some("codex_other".to_string()),
        limit_name: Some("codex_other".to_string()),
        primary: Some(RateLimitWindow {
            used_percent: 95,
            window_duration_mins: Some(60),
            resets_at: None,
        }),
        secondary: None,
        credits: None,
        individual_limit: None,
        plan_type: None,
        spend_control_reached: None,
        rate_limit_reached_type: None,
    }));

    assert!(matches!(
        chat.rate_limit_switch_prompt,
        RateLimitSwitchPromptState::Idle
    ));
}

#[tokio::test]
async fn rate_limit_usage_warnings_follow_workspace_credit_flags() {
    for (credits, should_warn) in [
        (
            CreditsSnapshot {
                has_credits: true,
                unlimited: false,
                balance: None,
            },
            false,
        ),
        (
            CreditsSnapshot {
                has_credits: true,
                unlimited: false,
                balance: Some(String::new()),
            },
            false,
        ),
        (
            CreditsSnapshot {
                has_credits: true,
                unlimited: false,
                balance: Some("0".to_string()),
            },
            false,
        ),
        (
            CreditsSnapshot {
                has_credits: true,
                unlimited: false,
                balance: Some("not-a-number".to_string()),
            },
            false,
        ),
        (
            CreditsSnapshot {
                has_credits: true,
                unlimited: false,
                balance: Some("25.00".to_string()),
            },
            false,
        ),
        (
            CreditsSnapshot {
                has_credits: false,
                unlimited: true,
                balance: None,
            },
            false,
        ),
        (
            CreditsSnapshot {
                has_credits: false,
                unlimited: false,
                balance: Some("25.00".to_string()),
            },
            true,
        ),
    ] {
        let (mut chat, mut rx, _) = make_chatwidget_manual(Some("gpt-5")).await;
        chat.has_chatgpt_account = true;
        let mut rate_limit_snapshot = snapshot(/*percent*/ 95.0);
        rate_limit_snapshot.credits = Some(credits);

        chat.on_rate_limit_snapshot(Some(rate_limit_snapshot));

        assert_eq!(!drain_insert_history(&mut rx).is_empty(), should_warn);
        assert_eq!(
            matches!(
                chat.rate_limit_switch_prompt,
                RateLimitSwitchPromptState::Pending
            ),
            should_warn
        );
        assert_eq!(chat.rate_limit_warnings.primary_index > 0, should_warn);
    }
}

#[tokio::test]
async fn rate_limit_usage_warnings_show_when_authoritative_snapshot_clears_credits() {
    let (mut chat, mut rx, _) = make_chatwidget_manual(Some("gpt-5")).await;
    chat.has_chatgpt_account = true;

    let mut initial_snapshot = snapshot(/*percent*/ 0.0);
    initial_snapshot.credits = Some(CreditsSnapshot {
        has_credits: true,
        unlimited: false,
        balance: None,
    });
    chat.on_rate_limit_snapshot(Some(initial_snapshot));

    chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 95.0)));

    assert!(
        !drain_insert_history(&mut rx).is_empty(),
        "an authoritative snapshot without credits should clear stale credit availability"
    );
    assert!(matches!(
        chat.rate_limit_switch_prompt,
        RateLimitSwitchPromptState::Pending
    ));
}

#[tokio::test]
async fn rate_limit_switch_prompt_clears_pending_when_workspace_credits_become_usable() {
    let (mut chat, _, _) = make_chatwidget_manual(Some("gpt-5")).await;
    chat.has_chatgpt_account = true;

    chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 95.0)));
    assert!(matches!(
        chat.rate_limit_switch_prompt,
        RateLimitSwitchPromptState::Pending
    ));

    let mut funded_snapshot = snapshot(/*percent*/ 95.0);
    funded_snapshot.credits = Some(CreditsSnapshot {
        has_credits: true,
        unlimited: false,
        balance: None,
    });
    chat.on_rate_limit_snapshot(Some(funded_snapshot));

    assert!(matches!(
        chat.rate_limit_switch_prompt,
        RateLimitSwitchPromptState::Idle
    ));
}

#[tokio::test]
async fn rate_limit_switch_prompt_dismisses_shown_when_workspace_credits_become_usable() {
    let (mut chat, _, _) = make_chatwidget_manual(Some("gpt-5")).await;
    chat.has_chatgpt_account = true;

    chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 95.0)));
    chat.maybe_show_pending_rate_limit_prompt();
    assert!(matches!(
        chat.rate_limit_switch_prompt,
        RateLimitSwitchPromptState::Shown
    ));
    assert!(!chat.bottom_pane.no_modal_or_popup_active());

    let mut funded_snapshot = snapshot(/*percent*/ 95.0);
    funded_snapshot.credits = Some(CreditsSnapshot {
        has_credits: true,
        unlimited: false,
        balance: None,
    });
    chat.on_rate_limit_snapshot(Some(funded_snapshot));

    assert!(matches!(
        chat.rate_limit_switch_prompt,
        RateLimitSwitchPromptState::Shown
    ));
    assert!(chat.bottom_pane.no_modal_or_popup_active());

    chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 0.0)));
    chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 95.0)));
    chat.maybe_show_pending_rate_limit_prompt();

    assert!(matches!(
        chat.rate_limit_switch_prompt,
        RateLimitSwitchPromptState::Shown
    ));
    assert!(chat.bottom_pane.no_modal_or_popup_active());
}

#[tokio::test]
async fn rate_limit_usage_warnings_preserve_workspace_limit_for_sparse_snapshots() {
    for rate_limit_reached_type in [
        RateLimitReachedType::WorkspaceOwnerCreditsDepleted,
        RateLimitReachedType::WorkspaceMemberCreditsDepleted,
        RateLimitReachedType::WorkspaceOwnerUsageLimitReached,
        RateLimitReachedType::WorkspaceMemberUsageLimitReached,
    ] {
        let (mut chat, mut rx, _) = make_chatwidget_manual(Some("gpt-5")).await;
        chat.has_chatgpt_account = true;

        let mut blocked_snapshot = snapshot(/*percent*/ 0.0);
        blocked_snapshot.credits = Some(CreditsSnapshot {
            has_credits: true,
            unlimited: false,
            balance: None,
        });
        blocked_snapshot.rate_limit_reached_type = Some(rate_limit_reached_type);
        chat.on_rate_limit_snapshot(Some(blocked_snapshot));

        chat.on_rolling_rate_limit_snapshot(snapshot(/*percent*/ 95.0));

        assert!(
            !drain_insert_history(&mut rx).is_empty(),
            "an explicit workspace hard stop should keep proactive usage warnings enabled"
        );
        assert!(matches!(
            chat.rate_limit_switch_prompt,
            RateLimitSwitchPromptState::Pending
        ));
    }
}

#[tokio::test]
async fn rate_limit_usage_warnings_keep_workspace_limit_after_rolling_credits() {
    for rate_limit_reached_type in [
        RateLimitReachedType::WorkspaceOwnerCreditsDepleted,
        RateLimitReachedType::WorkspaceMemberCreditsDepleted,
        RateLimitReachedType::WorkspaceOwnerUsageLimitReached,
        RateLimitReachedType::WorkspaceMemberUsageLimitReached,
    ] {
        for credits in [
            CreditsSnapshot {
                has_credits: true,
                unlimited: false,
                balance: None,
            },
            CreditsSnapshot {
                has_credits: true,
                unlimited: false,
                balance: Some(String::new()),
            },
            CreditsSnapshot {
                has_credits: true,
                unlimited: false,
                balance: Some("25.00".to_string()),
            },
            CreditsSnapshot {
                has_credits: true,
                unlimited: false,
                balance: Some("0".to_string()),
            },
            CreditsSnapshot {
                has_credits: true,
                unlimited: false,
                balance: Some("not-a-number".to_string()),
            },
            CreditsSnapshot {
                has_credits: false,
                unlimited: true,
                balance: None,
            },
        ] {
            let (mut chat, mut rx, _) = make_chatwidget_manual(Some("gpt-5")).await;
            chat.has_chatgpt_account = true;

            let mut blocked_snapshot = snapshot(/*percent*/ 0.0);
            blocked_snapshot.credits = Some(CreditsSnapshot {
                has_credits: true,
                unlimited: false,
                balance: None,
            });
            blocked_snapshot.rate_limit_reached_type = Some(rate_limit_reached_type);
            chat.on_rolling_rate_limit_snapshot(blocked_snapshot);

            let mut rolling_snapshot = snapshot(/*percent*/ 95.0);
            rolling_snapshot.credits = Some(credits);
            chat.on_rolling_rate_limit_snapshot(rolling_snapshot);

            assert!(
                !drain_insert_history(&mut rx).is_empty(),
                "usable rolling workspace credits must not suppress an existing workspace hard stop"
            );
            assert!(matches!(
                chat.rate_limit_switch_prompt,
                RateLimitSwitchPromptState::Pending
            ));
            assert_eq!(
                chat.codex_rate_limit_reached_type,
                Some(rate_limit_reached_type)
            );
        }
    }
}

#[tokio::test]
async fn rate_limit_usage_warnings_keep_explicit_rolling_workspace_limit() {
    for rate_limit_reached_type in [
        RateLimitReachedType::WorkspaceOwnerCreditsDepleted,
        RateLimitReachedType::WorkspaceMemberCreditsDepleted,
        RateLimitReachedType::WorkspaceOwnerUsageLimitReached,
        RateLimitReachedType::WorkspaceMemberUsageLimitReached,
    ] {
        for spend_control_reached in [None, Some(false)] {
            let (mut chat, mut rx, _) = make_chatwidget_manual(Some("gpt-5")).await;
            chat.has_chatgpt_account = true;

            let mut rolling_snapshot = snapshot(/*percent*/ 95.0);
            rolling_snapshot.credits = Some(CreditsSnapshot {
                has_credits: true,
                unlimited: false,
                balance: None,
            });
            rolling_snapshot.rate_limit_reached_type = Some(rate_limit_reached_type);
            rolling_snapshot.spend_control_reached = spend_control_reached;
            chat.on_rolling_rate_limit_snapshot(rolling_snapshot);

            assert!(
                !drain_insert_history(&mut rx).is_empty(),
                "an explicit rolling workspace hard stop should keep proactive usage warnings enabled"
            );
            assert!(matches!(
                chat.rate_limit_switch_prompt,
                RateLimitSwitchPromptState::Pending
            ));
            assert_eq!(
                chat.codex_rate_limit_reached_type,
                Some(rate_limit_reached_type)
            );
        }
    }
}

#[tokio::test]
async fn rate_limit_usage_warnings_keep_newly_reached_workspace_limit() {
    for (limit_id, should_warn) in [("codex", true), ("codex_other", false)] {
        let (mut chat, mut rx, _) = make_chatwidget_manual(Some("gpt-5")).await;
        chat.has_chatgpt_account = true;

        let mut initial_snapshot = snapshot(/*percent*/ 0.0);
        initial_snapshot.credits = Some(CreditsSnapshot {
            has_credits: true,
            unlimited: false,
            balance: None,
        });
        initial_snapshot.spend_control_reached = Some(false);
        chat.on_rate_limit_snapshot(Some(initial_snapshot));

        let mut capped_snapshot = snapshot(/*percent*/ 95.0);
        capped_snapshot.limit_id = Some(limit_id.to_string());
        capped_snapshot.credits = Some(CreditsSnapshot {
            has_credits: true,
            unlimited: false,
            balance: None,
        });
        capped_snapshot.rate_limit_reached_type =
            Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached);
        chat.on_rolling_rate_limit_snapshot(capped_snapshot);

        assert_eq!(!drain_insert_history(&mut rx).is_empty(), should_warn);
        assert_eq!(
            matches!(
                chat.rate_limit_switch_prompt,
                RateLimitSwitchPromptState::Pending
            ),
            should_warn
        );
        assert_eq!(
            chat.codex_rate_limit_reached_type,
            Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached)
        );

        chat.on_rate_limit_error(
            RateLimitErrorKind::UsageLimit,
            "Usage limit reached.".to_string(),
        );
        let popup = render_bottom_popup(&chat, /*width*/ 100);
        assert!(popup.contains("Request a limit increase from your owner"));
    }
}

#[tokio::test]
async fn rate_limit_usage_warnings_preserve_and_clear_spend_control_state() {
    let (mut chat, mut rx, _) = make_chatwidget_manual(Some("gpt-5")).await;
    chat.has_chatgpt_account = true;

    let mut blocked_snapshot = snapshot(/*percent*/ 0.0);
    blocked_snapshot.credits = Some(CreditsSnapshot {
        has_credits: true,
        unlimited: false,
        balance: None,
    });
    blocked_snapshot.spend_control_reached = Some(true);
    blocked_snapshot.rate_limit_reached_type =
        Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached);
    chat.on_rate_limit_snapshot(Some(blocked_snapshot));
    assert_eq!(chat.codex_spend_control_reached, Some(true));

    chat.on_rolling_rate_limit_snapshot(snapshot(/*percent*/ 95.0));
    assert!(
        !drain_insert_history(&mut rx).is_empty(),
        "a sparse rolling snapshot should preserve a reached spend control"
    );
    assert!(matches!(
        chat.rate_limit_switch_prompt,
        RateLimitSwitchPromptState::Pending
    ));
    assert_eq!(chat.codex_spend_control_reached, Some(true));

    let mut recovered_snapshot = snapshot(/*percent*/ 95.0);
    recovered_snapshot.credits = Some(CreditsSnapshot {
        has_credits: true,
        unlimited: false,
        balance: None,
    });
    recovered_snapshot.spend_control_reached = Some(false);
    chat.on_rolling_rate_limit_snapshot(recovered_snapshot);

    assert!(drain_insert_history(&mut rx).is_empty());
    assert!(matches!(
        chat.rate_limit_switch_prompt,
        RateLimitSwitchPromptState::Pending
    ));
    assert_eq!(chat.codex_spend_control_reached, Some(false));
    assert_eq!(
        chat.codex_rate_limit_reached_type,
        Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached)
    );

    chat.on_rolling_rate_limit_snapshot(snapshot(/*percent*/ 95.0));
    assert!(
        drain_insert_history(&mut rx).is_empty(),
        "a later sparse rolling snapshot should not clear an existing workspace hard stop"
    );
    assert!(matches!(
        chat.rate_limit_switch_prompt,
        RateLimitSwitchPromptState::Pending
    ));
    assert_eq!(chat.codex_spend_control_reached, Some(false));
    assert_eq!(
        chat.codex_rate_limit_reached_type,
        Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached)
    );
}

#[tokio::test]
async fn rolling_credits_preserve_depleted_workspace_error_routing() {
    let (mut chat, mut rx, _) = make_chatwidget_manual(Some("gpt-5")).await;
    chat.has_chatgpt_account = true;

    let mut blocked_snapshot = snapshot(/*percent*/ 0.0);
    blocked_snapshot.rate_limit_reached_type =
        Some(RateLimitReachedType::WorkspaceMemberCreditsDepleted);
    chat.on_rate_limit_snapshot(Some(blocked_snapshot));

    let mut rolling_snapshot = snapshot(/*percent*/ 95.0);
    rolling_snapshot.credits = Some(CreditsSnapshot {
        has_credits: true,
        unlimited: false,
        balance: Some("0".to_string()),
    });
    rolling_snapshot.spend_control_reached = Some(false);
    chat.on_rolling_rate_limit_snapshot(rolling_snapshot);

    assert!(!drain_insert_history(&mut rx).is_empty());
    assert!(matches!(
        chat.rate_limit_switch_prompt,
        RateLimitSwitchPromptState::Pending
    ));
    assert_eq!(
        chat.codex_rate_limit_reached_type,
        Some(RateLimitReachedType::WorkspaceMemberCreditsDepleted)
    );

    chat.on_rate_limit_error(
        RateLimitErrorKind::Generic,
        "Usage limit reached.".to_string(),
    );
    let popup = render_bottom_popup(&chat, /*width*/ 100);
    assert!(
        popup.contains("Ask your workspace owner to add more"),
        "popup: {popup}"
    );
}

#[tokio::test]
async fn rate_limit_usage_warnings_clear_workspace_limit_from_authoritative_snapshot() {
    let (mut chat, mut rx, _) = make_chatwidget_manual(Some("gpt-5")).await;
    chat.has_chatgpt_account = true;

    let mut blocked_snapshot = snapshot(/*percent*/ 0.0);
    blocked_snapshot.credits = Some(CreditsSnapshot {
        has_credits: true,
        unlimited: false,
        balance: None,
    });
    blocked_snapshot.rate_limit_reached_type =
        Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached);
    chat.on_rate_limit_snapshot(Some(blocked_snapshot));

    let mut recovered_snapshot = snapshot(/*percent*/ 0.0);
    recovered_snapshot.credits = Some(CreditsSnapshot {
        has_credits: true,
        unlimited: false,
        balance: None,
    });
    chat.on_rate_limit_snapshot(Some(recovered_snapshot));
    chat.on_rolling_rate_limit_snapshot(snapshot(/*percent*/ 95.0));

    assert!(
        drain_insert_history(&mut rx).is_empty(),
        "an authoritative recovery should prevent sparse updates from restoring a stale limit"
    );
    assert!(matches!(
        chat.rate_limit_switch_prompt,
        RateLimitSwitchPromptState::Idle
    ));
    assert_eq!(chat.codex_rate_limit_reached_type, None);
}

#[tokio::test]
async fn rate_limit_switch_prompt_shows_once_per_session() {
    let (mut chat, _, _) = make_chatwidget_manual(Some("gpt-5")).await;
    chat.has_chatgpt_account = true;

    chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 90.0)));
    assert!(
        chat.rate_limit_warnings.primary_index >= 1,
        "warnings not emitted"
    );
    chat.maybe_show_pending_rate_limit_prompt();
    assert!(matches!(
        chat.rate_limit_switch_prompt,
        RateLimitSwitchPromptState::Shown
    ));

    chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 95.0)));
    assert!(matches!(
        chat.rate_limit_switch_prompt,
        RateLimitSwitchPromptState::Shown
    ));
}

#[tokio::test]
async fn account_update_clears_derived_usage_limit_state_and_prompt() {
    let (mut chat, _, _) = make_chatwidget_manual(Some("gpt-5")).await;
    set_chatgpt_auth(&mut chat);
    let mut limits = snapshot(/*percent*/ 95.0);
    limits.rate_limit_reached_type = Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached);
    limits.spend_control_reached = Some(true);
    chat.on_rate_limit_snapshot(Some(limits));
    chat.maybe_show_pending_rate_limit_prompt();

    assert!(chat.rate_limit_warnings.primary_index > 0);
    assert!(chat.codex_rate_limit_reached_type.is_some());
    assert_eq!(chat.codex_spend_control_reached, Some(true));
    assert!(matches!(
        chat.rate_limit_switch_prompt,
        RateLimitSwitchPromptState::Shown
    ));
    assert!(!chat.bottom_pane.no_modal_or_popup_active());

    chat.update_account_state(
        /*status_account_display*/ None, /*plan_type*/ None,
        /*has_chatgpt_account*/ true, /*has_codex_backend_auth*/ true,
    );

    assert_eq!(chat.rate_limit_warnings.primary_index, 0);
    assert_eq!(chat.rate_limit_warnings.secondary_index, 0);
    assert_eq!(chat.codex_rate_limit_reached_type, None);
    assert_eq!(chat.codex_spend_control_reached, None);
    assert!(matches!(
        chat.rate_limit_switch_prompt,
        RateLimitSwitchPromptState::Idle
    ));
    assert!(chat.rate_limit_snapshots_by_limit_id.is_empty());
    assert!(chat.bottom_pane.no_modal_or_popup_active());
}

#[tokio::test]
async fn rate_limit_switch_prompt_respects_hidden_notice() {
    let (mut chat, _, _) = make_chatwidget_manual(Some("gpt-5")).await;
    chat.has_chatgpt_account = true;
    chat.config.notices.hide_rate_limit_model_nudge = Some(true);

    chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 95.0)));

    assert!(matches!(
        chat.rate_limit_switch_prompt,
        RateLimitSwitchPromptState::Idle
    ));
}

#[tokio::test]
async fn rate_limit_switch_prompt_defers_until_task_complete() {
    let (mut chat, _, _) = make_chatwidget_manual(Some("gpt-5")).await;
    chat.has_chatgpt_account = true;

    chat.bottom_pane.set_task_running(/*running*/ true);
    chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 90.0)));
    assert!(matches!(
        chat.rate_limit_switch_prompt,
        RateLimitSwitchPromptState::Pending
    ));

    chat.bottom_pane.set_task_running(/*running*/ false);
    chat.maybe_show_pending_rate_limit_prompt();
    assert!(matches!(
        chat.rate_limit_switch_prompt,
        RateLimitSwitchPromptState::Shown
    ));
}

#[tokio::test]
async fn rate_limit_switch_prompt_popup_snapshot() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5")).await;
    chat.has_chatgpt_account = true;

    chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 92.0)));
    chat.maybe_show_pending_rate_limit_prompt();

    let popup = render_bottom_popup(&chat, /*width*/ 80);
    assert_chatwidget_snapshot!("rate_limit_switch_prompt_popup", popup);
}

#[tokio::test]
async fn workspace_member_credits_depleted_prompts_and_sends_credits() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    let mut limits = snapshot(/*percent*/ 100.0);
    limits.rate_limit_reached_type = Some(RateLimitReachedType::WorkspaceMemberCreditsDepleted);
    chat.on_rate_limit_snapshot(Some(limits));

    chat.on_rate_limit_error(
        RateLimitErrorKind::Generic,
        "Usage limit reached.".to_string(),
    );
    let popup = render_bottom_popup(&chat, /*width*/ 90);
    assert_chatwidget_snapshot!("workspace_member_credits_depleted_prompt", popup);

    chat.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE));
    let event = next_send_add_credits_nudge_email_event(&mut rx);
    assert_eq!(event, AddCreditsNudgeCreditType::Credits);
}

#[tokio::test]
async fn workspace_member_usage_limit_prompts_and_sends_usage_limit() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    let mut limits = snapshot(/*percent*/ 100.0);
    limits.rate_limit_reached_type = Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached);
    chat.on_rate_limit_snapshot(Some(limits));

    chat.on_rate_limit_error(
        RateLimitErrorKind::UsageLimit,
        "Usage limit reached.".to_string(),
    );
    let popup = render_bottom_popup(&chat, /*width*/ 100);
    assert_chatwidget_snapshot!("workspace_member_usage_limit_prompt", popup);

    chat.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE));
    let event = next_send_add_credits_nudge_email_event(&mut rx);
    assert_eq!(event, AddCreditsNudgeCreditType::UsageLimit);
}

#[tokio::test]
async fn sparse_rate_limit_snapshot_preserves_member_limit_type_for_error_prompt() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    let mut usage_limits = snapshot(/*percent*/ 100.0);
    usage_limits.rate_limit_reached_type =
        Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached);
    chat.on_rate_limit_snapshot(Some(usage_limits));

    let mut rolling_limits = snapshot(/*percent*/ 100.0);
    rolling_limits.rate_limit_reached_type = None;
    chat.on_rolling_rate_limit_snapshot(rolling_limits);

    chat.on_rate_limit_error(
        RateLimitErrorKind::UsageLimit,
        "Usage limit reached.".to_string(),
    );
    let popup = render_bottom_popup(&chat, /*width*/ 100);
    assert!(
        popup.contains("Request a limit increase from your owner"),
        "popup: {popup}"
    );

    chat.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE));
    let event = next_send_add_credits_nudge_email_event(&mut rx);
    assert_eq!(event, AddCreditsNudgeCreditType::UsageLimit);
}

#[tokio::test]
async fn usage_limit_error_remaps_stale_member_credits_state_to_usage_limit_prompt() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    let mut limits = snapshot(/*percent*/ 100.0);
    limits.rate_limit_reached_type = Some(RateLimitReachedType::WorkspaceMemberCreditsDepleted);
    chat.on_rate_limit_snapshot(Some(limits));

    chat.on_rate_limit_error(
        RateLimitErrorKind::UsageLimit,
        "Usage limit reached.".to_string(),
    );
    let popup = render_bottom_popup(&chat, /*width*/ 100);
    assert!(
        popup.contains("Request a limit increase from your owner"),
        "popup: {popup}"
    );

    chat.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE));
    let event = next_send_add_credits_nudge_email_event(&mut rx);
    assert_eq!(event, AddCreditsNudgeCreditType::UsageLimit);
}

#[tokio::test]
async fn workspace_owner_limit_states_do_not_prompt_for_owner_nudge() {
    for (limit_type, error_kind) in [
        (
            RateLimitReachedType::WorkspaceOwnerCreditsDepleted,
            RateLimitErrorKind::Generic,
        ),
        (
            RateLimitReachedType::WorkspaceOwnerUsageLimitReached,
            RateLimitErrorKind::UsageLimit,
        ),
        (
            RateLimitReachedType::RateLimitReached,
            RateLimitErrorKind::Generic,
        ),
    ] {
        let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
        let mut limits = snapshot(/*percent*/ 100.0);
        limits.rate_limit_reached_type = Some(limit_type);
        chat.on_rate_limit_snapshot(Some(limits));

        chat.on_rate_limit_error(error_kind, "Usage limit reached.".to_string());
        let popup = render_bottom_popup(&chat, /*width*/ 90);
        assert!(!popup.contains("workspace owner"));
        assert_no_owner_nudge_or_rate_limit_refresh(&mut rx);
    }
}

#[tokio::test]
async fn workspace_owner_limit_states_render_state_specific_messages() {
    let cases = [
        (
            RateLimitReachedType::WorkspaceOwnerCreditsDepleted,
            RateLimitErrorKind::Generic,
            "You're out of credits. Your workspace is out of credits. Add credits to continue using Codex.",
        ),
        (
            RateLimitReachedType::WorkspaceOwnerUsageLimitReached,
            RateLimitErrorKind::UsageLimit,
            "Usage limit reached. You've reached your usage limit. Increase your limits to continue using codex.",
        ),
    ];

    let mut rendered_cases = Vec::new();
    for (limit_type, error_kind, expected) in cases {
        let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
        let mut limits = snapshot(/*percent*/ 100.0);
        limits.rate_limit_reached_type = Some(limit_type);
        chat.on_rate_limit_snapshot(Some(limits));

        chat.on_rate_limit_error(error_kind, "Usage limit reached.".to_string());
        let rendered = drain_insert_history(&mut rx)
            .into_iter()
            .map(|lines| lines_to_single_string(&lines))
            .collect::<String>();
        assert!(rendered.contains(expected), "rendered: {rendered}");
        rendered_cases.push(rendered);
    }

    assert_chatwidget_snapshot!(
        "workspace_owner_limit_state_messages",
        rendered_cases.join("\n---\n")
    );
}

#[tokio::test]
async fn missing_rate_limit_reached_type_does_not_prompt_or_refresh() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 100.0)));

    chat.on_rate_limit_error(
        RateLimitErrorKind::UsageLimit,
        "Usage limit reached.".to_string(),
    );
    let popup = render_bottom_popup(&chat, /*width*/ 90);
    assert!(!popup.contains("workspace owner"));
    assert_no_owner_nudge_or_rate_limit_refresh(&mut rx);
}

#[tokio::test]
async fn workspace_owner_nudge_default_no_dismisses_without_sending() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    let mut limits = snapshot(/*percent*/ 100.0);
    limits.rate_limit_reached_type = Some(RateLimitReachedType::WorkspaceMemberCreditsDepleted);
    chat.on_rate_limit_snapshot(Some(limits));

    chat.on_rate_limit_error(
        RateLimitErrorKind::Generic,
        "Usage limit reached.".to_string(),
    );
    chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));

    assert_no_owner_nudge_or_rate_limit_refresh(&mut rx);
}

#[tokio::test]
async fn workspace_owner_nudge_reappears_after_dismissing_no() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    let mut limits = snapshot(/*percent*/ 100.0);
    limits.rate_limit_reached_type = Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached);
    chat.on_rate_limit_snapshot(Some(limits));

    chat.on_rate_limit_error(
        RateLimitErrorKind::UsageLimit,
        "Usage limit reached.".to_string(),
    );
    chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
    assert_no_owner_nudge_or_rate_limit_refresh(&mut rx);

    chat.on_rate_limit_error(
        RateLimitErrorKind::UsageLimit,
        "Usage limit reached.".to_string(),
    );
    let popup = render_bottom_popup(&chat, /*width*/ 100);
    assert!(
        popup.contains("Request a limit increase from your owner"),
        "popup: {popup}"
    );
}

#[tokio::test]
async fn workspace_owner_credits_nudge_completion_renders_feedback() {
    let cases = [
        (
            Ok(AddCreditsNudgeEmailStatus::Sent),
            "Workspace owner notified.",
        ),
        (
            Ok(AddCreditsNudgeEmailStatus::CooldownActive),
            "Workspace owner was already notified recently.",
        ),
        (
            Err("request failed".to_string()),
            "Could not notify your workspace owner. Please try again.",
        ),
    ];

    let mut rendered_cases = Vec::new();
    for (result, expected) in cases {
        let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
        chat.start_add_credits_nudge_email_request(AddCreditsNudgeCreditType::Credits);
        chat.finish_add_credits_nudge_email_request(result);
        let rendered = drain_insert_history(&mut rx)
            .into_iter()
            .map(|lines| lines_to_single_string(&lines))
            .collect::<String>();
        assert!(rendered.contains(expected), "rendered: {rendered}");
        rendered_cases.push(rendered);
    }

    assert_chatwidget_snapshot!(
        "workspace_owner_credits_nudge_completion_feedback",
        rendered_cases.join("\n---\n")
    );
}

#[tokio::test]
async fn workspace_owner_usage_limit_nudge_completion_renders_feedback() {
    let cases = [
        (
            Ok(AddCreditsNudgeEmailStatus::Sent),
            "Limit increase requested.",
        ),
        (
            Ok(AddCreditsNudgeEmailStatus::CooldownActive),
            "A limit increase was already requested recently.",
        ),
        (
            Err("request failed".to_string()),
            "Could not request a limit increase. Please try again.",
        ),
    ];

    let mut rendered_cases = Vec::new();
    for (result, expected) in cases {
        let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
        chat.start_add_credits_nudge_email_request(AddCreditsNudgeCreditType::UsageLimit);
        chat.finish_add_credits_nudge_email_request(result);
        let rendered = drain_insert_history(&mut rx)
            .into_iter()
            .map(|lines| lines_to_single_string(&lines))
            .collect::<String>();
        assert!(rendered.contains(expected), "rendered: {rendered}");
        rendered_cases.push(rendered);
    }

    assert_chatwidget_snapshot!(
        "workspace_owner_usage_limit_nudge_completion_feedback",
        rendered_cases.join("\n---\n")
    );
}

fn next_send_add_credits_nudge_email_event(
    rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
) -> AddCreditsNudgeCreditType {
    while let Ok(event) = rx.try_recv() {
        if let AppEvent::SendAddCreditsNudgeEmail { credit_type } = event {
            return credit_type;
        }
    }
    panic!("expected SendAddCreditsNudgeEmail app event");
}

fn assert_no_owner_nudge_or_rate_limit_refresh(
    rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
) {
    while let Ok(event) = rx.try_recv() {
        assert!(
            !matches!(
                event,
                AppEvent::SendAddCreditsNudgeEmail { .. } | AppEvent::RefreshRateLimits { .. }
            ),
            "unexpected event: {event:?}"
        );
    }
}

#[tokio::test]
async fn streaming_final_answer_keeps_task_running_state() {
    let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.thread_id = Some(ThreadId::new());

    chat.on_task_started();
    chat.on_agent_message_delta("Final answer line\n".to_string());
    chat.on_commit_tick();
    drain_insert_history(&mut rx);

    assert!(chat.bottom_pane.is_task_running());
    assert!(!chat.bottom_pane.status_indicator_visible());

    chat.bottom_pane
        .set_composer_text("queued submission".to_string(), Vec::new(), Vec::new());
    chat.handle_key_event(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE));

    assert_eq!(chat.input_queue.queued_user_messages.len(), 1);
    assert_eq!(
        chat.input_queue.queued_user_messages.front().unwrap().text,
        "queued submission"
    );
    assert_matches!(op_rx.try_recv(), Err(TryRecvError::Empty));

    chat.handle_key_event(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL));
    match op_rx.try_recv() {
        Ok(Op::Interrupt) => {}
        other => panic!("expected Op::Interrupt, got {other:?}"),
    }
    assert!(!chat.bottom_pane.quit_shortcut_hint_visible());
}

#[tokio::test]
async fn single_line_final_answer_hides_working_status_snapshot() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5")).await;
    chat.thread_id = Some(ThreadId::new());

    complete_user_message(&mut chat, "user-1", "count to 1");
    chat.on_task_started();
    complete_assistant_message(
        &mut chat,
        "msg-final-single-line",
        "1",
        Some(MessagePhase::FinalAnswer),
    );

    assert!(chat.bottom_pane.is_task_running());
    assert!(!chat.bottom_pane.status_indicator_visible());

    let width: u16 = 40;
    let vt_height: u16 = 10;
    let ui_height = chat.desired_height(width);
    let viewport = Rect::new(0, vt_height - ui_height - 1, width, ui_height);
    let backend = VT100Backend::new(width, vt_height);
    let mut terminal = crate::tui_internal::custom_terminal::Terminal::with_options(backend).expect("terminal");
    terminal.set_viewport_area(viewport);

    for lines in drain_insert_history(&mut rx) {
        crate::tui_internal::insert_history::insert_history_lines(&mut terminal, lines)
            .expect("insert history lines");
    }

    terminal
        .draw(|frame| chat.render(frame.area(), frame.buffer_mut()))
        .expect("draw final answer");
    assert_chatwidget_snapshot!(
        "single_line_final_answer_hides_working_status",
        normalize_snapshot_paths(terminal.backend().vt100().screen().contents())
    );
}

#[tokio::test]
async fn ctrl_c_interrupt_pauses_active_goal_turn() {
    let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    let thread_id = start_active_goal_turn(&mut chat);

    chat.handle_key_event(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL));

    next_interrupt_op(&mut op_rx);
    assert_goal_paused_event(&mut rx, thread_id);
}

#[tokio::test]
async fn esc_interrupt_pauses_active_goal_turn() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.show_welcome_banner = false;
    let thread_id = start_active_goal_turn(&mut chat);

    chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));

    assert_matches!(rx.try_recv(), Ok(AppEvent::CodexOp(Op::Interrupt)));
    assert_goal_paused_event(&mut rx, thread_id);

    update_thread_goal(&mut chat, thread_id, AppThreadGoalStatus::Paused);
    let width = 80;
    let height = chat.desired_height(width);
    let mut terminal = ratatui::Terminal::new(TestBackend::new(width, height)).expect("terminal");
    terminal
        .draw(|f| chat.render(f.area(), f.buffer_mut()))
        .expect("draw goal paused footer");
    let snapshot = normalized_backend_snapshot(terminal.backend());
    #[cfg(target_os = "windows")]
    insta::with_settings!({ snapshot_suffix => "windows" }, {
        assert_chatwidget_snapshot!("esc_interrupt_goal_paused_footer", snapshot);
    });
    #[cfg(not(target_os = "windows"))]
    assert_chatwidget_snapshot!("esc_interrupt_goal_paused_footer", snapshot);
}

#[tokio::test]
async fn request_user_input_interrupt_pauses_active_goal_turn() {
    for key_event in [
        KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE),
        KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL),
    ] {
        let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
        let thread_id = start_active_goal_turn(&mut chat);
        chat.handle_request_user_input_now(ToolRequestUserInputParams {
            thread_id: thread_id.to_string(),
            item_id: "call-1".to_string(),
            turn_id: "turn-1".to_string(),
            questions: Vec::new(),
            auto_resolution_ms: None,
        });

        chat.handle_key_event(key_event);

        assert_matches!(rx.try_recv(), Ok(AppEvent::CodexOp(Op::Interrupt)));
        assert_goal_paused_event(&mut rx, thread_id);
    }
}

fn start_active_goal_turn(chat: &mut ChatWidget) -> ThreadId {
    let thread_id = ThreadId::new();
    chat.set_feature_enabled(Feature::Goals, /*enabled*/ true);
    chat.thread_id = Some(thread_id);
    update_thread_goal(chat, thread_id, AppThreadGoalStatus::Active);
    chat.on_task_started();
    thread_id
}

fn update_thread_goal(chat: &mut ChatWidget, thread_id: ThreadId, status: AppThreadGoalStatus) {
    let mut goal = test_thread_goal(
        status,
        /*token_budget*/ Some(50_000),
        /*tokens_used*/ 40_000,
    );
    let thread_id = thread_id.to_string();
    goal.thread_id = thread_id.clone();
    chat.handle_server_notification(
        ServerNotification::ThreadGoalUpdated(
            lemurclaw_core::app_server_protocol::ThreadGoalUpdatedNotification {
                thread_id,
                turn_id: None,
                goal,
            },
        ),
        /*replay_kind*/ None,
    );
}

fn assert_goal_paused_event(
    rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
    thread_id: ThreadId,
) {
    assert_matches!(
        rx.try_recv(),
        Ok(AppEvent::SetThreadGoalStatus {
            thread_id: event_thread_id,
            status: AppThreadGoalStatus::Paused,
        }) if event_thread_id == thread_id
    );
}

#[tokio::test]
async fn idle_commit_ticks_do_not_restore_status_without_commentary_completion() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    chat.on_task_started();
    assert_eq!(chat.bottom_pane.status_indicator_visible(), true);

    chat.on_agent_message_delta("Final answer line\n".to_string());
    chat.on_commit_tick();
    drain_insert_history(&mut rx);

    assert_eq!(chat.bottom_pane.status_indicator_visible(), false);
    assert_eq!(chat.bottom_pane.is_task_running(), true);

    // A second idle tick should not toggle the row back on and cause jitter.
    chat.on_commit_tick();
    assert_eq!(chat.bottom_pane.status_indicator_visible(), false);
}

#[tokio::test]
async fn final_answer_completion_restores_status_indicator_for_pending_steer() {
    let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.thread_id = Some(ThreadId::new());

    chat.on_task_started();
    assert_eq!(chat.bottom_pane.status_indicator_visible(), true);

    chat.on_agent_message_delta("Long output line 1\n".to_string());
    chat.on_commit_tick();
    drain_insert_history(&mut rx);
    chat.on_agent_message_delta("Long output line 2\n".to_string());
    chat.on_commit_tick();
    drain_insert_history(&mut rx);

    assert_eq!(chat.bottom_pane.status_indicator_visible(), false);
    assert_eq!(chat.bottom_pane.is_task_running(), true);

    chat.bottom_pane.set_composer_text(
        "Please summarize the rest more briefly.".to_string(),
        Vec::new(),
        Vec::new(),
    );
    chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));

    assert_eq!(chat.input_queue.pending_steers.len(), 1);
    let items = match next_submit_op(&mut op_rx) {
        Op::UserTurn { items, .. } => items,
        other => panic!("expected Op::UserTurn, got {other:?}"),
    };
    assert_eq!(
        items,
        vec![UserInput::Text {
            text: "Please summarize the rest more briefly.".to_string(),
            text_elements: Vec::new(),
        }]
    );

    complete_assistant_message(
        &mut chat,
        "msg-final",
        "Long output line 1\nLong output line 2\n",
        Some(MessagePhase::FinalAnswer),
    );

    assert_eq!(chat.bottom_pane.status_indicator_visible(), true);
    assert_eq!(chat.bottom_pane.is_task_running(), true);

    complete_user_message(
        &mut chat,
        "user-steer",
        "Please summarize the rest more briefly.",
    );

    assert!(chat.input_queue.pending_steers.is_empty());
    assert_eq!(chat.bottom_pane.status_indicator_visible(), true);
    assert_eq!(chat.bottom_pane.is_task_running(), true);
}

#[tokio::test]
async fn commentary_completion_restores_status_indicator_before_exec_begin() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    chat.on_task_started();
    assert_eq!(chat.bottom_pane.status_indicator_visible(), true);

    chat.on_agent_message_delta("Preamble line\n".to_string());
    chat.on_commit_tick();
    drain_insert_history(&mut rx);

    assert_eq!(chat.bottom_pane.status_indicator_visible(), false);

    complete_assistant_message(
        &mut chat,
        "msg-commentary",
        "Preamble line\n",
        Some(MessagePhase::Commentary),
    );

    assert_eq!(chat.bottom_pane.status_indicator_visible(), true);
    assert_eq!(chat.bottom_pane.is_task_running(), true);

    begin_exec(&mut chat, "call-1", "echo hi");
    assert_eq!(chat.bottom_pane.status_indicator_visible(), true);
}

#[tokio::test]
async fn fast_status_indicator_requires_chatgpt_auth() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.4")).await;
    set_fast_mode_test_catalog(&mut chat);
    assert!(get_available_model(&chat, "gpt-5.4").supports_fast_mode());
    chat.set_service_tier(Some(ServiceTier::Fast.request_value().to_string()));

    assert!(!chat.should_show_fast_status(chat.current_model(), chat.current_service_tier(),));

    set_chatgpt_auth(&mut chat);
    set_fast_mode_test_catalog(&mut chat);
    assert!(get_available_model(&chat, "gpt-5.4").supports_fast_mode());

    assert!(chat.should_show_fast_status(chat.current_model(), chat.current_service_tier(),));
}

#[tokio::test]
async fn fast_status_indicator_is_hidden_for_models_without_fast_support() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.2")).await;
    set_fast_mode_test_catalog(&mut chat);
    assert!(!get_available_model(&chat, "gpt-5.2").supports_fast_mode());
    chat.set_service_tier(Some(ServiceTier::Fast.request_value().to_string()));
    set_chatgpt_auth(&mut chat);
    set_fast_mode_test_catalog(&mut chat);
    assert!(!get_available_model(&chat, "gpt-5.2").supports_fast_mode());

    assert!(!chat.should_show_fast_status(chat.current_model(), chat.current_service_tier(),));
}

#[tokio::test]
async fn fast_status_indicator_is_hidden_when_fast_mode_is_off() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.4")).await;
    set_fast_mode_test_catalog(&mut chat);
    assert!(get_available_model(&chat, "gpt-5.4").supports_fast_mode());
    set_chatgpt_auth(&mut chat);
    set_fast_mode_test_catalog(&mut chat);
    assert!(get_available_model(&chat, "gpt-5.4").supports_fast_mode());

    assert!(!chat.should_show_fast_status(chat.current_model(), chat.current_service_tier(),));
}

// Snapshot test: ChatWidget at very small heights (idle)
// Ensures overall layout behaves when terminal height is extremely constrained.
#[tokio::test]
async fn ui_snapshots_small_heights_idle() {
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;
    let (chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    for h in [1u16, 2, 3] {
        let name = format!("chat_small_idle_h{h}");
        let mut terminal = Terminal::new(TestBackend::new(40, h)).expect("create terminal");
        terminal
            .draw(|f| chat.render(f.area(), f.buffer_mut()))
            .expect("draw chat idle");
        assert_chatwidget_snapshot!(name, normalized_backend_snapshot(terminal.backend()));
    }
}

// Snapshot test: ChatWidget at very small heights (task running)
// Validates how status + composer are presented within tight space.
#[tokio::test]
async fn ui_snapshots_small_heights_task_running() {
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    // Activate status line
    handle_turn_started(&mut chat, "turn-1");
    handle_agent_reasoning_delta(&mut chat, "**Thinking**");
    for h in [1u16, 2, 3] {
        let name = format!("chat_small_running_h{h}");
        let mut terminal = Terminal::new(TestBackend::new(40, h)).expect("create terminal");
        terminal
            .draw(|f| chat.render(f.area(), f.buffer_mut()))
            .expect("draw chat running");
        assert_chatwidget_snapshot!(name, normalized_backend_snapshot(terminal.backend()));
    }
}

#[tokio::test]
#[serial]
async fn ambient_pet_stays_hidden_until_a_pet_is_selected() {
    use ratatui::layout::Rect;

    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.set_pet_image_support_for_tests(crate::tui_internal::pets::PetImageSupport::Supported(
        crate::tui_internal::pets::ImageProtocol::Kitty,
    ));
    assert!(chat.ambient_pet.is_none());

    crate::tui_internal::pets::write_test_pack(&chat.config.codex_home);
    chat.set_tui_pet(Some("codex".to_string()));

    let area = Rect::new(
        /*x*/ 0, /*y*/ 0, /*width*/ 60, /*height*/ 20,
    );
    let draw = chat
        .ambient_pet_draw(area, area.bottom())
        .expect("ambient pet draw request");
    assert_eq!(draw.x, 51);
    assert_eq!(draw.y, 14);
    assert_eq!(draw.columns, 9);
    assert_eq!(draw.rows, 5);
    assert_eq!(
        draw.y.saturating_add(draw.rows),
        area.bottom().saturating_sub(/*rhs*/ 1)
    );

    handle_turn_started(&mut chat, "turn-1");
    handle_agent_reasoning_delta(&mut chat, "**Thinking**");
    let draw_with_status = chat
        .ambient_pet_draw(area, area.bottom())
        .expect("ambient pet draw request with status");
    assert_eq!(draw_with_status.y, draw.y);
    assert_eq!(
        draw_with_status.y.saturating_add(draw_with_status.rows),
        area.bottom().saturating_sub(/*rhs*/ 1)
    );
}

#[tokio::test]
#[serial]
async fn ambient_pet_screen_bottom_anchor_uses_terminal_bottom() {
    use lemurclaw_core::config::types::TuiPetAnchor;
    use ratatui::layout::Rect;

    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    enable_test_ambient_pet(&mut chat);

    let terminal_area = Rect::new(
        /*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 24,
    );
    let composer_bottom_y = 20;
    let default_draw = chat
        .ambient_pet_draw(terminal_area, composer_bottom_y)
        .expect("composer-anchored pet draw request");
    assert_eq!(default_draw.y, 14);

    chat.config.tui_pet_anchor = TuiPetAnchor::ScreenBottom;
    let screen_bottom_draw = chat
        .ambient_pet_draw(terminal_area, composer_bottom_y)
        .expect("screen-bottom anchored pet draw request");
    assert_eq!(screen_bottom_draw.y, 18);
}

#[tokio::test]
#[serial]
async fn ambient_pet_can_be_disabled() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    chat.set_tui_pet(Some(crate::tui_internal::pets::DISABLED_PET_ID.to_string()));

    assert!(chat.ambient_pet.is_none());
}

#[tokio::test]
#[serial]
async fn ambient_pet_reserves_history_wrap_width() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    enable_test_ambient_pet(&mut chat);

    assert_eq!(chat.history_wrap_width(/*width*/ 80), 69);

    chat.set_tui_pet(Some(crate::tui_internal::pets::DISABLED_PET_ID.to_string()));

    assert_eq!(chat.history_wrap_width(/*width*/ 80), 80);
}

#[tokio::test]
#[serial]
async fn ambient_pet_reduces_stream_width_and_composer_text_width() {
    use ratatui::Terminal;

    let (mut with_pet, _with_pet_rx, _with_pet_op_rx) =
        make_chatwidget_manual(/*model_override*/ None).await;
    enable_test_ambient_pet(&mut with_pet);
    with_pet.last_rendered_width.set(Some(80));
    let stream_width_with_pet = with_pet.current_stream_width(/*reserved_cols*/ 2);

    let (mut disabled, _disabled_rx, _disabled_op_rx) =
        make_chatwidget_manual(/*model_override*/ None).await;
    disabled.set_tui_pet(Some(crate::tui_internal::pets::DISABLED_PET_ID.to_string()));
    disabled.last_rendered_width.set(Some(80));
    let stream_width_without_pet = disabled.current_stream_width(/*reserved_cols*/ 2);

    assert_eq!(
        stream_width_with_pet,
        crate::tui_internal::width::usable_content_width(/*total_width*/ 69, /*reserved_cols*/ 2)
    );
    assert_eq!(
        stream_width_without_pet,
        crate::tui_internal::width::usable_content_width(/*total_width*/ 80, /*reserved_cols*/ 2)
    );
    assert!(stream_width_with_pet < stream_width_without_pet);

    let draft =
        "Minim commodo esse elit Lorem exercitation elit ipsum proident labore. Esse culpa aliqua"
            .to_string();
    with_pet
        .bottom_pane
        .set_composer_text(draft.clone(), Vec::new(), Vec::new());
    disabled
        .bottom_pane
        .set_composer_text(draft, Vec::new(), Vec::new());

    let mut with_pet_terminal =
        Terminal::new(TestBackend::new(/*width*/ 80, /*height*/ 6)).expect("create terminal");
    with_pet_terminal
        .draw(|f| with_pet.render(f.area(), f.buffer_mut()))
        .expect("draw pet-enabled chat");
    let mut disabled_terminal =
        Terminal::new(TestBackend::new(/*width*/ 80, /*height*/ 6)).expect("create terminal");
    disabled_terminal
        .draw(|f| disabled.render(f.area(), f.buffer_mut()))
        .expect("draw disabled-pet chat");

    let pet_row = buffer_row_containing(with_pet_terminal.backend().buffer(), "Minim")
        .expect("pet-enabled composer row should render draft");
    let disabled_row = buffer_row_containing(disabled_terminal.backend().buffer(), "Minim")
        .expect("disabled-pet composer row should render draft");

    assert!(row_tail_is_blank(&pet_row, /*start_col*/ 69));
    assert!(!row_tail_is_blank(&disabled_row, /*start_col*/ 69));
}

fn buffer_row_containing(buffer: &ratatui::buffer::Buffer, text: &str) -> Option<String> {
    (0..buffer.area.height)
        .map(|y| {
            (0..buffer.area.width)
                .map(|x| buffer.cell((x, y)).expect("cell should exist").symbol())
                .collect::<String>()
        })
        .find(|row| row.contains(text))
}

fn row_tail_is_blank(row: &str, start_col: usize) -> bool {
    row.chars().skip(start_col).all(char::is_whitespace)
}

#[tokio::test]
#[serial]
async fn ambient_pet_draw_uses_terminal_screen_area_not_short_inline_viewport() {
    use ratatui::layout::Rect;

    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    enable_test_ambient_pet(&mut chat);

    assert!(
        chat.ambient_pet_draw(
            Rect::new(
                /*x*/ 0, /*y*/ 21, /*width*/ 80, /*height*/ 3,
            ),
            /*composer_bottom_y*/ 24
        )
        .is_none(),
        "a normal short inline viewport cannot fit the ambient pet"
    );

    let draw = chat
        .ambient_pet_draw(
            Rect::new(
                /*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 24,
            ),
            /*composer_bottom_y*/ 24,
        )
        .expect("full terminal screen has room for the ambient pet");
    assert_eq!(draw.x, 71);
    assert_eq!(draw.y, 18);
}

#[tokio::test]
#[serial]
async fn ambient_pet_hides_notification_text_overlay() {
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    enable_test_ambient_pet(&mut chat);
    for (kind, label) in [
        (crate::tui_internal::pets::PetNotificationKind::Running, "Running"),
        (crate::tui_internal::pets::PetNotificationKind::Waiting, "Needs input"),
        (crate::tui_internal::pets::PetNotificationKind::Review, "Ready"),
        (crate::tui_internal::pets::PetNotificationKind::Failed, "Blocked"),
    ] {
        chat.set_ambient_pet_notification(kind, /*body*/ None);
        let mut terminal = Terminal::new(TestBackend::new(60, 20)).expect("create terminal");
        terminal
            .draw(|f| chat.render(f.area(), f.buffer_mut()))
            .expect("draw ambient pet notification");
        assert!(
            !normalized_backend_snapshot(terminal.backend()).contains(label),
            "did not expect {label} notification text to render"
        );
    }
}

// Snapshot test: status widget + approval modal active together
// The modal takes precedence visually; this captures the layout with a running
// task (status indicator active) while an approval request is shown.
#[tokio::test]
async fn status_widget_and_approval_modal_snapshot() {
    use crate::tui_internal::approval_events::ExecApprovalRequestEvent;

    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    // Begin a running task so the status indicator would be active.
    handle_turn_started(&mut chat, "turn-1");
    // Provide a deterministic header for the status line.
    handle_agent_reasoning_delta(&mut chat, "**Analyzing**");

    // Now show an approval modal (e.g. exec approval).
    let ev = ExecApprovalRequestEvent {
        call_id: "call-approve-exec".into(),
        approval_id: Some("call-approve-exec".into()),
        turn_id: "turn-approve-exec".into(),
        environment_id: None,
        command: vec!["echo".into(), "hello world".into()],
        cwd: test_path_buf("/tmp").abs(),
        reason: Some(
            "this is a test reason such as one that would be produced by the model".into(),
        ),
        network_approval_context: None,
        proposed_execpolicy_amendment: Some(ExecPolicyAmendment {
            command: vec!["echo".into(), "hello world".into()],
        }),
        proposed_network_policy_amendments: None,
        additional_permissions: None,
        available_decisions: None,
    };
    handle_exec_approval_request(&mut chat, "sub-approve-exec", ev);

    // Render at the widget's desired height and snapshot.
    let width: u16 = 100;
    let height = chat.desired_height(width);
    let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(width, height))
        .expect("create terminal");
    terminal.set_viewport_area(Rect::new(0, 0, width, height));
    terminal
        .draw(|f| chat.render(f.area(), f.buffer_mut()))
        .expect("draw status + approval modal");
    assert_chatwidget_snapshot!(
        "status_widget_and_approval_modal",
        normalized_backend_snapshot(terminal.backend())
    );
}

// Snapshot test: status widget active (StatusIndicatorView)
// Ensures the VT100 rendering of the status indicator is stable when active.
#[tokio::test]
async fn status_widget_active_snapshot() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    // Activate the status indicator by simulating a task start.
    handle_turn_started(&mut chat, "turn-1");
    // Provide a deterministic header via a bold reasoning chunk.
    handle_agent_reasoning_delta(&mut chat, "**Analyzing**");
    // Render and snapshot.
    let height = chat.desired_height(/*width*/ 80);
    let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(80, height))
        .expect("create terminal");
    terminal
        .draw(|f| chat.render(f.area(), f.buffer_mut()))
        .expect("draw status widget");
    assert_chatwidget_snapshot!(
        "status_widget_active",
        normalized_backend_snapshot(terminal.backend())
    );
}

#[tokio::test]
async fn stream_error_updates_status_indicator() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.bottom_pane.set_task_running(/*running*/ true);
    let msg = "Reconnecting... 2/5";
    let details = "Idle timeout waiting for SSE";
    handle_stream_error(&mut chat, msg, Some(details.to_string()));

    let cells = drain_insert_history(&mut rx);
    assert!(
        cells.is_empty(),
        "expected no history cell for StreamError event"
    );
    let status = chat
        .bottom_pane
        .status_widget()
        .expect("status indicator should be visible");
    assert_eq!(status.header(), msg);
    assert_eq!(status.details(), Some(details));
}

#[tokio::test]
async fn stream_error_restores_hidden_status_indicator() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.on_task_started();
    chat.on_agent_message_delta("Preamble line\n".to_string());
    chat.on_commit_tick();
    drain_insert_history(&mut rx);
    assert!(!chat.bottom_pane.status_indicator_visible());

    let msg = "Reconnecting... 2/5";
    let details = "Idle timeout waiting for SSE";
    handle_stream_error(&mut chat, msg, Some(details.to_string()));

    let status = chat
        .bottom_pane
        .status_widget()
        .expect("status indicator should be visible");
    assert_eq!(status.header(), msg);
    assert_eq!(status.details(), Some(details));
}

#[tokio::test]
async fn warning_event_adds_warning_history_cell() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    handle_warning(&mut chat, "test warning message");

    let cells = drain_insert_history(&mut rx);
    assert_eq!(cells.len(), 1, "expected one warning history cell");
    let rendered = lines_to_single_string(&cells[0]);
    assert!(
        rendered.contains("test warning message"),
        "warning cell missing content: {rendered}"
    );
}

#[tokio::test]
async fn unsupported_code_mode_warning_renders_as_warning_history_cell() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    handle_warning(
        &mut chat,
        "Code Mode is enabled in configuration, but model `gpt-5.4` does not advertise Code Mode support. This may degrade model performance. Disable `features.code_mode` and `features.code_mode_only`, or select a model whose metadata enables Code Mode.",
    );

    let cells = drain_insert_history(&mut rx);
    assert_eq!(cells.len(), 1, "expected one warning history cell");
    insta::assert_snapshot!(
        "unsupported_code_mode_warning",
        lines_to_single_string(&cells[0])
    );
}

#[tokio::test]
async fn repeated_model_metadata_warning_is_hidden_for_same_slug() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    let warning = "Model metadata for `unknown-model` not found. Defaulting to fallback metadata; this can degrade performance and cause issues.";

    handle_warning(&mut chat, warning);
    handle_warning(&mut chat, warning);

    let cells = drain_insert_history(&mut rx);
    assert_eq!(cells.len(), 1, "expected one warning history cell");
    let rendered = lines_to_single_string(&cells[0]);
    assert!(
        rendered.contains("unknown-model"),
        "warning cell missing model slug: {rendered}"
    );
}

#[tokio::test]
async fn repeated_generic_warning_is_not_hidden() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    handle_warning(&mut chat, "test warning message");
    handle_warning(&mut chat, "test warning message");

    let cells = drain_insert_history(&mut rx);
    assert_eq!(cells.len(), 2, "expected both warning history cells");
}

#[tokio::test]
async fn status_line_invalid_items_warn_once() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.config.tui_status_line = Some(vec![
        "model_name".to_string(),
        "bogus_item".to_string(),
        "lines_changed".to_string(),
        "bogus_item".to_string(),
    ]);
    chat.thread_id = Some(ThreadId::new());

    chat.refresh_status_line();
    let cells = drain_insert_history(&mut rx);
    assert_eq!(cells.len(), 1, "expected one warning history cell");
    let rendered = lines_to_single_string(&cells[0]);
    assert!(
        rendered.contains("bogus_item"),
        "warning cell missing invalid item content: {rendered}"
    );

    chat.refresh_status_line();
    let cells = drain_insert_history(&mut rx);
    assert!(
        cells.is_empty(),
        "expected invalid status line warning to emit only once"
    );
}

#[tokio::test]
async fn status_line_context_used_renders_labeled_percent() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.thread_id = Some(ThreadId::new());
    chat.config.tui_status_line = Some(vec!["context-used".to_string()]);

    chat.refresh_status_line();

    assert_eq!(status_line_text(&chat), Some("Context 0% used".to_string()));
    assert!(
        drain_insert_history(&mut rx).is_empty(),
        "context-used should remain a valid status line item"
    );
}

#[tokio::test]
async fn status_line_context_remaining_renders_labeled_percent() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.thread_id = Some(ThreadId::new());
    chat.config.tui_status_line = Some(vec!["context-remaining".to_string()]);

    chat.refresh_status_line();

    assert_eq!(
        status_line_text(&chat),
        Some("Context 100% left".to_string())
    );
    assert!(
        drain_insert_history(&mut rx).is_empty(),
        "context-remaining should remain a valid status line item"
    );
}

#[tokio::test]
async fn status_line_legacy_context_usage_renders_context_used_percent() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.thread_id = Some(ThreadId::new());
    chat.config.tui_status_line = Some(vec!["context-usage".to_string()]);

    chat.refresh_status_line();

    assert_eq!(status_line_text(&chat), Some("Context 0% used".to_string()));
    assert!(
        drain_insert_history(&mut rx).is_empty(),
        "legacy context-usage should remain a valid status line item"
    );
}

#[tokio::test]
async fn status_line_workspace_headline_renders_cached_value() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.thread_id = Some(ThreadId::new());
    chat.config.tui_status_line = Some(vec!["workspace-headline".to_string()]);
    chat.status_line_workspace_headline = Some("Workspace maintenance starts at 5pm".to_string());

    chat.refresh_status_line();

    assert_eq!(
        status_line_text(&chat),
        Some("Workspace maintenance starts at 5pm".to_string())
    );
    assert!(
        drain_insert_history(&mut rx).is_empty(),
        "workspace-headline should be a valid status line item"
    );
}

#[tokio::test]
async fn status_line_workspace_headline_omits_when_unavailable() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.thread_id = Some(ThreadId::new());
    chat.config.tui_status_line = Some(vec![
        "workspace-headline".to_string(),
        "run-state".to_string(),
    ]);

    chat.refresh_status_line();

    assert_eq!(status_line_text(&chat), Some("Ready".to_string()));
    assert!(
        drain_insert_history(&mut rx).is_empty(),
        "workspace-headline should be omitted without warning when no headline is cached"
    );
}

#[tokio::test]
async fn workspace_headline_update_applies_feature_disabled_result() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.config.tui_status_line = Some(vec!["workspace-headline".to_string()]);
    chat.status_line_workspace_headline = Some("Old headline".to_string());
    let request_id = 3;
    chat.status_line_workspace_headline_pending_request_id = Some(request_id);

    assert!(chat.set_status_line_workspace_headline(
        request_id,
        Ok(crate::tui_internal::workspace_messages::WorkspaceHeadlineFetchResult::FeatureDisabled),
    ));

    assert_eq!(status_line_text(&chat), None);
    assert!(chat.status_line_workspace_messages_disabled);
}

#[tokio::test]
async fn workspace_headline_update_applies_available_headline() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.config.tui_status_line = Some(vec!["workspace-headline".to_string()]);
    let request_id = 4;
    chat.status_line_workspace_headline_pending_request_id = Some(request_id);

    assert!(chat.set_status_line_workspace_headline(
        request_id,
        Ok(
            crate::tui_internal::workspace_messages::WorkspaceHeadlineFetchResult::Available(Some(
                "Fresh workspace headline".to_string(),
            ))
        ),
    ));

    assert_eq!(
        status_line_text(&chat),
        Some("Fresh workspace headline".to_string())
    );
    assert!(!chat.status_line_workspace_messages_disabled);
}

#[tokio::test]
async fn account_update_clears_workspace_headline_state() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.config.tui_status_line = Some(vec!["workspace-headline".to_string()]);
    chat.status_line_workspace_headline = Some("Old workspace headline".to_string());
    chat.status_line_workspace_headline_pending_request_id = Some(5);
    chat.status_line_workspace_headline_last_requested_at = Some(Instant::now());
    chat.status_line_workspace_messages_disabled = true;

    chat.update_account_state(
        /*status_account_display*/ None, /*plan_type*/ None,
        /*has_chatgpt_account*/ false, /*has_codex_backend_auth*/ false,
    );

    assert_eq!(
        (
            status_line_text(&chat),
            chat.status_line_workspace_headline_pending_request_id,
            chat.status_line_workspace_headline_last_requested_at,
            chat.status_line_workspace_messages_disabled,
        ),
        (None, None, None, false)
    );
}

#[tokio::test]
async fn workspace_headline_fetch_allows_backend_auth_without_chatgpt_account() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.config.tui_status_line = Some(vec!["workspace-headline".to_string()]);

    chat.update_account_state(
        /*status_account_display*/ None, /*plan_type*/ None,
        /*has_chatgpt_account*/ false, /*has_codex_backend_auth*/ true,
    );

    let request_id = take_workspace_headline_request_id(&mut rx);
    assert_eq!(
        chat.status_line_workspace_headline_pending_request_id,
        Some(request_id)
    );
}

#[tokio::test]
async fn account_update_discards_stale_workspace_headline_results() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.config.tui_status_line = Some(vec!["workspace-headline".to_string()]);

    chat.update_account_state(
        Some(StatusAccountDisplay::ChatGpt {
            email: Some("first@example.com".to_string()),
            plan: None,
        }),
        /*plan_type*/ None,
        /*has_chatgpt_account*/ true,
        /*has_codex_backend_auth*/ true,
    );
    let stale_request_id = take_workspace_headline_request_id(&mut rx);

    chat.update_account_state(
        Some(StatusAccountDisplay::ChatGpt {
            email: Some("second@example.com".to_string()),
            plan: None,
        }),
        /*plan_type*/ None,
        /*has_chatgpt_account*/ true,
        /*has_codex_backend_auth*/ true,
    );
    let current_request_id = take_workspace_headline_request_id(&mut rx);

    assert_ne!(stale_request_id, current_request_id);
    assert!(!chat.set_status_line_workspace_headline(
        stale_request_id,
        Ok(
            crate::tui_internal::workspace_messages::WorkspaceHeadlineFetchResult::Available(Some(
                "First account headline".to_string(),
            ))
        ),
    ));
    assert_eq!(
        (
            chat.status_line_workspace_headline.clone(),
            chat.status_line_workspace_headline_pending_request_id,
            chat.status_line_workspace_messages_disabled,
        ),
        (None, Some(current_request_id), false)
    );

    assert!(chat.set_status_line_workspace_headline(
        current_request_id,
        Ok(
            crate::tui_internal::workspace_messages::WorkspaceHeadlineFetchResult::Available(Some(
                "Second account headline".to_string(),
            ))
        ),
    ));
    assert!(!chat.set_status_line_workspace_headline(
        stale_request_id,
        Ok(crate::tui_internal::workspace_messages::WorkspaceHeadlineFetchResult::FeatureDisabled),
    ));
    assert_eq!(
        (
            status_line_text(&chat),
            chat.status_line_workspace_headline_pending_request_id,
            chat.status_line_workspace_messages_disabled,
        ),
        (Some("Second account headline".to_string()), None, false,)
    );
}

#[tokio::test]
async fn status_line_branch_state_resets_when_git_branch_disabled() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.status_line_branch = Some("main".to_string());
    chat.status_line_branch_pending = true;
    chat.status_line_branch_lookup_complete = true;
    chat.config.tui_status_line = Some(vec!["model_name".to_string()]);

    chat.refresh_status_line();

    assert_eq!(chat.status_line_branch, None);
    assert!(!chat.status_line_branch_pending);
    assert!(!chat.status_line_branch_lookup_complete);
}

#[tokio::test]
async fn status_line_branch_refreshes_after_turn_complete() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    install_noop_workspace_command_runner(&mut chat);
    chat.config.tui_status_line = Some(vec!["git-branch".to_string()]);
    chat.status_line_branch_lookup_complete = true;
    chat.status_line_branch_pending = false;

    handle_turn_completed(&mut chat, "turn-1", /*duration_ms*/ None);

    assert!(chat.status_line_branch_pending);
}

#[tokio::test]
async fn status_line_branch_refreshes_after_interrupt() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    install_noop_workspace_command_runner(&mut chat);
    chat.config.tui_status_line = Some(vec!["git-branch".to_string()]);
    chat.status_line_branch_lookup_complete = true;
    chat.status_line_branch_pending = false;

    handle_turn_interrupted(&mut chat, "turn-1");

    assert!(chat.status_line_branch_pending);
}

fn install_noop_workspace_command_runner(chat: &mut ChatWidget) {
    chat.workspace_command_runner = Some(std::sync::Arc::new(NoopWorkspaceCommandRunner));
}

struct NoopWorkspaceCommandRunner;

impl crate::tui_internal::workspace_command::WorkspaceCommandExecutor for NoopWorkspaceCommandRunner {
    fn run(
        &self,
        _command: crate::tui_internal::workspace_command::WorkspaceCommand,
    ) -> std::pin::Pin<
        Box<
            dyn std::future::Future<
                    Output = Result<
                        crate::tui_internal::workspace_command::WorkspaceCommandOutput,
                        crate::tui_internal::workspace_command::WorkspaceCommandError,
                    >,
                > + Send
                + '_,
        >,
    > {
        Box::pin(async {
            Ok(crate::tui_internal::workspace_command::WorkspaceCommandOutput {
                exit_code: 1,
                stdout: String::new(),
                stderr: String::new(),
            })
        })
    }
}

#[tokio::test]
async fn interrupted_turn_clears_visible_running_hook() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    handle_hook_started(
        &mut chat,
        hook_started_run(
            "pre-tool-use:0:/tmp/hooks.json",
            lemurclaw_core::app_server_protocol::HookEventName::PreToolUse,
            Some("checking command policy"),
        ),
    );
    reveal_running_hooks(&mut chat);
    let before_interrupt = active_hook_blob(&chat);

    handle_turn_interrupted(&mut chat, "turn-1");

    assert_chatwidget_snapshot!(
        "interrupted_turn_clears_visible_running_hook",
        format!(
            "before interrupt:\n{before_interrupt}after interrupt:\n{}",
            active_hook_blob(&chat)
        )
    );
}

#[tokio::test]
async fn completed_turn_clears_visible_running_hook() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    handle_hook_started(
        &mut chat,
        hook_started_run(
            "post-tool-use:0:/tmp/hooks.json",
            lemurclaw_core::app_server_protocol::HookEventName::PostToolUse,
            /*status_message*/ None,
        ),
    );
    reveal_running_hooks(&mut chat);
    let before_completion = active_hook_blob(&chat);

    handle_turn_completed(&mut chat, "turn-1", /*duration_ms*/ None);

    assert_chatwidget_snapshot!(
        "completed_turn_clears_visible_running_hook",
        format!(
            "before completion:\n{before_completion}after completion:\n{}",
            active_hook_blob(&chat)
        )
    );
}

#[tokio::test]
async fn status_line_fast_mode_renders_on_and_off() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.config.tui_status_line = Some(vec!["fast-mode".to_string()]);

    chat.refresh_status_line();
    assert_eq!(status_line_text(&chat), Some("Fast off".to_string()));

    chat.set_service_tier(Some(ServiceTier::Fast.request_value().to_string()));
    chat.refresh_status_line();
    assert_eq!(status_line_text(&chat), Some("Fast on".to_string()));
}

#[tokio::test]
async fn status_line_fast_mode_footer_snapshot() {
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.show_welcome_banner = false;
    chat.config.tui_status_line = Some(vec!["fast-mode".to_string()]);
    chat.set_service_tier(Some(ServiceTier::Fast.request_value().to_string()));
    chat.refresh_status_line();

    let width = 80;
    let height = chat.desired_height(width);
    let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("create terminal");
    terminal
        .draw(|f| chat.render(f.area(), f.buffer_mut()))
        .expect("draw fast-mode footer");
    assert_chatwidget_snapshot!(
        "status_line_fast_mode_footer",
        normalized_backend_snapshot(terminal.backend())
    );
}

#[tokio::test]
async fn status_line_model_with_reasoning_includes_fast_for_fast_capable_models() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.4")).await;
    set_fast_mode_test_catalog(&mut chat);
    assert!(get_available_model(&chat, "gpt-5.4").supports_fast_mode());
    chat.config.cwd = test_project_path().abs();
    chat.config.tui_status_line = Some(vec![
        "model-with-reasoning".to_string(),
        "context-used".to_string(),
        "current-dir".to_string(),
    ]);
    chat.set_reasoning_effort(Some(ReasoningEffortConfig::XHigh));
    chat.set_service_tier(Some(ServiceTier::Fast.request_value().to_string()));
    set_chatgpt_auth(&mut chat);
    set_fast_mode_test_catalog(&mut chat);
    assert!(get_available_model(&chat, "gpt-5.4").supports_fast_mode());
    chat.refresh_status_line();
    let test_cwd = test_path_display("/tmp/project");

    assert_eq!(
        status_line_text(&chat),
        Some(format!("gpt-5.4 xhigh fast · Context 0% used · {test_cwd}"))
    );

    chat.set_model("gpt-5.2");
    chat.refresh_status_line();

    assert_eq!(
        status_line_text(&chat),
        Some(format!("gpt-5.2 xhigh · Context 0% used · {test_cwd}"))
    );
}

#[tokio::test]
async fn terminal_title_model_updates_on_model_change_without_manual_refresh() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.4")).await;
    chat.config.tui_terminal_title = Some(vec!["model".to_string()]);
    chat.refresh_terminal_title();

    assert_eq!(chat.last_terminal_title, Some("gpt-5.4".to_string()));

    chat.set_model("gpt-5.2");

    assert_eq!(chat.last_terminal_title, Some("gpt-5.2".to_string()));
}

#[tokio::test]
async fn status_line_and_terminal_title_reasoning_render_only_effort() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.4")).await;
    chat.config.tui_status_line = Some(vec!["reasoning".to_string()]);
    chat.config.tui_terminal_title = Some(vec!["reasoning".to_string()]);
    chat.set_reasoning_effort(Some(ReasoningEffortConfig::XHigh));
    chat.set_service_tier(Some(ServiceTier::Fast.request_value().to_string()));

    chat.refresh_status_line();
    chat.refresh_terminal_title();

    assert_eq!(status_line_text(&chat), Some("xhigh".to_string()));
    assert_eq!(chat.last_terminal_title, Some("xhigh".to_string()));
}

#[tokio::test]
async fn status_line_reasoning_updates_on_mode_switch_without_manual_refresh() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.2")).await;
    chat.set_feature_enabled(Feature::CollaborationModes, /*enabled*/ true);
    chat.config.tui_status_line = Some(vec!["reasoning".to_string()]);
    chat.set_reasoning_effort(Some(ReasoningEffortConfig::High));

    assert_eq!(status_line_text(&chat), Some("high".to_string()));

    let plan_mask = collaboration_modes::plan_mask(chat.model_catalog.as_ref())
        .expect("expected plan collaboration mode");
    chat.set_collaboration_mask(plan_mask);

    assert_eq!(status_line_text(&chat), Some("medium".to_string()));
}

#[tokio::test]
async fn status_line_model_with_reasoning_updates_on_mode_switch_without_manual_refresh() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.2")).await;
    chat.set_feature_enabled(Feature::CollaborationModes, /*enabled*/ true);
    chat.config.tui_status_line = Some(vec!["model-with-reasoning".to_string()]);
    chat.set_reasoning_effort(Some(ReasoningEffortConfig::High));

    assert_eq!(status_line_text(&chat), Some("gpt-5.2 high".to_string()));

    let plan_mask = collaboration_modes::plan_mask(chat.model_catalog.as_ref())
        .expect("expected plan collaboration mode");
    chat.set_collaboration_mask(plan_mask);

    assert_eq!(status_line_text(&chat), Some("gpt-5.2 medium".to_string()));

    let default_mask = collaboration_modes::default_mask(chat.model_catalog.as_ref())
        .expect("expected default collaboration mode");
    chat.set_collaboration_mask(default_mask);

    assert_eq!(status_line_text(&chat), Some("gpt-5.2 high".to_string()));
}

#[tokio::test]
async fn status_line_model_with_reasoning_plan_mode_footer_snapshot() {
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.2")).await;
    chat.show_welcome_banner = false;
    chat.set_feature_enabled(Feature::CollaborationModes, /*enabled*/ true);
    chat.config.tui_status_line = Some(vec!["model-with-reasoning".to_string()]);
    chat.set_reasoning_effort(Some(ReasoningEffortConfig::High));

    let plan_mask = collaboration_modes::plan_mask(chat.model_catalog.as_ref())
        .expect("expected plan collaboration mode");
    chat.set_collaboration_mask(plan_mask);

    let width = 80;
    let height = chat.desired_height(width);
    let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("create terminal");
    terminal
        .draw(|f| chat.render(f.area(), f.buffer_mut()))
        .expect("draw plan-mode footer");
    assert_chatwidget_snapshot!(
        "status_line_model_with_reasoning_plan_mode_footer",
        normalized_backend_snapshot(terminal.backend())
    );
}

#[tokio::test]
async fn renamed_thread_footer_title_snapshot() {
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.2")).await;
    chat.show_welcome_banner = false;
    chat.config.tui_status_line = Some(vec![
        "model-with-reasoning".to_string(),
        "thread-title".to_string(),
    ]);
    chat.set_reasoning_effort(Some(ReasoningEffortConfig::High));
    chat.refresh_status_line();

    let thread_id = ThreadId::new();
    chat.thread_id = Some(thread_id);
    chat.handle_server_notification(
        ServerNotification::ThreadNameUpdated(
            lemurclaw_core::app_server_protocol::ThreadNameUpdatedNotification {
                thread_id: thread_id.to_string(),
                thread_name: Some("Roadmap cleanup".to_string()),
            },
        ),
        /*replay_kind*/ None,
    );

    let width = 80;
    let height = chat.desired_height(width);
    let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("create terminal");
    terminal
        .draw(|f| chat.render(f.area(), f.buffer_mut()))
        .expect("draw renamed-thread footer");
    assert_chatwidget_snapshot!(
        "renamed_thread_footer_title",
        normalized_backend_snapshot(terminal.backend())
    );
}

#[tokio::test]
async fn status_line_model_with_reasoning_fast_footer_snapshot() {
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.4")).await;
    set_fast_mode_test_catalog(&mut chat);
    assert!(get_available_model(&chat, "gpt-5.4").supports_fast_mode());
    chat.show_welcome_banner = false;
    chat.config.cwd = test_project_path().abs();
    chat.config.tui_status_line = Some(vec![
        "model-with-reasoning".to_string(),
        "context-used".to_string(),
        "current-dir".to_string(),
    ]);
    chat.set_reasoning_effort(Some(ReasoningEffortConfig::XHigh));
    chat.set_service_tier(Some(ServiceTier::Fast.request_value().to_string()));
    set_chatgpt_auth(&mut chat);
    set_fast_mode_test_catalog(&mut chat);
    assert!(get_available_model(&chat, "gpt-5.4").supports_fast_mode());
    chat.refresh_status_line();

    let width = 80;
    let height = chat.desired_height(width);
    let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("create terminal");
    terminal
        .draw(|f| chat.render(f.area(), f.buffer_mut()))
        .expect("draw model-with-reasoning footer");
    assert_chatwidget_snapshot!(
        "status_line_model_with_reasoning_fast_footer",
        normalized_backend_snapshot(terminal.backend())
    );
}

#[tokio::test]
async fn status_line_model_with_reasoning_context_remaining_footer_snapshot() {
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.4")).await;
    set_fast_mode_test_catalog(&mut chat);
    assert!(get_available_model(&chat, "gpt-5.4").supports_fast_mode());
    chat.show_welcome_banner = false;
    chat.config.cwd = test_project_path().abs();
    chat.config.tui_status_line = Some(vec![
        "model-with-reasoning".to_string(),
        "context-remaining".to_string(),
        "current-dir".to_string(),
    ]);
    chat.set_reasoning_effort(Some(ReasoningEffortConfig::XHigh));
    chat.set_service_tier(Some(ServiceTier::Fast.request_value().to_string()));
    set_chatgpt_auth(&mut chat);
    set_fast_mode_test_catalog(&mut chat);
    assert!(get_available_model(&chat, "gpt-5.4").supports_fast_mode());
    chat.refresh_status_line();

    let width = 80;
    let height = chat.desired_height(width);
    let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("create terminal");
    terminal
        .draw(|f| chat.render(f.area(), f.buffer_mut()))
        .expect("draw model-with-reasoning footer");
    assert_chatwidget_snapshot!(
        "status_line_model_with_reasoning_context_remaining_footer",
        normalized_backend_snapshot(terminal.backend())
    );
}

#[tokio::test]
async fn status_line_goal_active_token_budget_footer_snapshot() {
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.4")).await;
    chat.set_feature_enabled(Feature::Goals, /*enabled*/ true);
    chat.show_welcome_banner = false;
    chat.config.tui_status_line = Some(vec!["model-name".to_string()]);
    chat.refresh_status_line();
    chat.handle_server_notification(
        ServerNotification::ThreadGoalUpdated(
            lemurclaw_core::app_server_protocol::ThreadGoalUpdatedNotification {
                thread_id: "thread-1".to_string(),
                turn_id: None,
                goal: test_thread_goal(
                    lemurclaw_core::app_server_protocol::ThreadGoalStatus::Active,
                    /*token_budget*/ Some(50_000),
                    /*tokens_used*/ 40_000,
                ),
            },
        ),
        /*replay_kind*/ None,
    );

    let width = 80;
    let height = chat.desired_height(width);
    let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("create terminal");
    terminal
        .draw(|f| chat.render(f.area(), f.buffer_mut()))
        .expect("draw goal status footer");
    assert_chatwidget_snapshot!(
        "status_line_goal_active_token_budget_footer",
        normalized_backend_snapshot(terminal.backend())
    );
}

#[tokio::test]
async fn status_line_goal_complete_elapsed_footer_snapshot() {
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.4")).await;
    chat.set_feature_enabled(Feature::Goals, /*enabled*/ true);
    chat.show_welcome_banner = false;
    chat.config.tui_status_line = Some(vec!["model-name".to_string()]);
    chat.refresh_status_line();
    let mut goal = test_thread_goal(
        lemurclaw_core::app_server_protocol::ThreadGoalStatus::Complete,
        /*token_budget*/ None,
        /*tokens_used*/ 40_000,
    );
    goal.time_used_seconds = 2 * 24 * 60 * 60 + 23 * 60 * 60 + 42 * 60;
    chat.handle_server_notification(
        ServerNotification::ThreadGoalUpdated(
            lemurclaw_core::app_server_protocol::ThreadGoalUpdatedNotification {
                thread_id: "thread-1".to_string(),
                turn_id: None,
                goal,
            },
        ),
        /*replay_kind*/ None,
    );

    let width = 80;
    let height = chat.desired_height(width);
    let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("create terminal");
    terminal
        .draw(|f| chat.render(f.area(), f.buffer_mut()))
        .expect("draw goal status footer");
    assert_chatwidget_snapshot!(
        "status_line_goal_complete_elapsed_footer",
        normalized_backend_snapshot(terminal.backend())
    );
}

#[tokio::test]
async fn session_configured_clears_goal_status_footer() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.4")).await;
    chat.set_feature_enabled(Feature::Goals, /*enabled*/ true);
    chat.handle_server_notification(
        ServerNotification::ThreadGoalUpdated(
            lemurclaw_core::app_server_protocol::ThreadGoalUpdatedNotification {
                thread_id: "thread-1".to_string(),
                turn_id: None,
                goal: test_thread_goal(
                    lemurclaw_core::app_server_protocol::ThreadGoalStatus::Active,
                    /*token_budget*/ Some(50_000),
                    /*tokens_used*/ 40_000,
                ),
            },
        ),
        /*replay_kind*/ None,
    );
    assert_eq!(
        chat.current_goal_status_indicator,
        Some(GoalStatusIndicator::Active {
            usage: Some("40K / 50K".to_string())
        })
    );
    chat.turn_lifecycle
        .budget_limited_turn_ids
        .insert("turn-1".to_string());

    let rollout_file = NamedTempFile::new().unwrap();
    chat.handle_thread_session(crate::tui_internal::session_state::ThreadSessionState {
        thread_id: ThreadId::new(),
        forked_from_id: None,
        fork_parent_title: None,
        thread_name: None,
        model: "gpt-5.4".to_string(),
        model_provider_id: "test-provider".to_string(),
        service_tier: None,
        approval_policy: AskForApproval::Never,
        approvals_reviewer: ApprovalsReviewer::User,
        permission_profile: PermissionProfile::read_only(),
        active_permission_profile: None,
        cwd: test_path_buf("/home/user/project").abs(),
        runtime_workspace_roots: Vec::new(),
        instruction_source_paths: Vec::new(),
        reasoning_effort: Some(ReasoningEffortConfig::default()),
        collaboration_mode: None,
        personality: None,
        message_history: None,
        network_proxy: None,
        rollout_path: Some(rollout_file.path().to_path_buf()),
    });

    assert_eq!(chat.current_goal_status_indicator, None);
    assert!(chat.turn_lifecycle.budget_limited_turn_ids.is_empty());
}

#[tokio::test]
async fn thread_goal_update_for_other_thread_is_ignored() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.4")).await;
    chat.set_feature_enabled(Feature::Goals, /*enabled*/ true);
    chat.thread_id = Some(ThreadId::new());
    let other_thread_id = ThreadId::new().to_string();
    let mut goal = test_thread_goal(
        lemurclaw_core::app_server_protocol::ThreadGoalStatus::BudgetLimited,
        /*token_budget*/ Some(50_000),
        /*tokens_used*/ 50_000,
    );
    goal.thread_id = other_thread_id.clone();

    chat.handle_server_notification(
        ServerNotification::ThreadGoalUpdated(
            lemurclaw_core::app_server_protocol::ThreadGoalUpdatedNotification {
                thread_id: other_thread_id,
                turn_id: Some("turn-other".to_string()),
                goal,
            },
        ),
        /*replay_kind*/ None,
    );

    assert_eq!(chat.current_goal_status_indicator, None);
    assert!(chat.current_goal_status.is_none());
    assert!(chat.turn_lifecycle.budget_limited_turn_ids.is_empty());
}

#[test]
fn goal_status_indicator_formats_statuses_and_budgets() {
    assert_eq!(
        goal_status_indicator_from_app_goal(&test_thread_goal(
            lemurclaw_core::app_server_protocol::ThreadGoalStatus::Active,
            /*token_budget*/ Some(50_000),
            /*tokens_used*/ 40_000,
        )),
        Some(GoalStatusIndicator::Active {
            usage: Some("40K / 50K".to_string()),
        })
    );
    assert_eq!(
        goal_status_indicator_from_app_goal(&test_thread_goal(
            lemurclaw_core::app_server_protocol::ThreadGoalStatus::Active,
            /*token_budget*/ None,
            /*tokens_used*/ 0,
        )),
        Some(GoalStatusIndicator::Active {
            usage: Some("30m".to_string()),
        })
    );
    assert_eq!(
        goal_status_indicator_from_app_goal(&test_thread_goal(
            lemurclaw_core::app_server_protocol::ThreadGoalStatus::Blocked,
            /*token_budget*/ None,
            /*tokens_used*/ 0,
        )),
        Some(GoalStatusIndicator::Blocked)
    );
    assert_eq!(
        goal_status_indicator_from_app_goal(&test_thread_goal(
            lemurclaw_core::app_server_protocol::ThreadGoalStatus::UsageLimited,
            /*token_budget*/ None,
            /*tokens_used*/ 0,
        )),
        Some(GoalStatusIndicator::UsageLimited)
    );
    assert_eq!(
        goal_status_indicator_from_app_goal(&test_thread_goal(
            lemurclaw_core::app_server_protocol::ThreadGoalStatus::BudgetLimited,
            /*token_budget*/ Some(50_000),
            /*tokens_used*/ 51_000,
        )),
        Some(GoalStatusIndicator::BudgetLimited {
            usage: Some("51K / 50K tokens".to_string()),
        })
    );
    assert_eq!(
        goal_status_indicator_from_app_goal(&test_thread_goal(
            lemurclaw_core::app_server_protocol::ThreadGoalStatus::BudgetLimited,
            /*token_budget*/ None,
            /*tokens_used*/ 0,
        )),
        Some(GoalStatusIndicator::BudgetLimited { usage: None })
    );
    assert_eq!(
        goal_status_indicator_from_app_goal(&test_thread_goal(
            lemurclaw_core::app_server_protocol::ThreadGoalStatus::Complete,
            /*token_budget*/ Some(50_000),
            /*tokens_used*/ 40_000,
        )),
        Some(GoalStatusIndicator::Complete {
            usage: Some("40K tokens".to_string()),
        })
    );
}

#[test]
fn goal_status_indicator_line_formats_goal_text() {
    let cases = [
        (
            GoalStatusIndicator::Active {
                usage: Some("4K / 5K".to_string()),
            },
            "Pursuing goal (4K / 5K)",
        ),
        (
            GoalStatusIndicator::BudgetLimited {
                usage: Some("4K / 5K tokens".to_string()),
            },
            "Goal unmet (4K / 5K tokens)",
        ),
        (GoalStatusIndicator::Paused, "Goal paused (/goal resume)"),
        (GoalStatusIndicator::Blocked, "Goal blocked (/goal resume)"),
        (
            GoalStatusIndicator::UsageLimited,
            "Goal hit usage limits (/goal resume)",
        ),
        (
            GoalStatusIndicator::BudgetLimited { usage: None },
            "Goal abandoned",
        ),
        (
            GoalStatusIndicator::Complete {
                usage: Some("10h 12m".to_string()),
            },
            "Goal achieved (10h 12m)",
        ),
        (
            GoalStatusIndicator::Complete { usage: None },
            "Goal achieved",
        ),
    ];

    for (indicator, expected) in cases {
        let line =
            goal_status_indicator_line(Some(&indicator)).expect("goal indicator should render");
        let actual = line
            .spans
            .iter()
            .map(|span| span.content.as_ref())
            .collect::<String>();
        assert_eq!(expected, actual);
    }
}

fn test_thread_goal(
    status: lemurclaw_core::app_server_protocol::ThreadGoalStatus,
    token_budget: Option<i64>,
    tokens_used: i64,
) -> lemurclaw_core::app_server_protocol::ThreadGoal {
    lemurclaw_core::app_server_protocol::ThreadGoal {
        thread_id: "thread-1".to_string(),
        objective: "Keep improving the benchmark".to_string(),
        status,
        token_budget,
        tokens_used,
        time_used_seconds: 30 * 60,
        created_at: 0,
        updated_at: 0,
    }
}

#[tokio::test]
async fn runtime_metrics_websocket_timing_logs_and_final_separator_sums_totals() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.set_feature_enabled(Feature::RuntimeMetrics, /*enabled*/ true);

    chat.on_task_started();
    chat.apply_runtime_metrics_delta(RuntimeMetricsSummary {
        responses_api_engine_iapi_ttft_ms: 120,
        responses_api_engine_service_tbt_ms: 50.0,
        ..RuntimeMetricsSummary::default()
    });

    let first_log = drain_insert_history(&mut rx)
        .iter()
        .map(|lines| lines_to_single_string(lines))
        .find(|line| line.contains("WebSocket timing:"))
        .expect("expected websocket timing log");
    assert!(first_log.contains("TTFT: 120ms (iapi)"));
    assert!(first_log.contains("TBT: 50ms (service)"));

    chat.apply_runtime_metrics_delta(RuntimeMetricsSummary {
        responses_api_engine_iapi_ttft_ms: 80,
        ..RuntimeMetricsSummary::default()
    });

    let second_log = drain_insert_history(&mut rx)
        .iter()
        .map(|lines| lines_to_single_string(lines))
        .find(|line| line.contains("WebSocket timing:"))
        .expect("expected websocket timing log");
    assert!(second_log.contains("TTFT: 80ms (iapi)"));

    chat.on_task_complete(
        /*last_agent_message*/ None, /*duration_ms*/ None, /*from_replay*/ false,
    );
    let mut final_separator = None;
    while let Ok(event) = rx.try_recv() {
        if let AppEvent::InsertHistoryCell(cell) = event {
            final_separator = Some(lines_to_single_string(&cell.display_lines(/*width*/ 300)));
        }
    }
    let final_separator = final_separator.expect("expected final separator with runtime metrics");
    assert!(final_separator.contains("TTFT: 80ms (iapi)"));
    assert!(final_separator.contains("TBT: 50ms (service)"));
}

#[tokio::test]
async fn multiple_agent_messages_in_single_turn_emit_multiple_headers() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    // Begin turn
    handle_turn_started(&mut chat, "turn-1");

    // First finalized assistant message
    complete_assistant_message(&mut chat, "msg-first", "First message", /*phase*/ None);

    // Second finalized assistant message in the same turn
    complete_assistant_message(
        &mut chat,
        "msg-second",
        "Second message",
        /*phase*/ None,
    );

    // End turn
    handle_turn_completed(&mut chat, "turn-1", /*duration_ms*/ None);

    let cells = drain_insert_history(&mut rx);
    let combined: String = cells
        .iter()
        .map(|lines| lines_to_single_string(lines))
        .collect();
    assert!(
        combined.contains("First message"),
        "missing first message: {combined}"
    );
    assert!(
        combined.contains("Second message"),
        "missing second message: {combined}"
    );
    let first_idx = combined.find("First message").unwrap();
    let second_idx = combined.find("Second message").unwrap();
    assert!(first_idx < second_idx, "messages out of order: {combined}");
}

#[tokio::test]
async fn final_reasoning_then_message_without_deltas_are_rendered() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    // No deltas; only final reasoning followed by final message.
    handle_agent_reasoning_final(&mut chat);
    complete_assistant_message(
        &mut chat,
        "msg-result",
        "Here is the result.",
        /*phase*/ None,
    );

    // Drain history and snapshot the combined visible content.
    let cells = drain_insert_history(&mut rx);
    let combined = cells
        .iter()
        .map(|lines| lines_to_single_string(lines))
        .collect::<String>();
    assert_chatwidget_snapshot!(
        "final_reasoning_then_message_without_deltas_are_rendered",
        combined
    );
}

#[tokio::test]
async fn deltas_then_same_final_message_are_rendered_snapshot() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    // Stream some reasoning deltas first.
    handle_agent_reasoning_delta(&mut chat, "I will ");
    handle_agent_reasoning_delta(&mut chat, "first analyze the ");
    handle_agent_reasoning_delta(&mut chat, "request.");
    handle_agent_reasoning_final(&mut chat);

    // Then stream answer deltas, followed by the exact same final message.
    handle_agent_message_delta(&mut chat, "Here is the ");
    handle_agent_message_delta(&mut chat, "result.");

    complete_assistant_message(
        &mut chat,
        "msg-result",
        "Here is the result.",
        /*phase*/ None,
    );

    // Snapshot the combined visible content to ensure we render as expected
    // when deltas are followed by the identical final message.
    let cells = drain_insert_history(&mut rx);
    let combined = cells
        .iter()
        .map(|lines| lines_to_single_string(lines))
        .collect::<String>();
    assert_chatwidget_snapshot!(
        "deltas_then_same_final_message_are_rendered_snapshot",
        combined
    );
}

#[tokio::test]
async fn unterminated_agent_delta_does_not_redraw_unchanged_stream_tail() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.handle_streaming_delta("| Step | Owner |\n".to_string());
    assert!(chat.active_cell_is_stream_tail());
    let revision = chat.transcript.active_cell_revision;

    let (frame_requester, mut draw_rx) = FrameRequester::test_channel();
    chat.frame_requester = frame_requester;
    chat.handle_streaming_delta("| partial".to_string());

    assert_eq!(chat.transcript.active_cell_revision, revision);
    assert!(matches!(
        draw_rx.try_recv(),
        Err(tokio::sync::mpsc::error::TryRecvError::Empty)
    ));
}

#[tokio::test]
async fn newline_agent_delta_redraws_stream_tail_after_noop_catch_up() {
    let (frame_requester, mut draw_rx) = FrameRequester::test_channel();
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual_with_auth(
        /*model_override*/ None,
        /*has_chatgpt_account*/ false,
        /*has_codex_backend_auth*/ false,
        frame_requester,
    )
    .await;
    chat.on_task_started();
    chat.handle_streaming_delta("Earlier line\n".to_string());
    chat.on_commit_tick();
    assert!(!chat.bottom_pane.status_indicator_visible());
    while draw_rx.try_recv().is_ok() {}

    chat.handle_streaming_delta("Intro line\n| Step | Owner |\n".to_string());

    assert!(chat.active_cell_is_stream_tail());
    assert!(
        draw_rx.try_recv().is_ok(),
        "expected the changed assistant stream tail to schedule a redraw",
    );
}

#[tokio::test]
async fn newline_plan_delta_redraws_stream_tail_after_noop_catch_up() {
    let (frame_requester, mut draw_rx) = FrameRequester::test_channel();
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual_with_auth(
        /*model_override*/ Some("gpt-5"),
        /*has_chatgpt_account*/ false,
        /*has_codex_backend_auth*/ false,
        frame_requester,
    )
    .await;
    chat.set_feature_enabled(Feature::CollaborationModes, /*enabled*/ true);
    let plan_mask = collaboration_modes::mask_for_kind(chat.model_catalog.as_ref(), ModeKind::Plan)
        .expect("expected plan collaboration mask");
    chat.set_collaboration_mask(plan_mask);
    chat.on_task_started();
    chat.on_plan_delta("Earlier line\n".to_string());
    chat.on_commit_tick();
    assert!(!chat.bottom_pane.status_indicator_visible());
    while draw_rx.try_recv().is_ok() {}

    chat.on_plan_delta("Intro line\n| Step | Owner |\n".to_string());

    assert!(chat.active_cell_is_stream_tail());
    assert!(
        draw_rx.try_recv().is_ok(),
        "expected the changed plan stream tail to schedule a redraw",
    );
}

#[tokio::test]
async fn regular_commit_tick_clears_orphaned_plan_stream_tail() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5")).await;
    chat.set_feature_enabled(Feature::CollaborationModes, /*enabled*/ true);
    let plan_mask = collaboration_modes::mask_for_kind(chat.model_catalog.as_ref(), ModeKind::Plan)
        .expect("expected plan collaboration mask");
    chat.set_collaboration_mask(plan_mask);
    chat.on_task_started();
    chat.on_plan_delta("| Step | Owner |\n".to_string());
    assert!(chat.active_cell_is_stream_tail());

    chat.on_task_started();
    assert!(chat.active_cell_is_stream_tail());
    chat.on_commit_tick();

    assert!(!chat.active_cell_is_stream_tail());
}

#[tokio::test]
async fn reasoning_delta_redraws_only_when_header_becomes_visible() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    let (frame_requester, mut draw_rx) = FrameRequester::test_channel();
    chat.frame_requester = frame_requester;

    chat.on_agent_reasoning_delta("still looking".to_string());
    assert!(matches!(
        draw_rx.try_recv(),
        Err(tokio::sync::mpsc::error::TryRecvError::Empty)
    ));
    assert_eq!(chat.reasoning_header, None);

    chat.on_agent_reasoning_delta(" **Checking".to_string());
    assert!(matches!(
        draw_rx.try_recv(),
        Err(tokio::sync::mpsc::error::TryRecvError::Empty)
    ));

    chat.on_agent_reasoning_delta(" files**".to_string());
    assert!(draw_rx.try_recv().is_ok());
    assert_eq!(chat.reasoning_header.as_deref(), Some("Checking files"));

    chat.on_agent_reasoning_delta(" and preparing a response".to_string());
    assert!(matches!(
        draw_rx.try_recv(),
        Err(tokio::sync::mpsc::error::TryRecvError::Empty)
    ));
}

#[tokio::test]
async fn reasoning_delta_does_not_double_schedule_visible_status_redraw() {
    let (frame_requester, mut draw_rx) = FrameRequester::test_channel();
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual_with_auth(
        /*model_override*/ None,
        /*has_chatgpt_account*/ false,
        /*has_codex_backend_auth*/ false,
        frame_requester,
    )
    .await;
    chat.on_task_started();
    assert!(chat.bottom_pane.status_indicator_visible());
    while draw_rx.try_recv().is_ok() {}

    chat.on_agent_reasoning_delta("**Checking files**".to_string());

    assert_eq!(chat.reasoning_header.as_deref(), Some("Checking files"));
    assert!(draw_rx.try_recv().is_ok());
    assert!(matches!(
        draw_rx.try_recv(),
        Err(tokio::sync::mpsc::error::TryRecvError::Empty)
    ));
}

#[tokio::test]
async fn reasoning_delta_restores_recreated_status_indicator_header() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.on_task_started();
    chat.on_agent_reasoning_delta("**Checking files**".to_string());

    chat.on_agent_message_delta("Preamble line\n".to_string());
    chat.on_commit_tick();
    drain_insert_history(&mut rx);
    assert!(!chat.bottom_pane.status_indicator_visible());

    begin_unified_exec_startup(&mut chat, "call-1", "proc-1", "sleep 2");
    let status = chat
        .bottom_pane
        .status_widget()
        .expect("status indicator should be recreated");
    assert_eq!(status.header(), "Working");

    chat.on_agent_reasoning_delta(" and preparing a response".to_string());

    let status = chat
        .bottom_pane
        .status_widget()
        .expect("status indicator should remain visible");
    assert_eq!(status.header(), "Checking files");

    let width: u16 = 80;
    let height = chat.desired_height(width);
    let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(width, height))
        .expect("create terminal");
    terminal.set_viewport_area(Rect::new(/*x*/ 0, /*y*/ 0, width, height));
    terminal
        .draw(|frame| chat.render(frame.area(), frame.buffer_mut()))
        .expect("draw restored reasoning status");
    assert_chatwidget_snapshot!(
        "reasoning_delta_restores_recreated_status_indicator",
        normalized_backend_snapshot(terminal.backend())
    );
}

#[tokio::test]
async fn user_prompt_submit_app_server_hook_notifications_render_snapshot() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    chat.handle_server_notification(
        ServerNotification::HookStarted(AppServerHookStartedNotification {
            thread_id: ThreadId::new().to_string(),
            turn_id: Some("turn-1".to_string()),
            run: AppServerHookRunSummary {
                id: "user-prompt-submit:0:/tmp/hooks.json".to_string(),
                event_name: AppServerHookEventName::UserPromptSubmit,
                handler_type: AppServerHookHandlerType::Command,
                execution_mode: AppServerHookExecutionMode::Sync,
                scope: AppServerHookScope::Turn,
                source_path: PathBuf::from(test_path_display("/tmp/hooks.json")).abs(),
                source: lemurclaw_core::app_server_protocol::HookSource::User,
                display_order: 0,
                status: AppServerHookRunStatus::Running,
                status_message: Some("checking go-workflow input policy".to_string()),
                started_at: 1,
                completed_at: None,
                duration_ms: None,
                entries: Vec::new(),
            },
        }),
        /*replay_kind*/ None,
    );
    chat.handle_server_notification(
        ServerNotification::HookCompleted(AppServerHookCompletedNotification {
            thread_id: ThreadId::new().to_string(),
            turn_id: Some("turn-1".to_string()),
            run: AppServerHookRunSummary {
                id: "user-prompt-submit:0:/tmp/hooks.json".to_string(),
                event_name: AppServerHookEventName::UserPromptSubmit,
                handler_type: AppServerHookHandlerType::Command,
                execution_mode: AppServerHookExecutionMode::Sync,
                scope: AppServerHookScope::Turn,
                source_path: PathBuf::from(test_path_display("/tmp/hooks.json")).abs(),
                source: lemurclaw_core::app_server_protocol::HookSource::User,
                display_order: 0,
                status: AppServerHookRunStatus::Stopped,
                status_message: Some("checking go-workflow input policy".to_string()),
                started_at: 1,
                completed_at: Some(11),
                duration_ms: Some(10),
                entries: vec![
                    AppServerHookOutputEntry {
                        kind: AppServerHookOutputEntryKind::Warning,
                        text: "go-workflow must start from PlanMode".to_string(),
                    },
                    AppServerHookOutputEntry {
                        kind: AppServerHookOutputEntryKind::Stop,
                        text: "prompt blocked".to_string(),
                    },
                ],
            },
        }),
        /*replay_kind*/ None,
    );

    let cells = drain_insert_history(&mut rx);
    let combined = cells
        .iter()
        .map(|lines| lines_to_single_string(lines))
        .collect::<String>();
    assert_chatwidget_snapshot!(
        "user_prompt_submit_app_server_hook_notifications_render_snapshot",
        combined
    );
    assert!(!chat.bottom_pane.status_indicator_visible());
}

#[tokio::test]
async fn pre_tool_use_hook_events_render_snapshot() {
    assert_hook_events_snapshot(
        lemurclaw_core::app_server_protocol::HookEventName::PreToolUse,
        "pre-tool-use:0:/tmp/hooks.json",
        "warming the shell",
        "pre_tool_use_hook_events_render_snapshot",
    )
    .await;
}

#[tokio::test]
async fn post_tool_use_hook_events_render_snapshot() {
    assert_hook_events_snapshot(
        lemurclaw_core::app_server_protocol::HookEventName::PostToolUse,
        "post-tool-use:0:/tmp/hooks.json",
        "warming the shell",
        "post_tool_use_hook_events_render_snapshot",
    )
    .await;
}

#[tokio::test]
async fn completed_hook_with_no_entries_stays_out_of_history() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    handle_hook_started(
        &mut chat,
        hook_started_run(
            "post-tool-use:0:/tmp/hooks.json",
            lemurclaw_core::app_server_protocol::HookEventName::PostToolUse,
            /*status_message*/ None,
        ),
    );
    assert!(drain_insert_history(&mut rx).is_empty());
    reveal_running_hooks(&mut chat);
    let running_snapshot = hook_live_and_history_snapshot(&chat, "running", "");

    handle_hook_completed(
        &mut chat,
        hook_completed_run(
            "post-tool-use:0:/tmp/hooks.json",
            lemurclaw_core::app_server_protocol::HookEventName::PostToolUse,
            lemurclaw_core::app_server_protocol::HookRunStatus::Completed,
            Vec::new(),
        ),
    );

    assert!(drain_insert_history(&mut rx).is_empty());
    let completed_lingering_snapshot =
        hook_live_and_history_snapshot(&chat, "completed lingering", "");
    expire_quiet_hook_linger(&mut chat);
    let completed_snapshot = hook_live_and_history_snapshot(&chat, "completed after linger", "");
    assert_chatwidget_snapshot!(
        "hook_live_running_then_quiet_completed_snapshot",
        format!("{running_snapshot}\n\n{completed_lingering_snapshot}\n\n{completed_snapshot}")
    );
}

#[tokio::test]
async fn quiet_hook_linger_starts_when_delayed_redraw_reveals_hook() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    handle_hook_started(
        &mut chat,
        hook_started_run(
            "post-tool-use:0:/tmp/hooks.json",
            lemurclaw_core::app_server_protocol::HookEventName::PostToolUse,
            Some("checking output policy"),
        ),
    );
    assert!(drain_insert_history(&mut rx).is_empty());

    reveal_running_hooks_after_delayed_redraw(&mut chat);
    handle_hook_completed(
        &mut chat,
        hook_completed_run(
            "post-tool-use:0:/tmp/hooks.json",
            lemurclaw_core::app_server_protocol::HookEventName::PostToolUse,
            lemurclaw_core::app_server_protocol::HookRunStatus::Completed,
            Vec::new(),
        ),
    );

    assert!(drain_insert_history(&mut rx).is_empty());
    assert!(
        active_hook_blob(&chat).contains("Running PostToolUse hook"),
        "quiet hook should linger after the row becomes visible"
    );
    expire_quiet_hook_linger(&mut chat);
    assert_eq!(active_hook_blob(&chat), "<empty>\n");
}

#[tokio::test]
async fn blocked_and_failed_hooks_render_feedback_and_errors() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    handle_hook_completed(
        &mut chat,
        hook_completed_run(
            "pre-tool-use:0:/tmp/hooks.json",
            lemurclaw_core::app_server_protocol::HookEventName::PreToolUse,
            lemurclaw_core::app_server_protocol::HookRunStatus::Blocked,
            vec![lemurclaw_core::app_server_protocol::HookOutputEntry {
                kind: lemurclaw_core::app_server_protocol::HookOutputEntryKind::Feedback,
                text: "run tests before touching the fixture".to_string(),
            }],
        ),
    );
    handle_hook_completed(
        &mut chat,
        hook_completed_run(
            "post-tool-use:1:/tmp/hooks.json",
            lemurclaw_core::app_server_protocol::HookEventName::PostToolUse,
            lemurclaw_core::app_server_protocol::HookRunStatus::Failed,
            vec![lemurclaw_core::app_server_protocol::HookOutputEntry {
                kind: lemurclaw_core::app_server_protocol::HookOutputEntryKind::Error,
                text: "hook exited with code 7".to_string(),
            }],
        ),
    );

    let rendered = drain_insert_history(&mut rx)
        .iter()
        .map(|lines| lines_to_single_string(lines))
        .collect::<String>();
    assert_chatwidget_snapshot!("hook_blocked_failed_feedback_history_snapshot", rendered);
    assert!(
        rendered.contains(
            "PreToolUse hook (blocked)\n  feedback: run tests before touching the fixture"
        ),
        "expected blocked hook feedback: {rendered:?}"
    );
    assert!(
        rendered.contains("PostToolUse hook (failed)\n  error: hook exited with code 7"),
        "expected failed hook error: {rendered:?}"
    );
}

#[tokio::test]
async fn completed_hook_with_output_flushes_immediately() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    handle_hook_started(
        &mut chat,
        hook_started_run(
            "pre-tool-use:0:/tmp/hooks.json:tool-call-1",
            lemurclaw_core::app_server_protocol::HookEventName::PreToolUse,
            Some("checking command"),
        ),
    );
    reveal_running_hooks(&mut chat);
    let running_snapshot = hook_live_and_history_snapshot(&chat, "running", "");

    handle_hook_completed(
        &mut chat,
        hook_completed_run(
            "pre-tool-use:0:/tmp/hooks.json:tool-call-1",
            lemurclaw_core::app_server_protocol::HookEventName::PreToolUse,
            lemurclaw_core::app_server_protocol::HookRunStatus::Blocked,
            vec![lemurclaw_core::app_server_protocol::HookOutputEntry {
                kind: lemurclaw_core::app_server_protocol::HookOutputEntryKind::Feedback,
                text: "command blocked by policy".to_string(),
            }],
        ),
    );
    let history = drain_insert_history(&mut rx)
        .iter()
        .map(|lines| lines_to_single_string(lines))
        .collect::<String>();
    let completed_snapshot = hook_live_and_history_snapshot(&chat, "completed", &history);

    assert_chatwidget_snapshot!(
        "completed_hook_with_output_flushes_immediately_snapshot",
        format!("{running_snapshot}\n\n{completed_snapshot}")
    );
}

#[tokio::test]
async fn completed_hook_output_precedes_following_assistant_message() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    handle_hook_started(
        &mut chat,
        hook_started_run(
            "pre-tool-use:0:/tmp/hooks.json:tool-call-1",
            lemurclaw_core::app_server_protocol::HookEventName::PreToolUse,
            Some("checking command"),
        ),
    );
    reveal_running_hooks(&mut chat);

    handle_hook_completed(
        &mut chat,
        hook_completed_run(
            "pre-tool-use:0:/tmp/hooks.json:tool-call-1",
            lemurclaw_core::app_server_protocol::HookEventName::PreToolUse,
            lemurclaw_core::app_server_protocol::HookRunStatus::Blocked,
            vec![lemurclaw_core::app_server_protocol::HookOutputEntry {
                kind: lemurclaw_core::app_server_protocol::HookOutputEntryKind::Feedback,
                text: "command blocked by policy".to_string(),
            }],
        ),
    );

    complete_assistant_message(
        &mut chat,
        "msg-after-hook",
        "The hook feedback was applied.",
        /*phase*/ None,
    );

    let history = drain_insert_history(&mut rx)
        .iter()
        .map(|lines| lines_to_single_string(lines))
        .collect::<String>();
    assert_chatwidget_snapshot!(
        "completed_hook_output_precedes_following_assistant_message_snapshot",
        format!(
            "active hooks:\n{}history:\n{history}",
            active_hook_blob(&chat)
        )
    );
    let hook_index = history
        .find("PreToolUse hook (blocked)")
        .expect("hook feedback should be in history");
    let assistant_index = history
        .find("The hook feedback was applied.")
        .expect("assistant message should be in history");
    assert!(
        hook_index < assistant_index,
        "hook output should precede later assistant text: {history:?}"
    );
}

#[tokio::test]
async fn completed_same_id_hook_output_survives_restart() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    let hook_id = "stop:0:/tmp/hooks.json";

    handle_hook_started(
        &mut chat,
        hook_started_run(
            hook_id,
            lemurclaw_core::app_server_protocol::HookEventName::Stop,
            Some("checking stop condition"),
        ),
    );
    reveal_running_hooks(&mut chat);
    handle_hook_completed(
        &mut chat,
        hook_completed_run(
            hook_id,
            lemurclaw_core::app_server_protocol::HookEventName::Stop,
            lemurclaw_core::app_server_protocol::HookRunStatus::Stopped,
            vec![lemurclaw_core::app_server_protocol::HookOutputEntry {
                kind: lemurclaw_core::app_server_protocol::HookOutputEntryKind::Stop,
                text: "continue with more context".to_string(),
            }],
        ),
    );
    handle_hook_started(
        &mut chat,
        hook_started_run(
            hook_id,
            lemurclaw_core::app_server_protocol::HookEventName::Stop,
            Some("checking stop condition"),
        ),
    );
    reveal_running_hooks(&mut chat);

    let history = drain_insert_history(&mut rx)
        .iter()
        .map(|lines| lines_to_single_string(lines))
        .collect::<String>();
    assert_chatwidget_snapshot!(
        "completed_same_id_hook_output_survives_restart_snapshot",
        format!(
            "active hooks:\n{}history:\n{history}",
            active_hook_blob(&chat)
        )
    );
    assert!(
        history.contains("Stop hook (stopped)\n  stop: continue with more context"),
        "first hook output should not be overwritten: {history:?}"
    );
}

#[tokio::test]
async fn identical_parallel_running_hooks_collapse_to_count() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    for tool_call_id in ["tool-call-1", "tool-call-2", "tool-call-3"] {
        handle_hook_started(
            &mut chat,
            hook_started_run(
                &format!("pre-tool-use:0:/tmp/hooks.json:{tool_call_id}"),
                lemurclaw_core::app_server_protocol::HookEventName::PreToolUse,
                Some("checking command policy"),
            ),
        );
    }
    reveal_running_hooks(&mut chat);

    assert_chatwidget_snapshot!(
        "identical_parallel_running_hooks_collapse_to_count_snapshot",
        hook_live_and_history_snapshot(&chat, "running", "")
    );
}

#[tokio::test]
async fn overlapping_hook_live_cell_tracks_parallel_quiet_hooks() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    chat.set_status_header("Thinking".to_string());
    chat.bottom_pane.ensure_status_indicator();

    handle_hook_started(
        &mut chat,
        hook_started_run(
            "pre-tool-use:0:/tmp/hooks.json",
            lemurclaw_core::app_server_protocol::HookEventName::PreToolUse,
            Some("checking command policy"),
        ),
    );
    assert_eq!(chat.status_state.current_status.header, "Thinking");
    reveal_running_hooks(&mut chat);
    let first_running_snapshot = hook_live_and_history_snapshot(&chat, "pre running", "");

    handle_hook_started(
        &mut chat,
        hook_started_run(
            "post-tool-use:1:/tmp/hooks.json",
            lemurclaw_core::app_server_protocol::HookEventName::PostToolUse,
            Some("checking output policy"),
        ),
    );
    assert_eq!(chat.status_state.current_status.header, "Thinking");
    reveal_running_hooks(&mut chat);
    let second_running_snapshot = hook_live_and_history_snapshot(&chat, "post running", "");

    handle_hook_completed(
        &mut chat,
        hook_completed_run(
            "pre-tool-use:0:/tmp/hooks.json",
            lemurclaw_core::app_server_protocol::HookEventName::PreToolUse,
            lemurclaw_core::app_server_protocol::HookRunStatus::Completed,
            Vec::new(),
        ),
    );
    assert_eq!(chat.status_state.current_status.header, "Thinking");
    let older_completed_snapshot =
        hook_live_and_history_snapshot(&chat, "pre completed lingering", "");
    expire_quiet_hook_linger(&mut chat);
    let older_completed_expired_snapshot =
        hook_live_and_history_snapshot(&chat, "pre completed after linger", "");

    handle_hook_completed(
        &mut chat,
        hook_completed_run(
            "post-tool-use:1:/tmp/hooks.json",
            lemurclaw_core::app_server_protocol::HookEventName::PostToolUse,
            lemurclaw_core::app_server_protocol::HookRunStatus::Completed,
            Vec::new(),
        ),
    );
    assert_eq!(chat.status_state.current_status.header, "Thinking");
    assert!(chat.bottom_pane.status_indicator_visible());
    assert!(drain_insert_history(&mut rx).is_empty());
    let all_completed_lingering_snapshot =
        hook_live_and_history_snapshot(&chat, "all completed lingering", "");
    expire_quiet_hook_linger(&mut chat);
    let all_completed_snapshot = hook_live_and_history_snapshot(&chat, "all completed", "");
    assert_chatwidget_snapshot!(
        "overlapping_hook_live_cell_snapshot",
        format!(
            "{first_running_snapshot}\n\n{second_running_snapshot}\n\n{older_completed_snapshot}\n\n{older_completed_expired_snapshot}\n\n{all_completed_lingering_snapshot}\n\n{all_completed_snapshot}"
        )
    );
}

#[tokio::test]
async fn running_hook_does_not_displace_active_exec_cell() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    let begin = begin_exec(&mut chat, "call-1", "echo done");
    let exec_running = active_blob(&chat);

    handle_hook_started(
        &mut chat,
        hook_started_run(
            "post-tool-use:0:/tmp/hooks.json",
            lemurclaw_core::app_server_protocol::HookEventName::PostToolUse,
            Some("checking output policy"),
        ),
    );
    reveal_running_hooks(&mut chat);
    let exec_and_hook_running = format!(
        "active exec:\n{}active hooks:\n{}",
        active_blob(&chat),
        active_hook_blob(&chat)
    );

    end_exec(&mut chat, begin, "done", "", /*exit_code*/ 0);
    let history_after_exec = drain_insert_history(&mut rx)
        .iter()
        .map(|lines| lines_to_single_string(lines))
        .collect::<String>();
    let hook_running_after_exec = active_hook_blob(&chat);

    handle_hook_completed(
        &mut chat,
        hook_completed_run(
            "post-tool-use:0:/tmp/hooks.json",
            lemurclaw_core::app_server_protocol::HookEventName::PostToolUse,
            lemurclaw_core::app_server_protocol::HookRunStatus::Completed,
            Vec::new(),
        ),
    );
    assert!(drain_insert_history(&mut rx).is_empty());
    let quiet_hook_completed_lingering = active_hook_blob(&chat);
    expire_quiet_hook_linger(&mut chat);
    let quiet_hook_completed = active_hook_blob(&chat);

    assert_chatwidget_snapshot!(
        "hook_runs_while_exec_active_snapshot",
        format!(
            "exec running:\n{exec_running}\nexec and hook running:\n{exec_and_hook_running}\nhistory after exec:\n{history_after_exec}\nhook running after exec:\n{hook_running_after_exec}\nquiet hook completed lingering:\n{quiet_hook_completed_lingering}\nquiet hook completed:\n{quiet_hook_completed}"
        )
    );
}

#[tokio::test]
async fn hidden_active_hook_does_not_add_transcript_separator() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    begin_exec(&mut chat, "call-1", "echo done");
    let exec_only_line_count = chat
        .active_cell_transcript_lines(/*width*/ 80)
        .expect("active exec transcript lines")
        .len();

    handle_hook_started(
        &mut chat,
        hook_started_run(
            "post-tool-use:0:/tmp/hooks.json",
            lemurclaw_core::app_server_protocol::HookEventName::PostToolUse,
            Some("checking output policy"),
        ),
    );
    let hidden_hook_transcript = chat
        .active_cell_transcript_lines(/*width*/ 80)
        .expect("active exec transcript lines");
    assert_eq!(hidden_hook_transcript.len(), exec_only_line_count);

    reveal_running_hooks(&mut chat);
    let visible_hook_lines = chat
        .active_hook_cell
        .as_ref()
        .expect("active hook cell")
        .transcript_lines(/*width*/ 80);
    let visible_hook_transcript = chat
        .active_cell_transcript_lines(/*width*/ 80)
        .expect("active exec and hook transcript lines");
    assert_eq!(
        visible_hook_transcript.len(),
        exec_only_line_count + 1 + visible_hook_lines.len()
    );
    assert_eq!(
        lines_to_single_string(
            &visible_hook_transcript[exec_only_line_count..exec_only_line_count + 1],
        ),
        "\n"
    );
}

#[tokio::test]
async fn hook_completed_before_reveal_renders_completed_without_running_flash() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    handle_hook_started(
        &mut chat,
        hook_started_run(
            "session-start:0:/tmp/hooks.json",
            lemurclaw_core::app_server_protocol::HookEventName::SessionStart,
            Some("warming the shell"),
        ),
    );
    let started_hidden_snapshot = active_hook_blob(&chat);

    handle_hook_completed(
        &mut chat,
        hook_completed_run(
            "session-start:0:/tmp/hooks.json",
            lemurclaw_core::app_server_protocol::HookEventName::SessionStart,
            lemurclaw_core::app_server_protocol::HookRunStatus::Completed,
            vec![lemurclaw_core::app_server_protocol::HookOutputEntry {
                kind: lemurclaw_core::app_server_protocol::HookOutputEntryKind::Context,
                text: "session context\nsecond line".to_string(),
            }],
        ),
    );

    let history = drain_insert_history(&mut rx)
        .iter()
        .map(|lines| lines_to_single_string(lines))
        .collect::<String>();
    assert_chatwidget_snapshot!(
        "hook_completed_before_reveal_renders_completed_without_running_flash_snapshot",
        format!("started hidden:\n{started_hidden_snapshot}\nhistory:\n{history}")
    );
}

#[tokio::test]
async fn long_hook_context_is_truncated_with_transcript_hint_snapshot() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    handle_hook_completed(
        &mut chat,
        hook_completed_run(
            "session-start:0:/tmp/hooks.json",
            lemurclaw_core::app_server_protocol::HookEventName::SessionStart,
            lemurclaw_core::app_server_protocol::HookRunStatus::Stopped,
            vec![
                lemurclaw_core::app_server_protocol::HookOutputEntry {
                    kind: lemurclaw_core::app_server_protocol::HookOutputEntryKind::Context,
                    text: "This hook context is intentionally long enough to wrap across several terminal rows while keeping the complete value available in the transcript overlay. The main conversation should stay compact even when a hook injects a large block of instructions for the model."
                        .to_string(),
                },
                lemurclaw_core::app_server_protocol::HookOutputEntry {
                    kind: lemurclaw_core::app_server_protocol::HookOutputEntryKind::Stop,
                    text: "The hook stopped this turn for an important reason.\nThis second line must remain visible in full."
                        .to_string(),
                },
            ],
        ),
    );

    let history = drain_insert_history(&mut rx)
        .iter()
        .map(|lines| lines_to_single_string(lines))
        .collect::<String>();
    assert_chatwidget_snapshot!(
        "long_hook_context_is_truncated_with_transcript_hint",
        history
    );
}

#[tokio::test]
async fn session_start_hook_events_render_snapshot() {
    assert_hook_events_snapshot(
        lemurclaw_core::app_server_protocol::HookEventName::SessionStart,
        "session-start:0:/tmp/hooks.json",
        "warming the shell",
        "session_start_hook_events_render_snapshot",
    )
    .await;
}

fn hook_started_run(
    id: &str,
    event_name: lemurclaw_core::app_server_protocol::HookEventName,
    status_message: Option<&str>,
) -> lemurclaw_core::app_server_protocol::HookRunSummary {
    hook_run_summary(
        id,
        event_name,
        lemurclaw_core::app_server_protocol::HookRunStatus::Running,
        status_message,
        Vec::new(),
    )
}

fn hook_completed_run(
    id: &str,
    event_name: lemurclaw_core::app_server_protocol::HookEventName,
    status: lemurclaw_core::app_server_protocol::HookRunStatus,
    entries: Vec<lemurclaw_core::app_server_protocol::HookOutputEntry>,
) -> lemurclaw_core::app_server_protocol::HookRunSummary {
    hook_run_summary(
        id, event_name, status, /*status_message*/ None, entries,
    )
}

fn hook_run_summary(
    id: &str,
    event_name: lemurclaw_core::app_server_protocol::HookEventName,
    status: lemurclaw_core::app_server_protocol::HookRunStatus,
    status_message: Option<&str>,
    entries: Vec<lemurclaw_core::app_server_protocol::HookOutputEntry>,
) -> lemurclaw_core::app_server_protocol::HookRunSummary {
    lemurclaw_core::app_server_protocol::HookRunSummary {
        id: id.to_string(),
        event_name,
        handler_type: lemurclaw_core::app_server_protocol::HookHandlerType::Command,
        execution_mode: lemurclaw_core::app_server_protocol::HookExecutionMode::Sync,
        scope: lemurclaw_core::app_server_protocol::HookScope::Turn,
        source_path: PathBuf::from(test_path_display("/tmp/hooks.json")).abs(),
        source: lemurclaw_core::app_server_protocol::HookSource::User,
        display_order: 0,
        status,
        status_message: status_message.map(str::to_string),
        started_at: 1,
        completed_at: (status != lemurclaw_core::app_server_protocol::HookRunStatus::Running).then_some(2),
        duration_ms: (status != lemurclaw_core::app_server_protocol::HookRunStatus::Running).then_some(1),
        entries,
    }
}

fn hook_live_and_history_snapshot(chat: &ChatWidget, phase: &str, history: &str) -> String {
    let history = if history.is_empty() {
        "<empty>"
    } else {
        history
    };
    format!(
        "{phase}\nlive hooks:\n{}history:\n{history}",
        active_hook_blob(chat),
    )
}

// Combined visual snapshot using vt100 for history + direct buffer overlay for UI.
// This renders the final visual as seen in a terminal: history above, then a blank line,
// then the exec block, another blank line, the status line, a blank line, and the composer.
#[tokio::test]
async fn chatwidget_exec_and_status_layout_vt100_snapshot() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    complete_assistant_message(
        &mut chat,
        "msg-search",
        "I’m going to search the repo for where “Change Approved” is rendered to update that view.",
        /*phase*/ None,
    );

    let command = vec!["bash".into(), "-lc".into(), "rg \"Change Approved\"".into()];
    let parsed_cmd = [
        ParsedCommand::Search {
            query: Some("Change Approved".into()),
            path: None,
            cmd: "rg \"Change Approved\"".into(),
        },
        ParsedCommand::Read {
            name: "diff_render.rs".into(),
            cmd: "cat diff_render.rs".into(),
            path: "diff_render.rs".into(),
        },
    ];
    let command_actions = parsed_cmd
        .iter()
        .cloned()
        .map(|parsed| AppServerCommandAction::from_core_with_cwd(parsed, &chat.config.cwd))
        .collect::<Vec<_>>();
    let cwd = chat.config.cwd.clone();
    handle_exec_begin(
        &mut chat,
        AppServerThreadItem::CommandExecution {
            id: "c1".into(),
            command: lemurclaw_core::shell_command::parse_command::shlex_join(&command),
            cwd: cwd.clone().into(),
            process_id: None,
            source: ExecCommandSource::Agent,
            status: AppServerCommandExecutionStatus::InProgress,
            command_actions: command_actions.clone(),
            aggregated_output: None,
            exit_code: None,
            duration_ms: None,
        },
    );
    handle_exec_end(
        &mut chat,
        AppServerThreadItem::CommandExecution {
            id: "c1".into(),
            command: lemurclaw_core::shell_command::parse_command::shlex_join(&command),
            cwd: cwd.into(),
            process_id: None,
            source: ExecCommandSource::Agent,
            status: AppServerCommandExecutionStatus::Completed,
            command_actions,
            aggregated_output: None,
            exit_code: Some(0),
            duration_ms: Some(16000),
        },
    );
    handle_turn_started(&mut chat, "turn-1");
    handle_agent_reasoning_delta(&mut chat, "**Investigating rendering code**");
    chat.bottom_pane.set_composer_text(
        "Summarize recent commits".to_string(),
        Vec::new(),
        Vec::new(),
    );

    let width: u16 = 80;
    let ui_height: u16 = chat.desired_height(width);
    let vt_height: u16 = 40;
    let viewport = Rect::new(0, vt_height - ui_height - 1, width, ui_height);

    let backend = VT100Backend::new(width, vt_height);
    let mut term = crate::tui_internal::custom_terminal::Terminal::with_options(backend).expect("terminal");
    term.set_viewport_area(viewport);

    for lines in drain_insert_history(&mut rx) {
        crate::tui_internal::insert_history::insert_history_lines(&mut term, lines)
            .expect("Failed to insert history lines in test");
    }

    term.draw(|f| {
        chat.render(f.area(), f.buffer_mut());
    })
    .unwrap();

    assert_chatwidget_snapshot!(
        "chatwidget_exec_and_status_layout_vt100_snapshot",
        normalize_snapshot_paths(term.backend().vt100().screen().contents())
    );
}

// E2E vt100 snapshot for complex markdown with indented and nested fenced code blocks
#[tokio::test]
async fn chatwidget_markdown_code_blocks_vt100_snapshot() {
    let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;

    // Simulate a final agent message via streaming deltas instead of a single message

    handle_turn_started(&mut chat, "turn-1");
    // Build a vt100 visual from the history insertions only (no UI overlay)
    let width: u16 = 80;
    let height: u16 = 50;
    let backend = VT100Backend::new(width, height);
    let mut term = crate::tui_internal::custom_terminal::Terminal::with_options(backend).expect("terminal");
    // Place viewport at the last line so that history lines insert above it
    term.set_viewport_area(Rect::new(0, height - 1, width, 1));

    // Simulate streaming via AgentMessageDelta in 2-character chunks (no final AgentMessage).
    let source: &str = r#"

    -- Indented code block (4 spaces)
    SELECT *
    FROM "users"
    WHERE "email" LIKE '%@example.com';

````markdown
```sh
printf 'fenced within fenced\n'
```
````

```jsonc
{
  // comment allowed in jsonc
  "path": "C:\\Program Files\\App",
  "regex": "^foo.*(bar)?$"
}
```
"#;

    let mut it = source.chars();
    loop {
        let mut delta = String::new();
        match it.next() {
            Some(c) => delta.push(c),
            None => break,
        }
        if let Some(c2) = it.next() {
            delta.push(c2);
        }

        handle_agent_message_delta(&mut chat, delta);
        // Drive commit ticks and drain emitted history lines into the vt100 buffer.
        loop {
            chat.on_commit_tick();
            let mut inserted_any = false;
            while let Ok(app_ev) = rx.try_recv() {
                if let AppEvent::InsertHistoryCell(cell) = app_ev {
                    let lines = cell.display_lines(width);
                    crate::tui_internal::insert_history::insert_history_lines(&mut term, lines)
                        .expect("Failed to insert history lines in test");
                    inserted_any = true;
                }
            }
            if !inserted_any {
                break;
            }
        }
    }

    // Finalize the stream without sending a final AgentMessage, to flush any tail.
    handle_turn_completed(&mut chat, "turn-1", /*duration_ms*/ None);
    for lines in drain_insert_history(&mut rx) {
        crate::tui_internal::insert_history::insert_history_lines(&mut term, lines)
            .expect("Failed to insert history lines in test");
    }

    assert_chatwidget_snapshot!(
        "chatwidget_markdown_code_blocks_vt100_snapshot",
        normalize_snapshot_paths(term.backend().vt100().screen().contents())
    );
}

#[tokio::test]
async fn chatwidget_tall() {
    let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
    chat.thread_id = Some(ThreadId::new());
    handle_turn_started(&mut chat, "turn-1");
    for i in 0..30 {
        chat.queue_user_message(format!("Hello, world! {i}").into());
    }
    let width: u16 = 80;
    let height: u16 = 24;
    let backend = VT100Backend::new(width, height);
    let mut term = crate::tui_internal::custom_terminal::Terminal::with_options(backend).expect("terminal");
    let desired_height = chat.desired_height(width).min(height);
    term.set_viewport_area(Rect::new(0, height - desired_height, width, desired_height));
    term.draw(|f| {
        chat.render(f.area(), f.buffer_mut());
    })
    .unwrap();
    assert_chatwidget_snapshot!(
        "chatwidget_tall",
        normalize_snapshot_paths(term.backend().vt100().screen().contents())
    );
}