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
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
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/* eslint-disable @typescript-eslint/no-explicit-any */
import {
  describe,
  it,
  expect,
  vi,
  beforeEach,
  type Mock,
  type MockInstance,
} from 'vitest';
import { act } from 'react';
import { renderHookWithProviders } from '../../test-utils/render.js';
import { waitFor } from '../../test-utils/async.js';
import { useGeminiStream } from './useGeminiStream.js';
import { useKeypress } from './useKeypress.js';
import * as atCommandProcessor from './atCommandProcessor.js';
import {
  useToolScheduler,
  type TrackedToolCall,
  type TrackedCompletedToolCall,
  type TrackedExecutingToolCall,
  type TrackedCancelledToolCall,
  type TrackedWaitingToolCall,
} from './useToolScheduler.js';
import type {
  Config,
  EditorType,
  AnyToolInvocation,
  AnyDeclarativeTool,
  SpanMetadata,
  CompletedToolCall,
  ToolCallRequestInfo,
} from '@google/gemini-cli-core';
import {
  CoreToolCallStatus,
  ApprovalMode,
  AuthType,
  GeminiEventType as ServerGeminiEventType,
  ToolErrorType,
  ToolConfirmationOutcome,
  MessageBusType,
  tokenLimit,
  debugLogger,
  coreEvents,
  CoreEvent,
  SHELL_TOOL_NAME,
  MCPDiscoveryState,
  GeminiCliOperation,
  getPlanModeExitMessage,
  UPDATE_TOPIC_TOOL_NAME,
  TRUE_EMPTY_RESPONSE_MESSAGE,
} from '@google/gemini-cli-core';
import type { Part, PartListUnion } from '@google/genai';
import type { UseHistoryManagerReturn } from './useHistoryManager.js';
import type {
  SlashCommandProcessorResult,
  HistoryItemWithoutId,
  HistoryItem,
} from '../types.js';
import { MessageType, StreamingState } from '../types.js';

import type { LoadedSettings } from '../../config/settings.js';
import { findLastSafeSplitPoint } from '../utils/markdownUtilities.js';
import { theme } from '../semantic-colors.js';

// --- MOCKS ---
const mockSendMessageStream = vi
  .fn()
  .mockReturnValue((async function* () {})());
const mockStartChat = vi.fn();
const mockMessageBus = {
  publish: vi.fn(),
  subscribe: vi.fn(),
  unsubscribe: vi.fn(),
};

const MockedGeminiClientClass = vi.hoisted(() =>
  vi.fn().mockImplementation(function (this: any, _config: any) {
    // _config
    this.startChat = mockStartChat;
    this.sendMessageStream = mockSendMessageStream;
    this.addHistory = vi.fn();
    let mockHistory: any[] = [];
    this.getHistory = vi.fn().mockImplementation(() => mockHistory);
    this.setHistory = vi.fn().mockImplementation((newHistory: any[]) => {
      mockHistory = [...newHistory];
    });
    this.generateContent = vi.fn().mockResolvedValue({
      candidates: [
        { content: { parts: [{ text: 'Got it. Focusing on tests only.' }] } },
      ],
    });
    this.getCurrentSequenceModel = vi.fn().mockReturnValue('test-model');
    this.getChat = vi.fn().mockReturnValue({
      recordCompletedToolCalls: vi.fn(),
    });
    this.getChatRecordingService = vi.fn().mockReturnValue({
      recordThought: vi.fn(),
      initialize: vi.fn(),
      recordMessage: vi.fn(),
      recordMessageTokens: vi.fn(),
      recordToolCalls: vi.fn(),
      getConversationFile: vi.fn(),
    });
    this.getCurrentSequenceModel = vi
      .fn()
      .mockReturnValue('gemini-2.0-flash-exp');
  }),
);

const MockedUserPromptEvent = vi.hoisted(() =>
  vi.fn().mockImplementation(() => {}),
);
const mockParseAndFormatApiError = vi.hoisted(() => vi.fn());
const mockIsBackgroundExecutionData = vi.hoisted(
  () =>
    (data: unknown): data is { pid?: number } => {
      if (typeof data !== 'object' || data === null) {
        return false;
      }
      const value = data as {
        pid?: unknown;
        command?: unknown;
        initialOutput?: unknown;
      };
      return (
        (value.pid === undefined || typeof value.pid === 'number') &&
        (value.command === undefined || typeof value.command === 'string') &&
        (value.initialOutput === undefined ||
          typeof value.initialOutput === 'string')
      );
    },
);

const MockValidationRequiredError = vi.hoisted(
  () =>
    class extends Error {
      userHandled = false;
    },
);

const mockRunInDevTraceSpan = vi.hoisted(() =>
  vi.fn(async (opts, fn) => {
    const metadata: SpanMetadata = {
      name: opts.operation,
      attributes: opts.attributes || {},
    };
    return await fn({
      metadata,
    });
  }),
);

vi.mock('@google/gemini-cli-core', async (importOriginal) => {
  const actualCoreModule = (await importOriginal()) as any;
  return {
    ...actualCoreModule,
    isBackgroundExecutionData: mockIsBackgroundExecutionData,
    GitService: vi.fn(),
    GeminiClient: MockedGeminiClientClass,
    UserPromptEvent: MockedUserPromptEvent,
    ValidationRequiredError: MockValidationRequiredError,
    parseAndFormatApiError: mockParseAndFormatApiError,
    tokenLimit: vi.fn().mockReturnValue(100), // Mock tokenLimit
    recordToolCallInteractions: vi.fn().mockResolvedValue(undefined),
    getCodeAssistServer: vi.fn().mockReturnValue(undefined),
    runInDevTraceSpan: mockRunInDevTraceSpan,
  };
});

const mockUseToolScheduler = useToolScheduler as Mock;
vi.mock('./useToolScheduler.js', async (importOriginal) => {
  const actualSchedulerModule = (await importOriginal()) as any;
  return {
    ...(actualSchedulerModule || {}),
    useToolScheduler: vi.fn(),
  };
});

vi.mock('./useKeypress.js', () => ({
  useKeypress: vi.fn(),
}));

vi.mock('./useExecutionLifecycle.js', () => ({
  useExecutionLifecycle: vi.fn().mockReturnValue({
    handleShellCommand: vi.fn(),
    activeShellPtyId: null,
    lastShellOutputTime: 0,
    backgroundTaskCount: 0,
    isBackgroundTaskVisible: false,
    toggleBackgroundTasks: vi.fn(),
    backgroundCurrentExecution: vi.fn(),
    backgroundTasks: new Map(),
    dismissBackgroundTask: vi.fn(),
    registerBackgroundTask: vi.fn(),
  }),
}));

vi.mock('./atCommandProcessor.js');

vi.mock('../utils/markdownUtilities.js', () => ({
  findLastSafeSplitPoint: vi.fn((s: string) => s.length),
}));

vi.mock('./useStateAndRef.js', async () => {
  const React = await vi.importActual<typeof import('react')>('react');

  return {
    useStateAndRef: vi.fn((initial) => {
      // Keep the heavyweight test file lightweight, but still let
      // `isResponding` participate in real rerenders.
      if (initial === false) {
        const [state, setState] = React.useState(initial);
        const ref = React.useRef(initial);
        const setStateInternal = (
          updater: typeof initial | ((prev: typeof initial) => typeof initial),
        ) => {
          const nextValue =
            typeof updater === 'function'
              ? (updater as (prev: typeof initial) => typeof initial)(
                  ref.current,
                )
              : updater;
          ref.current = nextValue;
          setState(nextValue);
        };
        return [state, ref, setStateInternal];
      }

      let val = initial;
      const ref = { current: val };
      const setVal = vi.fn((updater) => {
        if (typeof updater === 'function') {
          val = updater(val);
        } else {
          val = updater;
        }
        ref.current = val;
      });
      return [val, ref, setVal];
    }),
  };
});

vi.mock('./useLogger.js', () => ({
  useLogger: vi.fn().mockReturnValue({
    logMessage: vi.fn().mockResolvedValue(undefined),
  }),
}));

const mockStartNewPrompt = vi.fn();
const mockAddUsage = vi.fn();
vi.mock('../contexts/SessionContext.js', async (importOriginal) => {
  const actual = (await importOriginal()) as any;
  return {
    ...actual,
    useSessionStats: vi.fn(() => ({
      startNewPrompt: mockStartNewPrompt,
      addUsage: mockAddUsage,
      getPromptCount: vi.fn(() => 5),
    })),
  };
});

vi.mock('./slashCommandProcessor.js', () => ({
  handleSlashCommand: vi.fn().mockReturnValue(false),
}));

vi.mock('./useAlternateBuffer.js', () => ({
  useAlternateBuffer: vi.fn(() => false),
}));

// --- END MOCKS ---

// --- Tests for useGeminiStream Hook ---
describe('useGeminiStream', () => {
  let mockAddItem = vi.fn();
  let mockOnDebugMessage = vi.fn();
  let mockHandleSlashCommand = vi.fn().mockResolvedValue(false);
  let mockScheduleToolCalls: Mock;
  let mockCancelAllToolCalls: Mock;
  let mockMarkToolsAsSubmitted: Mock;
  let handleAtCommandSpy: MockInstance;

  const emptyHistory: HistoryItem[] = [];
  let capturedOnComplete:
    | ((tools: CompletedToolCall[]) => Promise<void>)
    | null = null;
  const mockGetPreferredEditor = vi.fn(() => 'vscode' as EditorType);
  const mockOnAuthError = vi.fn();
  const mockPerformMemoryRefresh = vi.fn(() => Promise.resolve());
  const mockSetModelSwitchedFromQuotaError = vi.fn();
  const mockOnCancelSubmit = vi.fn();
  const mockSetShellInputFocused = vi.fn();

  const mockGetGeminiClient = vi.fn().mockImplementation(() => {
    const clientInstance = new MockedGeminiClientClass(mockConfig);
    return clientInstance;
  });

  const mockMcpClientManager = {
    getDiscoveryState: vi.fn().mockReturnValue(MCPDiscoveryState.COMPLETED),
    getMcpServerCount: vi.fn().mockReturnValue(0),
  };

  const mockConfig: Config = {
    apiKey: 'test-api-key',
    model: 'gemini-pro',
    sandbox: false,
    targetDir: '/test/dir',
    debugMode: false,
    question: undefined,
    coreTools: [],
    toolDiscoveryCommand: undefined,
    toolCallCommand: undefined,
    mcpServerCommand: undefined,
    mcpServers: undefined,
    userAgent: 'test-agent',
    userMemory: '',
    geminiMdFileCount: 0,
    alwaysSkipModificationConfirmation: false,
    vertexai: false,
    showMemoryUsage: false,
    contextFileName: undefined,
    storage: {
      getProjectTempDir: vi.fn(() => '/test/temp'),
      getProjectTempCheckpointsDir: vi.fn(() => '/test/temp/checkpoints'),
    } as any,
    getToolRegistry: vi.fn(
      () => ({ getToolSchemaList: vi.fn(() => []) }) as any,
    ),
    getProjectRoot: vi.fn(() => '/test/dir'),
    getCheckpointingEnabled: vi.fn(() => false),
    getGeminiClient: mockGetGeminiClient,
    getMcpClientManager: () => mockMcpClientManager as any,
    getApprovalMode: vi.fn(() => ApprovalMode.DEFAULT),
    getUsageStatisticsEnabled: () => true,
    getDebugMode: () => false,
    addHistory: vi.fn(),
    getSessionId: vi.fn(() => 'test-session-id'),
    setQuotaErrorOccurred: vi.fn(),
    resetBillingTurnState: vi.fn(),
    getQuotaErrorOccurred: vi.fn(() => false),
    getModel: vi.fn(() => 'gemini-2.5-pro'),
    getContentGeneratorConfig: vi.fn(() => ({
      model: 'test-model',
      apiKey: 'test-key',
      vertexai: false,
      authType: AuthType.USE_GEMINI,
    })),
    getContentGenerator: vi.fn(),
    isInteractive: () => false,
    getExperiments: () => {},
    getMaxSessionTurns: vi.fn(() => 100),
    getGlobalMemory: vi.fn(() => ''),
    getUserMemory: vi.fn(() => ''),
    getMessageBus: vi.fn(() => mockMessageBus),
    getBaseLlmClient: vi.fn(() => ({
      generateContent: vi.fn().mockResolvedValue({
        candidates: [
          { content: { parts: [{ text: 'Got it. Focusing on tests only.' }] } },
        ],
      }),
    })),
    getIdeMode: vi.fn(() => false),
    getEnableHooks: vi.fn(() => false),
  } as unknown as Config;

  beforeEach(() => {
    vi.clearAllMocks(); // Clear mocks before each test
    mockAddItem = vi.fn();
    mockOnDebugMessage = vi.fn();
    mockHandleSlashCommand = vi.fn().mockResolvedValue(false);

    // Mock return value for useReactToolScheduler
    mockScheduleToolCalls = vi.fn();
    mockCancelAllToolCalls = vi.fn();
    mockMarkToolsAsSubmitted = vi.fn();

    // Reset properties of mockConfig if needed
    (mockConfig.getCheckpointingEnabled as Mock).mockReturnValue(false);
    (mockConfig.getApprovalMode as Mock).mockReturnValue(ApprovalMode.DEFAULT);

    // Default mock for useReactToolScheduler to prevent toolCalls being undefined initially
    mockUseToolScheduler.mockReturnValue([
      [], // Default to empty array for toolCalls
      mockScheduleToolCalls,
      mockMarkToolsAsSubmitted,
      vi.fn(), // setToolCallsForDisplay
      mockCancelAllToolCalls,
      0, // lastToolOutputTime
    ]);

    // Reset mocks for GeminiClient instance methods (startChat and sendMessageStream)
    // The GeminiClient constructor itself is mocked at the module level.
    mockStartChat.mockClear().mockResolvedValue({
      sendMessageStream: mockSendMessageStream,
    } as unknown as any); // GeminiChat -> any
    mockSendMessageStream
      .mockClear()
      .mockReturnValue((async function* () {})());
    handleAtCommandSpy = vi.spyOn(atCommandProcessor, 'handleAtCommand');
    vi.spyOn(coreEvents, 'emitFeedback');
  });

  const mockLoadedSettings: LoadedSettings = {
    merged: {
      preferredEditor: 'vscode',
      ui: { errorVerbosity: 'full' },
    },
    user: { path: '/user/settings.json', settings: {} },
    workspace: { path: '/workspace/.gemini/settings.json', settings: {} },
    errors: [],
    forScope: vi.fn(),
    setValue: vi.fn(),
  } as unknown as LoadedSettings;

  const renderTestHook = async (
    initialToolCalls: TrackedToolCall[] = [],
    geminiClient?: any,
    loadedSettings: LoadedSettings = mockLoadedSettings,
  ) => {
    const client = geminiClient || mockConfig.getGeminiClient();
    let lastToolCalls = initialToolCalls;

    const initialProps = {
      client,
      history: emptyHistory,
      addItem: mockAddItem as unknown as UseHistoryManagerReturn['addItem'],
      config: mockConfig,
      onDebugMessage: mockOnDebugMessage,
      handleSlashCommand: mockHandleSlashCommand as unknown as (
        cmd: PartListUnion,
      ) => Promise<SlashCommandProcessorResult | false>,
      shellModeActive: false,
      loadedSettings,
      toolCalls: initialToolCalls,
    };

    mockUseToolScheduler.mockImplementation((onComplete) => {
      capturedOnComplete = onComplete;
      return [
        lastToolCalls,
        mockScheduleToolCalls,
        mockMarkToolsAsSubmitted,
        (
          updater:
            | TrackedToolCall[]
            | ((prev: TrackedToolCall[]) => TrackedToolCall[]),
        ) => {
          lastToolCalls =
            typeof updater === 'function' ? updater(lastToolCalls) : updater;
          rerender({ ...initialProps, toolCalls: lastToolCalls });
        },
        (signal: AbortSignal) => {
          mockCancelAllToolCalls(signal);
          lastToolCalls = lastToolCalls.map((tc) => {
            if (
              tc.status === CoreToolCallStatus.AwaitingApproval ||
              tc.status === CoreToolCallStatus.Executing ||
              tc.status === CoreToolCallStatus.Scheduled ||
              tc.status === CoreToolCallStatus.Validating
            ) {
              return {
                ...tc,
                status: CoreToolCallStatus.Cancelled,
                response: {
                  callId: tc.request.callId,
                  responseParts: [],
                  resultDisplay: 'Request cancelled.',
                },
                responseSubmittedToGemini: true,
              } as any as TrackedCancelledToolCall;
            }
            return tc;
          });
          rerender({ ...initialProps, toolCalls: lastToolCalls });
        },
        0,
      ];
    });

    const { result, rerender } = await renderHookWithProviders(
      (props: typeof initialProps) =>
        useGeminiStream(
          props.client,
          props.history,
          props.addItem,
          props.config,
          props.loadedSettings,
          props.onDebugMessage,
          props.handleSlashCommand,
          props.shellModeActive,
          mockGetPreferredEditor,
          mockOnAuthError,
          mockPerformMemoryRefresh,
          false,
          mockSetModelSwitchedFromQuotaError,
          mockOnCancelSubmit,
          mockSetShellInputFocused,
          80,
          24,
        ),
      {
        initialProps,
      },
    );
    return {
      result,
      rerender,
      mockMarkToolsAsSubmitted,
      mockSendMessageStream,
      client,
    };
  };

  // Helper to create mock tool calls - reduces boilerplate
  const createMockToolCall = (
    toolName: string,
    callId: string,
    confirmationType: 'edit' | 'info',
    status: TrackedToolCall['status'] = CoreToolCallStatus.AwaitingApproval,
    mockOnConfirm: Mock = vi.fn(),
  ): TrackedWaitingToolCall => ({
    request: {
      callId,
      name: toolName,
      args: {},
      isClientInitiated: false,
      prompt_id: 'prompt-id-1',
    },
    status: status as CoreToolCallStatus.AwaitingApproval,
    responseSubmittedToGemini: false,
    confirmationDetails:
      confirmationType === 'edit'
        ? {
            type: 'edit',
            title: 'Confirm Edit',
            fileName: 'file.txt',
            filePath: '/test/file.txt',
            fileDiff: 'fake diff',
            originalContent: 'old',
            newContent: 'new',
            onConfirm: mockOnConfirm,
          }
        : {
            type: 'info',
            title: `${toolName} confirmation`,
            prompt: `Execute ${toolName}?`,
            onConfirm: mockOnConfirm,
          },
    tool: {
      name: toolName,
      displayName: toolName,
      description: `${toolName} description`,
      build: vi.fn(),
    } as any,
    invocation: {
      getDescription: () => 'Mock description',
    } as unknown as AnyToolInvocation,
    correlationId: `corr-${callId}`,
  });

  // Helper to render hook with default parameters - reduces boilerplate
  const renderHookWithDefaults = async (
    options: {
      shellModeActive?: boolean;
      onCancelSubmit?: () => void;
      setShellInputFocused?: (focused: boolean) => void;
      performMemoryRefresh?: () => Promise<void>;
      onAuthError?: () => void;
      setModelSwitched?: Mock;
      modelSwitched?: boolean;
    } = {},
  ) => {
    const {
      shellModeActive = false,
      onCancelSubmit = () => {},
      setShellInputFocused = () => {},
      performMemoryRefresh = () => Promise.resolve(),
      onAuthError = () => {},
      setModelSwitched = vi.fn(),
      modelSwitched = false,
    } = options;

    return renderHookWithProviders(() =>
      useGeminiStream(
        new MockedGeminiClientClass(mockConfig),
        [],
        mockAddItem,
        mockConfig,
        mockLoadedSettings,
        mockOnDebugMessage,
        mockHandleSlashCommand,
        shellModeActive,
        () => 'vscode' as EditorType,
        onAuthError,
        performMemoryRefresh,
        modelSwitched,
        setModelSwitched,
        onCancelSubmit,
        setShellInputFocused,
        80,
        24,
      ),
    );
  };

  it('should not submit tool responses if not all tool calls are completed', async () => {
    const toolCalls: TrackedToolCall[] = [
      {
        request: {
          callId: 'call1',
          name: 'tool1',
          args: {},
          isClientInitiated: false,
          prompt_id: 'prompt-id-1',
        },
        status: CoreToolCallStatus.Success,
        responseSubmittedToGemini: false,
        response: {
          callId: 'call1',
          responseParts: [{ text: 'tool 1 response' }],
          error: undefined,
          errorType: undefined, // FIX: Added missing property
          resultDisplay: 'Tool 1 success display',
        },
        tool: {
          name: 'tool1',
          displayName: 'tool1',
          description: 'desc1',
          build: vi.fn(),
        } as any,
        invocation: {
          getDescription: () => `Mock description`,
        } as unknown as AnyToolInvocation,
        startTime: Date.now(),
        endTime: Date.now(),
      } as TrackedCompletedToolCall,
      {
        request: {
          callId: 'call2',
          name: 'tool2',
          args: {},
          prompt_id: 'prompt-id-1',
        },
        status: CoreToolCallStatus.Executing,
        responseSubmittedToGemini: false,
        tool: {
          name: 'tool2',
          displayName: 'tool2',
          description: 'desc2',
          build: vi.fn(),
        } as any,
        invocation: {
          getDescription: () => `Mock description`,
        } as unknown as AnyToolInvocation,
        startTime: Date.now(),
        liveOutput: '...',
      } as TrackedExecutingToolCall,
    ];

    const { mockMarkToolsAsSubmitted, mockSendMessageStream } =
      await renderTestHook(toolCalls);

    // Effect for submitting tool responses depends on toolCalls and isResponding
    // isResponding is initially false, so the effect should run.

    expect(mockMarkToolsAsSubmitted).not.toHaveBeenCalled();
    expect(mockSendMessageStream).not.toHaveBeenCalled(); // submitQuery uses this
  });

  it('should expose activePtyId for non-shell executing tools that report an execution ID', async () => {
    const remoteExecutingTool: TrackedExecutingToolCall = {
      request: {
        callId: 'remote-call-1',
        name: 'remote_agent_call',
        args: {},
        isClientInitiated: false,
        prompt_id: 'prompt-id-remote',
      },
      status: CoreToolCallStatus.Executing,
      responseSubmittedToGemini: false,
      tool: {
        name: 'remote_agent_call',
        displayName: 'Remote Agent',
        description: 'Remote agent execution',
        build: vi.fn(),
      } as any,
      invocation: {
        getDescription: () => 'Calling remote agent',
      } as unknown as AnyToolInvocation,
      startTime: Date.now(),
      liveOutput: 'working...',
      pid: 4242,
    };

    const { result } = await renderTestHook([remoteExecutingTool]);
    expect(result.current.activePtyId).toBe(4242);
  });

  it('should submit tool responses when all tool calls are completed and ready', async () => {
    const toolCall1ResponseParts: Part[] = [{ text: 'tool 1 final response' }];
    const toolCall2ResponseParts: Part[] = [{ text: 'tool 2 final response' }];
    const completedToolCalls: TrackedToolCall[] = [
      {
        request: {
          callId: 'call1',
          name: 'tool1',
          args: {},
          isClientInitiated: false,
          prompt_id: 'prompt-id-2',
        },
        status: CoreToolCallStatus.Success,
        responseSubmittedToGemini: false,
        response: {
          callId: 'call1',
          responseParts: toolCall1ResponseParts,
          errorType: undefined, // FIX: Added missing property
        },
        tool: {
          displayName: 'MockTool',
        },
        invocation: {
          getDescription: () => `Mock description`,
        } as unknown as AnyToolInvocation,
      } as TrackedCompletedToolCall,
      {
        request: {
          callId: 'call2',
          name: 'tool2',
          args: {},
          isClientInitiated: false,
          prompt_id: 'prompt-id-2',
        },
        status: CoreToolCallStatus.Error,
        responseSubmittedToGemini: false,
        response: {
          callId: 'call2',
          responseParts: toolCall2ResponseParts,
          errorType: ToolErrorType.UNHANDLED_EXCEPTION, // FIX: Added missing property
        },
      } as TrackedCompletedToolCall, // Treat error as a form of completion for submission
    ];

    // Capture the onComplete callback
    let capturedOnComplete:
      | ((completedTools: TrackedToolCall[]) => Promise<void>)
      | null = null;

    mockUseToolScheduler.mockImplementation((onComplete) => {
      capturedOnComplete = onComplete;
      return [
        [],
        mockScheduleToolCalls,
        mockMarkToolsAsSubmitted,
        vi.fn(),
        mockCancelAllToolCalls,
        0,
      ];
    });

    mockSendMessageStream.mockReturnValue(
      (async function* () {
        yield {
          type: ServerGeminiEventType.Content,
          value: 'Visible response text',
        };
      })(),
    );

    await renderHookWithProviders(() =>
      useGeminiStream(
        new MockedGeminiClientClass(mockConfig),
        [],
        mockAddItem,
        mockConfig,
        mockLoadedSettings,
        mockOnDebugMessage,
        mockHandleSlashCommand,
        false,
        () => 'vscode' as EditorType,
        () => {},
        () => Promise.resolve(),
        false,
        () => {},
        () => {},
        () => {},
        80,
        24,
      ),
    );

    // Trigger the onComplete callback with completed tools
    await act(async () => {
      if (capturedOnComplete) {
        // Wait a tick for refs to be set up
        await new Promise((resolve) => setTimeout(resolve, 0));
        await capturedOnComplete(completedToolCalls);
      }
    });

    await waitFor(() => {
      expect(mockMarkToolsAsSubmitted).toHaveBeenCalledTimes(1);
      expect(mockSendMessageStream).toHaveBeenCalledTimes(1);
    });

    const expectedMergedResponse = [
      ...toolCall1ResponseParts,
      ...toolCall2ResponseParts,
    ];
    expect(mockSendMessageStream).toHaveBeenCalledWith(
      expectedMergedResponse,
      expect.any(AbortSignal),
      'prompt-id-2',
      undefined,
      expectedMergedResponse,
    );
  });

  it('should inject steering hint prompt for continuation', async () => {
    const toolCallResponseParts: Part[] = [{ text: 'tool final response' }];
    const completedToolCalls: TrackedToolCall[] = [
      {
        request: {
          callId: 'call1',
          name: 'tool1',
          args: {},
          isClientInitiated: false,
          prompt_id: 'prompt-id-ack',
        },
        status: 'success',
        responseSubmittedToGemini: false,
        response: {
          callId: 'call1',
          responseParts: toolCallResponseParts,
          errorType: undefined,
        },
        tool: {
          displayName: 'MockTool',
        },
        invocation: {
          getDescription: () => `Mock description`,
        } as unknown as AnyToolInvocation,
      } as TrackedCompletedToolCall,
    ];

    mockSendMessageStream.mockReturnValue(
      (async function* () {
        yield {
          type: ServerGeminiEventType.Content,
          value: 'Applied the requested adjustment.',
        };
      })(),
    );

    let capturedOnComplete:
      | ((completedTools: TrackedToolCall[]) => Promise<void>)
      | null = null;
    mockUseToolScheduler.mockImplementation((onComplete) => {
      capturedOnComplete = onComplete;
      return [
        [],
        mockScheduleToolCalls,
        mockMarkToolsAsSubmitted,
        vi.fn(),
        mockCancelAllToolCalls,
        0,
      ];
    });

    await renderHookWithProviders(() =>
      useGeminiStream(
        new MockedGeminiClientClass(mockConfig),
        [],
        mockAddItem,
        mockConfig,
        mockLoadedSettings,
        mockOnDebugMessage,
        mockHandleSlashCommand,
        false,
        () => 'vscode' as EditorType,
        () => {},
        () => Promise.resolve(),
        false,
        () => {},
        () => {},
        () => {},
        80,
        24,
        undefined,
        () => 'focus on tests only',
      ),
    );

    await act(async () => {
      if (capturedOnComplete) {
        await new Promise((resolve) => setTimeout(resolve, 0));
        await capturedOnComplete(completedToolCalls);
      }
    });

    await waitFor(() => {
      expect(mockSendMessageStream).toHaveBeenCalledTimes(1);
    });

    const sentParts = mockSendMessageStream.mock.calls[0][0] as Part[];
    const injectedHintPart = sentParts[0] as { text?: string };
    expect(injectedHintPart.text).toContain('User steering update:');
    expect(injectedHintPart.text).toContain(
      '<user_input>\nfocus on tests only\n</user_input>',
    );
    expect(injectedHintPart.text).toContain(
      'Classify it as ADD_TASK, MODIFY_TASK, CANCEL_TASK, or EXTRA_CONTEXT.',
    );
    expect(injectedHintPart.text).toContain(
      'Do not cancel/skip tasks unless the user explicitly cancels them.',
    );

    expect(mockRunInDevTraceSpan).toHaveBeenCalledWith(
      expect.objectContaining({
        operation: GeminiCliOperation.SystemPrompt,
      }),
      expect.any(Function),
    );

    const spanArgs = mockRunInDevTraceSpan.mock.calls[0];
    const fn = spanArgs[1];
    const metadata = { attributes: {} };
    await act(async () => {
      await fn({ metadata });
    });
    expect(metadata).toMatchObject({
      input: sentParts,
    });
  });

  it('should auto-nudge the model when tool execution succeeds but model stream is empty', async () => {
    const toolCallResponseParts: Part[] = [{ text: 'tool final response' }];
    const completedToolCalls: TrackedToolCall[] = [
      {
        request: {
          callId: 'call1',
          name: 'tool1',
          args: {},
          isClientInitiated: false,
          prompt_id: 'prompt-id-ack',
        },
        status: 'success',
        responseSubmittedToGemini: false,
        response: {
          callId: 'call1',
          responseParts: toolCallResponseParts,
          errorType: undefined,
        },
        tool: {
          displayName: 'MockTool',
        },
        invocation: {
          getDescription: () => `Mock description`,
        } as unknown as AnyToolInvocation,
      } as TrackedCompletedToolCall,
    ];

    let callCount = 0;
    mockSendMessageStream.mockImplementation(() => {
      callCount += 1;
      if (callCount === 1) {
        return (async function* () {})();
      } else {
        return (async function* () {
          yield {
            type: ServerGeminiEventType.Content,
            value:
              'I have analyzed the empty response. Here is the final answer.',
          };
        })();
      }
    });

    let capturedOnComplete:
      | ((completedTools: TrackedToolCall[]) => Promise<void>)
      | null = null;
    mockUseToolScheduler.mockImplementation((onComplete) => {
      capturedOnComplete = onComplete;
      return [
        [],
        mockScheduleToolCalls,
        mockMarkToolsAsSubmitted,
        vi.fn(),
        mockCancelAllToolCalls,
        0,
      ];
    });

    await renderHookWithProviders(() =>
      useGeminiStream(
        new MockedGeminiClientClass(mockConfig),
        [],
        mockAddItem,
        mockConfig,
        mockLoadedSettings,
        mockOnDebugMessage,
        mockHandleSlashCommand,
        false,
        () => 'vscode' as EditorType,
        () => {},
        () => Promise.resolve(),
        false,
        () => {},
        () => {},
        () => {},
        80,
        24,
        undefined,
        () => 'focus on tests only',
      ),
    );

    await act(async () => {
      if (capturedOnComplete) {
        await new Promise((resolve) => setTimeout(resolve, 0));
        await capturedOnComplete(completedToolCalls);
      }
    });

    await waitFor(() => {
      expect(mockSendMessageStream).toHaveBeenCalledTimes(2);
    });

    const sentParts = mockSendMessageStream.mock.calls[1][0] as Part[];
    expect(sentParts[0].text).toContain(
      '[System: You successfully executed a tool but returned an empty response. Please analyze the tool output and explain your progress or final answer.]',
    );
  });

  it('should handle all tool calls being cancelled by rolling back the history', async () => {
    const cancelledToolCalls: TrackedToolCall[] = [
      {
        request: {
          callId: 'topic1',
          name: UPDATE_TOPIC_TOOL_NAME,
          args: {},
          isClientInitiated: false,
          prompt_id: 'prompt-id-3',
        },
        status: CoreToolCallStatus.Success,
        response: {
          callId: 'topic1',
          responseParts: [
            {
              functionResponse: {
                name: UPDATE_TOPIC_TOOL_NAME,
                id: 'topic1',
                response: {},
              },
            },
          ],
        },
        tool: { displayName: 'Update Topic Context' },
        invocation: { getDescription: () => 'Updating topic' },
      } as any,
      {
        request: {
          callId: '1',
          name: 'testTool',
          args: {},
          isClientInitiated: false,
          prompt_id: 'prompt-id-3',
        },
        status: CoreToolCallStatus.Cancelled,
        response: {
          callId: '1',
          responseParts: [{ text: CoreToolCallStatus.Cancelled }],
          errorType: undefined, // FIX: Added missing property
        },
        responseSubmittedToGemini: false,
        tool: {
          displayName: 'mock tool',
        },
        invocation: {
          getDescription: () => `Mock description`,
        },
      } as any,
    ];
    const client = new MockedGeminiClientClass(mockConfig);
    client.setHistory([{ role: 'user', parts: [{ text: 'User prompt' }] }]);

    // Capture the onComplete callback
    let capturedOnComplete:
      | ((completedTools: TrackedToolCall[]) => Promise<void>)
      | null = null;

    mockUseToolScheduler.mockImplementation((onComplete) => {
      capturedOnComplete = onComplete;
      return [
        [],
        mockScheduleToolCalls,
        mockMarkToolsAsSubmitted,
        vi.fn(),
        mockCancelAllToolCalls,
        0,
      ];
    });

    const { result } = await renderHookWithProviders(() =>
      useGeminiStream(
        client,
        [],
        mockAddItem,
        mockConfig,
        mockLoadedSettings,
        mockOnDebugMessage,
        mockHandleSlashCommand,
        false,
        () => 'vscode' as EditorType,
        () => {},
        () => Promise.resolve(),
        false,
        () => {},
        () => {},
        () => {},
        80,
        24,
      ),
    );

    // Call submitQuery to populate the user turn and set historyLengthAfterUserPromptRef
    await act(async () => {
      // eslint-disable-next-line @typescript-eslint/no-floating-promises
      result.current.submitQuery('User prompt');
    });

    // Model issues a functionCall request, which appends to history
    client.setHistory([
      { role: 'user', parts: [{ text: 'User prompt' }] },
      {
        role: 'model',
        parts: [{ functionCall: { name: 'testTool', args: {} } }],
      },
    ]);

    // Trigger the onComplete callback with cancelled tools
    await act(async () => {
      if (capturedOnComplete) {
        // Wait a tick for refs to be set up
        await new Promise((resolve) => setTimeout(resolve, 0));
        await capturedOnComplete(cancelledToolCalls);
      }
    });

    await waitFor(() => {
      expect(mockMarkToolsAsSubmitted).toHaveBeenCalledWith(['topic1', '1']);
      // Should NOT have appended cancellations via addHistory
      expect(client.addHistory).not.toHaveBeenCalled();
      // Should have rolled history back to pre-model length (1)
      expect(client.getHistory().length).toBe(1);
      // Ensure we do NOT call back to the API a second time (only the initial user turn was sent)
      expect(mockSendMessageStream).toHaveBeenCalledTimes(1);
    });
  });

  it('should record tool responses in history when the model was switched due to a quota error', async () => {
    // Regression test: returning early on a quota-triggered model switch
    // without recording the responses leaves the already-recorded
    // functionCall unpaired, which corrupts all subsequent requests.
    const responseParts: Part[] = [
      {
        functionResponse: {
          name: 'testTool',
          id: 'call1',
          response: { output: 'tool result' },
        },
      },
    ];
    const completedToolCalls: TrackedToolCall[] = [
      {
        request: {
          callId: 'call1',
          name: 'testTool',
          args: {},
          isClientInitiated: false,
          prompt_id: 'prompt-id-quota',
        },
        status: CoreToolCallStatus.Success,
        responseSubmittedToGemini: false,
        response: {
          callId: 'call1',
          responseParts,
          errorType: undefined,
        },
        tool: { displayName: 'MockTool' },
        invocation: {
          getDescription: () => `Mock description`,
        } as unknown as AnyToolInvocation,
      } as TrackedCompletedToolCall,
    ];

    const client = new MockedGeminiClientClass(mockConfig);
    const mockConsumeUserHint = vi.fn(() => 'switch to the nprd database');

    let capturedOnComplete:
      | ((completedTools: TrackedToolCall[]) => Promise<void>)
      | null = null;

    mockUseToolScheduler.mockImplementation((onComplete) => {
      capturedOnComplete = onComplete;
      return [
        [],
        mockScheduleToolCalls,
        mockMarkToolsAsSubmitted,
        vi.fn(),
        mockCancelAllToolCalls,
        0,
      ];
    });

    await renderHookWithProviders(() =>
      useGeminiStream(
        client,
        [],
        mockAddItem,
        mockConfig,
        mockLoadedSettings,
        mockOnDebugMessage,
        mockHandleSlashCommand,
        false,
        () => 'vscode' as EditorType,
        () => {},
        () => Promise.resolve(),
        true, // modelSwitchedFromQuotaError
        () => {},
        () => {},
        () => {},
        80,
        24,
        false,
        mockConsumeUserHint,
      ),
    );

    await act(async () => {
      if (capturedOnComplete) {
        await new Promise((resolve) => setTimeout(resolve, 0));
        await capturedOnComplete(completedToolCalls);
      }
    });

    await waitFor(() => {
      expect(mockMarkToolsAsSubmitted).toHaveBeenCalledWith(['call1']);
      // The tool response must be paired with its functionCall in history,
      // with no steering-hint text ahead of it...
      expect(client.addHistory).toHaveBeenCalledWith({
        role: 'user',
        parts: responseParts,
      });
      // ...the turn must NOT auto-continue on the fallback model...
      expect(mockSendMessageStream).not.toHaveBeenCalled();
      // ...and the pending hint is left for the next real submit.
      expect(mockConsumeUserHint).not.toHaveBeenCalled();
    });
  });

  it('should NOT stop responding when only update_topic is called', async () => {
    const topicToolCalls: TrackedToolCall[] = [
      {
        request: {
          callId: 'topic1',
          name: UPDATE_TOPIC_TOOL_NAME,
          args: {},
          isClientInitiated: false,
          prompt_id: 'prompt-id-3',
        },
        status: CoreToolCallStatus.Success,
        response: {
          callId: 'topic1',
          responseParts: [
            {
              functionResponse: {
                name: UPDATE_TOPIC_TOOL_NAME,
                id: 'topic1',
                response: {},
              },
            },
          ],
        },
        tool: { displayName: 'Update Topic Context' },
        invocation: { getDescription: () => 'Updating topic' },
      } as any,
    ];
    const client = new MockedGeminiClientClass(mockConfig);

    // Capture the onComplete callback
    let capturedOnComplete:
      | ((completedTools: TrackedToolCall[]) => Promise<void>)
      | null = null;

    mockUseToolScheduler.mockImplementation((onComplete) => {
      capturedOnComplete = onComplete;
      return [
        topicToolCalls,
        vi.fn(),
        mockMarkToolsAsSubmitted,
        vi.fn(),
        vi.fn(),
        0,
      ];
    });

    await renderHookWithProviders(() =>
      useGeminiStream(
        client,
        [],
        mockAddItem,
        mockConfig,
        mockLoadedSettings,
        mockOnDebugMessage,
        mockHandleSlashCommand,
        false,
        () => 'vscode' as EditorType,
        () => {},
        () => Promise.resolve(),
        false,
        () => {},
        () => {},
        () => {},
        80,
        24,
      ),
    );

    // Trigger the onComplete callback with the topic tool
    await act(async () => {
      if (capturedOnComplete) {
        await capturedOnComplete(topicToolCalls);
      }
    });

    await waitFor(() => {
      // The streaming state should still be Responding because we didn't cancel anything important
      // and we expect a continuation.
      expect(mockMarkToolsAsSubmitted).toHaveBeenCalledWith(['topic1']);
      // Should HAVE called back to the API for continuation
      expect(mockSendMessageStream).toHaveBeenCalled();
    });
  });

  it('should stop agent execution immediately when a tool call returns STOP_EXECUTION error', async () => {
    const stopExecutionToolCalls: TrackedCompletedToolCall[] = [
      {
        request: {
          callId: 'stop-call',
          name: 'stopTool',
          args: {},
          isClientInitiated: false,
          prompt_id: 'prompt-id-stop',
        },
        status: CoreToolCallStatus.Error,
        response: {
          callId: 'stop-call',
          responseParts: [{ text: 'error occurred' }],
          errorType: ToolErrorType.STOP_EXECUTION,
          error: new Error('Stop reason from hook'),
          resultDisplay: undefined,
        },
        responseSubmittedToGemini: false,
        tool: {
          displayName: 'stop tool',
        },
        invocation: {
          getDescription: () => `Mock description`,
        } as unknown as AnyToolInvocation,
      } as unknown as TrackedCompletedToolCall,
    ];
    const client = new MockedGeminiClientClass(mockConfig);

    const { result } = await renderTestHook([], client);

    // Trigger the onComplete callback with STOP_EXECUTION tool
    await act(async () => {
      if (capturedOnComplete) {
        await capturedOnComplete(stopExecutionToolCalls);
      }
    });

    await waitFor(() => {
      expect(mockMarkToolsAsSubmitted).toHaveBeenCalledWith(['stop-call']);
      // Should add an info message to history
      expect(mockAddItem).toHaveBeenCalledWith(
        expect.objectContaining({
          type: MessageType.INFO,
          text: expect.stringContaining(
            'Agent execution stopped: Stop reason from hook',
          ),
        }),
      );
      // Ensure we do NOT call back to the API
      expect(mockSendMessageStream).not.toHaveBeenCalled();
      // Streaming state should be Idle
      expect(result.current.streamingState).toBe(StreamingState.Idle);
    });

    const infoTexts = mockAddItem.mock.calls.map(
      ([item]) => (item as { text?: string }).text ?? '',
    );
    expect(
      infoTexts.some((text) =>
        text.includes(
          'Some internal tool attempts failed before this final error',
        ),
      ),
    ).toBe(false);
    expect(
      infoTexts.some((text) =>
        text.includes('This request failed. Press F12 for diagnostics'),
      ),
    ).toBe(false);
  });

  it('should add a compact suppressed-error note before STOP_EXECUTION terminal info in low verbosity mode', async () => {
    const stopExecutionToolCalls: TrackedCompletedToolCall[] = [
      {
        request: {
          callId: 'stop-call',
          name: 'stopTool',
          args: {},
          isClientInitiated: false,
          prompt_id: 'prompt-id-stop',
        },
        status: CoreToolCallStatus.Error,
        response: {
          callId: 'stop-call',
          responseParts: [{ text: 'error occurred' }],
          errorType: ToolErrorType.STOP_EXECUTION,
          error: new Error('Stop reason from hook'),
          resultDisplay: undefined,
        },
        responseSubmittedToGemini: false,
        tool: {
          displayName: 'stop tool',
        },
        invocation: {
          getDescription: () => `Mock description`,
        } as unknown as AnyToolInvocation,
      } as unknown as TrackedCompletedToolCall,
    ];
    const lowVerbositySettings = {
      // eslint-disable-next-line @typescript-eslint/no-misused-spread
      ...mockLoadedSettings,
      merged: {
        ...mockLoadedSettings.merged,
        ui: { errorVerbosity: 'low' },
      },
    } as LoadedSettings;
    const client = new MockedGeminiClientClass(mockConfig);

    const { result } = await renderTestHook([], client, lowVerbositySettings);

    await act(async () => {
      if (capturedOnComplete) {
        await capturedOnComplete(stopExecutionToolCalls);
      }
    });

    await waitFor(() => {
      expect(mockMarkToolsAsSubmitted).toHaveBeenCalledWith(['stop-call']);
      expect(mockSendMessageStream).not.toHaveBeenCalled();
      expect(result.current.streamingState).toBe(StreamingState.Idle);
    });

    const infoTexts = mockAddItem.mock.calls.map(
      ([item]) => (item as { text?: string }).text ?? '',
    );
    const noteIndex = infoTexts.findIndex((text) =>
      text.includes(
        'Some internal tool attempts failed before this final error',
      ),
    );
    const stopIndex = infoTexts.findIndex((text) =>
      text.includes('Agent execution stopped: Stop reason from hook'),
    );
    const failureHintIndex = infoTexts.findIndex((text) =>
      text.includes('This request failed. Press F12 for diagnostics'),
    );
    expect(noteIndex).toBeGreaterThanOrEqual(0);
    expect(stopIndex).toBeGreaterThanOrEqual(0);
    // The failure hint should NOT be present if the suppressed error note was shown
    expect(failureHintIndex).toBe(-1);
    expect(noteIndex).toBeLessThan(stopIndex);
  });

  it('should rollback multiple cancelled tool calls rather than appending them to history', async () => {
    const cancelledToolCall1: TrackedCancelledToolCall = {
      request: {
        callId: 'cancel-1',
        name: 'toolA',
        args: {},
        isClientInitiated: false,
        prompt_id: 'prompt-id-7',
      },
      tool: {
        name: 'toolA',
        displayName: 'toolA',
        description: 'descA',
        build: vi.fn(),
      } as any,
      invocation: {
        getDescription: () => `Mock description`,
      } as unknown as AnyToolInvocation,
      status: CoreToolCallStatus.Cancelled,
      response: {
        callId: 'cancel-1',
        responseParts: [
          { functionResponse: { name: 'toolA', id: 'cancel-1' } },
        ],
        resultDisplay: undefined,
        error: undefined,
        errorType: undefined, // FIX: Added missing property
      },
      responseSubmittedToGemini: false,
    };
    const cancelledToolCall2: TrackedCancelledToolCall = {
      request: {
        callId: 'cancel-2',
        name: 'toolB',
        args: {},
        isClientInitiated: false,
        prompt_id: 'prompt-id-8',
      },
      tool: {
        name: 'toolB',
        displayName: 'toolB',
        description: 'descB',
        build: vi.fn(),
      } as any,
      invocation: {
        getDescription: () => `Mock description`,
      } as unknown as AnyToolInvocation,
      status: CoreToolCallStatus.Cancelled,
      response: {
        callId: 'cancel-2',
        responseParts: [
          { functionResponse: { name: 'toolB', id: 'cancel-2' } },
        ],
        resultDisplay: undefined,
        error: undefined,
        errorType: undefined, // FIX: Added missing property
      },
      responseSubmittedToGemini: false,
    };
    const allCancelledTools = [cancelledToolCall1, cancelledToolCall2];
    const client = new MockedGeminiClientClass(mockConfig);
    client.setHistory([{ role: 'user', parts: [{ text: 'User prompt' }] }]);

    let capturedOnComplete:
      | ((completedTools: TrackedToolCall[]) => Promise<void>)
      | null = null;

    mockUseToolScheduler.mockImplementation((onComplete) => {
      capturedOnComplete = onComplete;
      return [
        [],
        mockScheduleToolCalls,
        mockMarkToolsAsSubmitted,
        vi.fn(),
        mockCancelAllToolCalls,
        0,
      ];
    });

    const { result } = await renderHookWithProviders(() =>
      useGeminiStream(
        client,
        [],
        mockAddItem,
        mockConfig,
        mockLoadedSettings,
        mockOnDebugMessage,
        mockHandleSlashCommand,
        false,
        () => 'vscode' as EditorType,
        () => {},
        () => Promise.resolve(),
        false,
        () => {},
        () => {},
        () => {},
        80,
        24,
      ),
    );

    // Call submitQuery to populate the user turn and set historyLengthAfterUserPromptRef
    await act(async () => {
      // eslint-disable-next-line @typescript-eslint/no-floating-promises
      result.current.submitQuery('User prompt');
    });

    // Model issues model turns, which appends to history
    client.setHistory([
      { role: 'user', parts: [{ text: 'User prompt' }] },
      { role: 'model', parts: [{ functionCall: { name: 'toolA', args: {} } }] },
    ]);

    // Trigger the onComplete callback with multiple cancelled tools
    await act(async () => {
      if (capturedOnComplete) {
        // Wait a tick for refs to be set up
        await new Promise((resolve) => setTimeout(resolve, 0));
        await capturedOnComplete(allCancelledTools);
      }
    });

    await waitFor(() => {
      // The tools should be marked as submitted locally
      expect(mockMarkToolsAsSubmitted).toHaveBeenCalledWith([
        'cancel-1',
        'cancel-2',
      ]);

      // Crucially, addHistory should NOT be called
      expect(client.addHistory).not.toHaveBeenCalled();

      // Instead, history should be rolled back to pre-model length (1)
      expect(client.getHistory().length).toBe(1);

      // No message should be sent back to the API for a turn with only cancellations
      expect(mockSendMessageStream).toHaveBeenCalledTimes(1);
    });
  });

  it('should not flicker streaming state to Idle between tool completion and submission', async () => {
    const toolCallResponseParts: PartListUnion = [
      { text: 'tool 1 final response' },
    ];

    const initialToolCalls: TrackedToolCall[] = [
      {
        request: {
          callId: 'call1',
          name: 'tool1',
          args: {},
          isClientInitiated: false,
          prompt_id: 'prompt-id-4',
        },
        status: CoreToolCallStatus.Executing,
        responseSubmittedToGemini: false,
        tool: {
          name: 'tool1',
          displayName: 'tool1',
          description: 'desc',
          build: vi.fn(),
        } as any,
        invocation: {
          getDescription: () => `Mock description`,
        } as unknown as AnyToolInvocation,
        startTime: Date.now(),
      } as TrackedExecutingToolCall,
    ];

    const completedToolCalls: TrackedToolCall[] = [
      {
        ...(initialToolCalls[0] as TrackedExecutingToolCall),
        status: CoreToolCallStatus.Success,
        response: {
          callId: 'call1',
          responseParts: toolCallResponseParts,
          error: undefined,
          errorType: undefined, // FIX: Added missing property
          resultDisplay: 'Tool 1 success display',
        },
        endTime: Date.now(),
      } as TrackedCompletedToolCall,
    ];

    // Capture the onComplete callback
    let capturedOnComplete:
      | ((completedTools: TrackedToolCall[]) => Promise<void>)
      | null = null;
    let currentToolCalls = initialToolCalls;

    mockUseToolScheduler.mockImplementation((onComplete) => {
      capturedOnComplete = onComplete;
      return [
        currentToolCalls,
        mockScheduleToolCalls,
        mockMarkToolsAsSubmitted,
        vi.fn(), // setToolCallsForDisplay
        mockCancelAllToolCalls,
        0,
      ];
    });

    const { result, rerender } = await renderHookWithProviders(() =>
      useGeminiStream(
        new MockedGeminiClientClass(mockConfig),
        [],
        mockAddItem,
        mockConfig,
        mockLoadedSettings,
        mockOnDebugMessage,
        mockHandleSlashCommand,
        false,
        () => 'vscode' as EditorType,
        () => {},
        () => Promise.resolve(),
        false,
        () => {},
        () => {},
        () => {},
        80,
        24,
      ),
    );

    // 1. Initial state should be Responding because a tool is executing.
    expect(result.current.streamingState).toBe(StreamingState.Responding);

    // 2. Update the tool calls to completed state and rerender
    currentToolCalls = completedToolCalls;
    mockUseToolScheduler.mockImplementation((onComplete) => {
      capturedOnComplete = onComplete;
      return [
        completedToolCalls,
        mockScheduleToolCalls,
        mockMarkToolsAsSubmitted,
        vi.fn(), // setToolCallsForDisplay
        mockCancelAllToolCalls,
        0,
      ];
    });

    act(() => {
      rerender();
    });

    // 3. The state should *still* be Responding, not Idle.
    // This is because the completed tool's response has not been submitted yet.
    expect(result.current.streamingState).toBe(StreamingState.Responding);

    // 4. Trigger the onComplete callback to simulate tool completion
    await act(async () => {
      if (capturedOnComplete) {
        // Wait a tick for refs to be set up
        await new Promise((resolve) => setTimeout(resolve, 0));
        await capturedOnComplete(completedToolCalls);
      }
    });

    // 5. Wait for submitQuery to be called
    await waitFor(() => {
      expect(mockSendMessageStream).toHaveBeenCalledWith(
        toolCallResponseParts,
        expect.any(AbortSignal),
        'prompt-id-4',
        undefined,
        toolCallResponseParts,
      );
    });

    // 6. After submission, the state should remain Responding until the stream completes.
    expect(result.current.streamingState).toBe(StreamingState.Responding);
  });

  describe('User Cancellation', () => {
    let keypressCallback: (key: any) => void;
    const mockUseKeypress = useKeypress as Mock;

    beforeEach(() => {
      // Capture the callback passed to useKeypress
      mockUseKeypress.mockImplementation((callback, options) => {
        if (options.isActive) {
          keypressCallback = callback;
        } else {
          keypressCallback = () => {};
        }
      });
    });

    const simulateEscapeKeyPress = () => {
      act(() => {
        keypressCallback({ name: 'escape' });
      });
    };

    it('should cancel an in-progress stream when escape is pressed', async () => {
      const mockStream = (async function* () {
        yield { type: 'content', value: 'Part 1' };
        // Keep the stream open
        await new Promise(() => {});
      })();
      mockSendMessageStream.mockReturnValue(mockStream);

      const { result } = await renderTestHook();

      // Start a query
      await act(async () => {
        // eslint-disable-next-line @typescript-eslint/no-floating-promises
        result.current.submitQuery('test query');
      });

      // Wait for the first part of the response
      await waitFor(() => {
        expect(result.current.streamingState).toBe(StreamingState.Responding);
      });

      // Simulate escape key press
      simulateEscapeKeyPress();

      // Verify cancellation message is added
      await waitFor(() => {
        expect(mockAddItem).toHaveBeenCalledWith({
          type: MessageType.INFO,
          text: 'Request cancelled.',
        });
      });

      // Verify state is reset
      expect(result.current.streamingState).toBe(StreamingState.Idle);
    });

    it('should call onCancelSubmit handler when escape is pressed', async () => {
      const cancelSubmitSpy = vi.fn();
      const mockStream = (async function* () {
        yield { type: 'content', value: 'Part 1' };
        // Keep the stream open
        await new Promise(() => {});
      })();
      mockSendMessageStream.mockReturnValue(mockStream);

      const { result } = await renderHookWithProviders(() =>
        useGeminiStream(
          mockConfig.getGeminiClient(),
          [],
          mockAddItem,
          mockConfig,
          mockLoadedSettings,
          mockOnDebugMessage,
          mockHandleSlashCommand,
          false,
          () => 'vscode' as EditorType,
          () => {},
          () => Promise.resolve(),
          false,
          () => {},
          cancelSubmitSpy,
          () => {},
          80,
          24,
        ),
      );

      // Start a query
      await act(async () => {
        // eslint-disable-next-line @typescript-eslint/no-floating-promises
        result.current.submitQuery('test query');
      });

      simulateEscapeKeyPress();

      expect(cancelSubmitSpy).toHaveBeenCalledWith(false, false);
    });

    it('should call setShellInputFocused(false) when escape is pressed', async () => {
      const setShellInputFocusedSpy = vi.fn();
      const mockStream = (async function* () {
        yield { type: 'content', value: 'Part 1' };
        await new Promise(() => {}); // Keep stream open
      })();
      mockSendMessageStream.mockReturnValue(mockStream);

      const { result } = await renderHookWithProviders(() =>
        useGeminiStream(
          mockConfig.getGeminiClient(),
          [],
          mockAddItem,
          mockConfig,
          mockLoadedSettings,
          mockOnDebugMessage,
          mockHandleSlashCommand,
          false,
          () => 'vscode' as EditorType,
          () => {},
          () => Promise.resolve(),
          false,
          () => {},
          vi.fn(),
          setShellInputFocusedSpy, // Pass the spy here
          80,
          24,
        ),
      );

      // Start a query
      await act(async () => {
        // eslint-disable-next-line @typescript-eslint/no-floating-promises
        result.current.submitQuery('test query');
      });

      simulateEscapeKeyPress();

      expect(setShellInputFocusedSpy).toHaveBeenCalledWith(false);
    });

    it('should not do anything if escape is pressed when not responding', async () => {
      const { result } = await renderTestHook();

      expect(result.current.streamingState).toBe(StreamingState.Idle);

      // Simulate escape key press
      simulateEscapeKeyPress();

      // No change should happen, no cancellation message
      expect(mockAddItem).not.toHaveBeenCalledWith(
        expect.objectContaining({
          text: 'Request cancelled.',
        }),
      );
    });

    it('should prevent further processing after cancellation', async () => {
      let continueStream: () => void;
      const streamPromise = new Promise<void>((resolve) => {
        continueStream = resolve;
      });

      const mockStream = (async function* () {
        yield { type: 'content', value: 'Initial' };
        await streamPromise; // Wait until we manually continue
        yield { type: 'content', value: ' Canceled' };
      })();
      mockSendMessageStream.mockReturnValue(mockStream);

      const { result } = await renderTestHook();

      await act(async () => {
        // eslint-disable-next-line @typescript-eslint/no-floating-promises
        result.current.submitQuery('long running query');
      });

      await waitFor(() => {
        expect(result.current.streamingState).toBe(StreamingState.Responding);
      });

      // Cancel the request
      simulateEscapeKeyPress();

      // Allow the stream to continue
      await act(async () => {
        continueStream();
        // Wait a bit to see if the second part is processed
        await new Promise((resolve) => setTimeout(resolve, 50));
      });

      // The text should not have been updated with " Canceled"
      const lastCall = mockAddItem.mock.calls.find(
        (call) => call[0].type === 'gemini',
      );
      expect(lastCall?.[0].text).toBe('Initial');

      // The final state should be idle after cancellation
      expect(result.current.streamingState).toBe(StreamingState.Idle);
    });

    it('should cancel if a tool call is in progress', async () => {
      const toolCalls: TrackedToolCall[] = [
        {
          request: { callId: 'call1', name: 'tool1', args: {} },
          status: CoreToolCallStatus.Executing,
          responseSubmittedToGemini: false,
          tool: {
            name: 'tool1',
            description: 'desc1',
            build: vi.fn().mockImplementation((_) => ({
              getDescription: () => `Mock description`,
            })),
          } as any,
          invocation: {
            getDescription: () => `Mock description`,
          },
          startTime: Date.now(),
          liveOutput: '...',
        } as TrackedExecutingToolCall,
      ];

      const { result } = await renderTestHook(toolCalls);

      // State is `Responding` because a tool is running
      expect(result.current.streamingState).toBe(StreamingState.Responding);

      // Try to cancel
      simulateEscapeKeyPress();

      // The cancel function should be called
      expect(mockCancelAllToolCalls).toHaveBeenCalled();
    });

    it('should transition to Idle state when cancelled while a tool call is in progress and completes', async () => {
      const toolCalls: TrackedToolCall[] = [
        {
          request: { callId: 'call1', name: 'tool1', args: {} },
          status: CoreToolCallStatus.Executing,
          responseSubmittedToGemini: false,
          tool: {
            name: 'tool1',
            description: 'desc1',
            build: vi.fn().mockImplementation((_) => ({
              getDescription: () => `Mock description`,
            })),
          } as any,
          invocation: {
            getDescription: () => `Mock description`,
          },
          startTime: Date.now(),
          liveOutput: '...',
        } as TrackedExecutingToolCall,
      ];

      const { result } = await renderTestHook(toolCalls);

      // State is `Responding` because a tool is running
      expect(result.current.streamingState).toBe(StreamingState.Responding);

      // Try to cancel
      simulateEscapeKeyPress();

      // Trigger the onComplete callback with the cancelled tool call
      await act(async () => {
        if (capturedOnComplete) {
          await capturedOnComplete([
            {
              ...toolCalls[0],
              status: CoreToolCallStatus.Cancelled,
              response: {
                callId: 'call1',
                responseParts: [],
              },
            } as any,
          ]);
        }
      });

      // The final state should be idle because the cancelled tool call was marked as submitted
      expect(result.current.streamingState).toBe(StreamingState.Idle);
    });

    it('should append cancelled tool responses to history when cancelled while a tool call is in progress and completes with response parts', async () => {
      const toolCalls: TrackedToolCall[] = [
        {
          request: { callId: 'call1', name: 'tool1', args: {} },
          status: CoreToolCallStatus.Executing,
          responseSubmittedToGemini: false,
          tool: {
            name: 'tool1',
            description: 'desc1',
            build: vi.fn().mockImplementation((_) => ({
              getDescription: () => `Mock description`,
            })),
          } as any,
          invocation: {
            getDescription: () => `Mock description`,
          },
          startTime: Date.now(),
          liveOutput: '...',
        } as TrackedExecutingToolCall,
      ];

      const { result, client } = await renderTestHook(toolCalls);

      // State is `Responding` because a tool is running
      expect(result.current.streamingState).toBe(StreamingState.Responding);

      // Try to cancel
      simulateEscapeKeyPress();

      const expectedResponseParts = [
        {
          functionResponse: {
            name: 'tool1',
            id: 'call1',
            response: { error: 'cancelled' },
          },
        },
      ];

      // Trigger the onComplete callback with the cancelled tool call having non-empty response parts
      await act(async () => {
        if (capturedOnComplete) {
          await capturedOnComplete([
            {
              ...toolCalls[0],
              status: CoreToolCallStatus.Cancelled,
              response: {
                callId: 'call1',
                responseParts: expectedResponseParts,
              },
            } as any,
          ]);
        }
      });

      // Assert that addHistory was called with the combined response parts
      expect(client.addHistory).toHaveBeenCalledWith({
        role: 'user',
        parts: expectedResponseParts,
      });

      // The final state should be idle because the cancelled tool call was marked as submitted
      expect(result.current.streamingState).toBe(StreamingState.Idle);
    });

    it('should cancel a request when a tool is awaiting confirmation', async () => {
      const mockOnConfirm = vi.fn().mockResolvedValue(undefined);
      const toolCalls: TrackedToolCall[] = [
        {
          request: {
            callId: 'confirm-call',
            name: 'some_tool',
            args: {},
            isClientInitiated: false,
            prompt_id: 'prompt-id-1',
          },
          status: CoreToolCallStatus.AwaitingApproval,
          responseSubmittedToGemini: false,
          tool: {
            name: 'some_tool',
            description: 'a tool',
            build: vi.fn().mockImplementation((_) => ({
              getDescription: () => `Mock description`,
            })),
          } as any,
          invocation: {
            getDescription: () => `Mock description`,
          } as unknown as AnyToolInvocation,
          confirmationDetails: {
            type: 'edit',
            title: 'Confirm Edit',
            onConfirm: mockOnConfirm,
            fileName: 'file.txt',
            filePath: '/test/file.txt',
            fileDiff: 'fake diff',
            originalContent: 'old',
            newContent: 'new',
          },
        } as TrackedWaitingToolCall,
      ];

      const { result } = await renderTestHook(toolCalls);

      // State is `WaitingForConfirmation` because a tool is awaiting approval
      expect(result.current.streamingState).toBe(
        StreamingState.WaitingForConfirmation,
      );

      // Try to cancel
      simulateEscapeKeyPress();

      // The imperative cancel function should be called on the scheduler
      expect(mockCancelAllToolCalls).toHaveBeenCalled();

      // A cancellation message should be added to history
      await waitFor(() => {
        expect(mockAddItem).toHaveBeenCalledWith(
          expect.objectContaining({
            text: 'Request cancelled.',
          }),
        );
      });

      // The final state should be idle
      expect(result.current.streamingState).toBe(StreamingState.Idle);
    });
  });

  describe('Retry Handling', () => {
    it('should ignore retryStatus updates when not responding', async () => {
      const { result } = await renderHookWithDefaults();

      const retryPayload = {
        model: 'gemini-2.5-pro',
        attempt: 2,
        maxAttempts: 3,
        delayMs: 1000,
      };

      await act(async () => {
        coreEvents.emit(CoreEvent.RetryAttempt, retryPayload);
      });

      expect(result.current.retryStatus).toBeNull();
    });

    it('should reset retryStatus when isResponding becomes false', async () => {
      const { result } = await renderTestHook();

      const retryPayload = {
        model: 'gemini-2.5-pro',
        attempt: 2,
        maxAttempts: 3,
        delayMs: 1000,
      };

      // Start a query to make isResponding true
      const mockStream = (async function* () {
        yield { type: ServerGeminiEventType.Content, value: 'Part 1' };
        await new Promise(() => {}); // Keep stream open
      })();
      mockSendMessageStream.mockReturnValue(mockStream);

      await act(async () => {
        // eslint-disable-next-line @typescript-eslint/no-floating-promises
        result.current.submitQuery('test query');
      });

      await waitFor(() => {
        expect(result.current.streamingState).toBe(StreamingState.Responding);
      });

      // Emit retry event
      await act(async () => {
        coreEvents.emit(CoreEvent.RetryAttempt, retryPayload);
      });

      expect(result.current.retryStatus).toEqual(retryPayload);

      // Cancel to make isResponding false
      await act(async () => {
        result.current.cancelOngoingRequest();
      });

      expect(result.current.retryStatus).toBeNull();
    });

    it('should ignore late retry events after cancellation', async () => {
      const { result } = await renderTestHook();
      const retryPayload = {
        model: 'gemini-2.5-pro',
        attempt: 2,
        maxAttempts: 3,
        delayMs: 1000,
      };
      const lateRetryPayload = {
        model: 'gemini-2.5-pro',
        attempt: 3,
        maxAttempts: 3,
        delayMs: 2000,
      };

      const mockStream = (async function* () {
        yield { type: ServerGeminiEventType.Content, value: 'Part 1' };
        await new Promise(() => {}); // Keep stream open
      })();
      mockSendMessageStream.mockReturnValue(mockStream);

      await act(async () => {
        // eslint-disable-next-line @typescript-eslint/no-floating-promises
        result.current.submitQuery('test query');
      });

      await waitFor(() => {
        expect(result.current.streamingState).toBe(StreamingState.Responding);
      });

      await act(async () => {
        coreEvents.emit(CoreEvent.RetryAttempt, retryPayload);
      });

      expect(result.current.retryStatus).toEqual(retryPayload);

      await act(async () => {
        result.current.cancelOngoingRequest();
      });

      await waitFor(() => {
        expect(result.current.retryStatus).toBeNull();
      });

      await act(async () => {
        coreEvents.emit(CoreEvent.RetryAttempt, lateRetryPayload);
      });

      expect(result.current.retryStatus).toBeNull();
    });
  });

  describe('Slash Command Handling', () => {
    it('should schedule a tool call when the command processor returns a schedule_tool action', async () => {
      const clientToolRequest: SlashCommandProcessorResult = {
        type: 'schedule_tool',
        toolName: 'activate_skill',
        toolArgs: { name: 'test-skill' },
      };
      mockHandleSlashCommand.mockResolvedValue(clientToolRequest);

      const { result } = await renderTestHook();

      await act(async () => {
        await result.current.submitQuery('/memory show');
      });

      await waitFor(() => {
        expect(mockScheduleToolCalls).toHaveBeenCalledWith(
          [
            expect.objectContaining({
              name: 'activate_skill',
              args: { name: 'test-skill' },
              isClientInitiated: true,
            }),
          ],
          expect.any(AbortSignal),
        );
        expect(mockSendMessageStream).not.toHaveBeenCalled();
      });
    });

    it('should stop processing and not call Gemini when a command is handled without a tool call', async () => {
      const uiOnlyCommandResult: SlashCommandProcessorResult = {
        type: 'handled',
      };
      mockHandleSlashCommand.mockResolvedValue(uiOnlyCommandResult);

      const { result } = await renderTestHook();

      await act(async () => {
        await result.current.submitQuery('/help');
      });

      await waitFor(() => {
        expect(mockHandleSlashCommand).toHaveBeenCalledWith('/help');
        expect(mockScheduleToolCalls).not.toHaveBeenCalled();
        expect(mockSendMessageStream).not.toHaveBeenCalled(); // No LLM call made
      });
    });

    it('should call Gemini with prompt content when slash command returns a `submit_prompt` action', async () => {
      const customCommandResult: SlashCommandProcessorResult = {
        type: 'submit_prompt',
        content: 'This is the actual prompt from the command file.',
      };
      mockHandleSlashCommand.mockResolvedValue(customCommandResult);

      const { result, mockSendMessageStream: localMockSendMessageStream } =
        await renderTestHook();

      await act(async () => {
        await result.current.submitQuery('/my-custom-command');
      });

      await waitFor(() => {
        expect(mockHandleSlashCommand).toHaveBeenCalledWith(
          '/my-custom-command',
        );

        expect(localMockSendMessageStream).not.toHaveBeenCalledWith(
          '/my-custom-command',
          expect.anything(),
          expect.anything(),
        );

        expect(localMockSendMessageStream).toHaveBeenCalledWith(
          'This is the actual prompt from the command file.',
          expect.any(AbortSignal),
          expect.any(String),
          undefined,
          '/my-custom-command',
        );

        expect(mockScheduleToolCalls).not.toHaveBeenCalled();
      });
    });

    it('should correctly handle a submit_prompt action with empty content', async () => {
      const emptyPromptResult: SlashCommandProcessorResult = {
        type: 'submit_prompt',
        content: '',
      };
      mockHandleSlashCommand.mockResolvedValue(emptyPromptResult);

      const { result, mockSendMessageStream: localMockSendMessageStream } =
        await renderTestHook();

      await act(async () => {
        await result.current.submitQuery('/emptycmd');
      });

      await waitFor(() => {
        expect(mockHandleSlashCommand).toHaveBeenCalledWith('/emptycmd');
        expect(localMockSendMessageStream).toHaveBeenCalledWith(
          '',
          expect.any(AbortSignal),
          expect.any(String),
          undefined,
          '/emptycmd',
        );
      });
    });

    it('should not call handleSlashCommand for line comments', async () => {
      const { result, mockSendMessageStream: localMockSendMessageStream } =
        await renderTestHook();

      await act(async () => {
        await result.current.submitQuery('// This is a line comment');
      });

      await waitFor(() => {
        expect(mockHandleSlashCommand).not.toHaveBeenCalled();
        expect(localMockSendMessageStream).toHaveBeenCalledWith(
          '// This is a line comment',
          expect.any(AbortSignal),
          expect.any(String),
          undefined,
          '// This is a line comment',
        );
      });
    });

    it('should not call handleSlashCommand for block comments', async () => {
      const { result, mockSendMessageStream: localMockSendMessageStream } =
        await renderTestHook();

      await act(async () => {
        await result.current.submitQuery('/* This is a block comment */');
      });

      await waitFor(() => {
        expect(mockHandleSlashCommand).not.toHaveBeenCalled();
        expect(localMockSendMessageStream).toHaveBeenCalledWith(
          '/* This is a block comment */',
          expect.any(AbortSignal),
          expect.any(String),
          undefined,
          '/* This is a block comment */',
        );
      });
    });

    it('should not call handleSlashCommand is shell mode is active', async () => {
      const { result } = await renderHookWithProviders(() =>
        useGeminiStream(
          new MockedGeminiClientClass(mockConfig),
          [],
          mockAddItem,
          mockConfig,
          mockLoadedSettings,
          () => {},
          mockHandleSlashCommand,
          true,
          () => 'vscode' as EditorType,
          () => {},
          () => Promise.resolve(),
          false,
          () => {},
          () => {},
          () => {},
          80,
          24,
        ),
      );

      await act(async () => {
        await result.current.submitQuery('/about');
      });

      await waitFor(() => {
        expect(mockHandleSlashCommand).not.toHaveBeenCalled();
      });
    });

    it('should record client-initiated tool calls in GeminiChat history', async () => {
      const { result, client: mockGeminiClient } = await renderTestHook();

      mockHandleSlashCommand.mockResolvedValue({
        type: 'schedule_tool',
        toolName: 'activate_skill',
        toolArgs: { name: 'test-skill' },
      });

      await act(async () => {
        await result.current.submitQuery('/test-skill');
      });

      // Simulate tool completion
      const completedTool = {
        request: {
          callId: 'test-call-id',
          name: 'activate_skill',
          args: { name: 'test-skill' },
          isClientInitiated: true,
        },
        status: CoreToolCallStatus.Success,
        invocation: {
          getDescription: () => 'Activating skill test-skill',
        },
        tool: {
          isOutputMarkdown: true,
        },
        response: {
          responseParts: [
            {
              functionResponse: {
                name: 'activate_skill',
                response: { content: 'skill instructions' },
              },
            },
          ],
        },
      } as unknown as TrackedCompletedToolCall;

      await act(async () => {
        if (capturedOnComplete) {
          await capturedOnComplete([completedTool]);
        }
      });

      // Verify that the tool call and response were added to GeminiChat history
      expect(mockGeminiClient.addHistory).toHaveBeenCalledWith({
        role: 'model',
        parts: [
          {
            functionCall: {
              name: 'activate_skill',
              args: { name: 'test-skill' },
            },
          },
        ],
      });
      expect(mockGeminiClient.addHistory).toHaveBeenCalledWith({
        role: 'user',
        parts: completedTool.response.responseParts,
      });
    });

    it('should NOT record other client-initiated tool calls in history', async () => {
      const { result, client: mockGeminiClient } = await renderTestHook();

      mockHandleSlashCommand.mockResolvedValue({
        type: 'schedule_tool',
        toolName: 'write_todos',
        toolArgs: { todos: [] },
      });

      await act(async () => {
        await result.current.submitQuery('/todos');
      });

      // Simulate tool completion
      const completedTool = {
        request: {
          callId: 'test-call-id',
          name: 'write_todos',
          args: { todos: [] },
          isClientInitiated: true,
        },
        status: CoreToolCallStatus.Success,
        invocation: {
          getDescription: () => 'Saving memory',
        },
        tool: {
          isOutputMarkdown: true,
        },
        response: {
          responseParts: [
            {
              functionResponse: {
                name: 'write_todos',
                response: { success: true },
              },
            },
          ],
        },
      } as unknown as TrackedCompletedToolCall;

      await act(async () => {
        if (capturedOnComplete) {
          await capturedOnComplete([completedTool]);
        }
      });

      // Verify that addHistory was NOT called
      expect(mockGeminiClient.addHistory).not.toHaveBeenCalled();
    });
  });

  describe('Error Handling', () => {
    it('should call parseAndFormatApiError with the correct authType on stream initialization failure', async () => {
      // 1. Setup
      const mockError = new Error('Rate limit exceeded');
      const mockAuthType = AuthType.LOGIN_WITH_GOOGLE;
      mockParseAndFormatApiError.mockClear();
      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield { type: 'content', value: '' };
          throw mockError;
        })(),
      );

      const testConfig = {
        // eslint-disable-next-line @typescript-eslint/no-misused-spread
        ...mockConfig,
        getContentGenerator: vi.fn(),
        getContentGeneratorConfig: vi.fn(() => ({
          authType: mockAuthType,
        })),
        getModel: vi.fn(() => 'gemini-2.5-pro'),
      } as unknown as Config;

      const { result } = await renderHookWithProviders(() =>
        useGeminiStream(
          new MockedGeminiClientClass(testConfig),
          [],
          mockAddItem,
          testConfig,
          mockLoadedSettings,
          mockOnDebugMessage,
          mockHandleSlashCommand,
          false,
          () => 'vscode' as EditorType,
          () => {},
          () => Promise.resolve(),
          false,
          () => {},
          () => {},
          () => {},
          80,
          24,
        ),
      );

      // 2. Action
      await act(async () => {
        await result.current.submitQuery('test query');
      });

      // 3. Assertion
      await waitFor(() => {
        expect(mockParseAndFormatApiError).toHaveBeenCalledWith(
          'Rate limit exceeded',
          mockAuthType,
          undefined,
          'gemini-2.5-pro',
          'gemini-2.5-flash',
        );
      });
    });

    it('should use TRUE_EMPTY_RESPONSE_MESSAGE when receiving an invalid stream event of type NO_RESPONSE_TEXT', async () => {
      mockSendMessageStream.mockClear();
      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield {
            type: ServerGeminiEventType.InvalidStream,
            value: {
              type: 'NO_RESPONSE_TEXT',
              message: 'empty response text',
            },
          };
        })(),
      );

      const { result } = await renderTestHook();

      await act(async () => {
        await result.current.submitQuery('test query');
      });

      await waitFor(() => {
        expect(mockAddItem).toHaveBeenCalledWith(
          expect.objectContaining({
            type: MessageType.ERROR,
            text: TRUE_EMPTY_RESPONSE_MESSAGE,
          }),
          expect.any(Number),
        );
      });
    });

    it('should use the event message when receiving a non-NO_RESPONSE_TEXT invalid stream event', async () => {
      mockSendMessageStream.mockClear();
      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield {
            type: ServerGeminiEventType.InvalidStream,
            value: {
              type: 'MALFORMED_FUNCTION_CALL',
              message: 'Custom malformed function call message',
            },
          };
        })(),
      );

      const { result } = await renderTestHook();

      await act(async () => {
        await result.current.submitQuery('test query');
      });

      await waitFor(() => {
        expect(mockAddItem).toHaveBeenCalledWith(
          expect.objectContaining({
            type: MessageType.ERROR,
            text: 'Custom malformed function call message',
          }),
          expect.any(Number),
        );
      });
    });
  });

  describe('handleApprovalModeChange', () => {
    it('should auto-approve all pending tool calls when switching to YOLO mode', async () => {
      const awaitingApprovalToolCalls: TrackedToolCall[] = [
        createMockToolCall('replace', 'call1', 'edit'),
        createMockToolCall('read_file', 'call2', 'info'),
      ];

      const { result } = await renderTestHook(awaitingApprovalToolCalls);

      await act(async () => {
        await result.current.handleApprovalModeChange(ApprovalMode.YOLO);
      });

      // Both tool calls should be auto-approved
      expect(mockMessageBus.publish).toHaveBeenCalledTimes(2);
      expect(mockMessageBus.publish).toHaveBeenCalledWith(
        expect.objectContaining({
          type: MessageBusType.TOOL_CONFIRMATION_RESPONSE,
          correlationId: 'corr-call1',
          outcome: ToolConfirmationOutcome.ProceedOnce,
        }),
      );
      expect(mockMessageBus.publish).toHaveBeenCalledWith(
        expect.objectContaining({
          correlationId: 'corr-call2',
          outcome: ToolConfirmationOutcome.ProceedOnce,
        }),
      );
    });

    it('should only auto-approve edit tools when switching to AUTO_EDIT mode', async () => {
      const awaitingApprovalToolCalls: TrackedToolCall[] = [
        createMockToolCall('replace', 'call1', 'edit'),
        createMockToolCall('write_file', 'call2', 'edit'),
        createMockToolCall('read_file', 'call3', 'info'),
      ];

      const { result } = await renderTestHook(awaitingApprovalToolCalls);

      await act(async () => {
        await result.current.handleApprovalModeChange(ApprovalMode.AUTO_EDIT);
      });

      // Only replace and write_file should be auto-approved
      expect(mockMessageBus.publish).toHaveBeenCalledTimes(2);
      expect(mockMessageBus.publish).toHaveBeenCalledWith(
        expect.objectContaining({ correlationId: 'corr-call1' }),
      );
      expect(mockMessageBus.publish).toHaveBeenCalledWith(
        expect.objectContaining({ correlationId: 'corr-call2' }),
      );
      expect(mockMessageBus.publish).not.toHaveBeenCalledWith(
        expect.objectContaining({ correlationId: 'corr-call3' }),
      );
    });

    it('should auto-approve shell commands with redirection when switching to AUTO_EDIT mode', async () => {
      const shellCall = createMockToolCall(
        SHELL_TOOL_NAME,
        'call-shell',
        'info',
      );
      shellCall.request.args = { command: 'ls > files.txt' };

      const { result } = await renderTestHook([shellCall]);

      await act(async () => {
        await result.current.handleApprovalModeChange(ApprovalMode.AUTO_EDIT);
      });

      // Shell command with redirection should be auto-approved
      expect(mockMessageBus.publish).toHaveBeenCalledWith(
        expect.objectContaining({ correlationId: 'corr-call-shell' }),
      );
    });

    it('should NOT auto-approve shell commands without redirection when switching to AUTO_EDIT mode', async () => {
      const shellCall = createMockToolCall(
        SHELL_TOOL_NAME,
        'call-shell',
        'info',
      );
      shellCall.request.args = { command: 'ls -la' };

      const { result } = await renderTestHook([shellCall]);

      await act(async () => {
        await result.current.handleApprovalModeChange(ApprovalMode.AUTO_EDIT);
      });

      // Regular shell command should NOT be auto-approved
      expect(mockMessageBus.publish).not.toHaveBeenCalled();
    });

    it('should not auto-approve any tools when switching to REQUIRE_CONFIRMATION mode', async () => {
      const awaitingApprovalToolCalls: TrackedToolCall[] = [
        createMockToolCall('replace', 'call1', 'edit'),
      ];

      const { result } = await renderTestHook(awaitingApprovalToolCalls);

      await act(async () => {
        await result.current.handleApprovalModeChange(ApprovalMode.DEFAULT);
      });

      // No tools should be auto-approved
      expect(mockMessageBus.publish).not.toHaveBeenCalled();
    });

    it('should handle errors gracefully when auto-approving tool calls', async () => {
      const debuggerSpy = vi
        .spyOn(debugLogger, 'warn')
        .mockImplementation(() => {});

      mockMessageBus.publish.mockRejectedValueOnce(new Error('Bus error'));

      const awaitingApprovalToolCalls: TrackedToolCall[] = [
        createMockToolCall('replace', 'call1', 'edit'),
        createMockToolCall('write_file', 'call2', 'edit'),
      ];

      const { result } = await renderTestHook(awaitingApprovalToolCalls);

      await act(async () => {
        await result.current.handleApprovalModeChange(ApprovalMode.YOLO);
      });

      // Both should be attempted despite first error
      expect(mockMessageBus.publish).toHaveBeenCalledTimes(2);
      expect(debuggerSpy).toHaveBeenCalledWith(
        'Failed to auto-approve tool call call1:',
        expect.any(Error),
      );

      debuggerSpy.mockRestore();
    });

    it('should skip tool calls without confirmationDetails', async () => {
      const awaitingApprovalToolCalls: TrackedToolCall[] = [
        {
          request: {
            callId: 'call1',
            name: 'replace',
            args: { old_string: 'old', new_string: 'new' },
            isClientInitiated: false,
            prompt_id: 'prompt-id-1',
          },
          status: CoreToolCallStatus.AwaitingApproval,
          responseSubmittedToGemini: false,
          // No confirmationDetails
          tool: {
            name: 'replace',
            displayName: 'replace',
            description: 'Replace text',
            build: vi.fn(),
          } as unknown as AnyDeclarativeTool,
          invocation: {
            getDescription: () => 'Mock description',
          } as unknown as AnyToolInvocation,
          correlationId: 'corr-1',
        } as unknown as TrackedWaitingToolCall,
      ];

      const { result } = await renderTestHook(awaitingApprovalToolCalls);

      // Should not throw an error
      await act(async () => {
        await result.current.handleApprovalModeChange(ApprovalMode.YOLO);
      });
    });

    it('should only process tool calls with awaiting_approval status', async () => {
      const mockOnConfirmAwaiting = vi.fn().mockResolvedValue(undefined);
      const mixedStatusToolCalls: TrackedToolCall[] = [
        createMockToolCall(
          'replace',
          'call1',
          'edit',
          CoreToolCallStatus.AwaitingApproval,
          mockOnConfirmAwaiting,
        ),
        {
          request: {
            callId: 'call2',
            name: 'write_file',
            args: { path: '/test/file.txt', content: 'content' },
            isClientInitiated: false,
            prompt_id: 'prompt-id-1',
          },
          status: CoreToolCallStatus.Executing,
          responseSubmittedToGemini: false,
          tool: {
            name: 'write_file',
            displayName: 'write_file',
            description: 'Write file',
            build: vi.fn(),
          } as unknown as AnyDeclarativeTool,
          invocation: {
            getDescription: () => 'Mock description',
          } as unknown as AnyToolInvocation,
          startTime: Date.now(),
          liveOutput: 'Writing...',
          correlationId: 'corr-call2',
        } as TrackedExecutingToolCall,
      ];

      const { result } = await renderTestHook(mixedStatusToolCalls);

      await act(async () => {
        await result.current.handleApprovalModeChange(ApprovalMode.YOLO);
      });

      // Only the awaiting_approval tool should be processed.
      expect(mockMessageBus.publish).toHaveBeenCalledTimes(1);
      expect(mockMessageBus.publish).toHaveBeenCalledWith(
        expect.objectContaining({ correlationId: 'corr-call1' }),
      );
      expect(mockMessageBus.publish).not.toHaveBeenCalledWith(
        expect.objectContaining({ correlationId: 'corr-call2' }),
      );
    });

    it('should inject a notification message when manually exiting Plan Mode', async () => {
      // Setup mockConfig to return PLAN mode initially
      (mockConfig.getApprovalMode as Mock).mockReturnValue(ApprovalMode.PLAN);

      // Render the hook, which will initialize the previousApprovalModeRef with PLAN
      const { result, client } = await renderTestHook([]);

      // Update mockConfig to return DEFAULT mode (new mode)
      (mockConfig.getApprovalMode as Mock).mockReturnValue(
        ApprovalMode.DEFAULT,
      );

      await act(async () => {
        // Trigger manual exit from Plan Mode
        await result.current.handleApprovalModeChange(ApprovalMode.DEFAULT);
      });

      // Verify that addHistory was called with the notification message
      expect(client.addHistory).toHaveBeenCalledWith({
        role: 'user',
        parts: [
          {
            text: getPlanModeExitMessage(ApprovalMode.DEFAULT, true),
          },
        ],
      });
    });
  });

  describe('handleFinishedEvent', () => {
    it('should add info message for MAX_TOKENS finish reason', async () => {
      // Setup mock to return a stream with MAX_TOKENS finish reason
      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield {
            type: ServerGeminiEventType.Content,
            value: 'This is a truncated response...',
          };
          yield {
            type: ServerGeminiEventType.Finished,
            value: { reason: 'MAX_TOKENS', usageMetadata: undefined },
          };
        })(),
      );

      const { result } = await renderHookWithProviders(() =>
        useGeminiStream(
          new MockedGeminiClientClass(mockConfig),
          [],
          mockAddItem,
          mockConfig,
          mockLoadedSettings,
          mockOnDebugMessage,
          mockHandleSlashCommand,
          false,
          () => 'vscode' as EditorType,
          () => {},
          () => Promise.resolve(),
          false,
          () => {},
          () => {},
          () => {},
          80,
          24,
        ),
      );

      // Submit a query
      await act(async () => {
        await result.current.submitQuery('Generate long text');
      });

      // Check that the info message was added
      await waitFor(() => {
        expect(mockAddItem).toHaveBeenCalledWith(
          {
            type: 'info',
            text: '⚠️  Response truncated due to token limits.',
          },
          expect.any(Number),
        );
      });
    });

    describe('ContextWindowWillOverflow event', () => {
      beforeEach(() => {
        vi.mocked(tokenLimit).mockReturnValue(100);
      });

      it.each([
        {
          name: 'without suggestion when remaining tokens are > 75% of limit',
          requestTokens: 20,
          remainingTokens: 80,
          expectedMessage:
            'Sending this message (20 tokens) might exceed the context window limit (80 tokens left).',
        },
        {
          name: 'with suggestion when remaining tokens are < 75% of limit',
          requestTokens: 30,
          remainingTokens: 70,
          expectedMessage:
            'Sending this message (30 tokens) might exceed the context window limit (70 tokens left). Please try reducing the size of your message or use the `/compress` command to compress the chat history.',
        },
      ])(
        'should add message $name',
        async ({ requestTokens, remainingTokens, expectedMessage }) => {
          mockSendMessageStream.mockReturnValue(
            (async function* () {
              yield {
                type: ServerGeminiEventType.ContextWindowWillOverflow,
                value: {
                  estimatedRequestTokenCount: requestTokens,
                  remainingTokenCount: remainingTokens,
                },
              };
            })(),
          );

          const { result } = await renderHookWithDefaults();

          await act(async () => {
            await result.current.submitQuery('Test overflow');
          });

          await waitFor(() => {
            expect(mockAddItem).toHaveBeenCalledWith({
              type: 'info',
              text: expectedMessage,
            });
          });
        },
      );
    });

    it('should call onCancelSubmit when ContextWindowWillOverflow event is received', async () => {
      const onCancelSubmitSpy = vi.fn();
      // Setup mock to return a stream with ContextWindowWillOverflow event
      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield {
            type: ServerGeminiEventType.ContextWindowWillOverflow,
            value: {
              estimatedRequestTokenCount: 100,
              remainingTokenCount: 50,
            },
          };
        })(),
      );

      const { result } = await renderHookWithProviders(() =>
        useGeminiStream(
          new MockedGeminiClientClass(mockConfig),
          [],
          mockAddItem,
          mockConfig,
          mockLoadedSettings,
          mockOnDebugMessage,
          mockHandleSlashCommand,
          false,
          () => 'vscode' as EditorType,
          () => {},
          () => Promise.resolve(),
          false,
          () => {},
          onCancelSubmitSpy,
          () => {},
          80,
          24,
        ),
      );

      // Submit a query
      await act(async () => {
        await result.current.submitQuery('Test overflow');
      });

      // Check that onCancelSubmit was called
      await waitFor(() => {
        expect(onCancelSubmitSpy).toHaveBeenCalledWith(true);
      });
    });

    it('should add informational messages when ChatCompressed event is received', async () => {
      vi.mocked(tokenLimit).mockReturnValue(10000);
      // Setup mock to return a stream with ChatCompressed event
      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield {
            type: ServerGeminiEventType.ChatCompressed,
            value: {
              originalTokenCount: 1000,
              newTokenCount: 500,
              compressionStatus: 'compressed',
            },
          };
        })(),
      );

      const { result } = await renderHookWithDefaults();

      // Submit a query
      await act(async () => {
        await result.current.submitQuery('Test compression');
      });

      // Check that the succinct info message was added
      await waitFor(() => {
        expect(mockAddItem).toHaveBeenCalledWith(
          expect.objectContaining({
            type: MessageType.INFO,
            text: 'Context compressed from 10% to 5%.',
            secondaryText: 'Change threshold in /settings.',
            color: theme.status.warning,
          }),
          expect.any(Number),
        );
      });
    });

    it.each([
      {
        reason: 'STOP',
        shouldAddMessage: false,
      },
      {
        reason: 'FINISH_REASON_UNSPECIFIED',
        shouldAddMessage: false,
      },
      {
        reason: 'SAFETY',
        message: '⚠️  Response stopped due to safety reasons.',
      },
      {
        reason: 'RECITATION',
        message: '⚠️  Response stopped due to recitation policy.',
      },
      {
        reason: 'LANGUAGE',
        message: '⚠️  Response stopped due to unsupported language.',
      },
      {
        reason: 'BLOCKLIST',
        message: '⚠️  Response stopped due to forbidden terms.',
      },
      {
        reason: 'PROHIBITED_CONTENT',
        message: '⚠️  Response stopped due to prohibited content.',
      },
      {
        reason: 'SPII',
        message:
          '⚠️  Response stopped due to sensitive personally identifiable information.',
      },
      {
        reason: 'OTHER',
        message: '⚠️  Response stopped for other reasons.',
      },
      {
        reason: 'MALFORMED_FUNCTION_CALL',
        message: '⚠️  Response stopped due to malformed function call.',
      },
      {
        reason: 'IMAGE_SAFETY',
        message: '⚠️  Response stopped due to image safety violations.',
      },
      {
        reason: 'UNEXPECTED_TOOL_CALL',
        message: '⚠️  Response stopped due to unexpected tool call.',
      },
    ])(
      'should handle $reason finish reason correctly',
      async ({ reason, shouldAddMessage = true, message }) => {
        mockSendMessageStream.mockReturnValue(
          (async function* () {
            yield {
              type: ServerGeminiEventType.Content,
              value: `Response for ${reason}`,
            };
            yield {
              type: ServerGeminiEventType.Finished,
              value: { reason, usageMetadata: undefined },
            };
          })(),
        );

        const { result } = await renderHookWithDefaults();

        await act(async () => {
          await result.current.submitQuery(`Test ${reason}`);
        });

        if (shouldAddMessage) {
          await waitFor(() => {
            expect(mockAddItem).toHaveBeenCalledWith(
              {
                type: 'info',
                text: message,
              },
              expect.any(Number),
            );
          });
        } else {
          // Verify state returns to idle without any info messages
          await waitFor(() => {
            expect(result.current.streamingState).toBe(StreamingState.Idle);
          });

          const infoMessages = mockAddItem.mock.calls.filter(
            (call) => call[0].type === 'info',
          );
          expect(infoMessages).toHaveLength(0);
        }
      },
    );
  });

  it('should flush pending text rationale before scheduling tool calls to ensure correct history order', async () => {
    const addItemOrder: string[] = [];
    let capturedOnComplete: (tools: CompletedToolCall[]) => Promise<void>;

    const mockScheduleToolCalls = vi.fn(async (requests) => {
      addItemOrder.push('scheduleToolCalls_START');
      // Simulate tools completing and triggering onComplete immediately.
      // This mimics the behavior that caused the regression where tool results
      // were added to history during the await scheduleToolCalls(...) block.
      const tools = requests.map((r: ToolCallRequestInfo) => ({
        request: r,
        status: CoreToolCallStatus.Success,
        tool: { displayName: r.name, name: r.name },
        invocation: { getDescription: () => 'desc' },
        response: { responseParts: [], resultDisplay: 'done' },
        startTime: Date.now(),
        endTime: Date.now(),
      }));
      // Wait a tick for refs to be set up
      await new Promise((resolve) => setTimeout(resolve, 0));
      await capturedOnComplete(tools);
      addItemOrder.push('scheduleToolCalls_END');
    });

    mockAddItem.mockImplementation((item: HistoryItemWithoutId) => {
      addItemOrder.push(`addItem:${item.type}`);
    });

    // We need to capture the onComplete callback from useToolScheduler
    mockUseToolScheduler.mockImplementation((onComplete) => {
      capturedOnComplete = onComplete;
      return [
        [], // toolCalls
        mockScheduleToolCalls,
        vi.fn(), // markToolsAsSubmitted
        vi.fn(), // setToolCallsForDisplay
        vi.fn(), // cancelAllToolCalls
        0, // lastToolOutputTime
      ];
    });

    const { result } = await renderHookWithProviders(() =>
      useGeminiStream(
        new MockedGeminiClientClass(mockConfig),
        [],
        mockAddItem,
        mockConfig,
        mockLoadedSettings,
        vi.fn(),
        vi.fn(),
        false,
        () => 'vscode' as EditorType,
        vi.fn(),
        vi.fn(),
        false,
        vi.fn(),
        vi.fn(),
        vi.fn(),
        80,
        24,
      ),
    );

    const mockStream = (async function* () {
      yield {
        type: ServerGeminiEventType.Content,
        value: 'Rationale rationale.',
      };
      yield {
        type: ServerGeminiEventType.ToolCallRequest,
        value: { callId: '1', name: 'test_tool', args: {} },
      };
    })();
    mockSendMessageStream.mockReturnValue(mockStream);

    await act(async () => {
      await result.current.submitQuery('test input');
    });

    // Expectation: addItem:gemini (rationale) MUST happen before scheduleToolCalls_START
    const rationaleIndex = addItemOrder.indexOf('addItem:gemini');
    const scheduleIndex = addItemOrder.indexOf('scheduleToolCalls_START');
    const toolGroupIndex = addItemOrder.indexOf('addItem:tool_group');

    expect(rationaleIndex).toBeGreaterThan(-1);
    expect(scheduleIndex).toBeGreaterThan(-1);
    expect(toolGroupIndex).toBeGreaterThan(-1);

    // This is the core fix validation: Rationale comes before tools are even scheduled (awaited)
    expect(rationaleIndex).toBeLessThan(scheduleIndex);
    expect(rationaleIndex).toBeLessThan(toolGroupIndex);

    // Ensure all state updates from recursive submitQuery are settled
    await waitFor(() => {
      expect(result.current.streamingState).toBe(StreamingState.Idle);
    });
  });

  it('should process @include commands, adding user turn after processing to prevent race conditions', async () => {
    const rawQuery = '@include file.txt Summarize this.';
    const processedQueryParts = [
      { text: 'Summarize this with content from @file.txt' },
      { text: 'File content...' },
    ];
    const userMessageTimestamp = Date.now();
    vi.spyOn(Date, 'now').mockReturnValue(userMessageTimestamp);

    handleAtCommandSpy.mockResolvedValue({
      processedQuery: processedQueryParts,
      shouldProceed: true,
    });

    const { result } = await renderHookWithProviders(() =>
      useGeminiStream(
        mockConfig.getGeminiClient(),
        [],
        mockAddItem,
        mockConfig,
        mockLoadedSettings,
        mockOnDebugMessage,
        mockHandleSlashCommand,
        false, // shellModeActive
        vi.fn(), // getPreferredEditor
        vi.fn(), // onAuthError
        vi.fn(), // performMemoryRefresh
        false, // modelSwitched
        vi.fn(), // setModelSwitched
        vi.fn(), // onCancelSubmit
        vi.fn(), // setShellInputFocused
        80, // terminalWidth
        24, // terminalHeight
      ),
    );

    await act(async () => {
      await result.current.submitQuery(rawQuery);
    });

    expect(handleAtCommandSpy).toHaveBeenCalledWith(
      expect.objectContaining({
        query: rawQuery,
      }),
    );

    expect(mockAddItem).toHaveBeenCalledWith(
      {
        type: MessageType.USER,
        text: rawQuery,
      },
      userMessageTimestamp,
    );

    // FIX: The expectation now matches the actual call signature.
    expect(mockSendMessageStream).toHaveBeenCalledWith(
      processedQueryParts, // Argument 1: The parts array directly
      expect.any(AbortSignal), // Argument 2: An AbortSignal
      expect.any(String), // Argument 3: The prompt_id string
      undefined,
      rawQuery,
    );
  });

  it('should display user query, then tool execution, then model response', async () => {
    const userQuery = 'read this @file(test.txt)';
    const toolExecutionMessage = 'Reading file: test.txt';
    const modelResponseContent = 'The content of test.txt is: Hello World!';

    // Mock handleAtCommand to simulate a tool call and add a tool_group message
    handleAtCommandSpy.mockImplementation(
      async ({ addItem: atCommandAddItem, messageId }) => {
        atCommandAddItem(
          {
            type: 'tool_group',
            tools: [
              {
                callId: 'client-read-123',
                name: 'read_file',
                description: toolExecutionMessage,
                status: CoreToolCallStatus.Success,
                resultDisplay: toolExecutionMessage,
                confirmationDetails: undefined,
              },
            ],
          },
          messageId,
        );
        return { shouldProceed: true, processedQuery: userQuery };
      },
    );

    // Mock the Gemini stream to return a model response after the tool
    mockSendMessageStream.mockReturnValue(
      (async function* () {
        yield {
          type: ServerGeminiEventType.Content,
          value: modelResponseContent,
        };
        yield {
          type: ServerGeminiEventType.Finished,
          value: { reason: 'STOP' },
        };
      })(),
    );

    const { result } = await renderTestHook();

    await act(async () => {
      await result.current.submitQuery(userQuery);
    });

    // Assert the order of messages added to the history
    await waitFor(() => {
      expect(mockAddItem).toHaveBeenCalledTimes(3); // User prompt + tool execution + model response

      // 1. User's prompt
      expect(mockAddItem).toHaveBeenNthCalledWith(
        1,
        expect.objectContaining({
          type: MessageType.USER,
          text: userQuery,
        }),
        expect.any(Number),
      );

      // 2. Tool execution message
      expect(mockAddItem).toHaveBeenNthCalledWith(
        2,
        expect.objectContaining({
          type: 'tool_group',
          tools: expect.arrayContaining([
            expect.objectContaining({
              name: 'read_file',
              status: CoreToolCallStatus.Success,
            }),
          ]),
        }),
        expect.any(Number),
      );

      // 3. Model's response
      expect(mockAddItem).toHaveBeenNthCalledWith(
        3,
        expect.objectContaining({
          type: 'gemini',
          text: modelResponseContent,
        }),
        expect.any(Number),
      );
    });
  });
  describe('Thought Reset', () => {
    it('should keep full thinking entries in history when mode is full', async () => {
      const fullThinkingSettings: LoadedSettings = {
        // eslint-disable-next-line @typescript-eslint/no-misused-spread
        ...mockLoadedSettings,
        merged: {
          ...mockLoadedSettings.merged,
          ui: { inlineThinkingMode: 'full' },
        },
      } as unknown as LoadedSettings;

      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield {
            type: ServerGeminiEventType.Thought,
            value: {
              subject: 'Full thought',
              description: 'Detailed thinking',
            },
          };
          yield {
            type: ServerGeminiEventType.Content,
            value: 'Response',
          };
        })(),
      );

      const { result } = await renderHookWithProviders(() =>
        useGeminiStream(
          new MockedGeminiClientClass(mockConfig),
          [],
          mockAddItem,
          mockConfig,
          fullThinkingSettings,
          mockOnDebugMessage,
          mockHandleSlashCommand,
          false,
          () => 'vscode' as EditorType,
          () => {},
          () => Promise.resolve(),
          false,
          () => {},
          () => {},
          () => {},
          80,
          24,
        ),
      );

      await act(async () => {
        await result.current.submitQuery('Test query');
      });

      expect(mockAddItem).toHaveBeenCalledWith(
        expect.objectContaining({
          type: 'thinking',
          thought: expect.objectContaining({ subject: 'Full thought' }),
        }),
      );
    });

    it('keeps thought transient and clears it on first non-thought event', async () => {
      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield {
            type: ServerGeminiEventType.Thought,
            value: {
              subject: 'Assessing intent',
              description: 'Inspecting context',
            },
          };
          yield {
            type: ServerGeminiEventType.Content,
            value: 'Model response content',
          };
          yield {
            type: ServerGeminiEventType.Finished,
            value: { reason: 'STOP', usageMetadata: undefined },
          };
        })(),
      );

      const { result } = await renderTestHook();

      await act(async () => {
        await result.current.submitQuery('Test query');
      });

      await waitFor(() => {
        expect(mockAddItem).toHaveBeenCalledWith(
          expect.objectContaining({
            type: 'gemini',
            text: 'Model response content',
          }),
          expect.any(Number),
        );
      });

      expect(result.current.thought).toBeNull();
      expect(mockAddItem).not.toHaveBeenCalledWith(
        expect.objectContaining({ type: 'thinking' }),
        expect.any(Number),
      );
    });

    it('should reset thought to null when starting a new prompt', async () => {
      // First, simulate a response with a thought
      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield {
            type: ServerGeminiEventType.Thought,
            value: {
              subject: 'Previous thought',
              description: 'Old description',
            },
          };
          yield {
            type: ServerGeminiEventType.Content,
            value: 'Some response content',
          };
          yield {
            type: ServerGeminiEventType.Finished,
            value: { reason: 'STOP', usageMetadata: undefined },
          };
        })(),
      );

      const { result } = await renderHookWithProviders(() =>
        useGeminiStream(
          new MockedGeminiClientClass(mockConfig),
          [],
          mockAddItem,
          mockConfig,
          mockLoadedSettings,
          mockOnDebugMessage,
          mockHandleSlashCommand,
          false,
          () => 'vscode' as EditorType,
          () => {},
          () => Promise.resolve(),
          false,
          () => {},
          () => {},
          () => {},
          80,
          24,
        ),
      );

      // Submit first query to set a thought
      await act(async () => {
        await result.current.submitQuery('First query');
      });

      // Wait for the first response to complete
      await waitFor(() => {
        expect(mockAddItem).toHaveBeenCalledWith(
          expect.objectContaining({
            type: 'gemini',
            text: 'Some response content',
          }),
          expect.any(Number),
        );
      });

      // Now simulate a new response without a thought
      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield {
            type: ServerGeminiEventType.Content,
            value: 'New response content',
          };
          yield {
            type: ServerGeminiEventType.Finished,
            value: { reason: 'STOP', usageMetadata: undefined },
          };
        })(),
      );

      // Submit second query - thought should be reset
      await act(async () => {
        await result.current.submitQuery('Second query');
      });

      // The thought should be reset to null when starting the new prompt
      // We can verify this by checking that the LoadingIndicator would not show the previous thought
      // The actual thought state is internal to the hook, but we can verify the behavior
      // by ensuring the second response doesn't show the previous thought
      await waitFor(() => {
        expect(mockAddItem).toHaveBeenCalledWith(
          expect.objectContaining({
            type: 'gemini',
            text: 'New response content',
          }),
          expect.any(Number),
        );
      });
    });

    it('should memoize pendingHistoryItems', async () => {
      mockUseToolScheduler.mockReturnValue([
        [],
        mockScheduleToolCalls,
        mockMarkToolsAsSubmitted,
        vi.fn(),
        mockCancelAllToolCalls,
        0,
      ]);

      const { result, rerender } = await renderHookWithProviders(() =>
        useGeminiStream(
          mockConfig.getGeminiClient(),
          [],
          mockAddItem,
          mockConfig,
          mockLoadedSettings,
          mockOnDebugMessage,
          mockHandleSlashCommand,
          false,
          () => 'vscode' as EditorType,
          () => {},
          () => Promise.resolve(),
          false,
          () => {},
          () => {},
          () => {},
          80,
          24,
        ),
      );

      const firstResult = result.current.pendingHistoryItems;
      rerender();
      const secondResult = result.current.pendingHistoryItems;

      expect(firstResult).toStrictEqual(secondResult);

      const newToolCalls: TrackedToolCall[] = [
        {
          request: { callId: 'call1', name: 'tool1', args: {} },
          status: CoreToolCallStatus.Executing,
          tool: {
            name: 'tool1',
            displayName: 'tool1',
            description: 'desc1',
            build: vi.fn(),
          },
          invocation: {
            getDescription: () => 'Mock description',
          },
        } as unknown as TrackedExecutingToolCall,
      ];

      mockUseToolScheduler.mockReturnValue([
        newToolCalls,
        mockScheduleToolCalls,
        mockMarkToolsAsSubmitted,
        vi.fn(),
        mockCancelAllToolCalls,
        0,
      ]);

      rerender();
      const thirdResult = result.current.pendingHistoryItems;

      expect(thirdResult).not.toStrictEqual(secondResult);
    });

    it('should reset thought to null when user cancels', async () => {
      // Mock a stream that yields a thought then gets cancelled
      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield {
            type: ServerGeminiEventType.Thought,
            value: { subject: 'Some thought', description: 'Description' },
          };
          yield { type: ServerGeminiEventType.UserCancelled };
        })(),
      );

      const { result } = await renderHookWithProviders(() =>
        useGeminiStream(
          new MockedGeminiClientClass(mockConfig),
          [],
          mockAddItem,
          mockConfig,
          mockLoadedSettings,
          mockOnDebugMessage,
          mockHandleSlashCommand,
          false,
          () => 'vscode' as EditorType,
          () => {},
          () => Promise.resolve(),
          false,
          () => {},
          () => {},
          () => {},
          80,
          24,
        ),
      );

      // Submit query
      await act(async () => {
        await result.current.submitQuery('Test query');
      });

      // Verify cancellation message was added
      await waitFor(() => {
        expect(mockAddItem).toHaveBeenCalledWith(
          expect.objectContaining({
            type: 'info',
            text: 'User cancelled the request.',
          }),
          expect.any(Number),
        );
      });

      // Verify state is reset to idle
      expect(result.current.streamingState).toBe(StreamingState.Idle);
    });

    it('should reset thought to null when there is an error', async () => {
      // Mock a stream that yields a thought then encounters an error
      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield {
            type: ServerGeminiEventType.Thought,
            value: { subject: 'Some thought', description: 'Description' },
          };
          yield {
            type: ServerGeminiEventType.Error,
            value: { error: { message: 'Test error' } },
          };
        })(),
      );

      const { result } = await renderHookWithProviders(() =>
        useGeminiStream(
          new MockedGeminiClientClass(mockConfig),
          [],
          mockAddItem,
          mockConfig,
          mockLoadedSettings,
          mockOnDebugMessage,
          mockHandleSlashCommand,
          false,
          () => 'vscode' as EditorType,
          () => {},
          () => Promise.resolve(),
          false,
          () => {},
          () => {},
          () => {},
          80,
          24,
        ),
      );

      // Submit query
      await act(async () => {
        await result.current.submitQuery('Test query');
      });

      // Verify error message was added
      await waitFor(() => {
        expect(mockAddItem).toHaveBeenCalledWith(
          expect.objectContaining({
            type: CoreToolCallStatus.Error,
          }),
          expect.any(Number),
        );
      });

      // Verify parseAndFormatApiError was called
      expect(mockParseAndFormatApiError).toHaveBeenCalledWith(
        { message: 'Test error' },
        expect.any(String),
        undefined,
        'gemini-2.5-pro',
        'gemini-2.5-flash',
      );
    });

    it('should update lastOutputTime on Gemini thought and content events', async () => {
      vi.useFakeTimers();
      const startTime = 1000000;
      vi.setSystemTime(startTime);

      // Mock a stream that yields a thought then content
      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield {
            type: ServerGeminiEventType.Thought,
            value: { subject: 'Thinking...', description: '' },
          };
          // Advance time for the next event
          vi.advanceTimersByTime(1000);
          yield {
            type: ServerGeminiEventType.Content,
            value: 'Hello',
          };
        })(),
      );

      const { result } = await renderHookWithProviders(() =>
        useGeminiStream(
          new MockedGeminiClientClass(mockConfig),
          [],
          mockAddItem,
          mockConfig,
          mockLoadedSettings,
          mockOnDebugMessage,
          mockHandleSlashCommand,
          false,
          () => 'vscode' as EditorType,
          () => {},
          () => Promise.resolve(),
          false,
          () => {},
          () => {},
          () => {},
          80,
          24,
        ),
      );

      // Reset fake timers to startTime because the asynchronous render lifecycle
      // (via waitUntilReady) advances the mock clock while waiting for initial
      // components to settle.
      vi.setSystemTime(startTime);

      // Submit query
      await act(async () => {
        await result.current.submitQuery('Test query');
      });

      // Verify lastOutputTime was updated
      // It should be the time of the last event (startTime + 1000)
      expect(result.current.lastOutputTime).toBe(startTime + 1000);

      vi.useRealTimers();
    });
  });

  describe('Loop Detection Confirmation', () => {
    beforeEach(() => {
      // Add mock for getLoopDetectionService to the config
      const mockLoopDetectionService = {
        disableForSession: vi.fn(),
      };
      mockConfig.getGeminiClient = vi.fn().mockReturnValue({
        ...new MockedGeminiClientClass(mockConfig),
        getLoopDetectionService: () => mockLoopDetectionService,
      });
    });

    it('should set loopDetectionConfirmationRequest when LoopDetected event is received', async () => {
      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield {
            type: ServerGeminiEventType.Content,
            value: 'Some content',
          };
          yield {
            type: ServerGeminiEventType.LoopDetected,
          };
        })(),
      );

      const { result } = await renderTestHook();

      await act(async () => {
        await result.current.submitQuery('test query');
      });

      await waitFor(() => {
        expect(result.current.loopDetectionConfirmationRequest).not.toBeNull();
        expect(
          typeof result.current.loopDetectionConfirmationRequest?.onComplete,
        ).toBe('function');
      });
    });

    it('should disable loop detection and show message when user selects "disable"', async () => {
      const mockLoopDetectionService = {
        disableForSession: vi.fn(),
      };
      const mockClient = {
        ...new MockedGeminiClientClass(mockConfig),
        getLoopDetectionService: () => mockLoopDetectionService,
      };
      mockConfig.getGeminiClient = vi.fn().mockReturnValue(mockClient);

      // Mock for the initial request
      mockSendMessageStream.mockReturnValueOnce(
        (async function* () {
          yield {
            type: ServerGeminiEventType.LoopDetected,
          };
        })(),
      );

      // Mock for the retry request
      mockSendMessageStream.mockReturnValueOnce(
        (async function* () {
          yield {
            type: ServerGeminiEventType.Content,
            value: 'Retry successful',
          };
          yield {
            type: ServerGeminiEventType.Finished,
            value: { reason: 'STOP' },
          };
        })(),
      );

      const { result } = await renderTestHook();

      await act(async () => {
        await result.current.submitQuery('test query');
      });

      // Wait for confirmation request to be set
      await waitFor(() => {
        expect(result.current.loopDetectionConfirmationRequest).not.toBeNull();
      });

      // Simulate user selecting "disable"
      await act(async () => {
        result.current.loopDetectionConfirmationRequest?.onComplete({
          userSelection: 'disable',
        });
      });

      // Verify loop detection was disabled
      expect(mockLoopDetectionService.disableForSession).toHaveBeenCalledTimes(
        1,
      );

      // Verify confirmation request was cleared
      expect(result.current.loopDetectionConfirmationRequest).toBeNull();

      // Verify appropriate message was added
      expect(mockAddItem).toHaveBeenCalledWith({
        type: 'info',
        text: 'Loop detection has been disabled for this session. Retrying request...',
      });

      // Verify that the request was retried
      await waitFor(() => {
        expect(mockSendMessageStream).toHaveBeenCalledTimes(2);
        expect(mockSendMessageStream).toHaveBeenNthCalledWith(
          2,
          'test query',
          expect.any(AbortSignal),
          expect.any(String),
          undefined,
          'test query',
        );
      });
    });

    it('should keep loop detection enabled and show message when user selects "keep"', async () => {
      const mockLoopDetectionService = {
        disableForSession: vi.fn(),
      };
      const mockClient = {
        ...new MockedGeminiClientClass(mockConfig),
        getLoopDetectionService: () => mockLoopDetectionService,
      };
      mockConfig.getGeminiClient = vi.fn().mockReturnValue(mockClient);

      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield {
            type: ServerGeminiEventType.LoopDetected,
          };
        })(),
      );

      const { result } = await renderTestHook();

      await act(async () => {
        await result.current.submitQuery('test query');
      });

      // Wait for confirmation request to be set
      await waitFor(() => {
        expect(result.current.loopDetectionConfirmationRequest).not.toBeNull();
      });

      // Simulate user selecting "keep"
      await act(async () => {
        result.current.loopDetectionConfirmationRequest?.onComplete({
          userSelection: 'keep',
        });
      });

      // Verify loop detection was NOT disabled
      expect(mockLoopDetectionService.disableForSession).not.toHaveBeenCalled();

      // Verify confirmation request was cleared
      expect(result.current.loopDetectionConfirmationRequest).toBeNull();

      // Verify appropriate message was added
      expect(mockAddItem).toHaveBeenCalledWith({
        type: 'info',
        text: 'A potential loop was detected. This can happen due to repetitive tool calls or other model behavior. The request has been halted.',
      });

      // Verify that the request was NOT retried
      expect(mockSendMessageStream).toHaveBeenCalledTimes(1);
    });

    it('should handle multiple loop detection events properly', async () => {
      const { result } = await renderTestHook();

      // First loop detection - set up fresh mock for first call
      mockSendMessageStream.mockReturnValueOnce(
        (async function* () {
          yield {
            type: ServerGeminiEventType.LoopDetected,
          };
        })(),
      );

      // First loop detection
      await act(async () => {
        await result.current.submitQuery('first query');
      });

      await waitFor(() => {
        expect(result.current.loopDetectionConfirmationRequest).not.toBeNull();
      });

      // Simulate user selecting "keep" for first request
      await act(async () => {
        result.current.loopDetectionConfirmationRequest?.onComplete({
          userSelection: 'keep',
        });
      });

      expect(result.current.loopDetectionConfirmationRequest).toBeNull();

      // Verify first message was added
      expect(mockAddItem).toHaveBeenCalledWith({
        type: 'info',
        text: 'A potential loop was detected. This can happen due to repetitive tool calls or other model behavior. The request has been halted.',
      });

      // Second loop detection - set up fresh mock for second call
      mockSendMessageStream.mockReturnValueOnce(
        (async function* () {
          yield {
            type: ServerGeminiEventType.LoopDetected,
          };
        })(),
      );

      // Mock for the retry request
      mockSendMessageStream.mockReturnValueOnce(
        (async function* () {
          yield {
            type: ServerGeminiEventType.Content,
            value: 'Retry successful',
          };
          yield {
            type: ServerGeminiEventType.Finished,
            value: { reason: 'STOP' },
          };
        })(),
      );

      // Second loop detection
      await act(async () => {
        await result.current.submitQuery('second query');
      });

      await waitFor(() => {
        expect(result.current.loopDetectionConfirmationRequest).not.toBeNull();
      });

      // Simulate user selecting "disable" for second request
      await act(async () => {
        result.current.loopDetectionConfirmationRequest?.onComplete({
          userSelection: 'disable',
        });
      });

      expect(result.current.loopDetectionConfirmationRequest).toBeNull();

      // Verify second message was added
      expect(mockAddItem).toHaveBeenCalledWith({
        type: 'info',
        text: 'Loop detection has been disabled for this session. Retrying request...',
      });

      // Verify that the request was retried
      await waitFor(() => {
        expect(mockSendMessageStream).toHaveBeenCalledTimes(3); // 1st query, 2nd query, retry of 2nd query
        expect(mockSendMessageStream).toHaveBeenNthCalledWith(
          3,
          'second query',
          expect.any(AbortSignal),
          expect.any(String),
          undefined,
          'second query',
        );
      });
    });

    it('should process LoopDetected event after moving pending history to history', async () => {
      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield {
            type: ServerGeminiEventType.Content,
            value: 'Some response content',
          };
          yield {
            type: ServerGeminiEventType.LoopDetected,
          };
        })(),
      );

      const { result } = await renderTestHook();

      await act(async () => {
        await result.current.submitQuery('test query');
      });

      // Verify that the content was added to history before the loop detection dialog
      await waitFor(() => {
        expect(mockAddItem).toHaveBeenCalledWith(
          expect.objectContaining({
            type: 'gemini',
            text: 'Some response content',
          }),
          expect.any(Number),
        );
      });

      // Then verify loop detection confirmation request was set
      await waitFor(() => {
        expect(result.current.loopDetectionConfirmationRequest).not.toBeNull();
      });
    });

    describe('Race Condition Prevention', () => {
      it('should reject concurrent submitQuery when already responding', async () => {
        // Stream that stays open (simulates "still responding")
        mockSendMessageStream.mockReturnValue(
          (async function* () {
            yield {
              type: ServerGeminiEventType.Content,
              value: 'First response',
            };
            // Keep the stream open
            await new Promise(() => {});
          })(),
        );

        const { result } = await renderTestHook();

        // Start first query without awaiting (fire-and-forget, like existing tests)
        await act(async () => {
          // eslint-disable-next-line @typescript-eslint/no-floating-promises
          result.current.submitQuery('first query');
        });

        // Wait for the stream to start responding
        await waitFor(() => {
          expect(result.current.streamingState).toBe(StreamingState.Responding);
        });

        // Try a second query while first is still responding
        await act(async () => {
          // eslint-disable-next-line @typescript-eslint/no-floating-promises
          result.current.submitQuery('second query');
        });

        // Should have only called sendMessageStream once (second was rejected)
        expect(mockSendMessageStream).toHaveBeenCalledTimes(1);
      });

      it('should allow continuation queries via loop detection retry', async () => {
        const mockLoopDetectionService = {
          disableForSession: vi.fn(),
        };
        const mockClient = {
          ...new MockedGeminiClientClass(mockConfig),
          getLoopDetectionService: () => mockLoopDetectionService,
        };
        mockConfig.getGeminiClient = vi.fn().mockReturnValue(mockClient);

        // First call triggers loop detection
        mockSendMessageStream.mockReturnValueOnce(
          (async function* () {
            yield {
              type: ServerGeminiEventType.LoopDetected,
            };
          })(),
        );

        // Retry call succeeds
        mockSendMessageStream.mockReturnValueOnce(
          (async function* () {
            yield {
              type: ServerGeminiEventType.Content,
              value: 'Retry success',
            };
            yield {
              type: ServerGeminiEventType.Finished,
              value: { reason: 'STOP' },
            };
          })(),
        );

        const { result } = await renderTestHook();

        await act(async () => {
          await result.current.submitQuery('test query');
        });

        await waitFor(() => {
          expect(
            result.current.loopDetectionConfirmationRequest,
          ).not.toBeNull();
        });

        // User selects "disable" which triggers a continuation query
        await act(async () => {
          result.current.loopDetectionConfirmationRequest?.onComplete({
            userSelection: 'disable',
          });
        });

        // Verify disableForSession was called
        expect(
          mockLoopDetectionService.disableForSession,
        ).toHaveBeenCalledTimes(1);

        // Continuation query should have gone through (2 total calls)
        await waitFor(() => {
          expect(mockSendMessageStream).toHaveBeenCalledTimes(2);
          expect(mockSendMessageStream).toHaveBeenNthCalledWith(
            2,
            'test query',
            expect.any(AbortSignal),
            expect.any(String),
            undefined,
            'test query',
          );
        });
      });
    });
  });

  describe('Agent Execution Events', () => {
    it('should handle AgentExecutionStopped event with systemMessage', async () => {
      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield {
            type: ServerGeminiEventType.AgentExecutionStopped,
            value: {
              reason: 'hook-reason',
              systemMessage: 'Custom stop message',
            },
          };
        })(),
      );

      const { result } = await renderTestHook();

      await act(async () => {
        await result.current.submitQuery('test stop');
      });

      await waitFor(() => {
        expect(mockAddItem).toHaveBeenCalledWith(
          {
            type: MessageType.INFO,
            text: 'Agent execution stopped: Custom stop message',
          },
          expect.any(Number),
        );
        expect(result.current.streamingState).toBe(StreamingState.Idle);
      });
    });

    it('should handle AgentExecutionStopped event by falling back to reason when systemMessage is missing', async () => {
      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield {
            type: ServerGeminiEventType.AgentExecutionStopped,
            value: { reason: 'Stopped by hook' },
          };
        })(),
      );

      const { result } = await renderTestHook();

      await act(async () => {
        await result.current.submitQuery('test stop');
      });

      await waitFor(() => {
        expect(mockAddItem).toHaveBeenCalledWith(
          {
            type: MessageType.INFO,
            text: 'Agent execution stopped: Stopped by hook',
          },
          expect.any(Number),
        );
        expect(result.current.streamingState).toBe(StreamingState.Idle);
      });
    });

    it('should handle AgentExecutionBlocked event with systemMessage', async () => {
      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield {
            type: ServerGeminiEventType.AgentExecutionBlocked,
            value: {
              reason: 'hook-reason',
              systemMessage: 'Custom block message',
            },
          };
        })(),
      );

      const { result } = await renderTestHook();

      await act(async () => {
        await result.current.submitQuery('test block');
      });

      await waitFor(() => {
        expect(mockAddItem).toHaveBeenCalledWith(
          {
            type: MessageType.WARNING,
            text: 'Agent execution blocked: Custom block message',
          },
          expect.any(Number),
        );
      });
    });

    it('should handle AgentExecutionBlocked event by falling back to reason when systemMessage is missing', async () => {
      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield {
            type: ServerGeminiEventType.AgentExecutionBlocked,
            value: { reason: 'Blocked by hook' },
          };
        })(),
      );

      const { result } = await renderTestHook();

      await act(async () => {
        await result.current.submitQuery('test block');
      });

      await waitFor(() => {
        expect(mockAddItem).toHaveBeenCalledWith(
          {
            type: MessageType.WARNING,
            text: 'Agent execution blocked: Blocked by hook',
          },
          expect.any(Number),
        );
      });
    });
  });

  describe('Stream Splitting', () => {
    it('should not add empty history item when splitting message results in empty or whitespace-only beforeText', async () => {
      // Mock split point to always be 0, causing beforeText to be empty
      vi.mocked(findLastSafeSplitPoint).mockReturnValue(0);

      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield { type: ServerGeminiEventType.Content, value: 'test content' };
        })(),
      );

      const { result } = await renderTestHook();

      await act(async () => {
        await result.current.submitQuery('user query');
      });

      await waitFor(() => {
        // We expect the stream to be processed.
        // Since beforeText is empty (0 split), addItem should NOT be called for it.
        // addItem IS called for the user query "user query".
      });

      // Check addItem calls.
      // It should be called for user query and for the content.
      expect(mockAddItem).toHaveBeenCalledTimes(2);
      expect(mockAddItem).toHaveBeenCalledWith(
        expect.objectContaining({ type: 'user', text: 'user query' }),
        expect.any(Number),
      );
      expect(mockAddItem).toHaveBeenLastCalledWith(
        expect.objectContaining({
          type: 'gemini_content',
          text: 'test content',
        }),
        expect.any(Number),
      );

      // Verify that pendingHistoryItem is empty after (afterText).
      expect(result.current.pendingHistoryItems.length).toEqual(0);

      // Reset mock
      vi.mocked(findLastSafeSplitPoint).mockReset();
      vi.mocked(findLastSafeSplitPoint).mockImplementation(
        (s: string) => s.length,
      );
    });

    it('should add whitespace-only history item when splitting message', async () => {
      // Input: "   content"
      // Split at 3 -> before: "   ", after: "content"
      vi.mocked(findLastSafeSplitPoint).mockReturnValue(3);

      mockSendMessageStream.mockReturnValue(
        (async function* () {
          yield { type: ServerGeminiEventType.Content, value: '   content' };
        })(),
      );

      const { result } = await renderTestHook();

      await act(async () => {
        await result.current.submitQuery('user query');
      });

      await waitFor(() => {});

      expect(mockAddItem).toHaveBeenCalledTimes(3);
      expect(mockAddItem).toHaveBeenCalledWith(
        expect.objectContaining({ type: 'user', text: 'user query' }),
        expect.any(Number),
      );
      expect(mockAddItem).toHaveBeenLastCalledWith(
        expect.objectContaining({
          type: 'gemini_content',
          text: 'content',
        }),
        expect.any(Number),
      );

      expect(result.current.pendingHistoryItems.length).toEqual(0);
    });
  });

  it('should trace UserPrompt telemetry on submitQuery', async () => {
    const { result } = await renderTestHook();

    mockSendMessageStream.mockReturnValue(
      (async function* () {
        yield { type: ServerGeminiEventType.Content, value: 'Response' };
      })(),
    );

    await act(async () => {
      await result.current.submitQuery('telemetry test query');
    });

    const userPromptCall = mockRunInDevTraceSpan.mock.calls.find(
      (call) =>
        call[0].operation === GeminiCliOperation.UserPrompt ||
        call[0].operation === 'UserPrompt',
    );
    expect(userPromptCall).toBeDefined();

    const spanMetadata = {} as SpanMetadata;
    await act(async () => {
      await userPromptCall![1]({ metadata: spanMetadata });
    });
    expect(spanMetadata.input).toBe('telemetry test query');
  });
});