mindfork 0.11.0

A terminal AI chat written in Rust: local models via llama.cpp or OpenAI, Anthropic, Gemini and Grok in the cloud, with persistent memory, notes, RAG and tools.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
//! Assistant reply generation: send/regenerate/delete-exchange commands,
//! starting a turn, and the background task for the client-side agentic loop (spec §6.3).

use std::collections::HashSet;
use std::sync::Arc;

use futures_util::StreamExt;
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
use tokio_util::sync::CancellationToken;
use uuid::Uuid;

use crate::app::events::{AppEvent, ToolDecision};
use crate::entities::chat::DeletedCause;
use crate::entities::message::{
    Message, MessageFinish, MessageMetadata, MessageRole, ToolCallRecord,
};
use crate::entities::profile::ToolId;
use crate::entities::sampling::SamplingConfig;
use crate::entities::subagent::{RunKind, RunOutcome, SubagentRun};
use crate::features::tools::subagent::{
    CALL_SUBAGENT_ID, START_SUBAGENT_ID, SubagentArgs, withheld_from_subagent,
};
use crate::features::tools::{
    ChatEffect, ToolContext, ToolParams, ToolRegistry, TurnInfo, control, effective_tool_ids,
};
use crate::shared::api::{
    ApiMessage, ApiToolCall, ChatChunk, ChatRequest, EngineBackend, FinishReason,
    ThinkingAccumulator, ThinkingBlock, ThinkingRef, ToolCallAccumulator, VisionSupport,
};
use crate::shared::config::ServerMode;
use crate::shared::session_budget::SessionBudget;
use crate::shared::tokens::estimate_prompt;

use super::Orchestrator;
use super::request::{
    PromptContext, RequestEnv, build_request, build_request_in, last_user_message_at,
    withhold_images,
};

/// How long the turn waits to learn whether the engine takes images
/// ([`TurnLoop::vision`]). Long enough for a local `/props` many times over, short enough
/// that a server which accepts a connection and then says nothing cannot hold a turn.
const VISION_PROBE: std::time::Duration = std::time::Duration::from_secs(5);

/// Result of a completed generation task (internal channel).
/// What the generation task sends the orchestrator on its one channel: the
/// turn's progress while it runs, then its result. One channel, so every
/// progress message of a turn is delivered **before** its result — which is
/// what lets the orchestrator's in-flight table (docs/subagent-live.md §3.2)
/// be dropped at landing without a race.
pub(super) enum GenMessage {
    Progress { id: Uuid, progress: TurnProgress },
    Done(GenResult),
}

/// One step of a running turn, as the orchestrator's in-flight table needs
/// it (docs/subagent-live.md §3.1): the parent's rounds as they file, and a
/// sub-agent run's life — start, rounds, end — so the transcript is a row of
/// the list and openable while it runs (spec §9.3.2).
pub(super) enum TurnProgress {
    /// The parent's loop filed a round: its assistant message, then the tool
    /// messages — exactly what `file_round` pushed.
    RoundFiled(Vec<Message>),
    /// A sub-agent is about to run: the run as it will land — id, persona,
    /// title, `name`, `created_at`, `User(message)` — with no rounds and no
    /// outcome yet.
    ChildStarted(Box<SubagentRun>),
    /// The sub-agent's loop filed a round. Every `Child*` step names its
    /// run: several runs can be in flight at once (spec §9.3.2, stage 2 of
    /// docs/research/parallel-subagents.md), and the mirror keys on the id.
    ChildRoundFiled { run: Uuid, messages: Vec<Message> },
    /// One step of the turn's own stream (docs/history/subagent-live.md §8,
    /// last bullet): the orchestrator mirrors the round in progress, so the
    /// chat's feed can be rebuilt whole when the user comes back to it
    /// mid-turn. The screen gets the same step directly, as it always did.
    OwnStep(StreamStep),
    /// One step of the sub-agent's stream (§8): the same events its loop
    /// would send a feed, carried as progress so they stay in order with
    /// `ChildRoundFiled` on the one channel. The orchestrator keeps the
    /// round's partial and forwards the step to the screen while the
    /// transcript is the open conversation.
    ChildStep { run: Uuid, step: StreamStep },
    /// The sub-agent run's own token count so far (completion, reasoning).
    ChildTokens {
        run: Uuid,
        completion: u64,
        reasoning: Option<u32>,
    },
    /// Where a run stands (spec §11.10, docs/research/tasks-screen.md §4.3):
    /// the same report the status-bar chip gets straight from the task
    /// ([`AppEvent::SubagentProgress`]), carried to the orchestrator too and
    /// stored on the run's mirror — so a background run's position outlives
    /// the screen that happens to be open, and the tasks screen reads it
    /// off the seat.
    ChildProgress {
        run: Uuid,
        progress: crate::app::events::SubagentProgress,
    },
    /// A dialogue's next line begins (spec §9.13): which side of the
    /// transcript the coming stream belongs to, so the open transcript draws
    /// it in the right bubble. Also resets the round-in-progress partial.
    ChildLineStarted { run: Uuid, role: MessageRole },
    /// A dialogue **edited** its transcript — the director discarded or
    /// rewrote a line — so appending cannot express it: the full replacement.
    ChildTranscript { run: Uuid, messages: Vec<Message> },
    /// The run returned; the landed run carries the same fields.
    ChildEnded {
        run: Uuid,
        outcome: RunOutcome,
        finished_at: chrono::DateTime<chrono::Utc>,
        tokens: u64,
    },
    /// A `start_subagent` call (spec §9.3.2,
    /// docs/research/background-subagents.md §4.2): everything the run
    /// needs, built by the parent as for a group child, handed to the
    /// orchestrator to spawn **outside** the turn — its own task, its own
    /// token, the app's budget. The parent's record lands with the turn
    /// carrying a placeholder; [`super::Orchestrator::spawn_background_run`]
    /// fills it in when the run ends.
    BackgroundStart(Box<BackgroundStart>),
}

/// One step of a loop's stream, as the orchestrator mirrors it (see
/// [`TurnProgress::OwnStep`] / [`TurnProgress::ChildStep`]).
pub(super) enum StreamStep {
    Chunk(String),
    Thoughts(String),
    ToolStarted {
        call_id: String,
        name: String,
        arguments: String,
    },
    ToolCall {
        call_id: String,
        name: String,
        arguments: String,
        result: String,
        images: usize,
    },
    Continue,
    Rewrite,
}

pub(super) struct GenResult {
    pub(super) id: Uuid,
    pub(super) chat_id: Uuid,
    /// New domain messages (assistant with tool_calls, tool results, the final one) —
    /// in order of appearance; the orchestrator appends them to `Chat`.
    pub(super) messages: Vec<Message>,
    /// Tool effects (applied by the orchestrator — the owner of `Chat`).
    pub(super) effects: Vec<ChatEffect>,
    /// Messages discarded by the "rewrite" tool (`rewrite_current_message`):
    /// the previous (incorrect) version + its tool message. Kept in `Chat.deleted`
    /// for manual recovery; not part of inference/the feed. See spec §9.3.
    pub(super) deleted: Vec<Message>,
    /// What the **last** round of this turn actually cost, as the server counted
    /// it. The auto-compaction trigger reads it (spec §6.7); `None` when the
    /// provider reported no `usage`, and then the trigger stays quiet rather than
    /// guessing (sub-decision S2).
    pub(super) usage: Option<TurnUsage>,
    /// The message this turn **continues** (`/continue`, spec §6.4): the turn's
    /// first assistant message is folded into it in place rather than pushed.
    pub(super) continuation: Option<Uuid>,
    /// How many of the chat's images the request carried as markers, because the engine
    /// takes none — the orchestrator's once-per-chat note reads it.
    pub(super) images_withheld: usize,
}

/// The exact size of one round, as reported by the server's `usage`.
///
/// The last round of a turn is the largest — within a turn the history only
/// grows — and the *next* turn's prompt is close to `prompt + completion` plus
/// whatever the user types, which is what makes this a usable trigger input.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct TurnUsage {
    pub(super) prompt_tokens: u32,
    pub(super) completion_tokens: u64,
    /// The turn's largest prefill sample as the engine measured it (llama.cpp
    /// only; `None` elsewhere) — what the slow-prefill note is computed
    /// from (docs/research/slow-prefill-detection.md §3).
    pub(super) prefill: Option<crate::shared::api::contract::Prefill>,
}

impl TurnUsage {
    /// A lower bound on the next turn's prompt: this turn's prompt plus what was
    /// generated on top of it. The user's next message and any injection deltas
    /// come on top — which the threshold's headroom is there to absorb.
    pub(super) fn next_prompt_estimate(self) -> u64 {
        self.prompt_tokens as u64 + self.completion_tokens
    }
}

/// What `/continue` resumes (spec §6.4): the trailing partial assistant
/// message. `text` rides along for the echo filter — llama.cpp returns
/// prefill + continuation, and the stream must not re-deliver what is already
/// on screen (docs/research/continue-generation.md §4d, §7.1).
#[derive(Debug, Clone)]
pub(super) struct ContinuationSeed {
    pub(super) message_id: Uuid,
    pub(super) text: std::sync::Arc<str>,
}

/// Strips a server echo of the continuation seed from the front of a round's
/// text stream. Bytes are withheld while they keep matching the seed; on a
/// full match the echo is dropped and everything after it flows; on the first
/// mismatch the withheld bytes plus the current delta flow as real content —
/// a non-echoing server (a future llama.cpp, vLLM) loses nothing. A stream
/// that dies while still matching was echoing (the only servers this filter
/// is enabled for echo, and real content diverges at the first new byte), so
/// the withheld bytes are dropped rather than appended twice.
pub(super) struct EchoFilter {
    seed: std::sync::Arc<str>,
    matched: usize,
    decided: bool,
}

impl EchoFilter {
    pub(super) fn new(seed: std::sync::Arc<str>) -> Self {
        Self {
            seed,
            matched: 0,
            decided: false,
        }
    }

    /// The visible part of `delta` — empty while the echo is being consumed,
    /// possibly prefixed with previously withheld bytes on a mismatch.
    pub(super) fn push(&mut self, delta: &str) -> String {
        if self.decided {
            return delta.to_string();
        }
        let remaining = &self.seed.as_bytes()[self.matched..];
        let n = delta.len().min(remaining.len());
        if delta.as_bytes()[..n] == remaining[..n] {
            self.matched += n;
            if self.matched == self.seed.len() {
                self.decided = true;
                // `n` ends exactly where the seed does — a char boundary of
                // the seed, and the bytes match, so of `delta` too.
                return delta[n..].to_string();
            }
            String::new()
        } else {
            self.decided = true;
            // The withheld bytes are byte-identical to the seed's prefix, and
            // `matched` only ever advanced by whole deltas — a char boundary.
            format!("{}{delta}", &self.seed[..self.matched])
        }
    }
}

impl Orchestrator {
    pub(super) fn handle_send(&mut self, text: String) {
        if !self.gen_state.is_idle() {
            return;
        }
        let text = text.trim().to_string();
        // An empty message is normally nothing to send — unless images are staged, in
        // which case "look at this" with no words is a complete request (spec §9.10).
        let has_staged_images = self
            .active_id
            .and_then(|id| self.staged_images.get(&id))
            .is_some_and(|staged| !staged.is_empty());
        if text.is_empty() && !has_staged_images {
            return;
        }
        let Some(active_id) = self.active_id else {
            let _ = self.evt_tx.send(AppEvent::Error(
                self.ui_locale().t("ui.err.no_active_chat").into(),
            ));
            return;
        };
        // A sub-agent transcript is read-only (spec §11.2): the screen refuses
        // first; this is the route-independent answer, with the text returned.
        if self.parent_of(active_id).is_some() {
            let _ = self.evt_tx.send(AppEvent::Error(
                self.ui_locale().t("ui.err.read_only_chat").into(),
            ));
            let _ = self.evt_tx.send(AppEvent::RestoreInput(text));
            return;
        }
        let Some(backend) = self.ready_backend() else {
            // Server not ready: the UI already cleared the input box — return the
            // text so the user doesn't lose the message (the error is shown separately).
            let _ = self.evt_tx.send(AppEvent::RestoreInput(text));
            return;
        };

        // Staging is consumed here and nowhere else: the images become part of the
        // message, and from this point `/image remove` can no longer reach them. Taken
        // only after every early return above, so a failed send leaves them staged.
        let images = self.take_staged_images(active_id);

        // Add the user's message to the history and echo it in the feed. The UI
        // cleared the input box on send — also clear the chat's saved draft.
        {
            let Some(chat) = self.chat_mut(active_id) else {
                return;
            };
            chat.push_message(Message::user(&text).with_images(images));
            chat.draft.clear();
        }
        self.mark_dirty(active_id);
        let _ = self.evt_tx.send(AppEvent::UserMessage(text));

        self.start_generation(active_id, backend, None);
        // Automatic titling at the `AfterUserMessage` point (spec §11.2), fired
        // for the conversation's first user message — **after** the reply's own
        // request, so on a single-slot server the title never queues ahead of
        // the answer (docs/history/auto-chat-title.md D3).
        if self
            .chats
            .iter()
            .find(|c| c.id == active_id)
            .is_some_and(|c| crate::features::rename_chat::is_first_user_message(&c.messages))
        {
            self.maybe_auto_title(
                active_id,
                crate::shared::config::AutoTitleMode::AfterUserMessage,
            );
        }
    }

    /// Regenerates the last assistant reply (spec §11.7): deletes everything after
    /// the last user message (the old reply + tool messages) and starts generation
    /// again from the same request. The feed is rebuilt via a re-emit of
    /// `ChatActivated`. Ignored during generation.
    pub(super) fn handle_regenerate(&mut self) {
        if !self.gen_state.is_idle() {
            return;
        }
        // Unconditional (not a setting): the reply being spoken is about to vanish.
        self.stop_tts();
        let Some(active_id) = self.active_id else {
            return;
        };
        // Check server readiness BEFORE truncating the history: otherwise, on a
        // not-yet-ready server (model loading), the old reply would be wiped out
        // and the new one wouldn't arrive.
        let Some(backend) = self.ready_backend() else {
            return;
        };
        {
            let Some(chat) = self.chat_mut(active_id) else {
                return;
            };
            // A task notification is a user-side row (spec §9.3.2): the
            // reply it woke is redone, the notification kept.
            let Some(idx) = chat
                .messages
                .iter()
                .rposition(|m| m.role == MessageRole::User || m.is_notification())
            else {
                return; // no user message — nothing to regenerate
            };
            // Save what's deleted (the assistant's reply + the round's tool messages)
            // and the input draft, for manual recovery (spec §11.7).
            let draft = chat.draft.clone();
            let removed = chat.messages.split_off(idx + 1);
            chat.record_deleted(removed, draft, DeletedCause::Regenerate);
            chat.modified_at = chrono::Utc::now();
        }
        self.mark_dirty(active_id);
        self.activate(active_id); // rebuild the feed without the old reply
        self.emit_chat_list();
        // A background run whose exchange just left the live messages ends
        // with it (research fork F8).
        self.cancel_orphaned_background_runs(active_id);
        self.start_generation(active_id, backend, None);
    }

    /// Resumes the last interrupted assistant reply in place (`/continue`,
    /// spec §6.4): the history goes out with the partial as its trailing
    /// assistant message and the engine continues it (assistant prefill),
    /// everything that arrives appending into the same `Message`. A turn
    /// interrupted **between** tool rounds — the chat ends with tool results —
    /// resumes the agentic loop instead, with nothing to prefill. Every
    /// refusal answers with the route that works (docs/lessons.md §4); the
    /// cheap state gates (`generating`, no chat, a read-only transcript) were
    /// already answered by the typed route on the screen.
    /// Whether `/continue` resumes a partial reply on the engine as configured —
    /// the one answer the command's gate, a turn's `Finished.continuable` and its
    /// interruption notes all read (spec §6.4). The catalogue's answer is what
    /// tells an `external` gateway from a llama.cpp
    /// (docs/history/gateway-images-and-continue.md, fork H2).
    pub(super) fn continuation_supported(&self) -> bool {
        self.config.engine.mode.supports_continuation(
            self.effective_model_name().as_deref(),
            self.endpoint_catalogued(),
        )
    }

    pub(super) fn handle_continue(&mut self) {
        if !self.gen_state.is_idle() {
            return;
        }
        let Some(active_id) = self.active_id else {
            return;
        };
        if self.parent_of(active_id).is_some() {
            let _ = self.evt_tx.send(AppEvent::Error(
                self.ui_locale().t("ui.err.read_only_chat").into(),
            ));
            return;
        }
        // The capability gate first — its answer does not depend on the server
        // being up, and a cloud user should hear "cannot" rather than wait out
        // a readiness check to hear it (single source of truth: research §2).
        if !self.continuation_supported() {
            // A gateway gets its own note: the generic one says external engines
            // continue, which is exactly what is not true here.
            let key =
                if self.config.engine.mode == ServerMode::External && self.endpoint_catalogued() {
                    "ui.cmd.continue_unsupported_gateway"
                } else {
                    "ui.cmd.continue_unsupported"
                };
            let _ = self
                .evt_tx
                .send(AppEvent::Error(self.ui_locale().t(key).into()));
            return;
        }
        let seed = {
            let Some(chat) = self.chats.iter().find(|c| c.id == active_id) else {
                return;
            };
            match chat.messages.last() {
                // Interrupted between rounds: the loop resumes on the recorded
                // tool results — the ordinary agentic request shape.
                Some(m) if m.role == MessageRole::Tool => None,
                Some(m) if m.role == MessageRole::Assistant => {
                    if m.text.is_empty() {
                        // Cut inside the reasoning, before any visible text —
                        // no provider can resume a thought over a chat API (F4).
                        let _ = self.evt_tx.send(AppEvent::Error(
                            self.ui_locale().t("ui.cmd.continue_thoughts").into(),
                        ));
                        return;
                    }
                    let finish = m.metadata.as_ref().and_then(|md| md.finish);
                    if finish == Some(crate::entities::message::MessageFinish::Stop) {
                        let _ = self.evt_tx.send(AppEvent::Error(
                            self.ui_locale().t("ui.cmd.continue_complete").into(),
                        ));
                        return;
                    }
                    // `Cancelled`/`Error`/`Length`, and `None` for messages
                    // stored before the bookkeeping existed (fork F1).
                    Some(ContinuationSeed {
                        message_id: m.id,
                        text: std::sync::Arc::from(m.text.as_str()),
                    })
                }
                _ => {
                    let _ = self.evt_tx.send(AppEvent::Error(
                        self.ui_locale().t("ui.cmd.continue_nothing").into(),
                    ));
                    return;
                }
            }
        };
        let Some(backend) = self.ready_backend() else {
            return;
        };
        // A tool-result tail resumes as an ordinary next round (`seed` is
        // `None`); a text tail rides the prefill.
        self.start_generation(active_id, backend, seed);
    }

    /// Deletes the last exchange: the assistant's reply together with the user
    /// message that triggered it (spec §11.7). The user's text is returned to the
    /// input box (`RestoreInput`) so it can be edited and resent.
    /// Ignored during generation.
    pub(super) fn handle_delete_last(&mut self) {
        if !self.gen_state.is_idle() {
            return;
        }
        // Unconditional (not a setting): the exchange being spoken is about to vanish.
        self.stop_tts();
        let Some(active_id) = self.active_id else {
            return;
        };
        let user_text;
        {
            let Some(chat) = self.chat_mut(active_id) else {
                return;
            };
            // A task notification is a user-side row (spec §9.3.2): the
            // exchange it woke goes with it, and nothing returns to the box.
            let Some(idx) = chat
                .messages
                .iter()
                .rposition(|m| m.role == MessageRole::User || m.is_notification())
            else {
                return; // no user message — nothing to delete
            };
            user_text = if chat.messages[idx].is_notification() {
                String::new()
            } else {
                chat.messages[idx].text.clone()
            };
            // Save what's deleted (the user message + the assistant's reply) and the
            // input draft BEFORE returning the user's text to the field — for manual
            // recovery (spec §11.7).
            let draft = chat.draft.clone();
            let removed = chat.messages.split_off(idx);
            chat.record_deleted(removed, draft, DeletedCause::DeleteExchange);
            chat.modified_at = chrono::Utc::now();
        }
        self.mark_dirty(active_id);
        self.activate(active_id); // rebuild the feed without the deleted exchange
        self.emit_chat_list();
        self.cancel_orphaned_background_runs(active_id);
        let _ = self.evt_tx.send(AppEvent::RestoreInput(user_text));
    }

    /// Returns the engine if the chat server is ready; otherwise emits a clear
    /// error into the chat feed (`AppEvent::Error`) and returns `None`. Gates both
    /// send and regenerate — so the request doesn't go to a still-loading server
    /// (otherwise 503 → "engine returned an error status"). For chat-list
    /// operations (auto-title) the error must go into the overlay — there
    /// [`EngineManager::backend_if_ready`](super::engines::EngineManager) is used directly.
    pub(super) fn ready_backend(&self) -> Option<Arc<dyn EngineBackend>> {
        match self.engines.backend_if_ready(self.ui_locale()) {
            Ok(backend) => Some(backend),
            Err(msg) => {
                let _ = self.evt_tx.send(AppEvent::Error(msg));
                None
            }
        }
    }

    /// Starts generation from the chat's current state (the history is already
    /// prepared: either the user's message was appended, or the old reply was
    /// truncated). The shared part for sending a new message, regenerating,
    /// and `/continue` — which passes the `continuation` seed so the turn
    /// prefills the trailing partial and appends into it (spec §6.4).
    pub(super) fn start_generation(
        &mut self,
        active_id: Uuid,
        backend: Arc<dyn EngineBackend>,
        continuation: Option<ContinuationSeed>,
    ) {
        self.start_generation_woken(active_id, backend, continuation, false);
    }

    /// The turn the app starts on a background run's task notification
    /// (spec §9.3.2): nobody typed anything, so an empty first generation is
    /// worth one muted re-ask rather than an empty bubble (fork F11).
    pub(super) fn start_woken_generation(
        &mut self,
        active_id: Uuid,
        backend: Arc<dyn EngineBackend>,
    ) {
        self.start_generation_woken(active_id, backend, None, true);
    }

    /// [`Self::start_generation`] with the one flag its two entry points
    /// differ by.
    fn start_generation_woken(
        &mut self,
        active_id: Uuid,
        backend: Arc<dyn EngineBackend>,
        continuation: Option<ContinuationSeed>,
        woken: bool,
    ) {
        // Speech stops per the setting (off by default: listening to the reply
        // while the next one is being written is legitimate). See spec §11.9.
        if self.config.tts.stop_on_generation_start {
            self.stop_tts();
        }
        // A snapshot at the start of the turn: sampling, available tools, context.
        let sampling = self.effective_sampling(active_id);
        let Some(chat_ref) = self.chats.iter().find(|c| c.id == active_id) else {
            return;
        };
        let profile_id = chat_ref.profile_id;
        let profile_lang = self
            .profiles
            .iter()
            .find(|p| p.id == profile_id)
            .map(|p| p.language)
            .unwrap_or_default();
        let enabled = self
            .profiles
            .iter()
            .find(|p| p.id == profile_id)
            .map(|p| p.enabled_tools.clone())
            .unwrap_or_default();
        // Where this chat's verbatim history starts, if compression folded
        // anything away. It decides three things at once, which is the point:
        // what the request carries, whether the summary block is in the prompt,
        // and whether the read-back tools are offered (spec §6.7, S12).
        let history_upto = chat_ref
            .compaction_view(self.config.compaction.enabled)
            .map(|(_, upto)| upto);
        // The chat's attached code project (spec §9.12). Like the folded range
        // above, it decides two things at once — whether the `code_*` tools are
        // offered and whether the prompt carries the workspace block — so the
        // block can never name a tool the turn does not have.
        let workspace = chat_ref.workspace.clone();
        // Where the editing tools record what a file looked like before they
        // changed it. Derived here, with the workspace, so the two cannot
        // disagree about which chat is being edited.
        let workspace_journal = workspace.as_ref().map(|_| {
            self.storage
                .json()
                .workspace_dir()
                .join(active_id.to_string())
        });
        // Where `python_exec` keeps what the code saved (docs/history/sandbox-file-exchange.md
        // §11 S5): every chat has one, created with its first file.
        let files_dir = self.stored_files_dir(active_id);
        // The effective set = profile ∩ global switches (spec §9.4).
        let allowed = effective_tool_ids(
            &enabled,
            &crate::features::tools::ToolGates {
                web: self.config.tools.web_enabled,
                python: self.config.tools.python_enabled,
                fs: self.config.tools.fs_enabled,
                mcp: self.config.mcp.enabled,
                background: self.config.tools.subagent_background,
                history: history_upto.is_some(),
                workspace: workspace.is_some(),
                // Which slots carry a line, so a `code_test` with nothing to
                // run is never advertised (spec §9.12).
                workspace_commands: workspace
                    .as_ref()
                    .map(crate::features::tools::code::WorkspaceCommands::of)
                    .unwrap_or_default(),
                sampling_provider: self.config.engine.mode.cloud_provider(),
                sampling_endpoint: self.endpoint_sampling_fields(),
            },
        );
        // Does this turn actually offer the read-back tools? A folded range
        // normally implies them, but a profile can have them switched off — and
        // then the summary block must not name them (spec §6.7).
        let history_tools = allowed.iter().any(|t| {
            t == crate::features::tools::history::HISTORY_READ_ID
                || t == crate::features::tools::history::HISTORY_SEARCH_ID
        });
        // Can this turn hand the chat's files to the code? Since stage 5's parity, that is
        // the tool being offered at all — both modes run in a job directory
        // (docs/history/sandbox-file-exchange.md §12 T4/T5, §14 V1). One value, read twice: the
        // images snapshot below is built only for such a turn, and so is the block that
        // tells the model what it may name — in that mode's own folder form (§14 V2).
        let stages_files = allowed
            .iter()
            .any(|t| t == crate::features::tools::PYTHON_EXEC_ID);
        let python_dirs = self.config.tools.python_mode.dirs();
        let profile_loc = crate::shared::i18n::locale(profile_lang);
        let schemas = self.registry.schemas_for(&allowed, profile_loc);
        // Copied out before the `chat_mut` borrow below (config can't be read
        // while `Chat` is mutably borrowed). `AttachmentSettings` is `Copy`.
        let attach_cfg = self.config.attachments;
        let compact_cfg = self.config.compaction.clone();
        // Which attached files have a semantic index — the pinned block only
        // offers `attachment_search` for those (spec §9.7). One indexed lookup,
        // and only when the chat has attachments at all.
        let indexed: Vec<Uuid> = if chat_ref.attachments.is_empty() {
            Vec::new()
        } else {
            self.storage
                .db()
                .attachment_indexed_ids(active_id)
                .unwrap_or_default()
        };
        // The other chats of this profile, for `chat_search`/`chat_read`
        // (spec §9.11) — built only when the turn actually offers the pair,
        // like the history render below. The snapshot is those tools' whole
        // world, so the scope (this profile, not this chat, nothing hidden) is
        // decided in one place: `snapshot_other_chats`.
        let chat_tools_on = allowed.iter().any(|t| {
            t == crate::features::tools::chats::CHAT_SEARCH_ID
                || t == crate::features::tools::chats::CHAT_READ_ID
        });
        let other_chats: Vec<crate::features::tools::chats::ChatRef> = if chat_tools_on {
            crate::features::tools::chats::snapshot_other_chats(&self.chats, profile_id, active_id)
        } else {
            Vec::new()
        };

        // The profile's "self-model" at the start of the turn. Injection into the
        // system prompt happens only if the profile enabled get_self_model (opt-in);
        // the injection itself (observations by relevance to the last message +
        // recency) happens in the generation task (needs async embedding). See
        // docs/history/narrative-as-notes.md (Tier 2).
        let self_model_params =
            crate::entities::self_model::SelfModelParams::from_settings(&self.config.self_model);
        let inject_enabled = enabled
            .iter()
            .any(|t| t == crate::features::tools::self_model::GET_SELF_MODEL_ID);
        // A one-time idempotent migration of the old "self-model" narrative into
        // self-notes (@self). Best-effort. See docs/history/narrative-as-notes.md, step 6.
        if inject_enabled {
            crate::features::tools::notes::migrate_self_narrative(&self.storage, profile_id);
        }
        let self_model = self.storage.db().self_model_get(profile_id).ok().flatten();

        // The turn's cancellation token is created before the tool context: its
        // clone goes into `ToolContext.cancel` (long-running tools — MCP/network —
        // are interrupted via Esc).
        let cancel = CancellationToken::new();

        // Resolved once and used three times: `ToolContext.model_name` (what
        // `get_llm_name` answers, spec §9.14), the `GenerationStarted` event
        // below (the live bubble's header) and `GenSpawn.model_name` (the
        // finished message's metadata). One read, so no pair of them can
        // disagree. In `external` mode with no model named in settings this is
        // what the engine said it is running (see `model_name::ModelDiscovery`)
        // — the message records the model that actually answered, not a blank.
        let model_name = self.effective_model_name();
        let engine_mode = self.config.engine.mode;

        // Build the request/context + take the last user message (for relevance-
        // based injection of observations in the task).
        // The turn's session budget (spec §11.6): every stream of the turn —
        // the loops' own and a tool's summary request (`ToolContext::sessions`)
        // — takes a permit of this one budget, and under a shared KV pool
        // (`session_pool`, admission-by-budget §4.4) a reservation of it, so
        // it is made before the context and shared with the task.
        // App-wide since background runs (docs/research/background-subagents.md
        // §4.7): the same `Arc` a run out in the background holds, so the
        // run and this turn take turns under one permit count and one pool.
        let sessions = self.session_budget();
        let mut request;
        let ctx;
        let last_user;
        // Which `tool-image-N` names the chat has already spent. Collected whatever the
        // turn stages, unlike the images themselves: a name is a few bytes, and a turn
        // that cannot stage a file can still produce an image the next turn will name
        // against.
        let image_names;
        {
            let Some(chat) = self.chat_mut(active_id) else {
                return;
            };
            // What the code may be handed this turn (docs/history/sandbox-file-exchange.md §12
            // T2/T4): the images the conversation carries, and the chat's files as the one
            // numbered list the block shows, the tool resolves and the popup reports.
            // Empty — and not even collected — for a turn that cannot stage anything.
            let images: Vec<crate::entities::message_image::MessageImage> = if stages_files {
                chat.messages
                    .iter()
                    .flat_map(|m| m.images.iter().cloned())
                    .collect()
            } else {
                Vec::new()
            };
            image_names = ToolImageNames::seeded(
                chat.messages
                    .iter()
                    .flat_map(|m| m.images.iter())
                    .map(|i| i.name.as_str()),
            );
            let inputs = if stages_files {
                crate::features::chat_inputs::items(
                    &chat.attachments,
                    &chat.files,
                    &images.iter().collect::<Vec<_>>(),
                    &files_dir,
                )
            } else {
                Vec::new()
            };
            request = build_request(
                chat,
                sampling.clone(),
                schemas,
                &PromptContext {
                    attachments: &attach_cfg,
                    compaction: &compact_cfg,
                    indexed: &indexed,
                    files: &inputs,
                    python_dirs,
                    history_tools,
                    // A project can be attached while the profile has some or
                    // all of the tools switched off; the block describes what
                    // this turn actually has, and nothing else.
                    offered_tools: &allowed,
                    loc: profile_loc,
                },
            );
            last_user = chat
                .messages
                .iter()
                .rev()
                .find(|m| m.role == MessageRole::User)
                .map(|m| m.text.clone())
                .unwrap_or_default();
            // `turn` is built by the last access to `chat`; after this the `chat`
            // borrow ends and `self` (deps/config) can be read for `new`.
            let turn = TurnInfo {
                profile_id,
                chat_id: active_id,
                system_message: chat.system_message.clone(),
                effective_sampling: sampling,
                last_user_message_at: last_user_message_at(chat),
                // The turn's attachment snapshot — what `attachment_read` sees
                // (spec §9.7). `Arc` — the context is cloned per call and the
                // texts can be large.
                attachments: std::sync::Arc::from(chat.attachments.clone()),
                // The very list the pinned block was just rendered from, handed to the
                // tools so `files` resolves against what the model was told rather than
                // against a list re-derived a round later (fork F12, §12 T2).
                inputs: std::sync::Arc::from(inputs),
                // The folded-away range, rendered for `history_read`/
                // `history_search` (spec §6.7). Rendered only when the tools are
                // actually in this turn's set: with none of them offered, the
                // work would be pure cost — and a chat with no compaction skips
                // it entirely, which is every chat until the first roll.
                history: history_upto
                    .filter(|_| history_tools)
                    .and_then(|upto| {
                        crate::features::compaction::HistoryView::render(
                            &chat.messages[..upto],
                            profile_loc,
                        )
                    })
                    .map(std::sync::Arc::new),
                other_chats: std::sync::Arc::from(other_chats),
                workspace: workspace.clone(),
                workspace_journal,
                files_dir: Some(files_dir),
                // The chat's stored files, which a call versions its names against
                // (docs/history/sandbox-file-exchange.md §11 S5).
                files: std::sync::Arc::from(chat.files.clone()),
                // The images the conversation carries, which a call can stage into
                // `/w/in` (§12 T4). Cloned only for a turn that can actually use them —
                // otherwise a chat's pixels would be copied into every context that has
                // no way to reach them.
                images: std::sync::Arc::from(images),
                stages_files,
                lang: profile_lang,
                cancel: cancel.clone(),
                model_name: model_name.clone(),
                engine_mode,
                sessions: Some(sessions.clone()),
                silent_lane: false,
            };
            ctx = ToolContext::new(
                self.tool_deps(backend.clone()),
                ToolParams::from_config(&self.config),
                turn,
            );
        }

        // The history already ends with the partial being continued —
        // `build_request` sent it as the trailing assistant message; the flag
        // is what makes the wire ask the server to continue it in place.
        request.continue_final = continuation.is_some();

        let id = Uuid::new_v4();
        let _ = self.evt_tx.send(AppEvent::GenerationStarted {
            generation_id: id,
            model: model_name.clone(),
            continuation: continuation.is_some(),
        });
        self.gen_state.begin(id, cancel.clone());
        self.inflight = Some(super::InflightTurn {
            generation: id,
            chat: active_id,
            rounds: Vec::new(),
            partial: Default::default(),
            children: Vec::new(),
            continuation: continuation.is_some(),
        });
        // The confirmation channel for this turn (fork F8). The sender is kept
        // next to the turn id so a reply arriving for an older turn — the user
        // pressed a key just as the turn was cancelled and a new one began — is
        // dropped instead of unblocking the wrong call.
        let (confirm_tx, confirm_rx) = tokio::sync::mpsc::unbounded_channel();
        self.confirm = Some((id, confirm_tx));
        spawn_generation(GenSpawn {
            backend,
            registry: self.registry.clone(),
            ctx,
            request,
            image_names,
            cancel,
            confirm_dangerous: self.config.tools.confirm_dangerous,
            image_cfg: self.config.images,
            confirm_rx,
            id,
            chat_id: active_id,
            max_rounds: self.config.max_tool_rounds,
            workspace_max_rounds: self.config.workspace.max_rounds,
            subagent: SubagentLimits::from_config(&self.config.tools),
            sessions,
            concurrent_calls: self.config.engine.active_concurrent_calls(),
            compaction_summary: self
                .chats
                .iter()
                .find(|c| c.id == active_id)
                .and_then(|c| c.compaction_view(self.config.compaction.enabled))
                .map(|(s, _)| s.to_string()),
            allowed,
            self_model,
            self_model_params,
            inject_enabled,
            maintenance_protocol: self.config.self_model.maintenance_protocol,
            last_user,
            engine_mode,
            continuation_supported: self.continuation_supported(),
            endpoint_sampling_fields: self.endpoint_sampling_fields(),
            model_name,
            ui_loc: self.ui_locale(),
            compaction_enabled: self.config.compaction.enabled,
            continuation,
            woken,
            evt_tx: self.evt_tx.clone(),
            done_tx: self.done_tx.clone(),
            background: self.background_slots.clone(),
        });
    }

    /// Did this turn deliver the conversation's **first** substantive reply?
    ///
    /// Asked **before** the turn's result is applied: afterwards the reply is
    /// part of the history and the question can no longer be asked.
    /// Regenerating the first reply re-fires by construction — the truncation
    /// removed the only reply, so the next one is again the first
    /// (spec §11.2, D2).
    fn is_first_reply(&self, res: &GenResult) -> bool {
        let substantive = res
            .messages
            .iter()
            .any(|m| m.role == MessageRole::Assistant && !m.text.trim().is_empty());
        substantive
            && self
                .chats
                .iter()
                .find(|c| c.id == res.chat_id)
                .is_some_and(|c| {
                    c.messages.iter().any(|m| m.role == MessageRole::User)
                        && !crate::features::rename_chat::has_assistant_reply(&c.messages)
                })
    }

    /// The slow-prefill note (docs/research/slow-prefill-detection.md §3.3):
    /// from the turn's largest prefill sample as the engine measured it, the
    /// seconds a stream cancelled during its prompt would hold its slot at
    /// the batch this server runs — the managed launch line's, or llama.cpp's
    /// default for an external server — and, when that is worth saying, one
    /// feed note per server session naming the figures and the one change:
    /// the *Batch (-b)* field for a managed server, the launch line for an
    /// external one. A cloud, a server without timings, a batch at the knee
    /// or a prompt too short to measure say nothing.
    pub(super) fn note_slow_prefill(
        &mut self,
        prefill: Option<crate::shared::api::contract::Prefill>,
    ) {
        use crate::shared::api::managed::{LLAMA_DEFAULT_BATCH, launched_batch, prefill_hold};
        use crate::shared::config::ServerMode;
        let Some(prefill) = prefill else { return };
        let managed = &self.config.engine.managed;
        let (batch, key) = match self.config.engine.mode {
            ServerMode::Managed => (
                launched_batch(managed.batch_size, managed.gpu_layers),
                "ui.notice.slow_prefill_managed",
            ),
            ServerMode::External => (LLAMA_DEFAULT_BATCH, "ui.notice.slow_prefill_external"),
            _ => return,
        };
        let Some(hold) = prefill_hold(batch, prefill) else {
            return;
        };
        let tps = prefill.tokens_per_second().unwrap_or_default().round() as u32;
        tracing::info!(
            tokens = prefill.tokens,
            ms = prefill.ms,
            tps,
            batch,
            hold,
            "slow prefill: a cancelled stream would hold its slot for a batch"
        );
        if !self.engines.claim_prefill_note() {
            return;
        }
        let loc = self.ui_locale();
        let _ = self.evt_tx.send(AppEvent::Notice(loc.tf(
            key,
            &[
                ("tps", &tps.to_string()),
                ("hold", &hold.to_string()),
                ("batch", &batch.to_string()),
            ],
        )));
    }

    pub(super) fn handle_done(&mut self, res: GenResult) {
        // Apply only the result of the current generation (protection against
        // stale ones): finish() transitions to Idle only on a matching id.
        if !self.gen_state.finish(res.id) {
            return;
        }
        // The turn is over: drop its confirmation sender, so `confirm` really is
        // `None` between turns as its doc says. Nothing depends on this — a reply
        // arriving now is dropped by the `generation_id` guard, and the receiver
        // is gone with the task — but a field that outlives what it describes is
        // an invitation to reason wrongly about it later.
        self.confirm = None;
        self.note_withheld_images(res.chat_id, res.images_withheld);
        let mut res = res;
        self.carry_inflight_rename(&mut res);
        if res.messages.is_empty() && res.effects.is_empty() && res.deleted.is_empty() {
            // A turn that landed nothing still ends the wait of a result
            // that arrived meanwhile (docs/research/background-subagents.md §4.4).
            self.land_pending_runs(res.chat_id);
            return;
        }
        // Did the model edit the "self-model" via its own tools this turn? If so —
        // signal `SelfModelChanged` (an open `F3` screen will re-fetch the snapshot).
        let self_model_touched = res.messages.iter().any(|m| {
            m.tool_calls
                .iter()
                .any(|tc| crate::features::tools::self_model::is_self_model_tool(&tc.name))
        });
        // Read before the apply below — afterwards the reply is part of the
        // history and the question can no longer be asked.
        let first_reply = self.is_first_reply(&res);
        // The exchange's language model, for the profile's history (spec
        // §9.14). Also read before the apply: the messages move into the chat
        // below, and a `/continue` tail is folded away by `land_continuation`.
        // Every round of one turn carries the same frozen name (the single
        // `effective_model_name` read), so the newest metadata suffices; a
        // turn whose engine did not say a name records nothing (`model: None`).
        let turn_llm: Option<(String, crate::shared::config::ServerMode)> = res
            .messages
            .iter()
            .rev()
            .filter(|m| m.role == MessageRole::Assistant)
            .find_map(|m| {
                let md = m.metadata.as_ref()?;
                Some((md.model.clone()?, md.mode))
            });
        // Sub-agent runs that landed with this turn and have a reply to name
        // themselves by — titled below, once they are part of the chat
        // (docs/research/subagent-chats.md §3.10).
        let landed_runs: Vec<Uuid> = res
            .messages
            .iter()
            .flat_map(|m| m.tool_calls.iter())
            .filter_map(|r| r.subagent.as_deref())
            .filter(|run| run.final_reply().is_some())
            .map(|run| run.id)
            .collect();
        // Attachments a tool produced this turn (spec §9.9) and the files it stored
        // (docs/history/sandbox-file-exchange.md §11 S7) — applied below, outside the `chat`
        // borrow.
        let mut landed = Landed::default();
        if let Some(chat) = self.chat_mut(res.chat_id) {
            // Discarded by the "rewrite" tool — into the deleted archive (manual
            // recovery by editing JSON), like Ctrl+E/Ctrl+R. See spec §9.3, §11.7.
            if !res.deleted.is_empty() {
                let deleted = std::mem::take(&mut res.deleted);
                chat.record_deleted(deleted, String::new(), DeletedCause::Rewrite);
            }
            land_continuation(chat, &mut res);
            for msg in res.messages {
                chat.push_message(msg);
            }
            // Tool effects are applied by the orchestrator (the owner of Chat, §4.4.2).
            landed = apply_effects(chat, res.effects);
            self.mark_dirty(res.chat_id);
            self.emit_chat_list();
        }
        // The same path `/file attach` takes — one place decides what attaching
        // entails (spec §9.7). A turn cancelled after the tool ran still gets
        // here: the transcript was already paid for.
        for a in landed.attached {
            self.insert_attachment(res.chat_id, a, None);
        }
        self.list_stored_files(res.chat_id, landed.stored);
        // A background run that ended while this turn ran: its notification
        // goes after the turn's rows, and the assistant may be woken on it
        // (docs/research/background-subagents.md §4.4). Before the silent
        // follow-ups, which a turn in flight makes wait their turn.
        self.land_pending_runs(res.chat_id);
        // The profile's language-model history (spec §9.14): an exchange just
        // completed, so append a record when the model differs — by name or
        // mode — from the newest one (the store decides, `llm_history_note`).
        if let Some((model, mode)) = turn_llm {
            self.record_llm_history(res.chat_id, model, mode);
        }
        if self_model_touched {
            let _ = self.evt_tx.send(AppEvent::SelfModelChanged);
        }
        // The conversation's first reply just landed — maybe give the chat its
        // name (`interface.auto_title` at `AfterAssistantReply`, spec §11.2).
        // Ahead of the four background follow-ups only because it is the one
        // the user can see happen; none of the five depend on each other.
        if first_reply {
            self.maybe_auto_title(
                res.chat_id,
                crate::shared::config::AutoTitleMode::AfterAssistantReply,
            );
        }
        // A sub-agent transcript's whole life lands at once, so both trigger
        // points are now — one request per landed run (spec §9.3.2, §11.2).
        for run in landed_runs {
            self.maybe_auto_title_run(run);
        }
        // Maybe the conversation is approaching the model's context window
        // (spec §6.7) — it reads what this turn actually cost, the freshest
        // measurement available. **Ahead** of the three loops below: the
        // silent lane runs one request at a time in the order they were
        // asked for, and the roll is the one silent task that protects the
        // *next* turn (docs/research/silent-tasks-budget.md §4.5, fork F6).
        // The slow-prefill note, from the engine's own clock over the prompt
        // (docs/research/slow-prefill-detection.md §3.3): once per server
        // session, before the roll it may be about to advise on.
        self.note_slow_prefill(res.usage.as_ref().and_then(|u| u.prefill));
        self.maybe_auto_compact(res.chat_id, res.usage);
        // Then background auto-reflection (Tier 3), notes auto-consolidation
        // ("sleep", Tier 3), and/or self-model auto-consolidation ("sleep"
        // for the self-model, stage A1 — docs/history/self-model-consolidation.md).
        self.maybe_auto_reflect(res.chat_id);
        self.maybe_auto_consolidate(res.chat_id);
        self.maybe_auto_self_consolidate(res.chat_id);
    }

    /// Appends a record to the chat's profile's language-model history when
    /// the exchange's model differs from the newest record (spec §9.14; the
    /// dedup lives in [`crate::shared::storage::Db::llm_history_note`]).
    /// Best-effort, like the reflection follow-ups around its call site: a
    /// failed write is logged and never fails the turn (docs/lessons.md §8 —
    /// prefer best-effort on paths that protect data).
    fn record_llm_history(
        &self,
        chat_id: Uuid,
        model: String,
        mode: crate::shared::config::ServerMode,
    ) {
        let Some(profile_id) = self
            .chats
            .iter()
            .find(|c| c.id == chat_id)
            .map(|c| c.profile_id)
        else {
            return;
        };
        let rec = crate::entities::profile::LlmChange {
            changed_at: chrono::Utc::now(),
            model,
            mode,
        };
        if let Err(err) = self.storage.db().llm_history_note(profile_id, &rec) {
            tracing::warn!(error = %err, profile = %profile_id,
                "failed to record the language-model history");
        }
    }

    /// Retires the in-flight mirror (docs/history/subagent-live.md §3.6): every
    /// progress message preceded the turn's result on the one channel. What it
    /// still knows — a title the user gave the running transcript — is carried
    /// onto the landed run's record here, then it goes.
    fn carry_inflight_rename(&mut self, res: &mut GenResult) {
        let Some(inflight) = self.inflight.take().filter(|t| t.generation == res.id) else {
            return;
        };
        // Every running transcript the user named while it ran — there can
        // be several in one turn now (spec §9.3.2).
        for edited in inflight
            .children
            .iter()
            .map(|c| &c.run)
            .filter(|r| r.renamed_manually)
        {
            if let Some(run) = res
                .messages
                .iter_mut()
                .flat_map(|m| m.tool_calls.iter_mut())
                .filter_map(|r| r.subagent.as_deref_mut())
                .find(|r| r.id == edited.id)
            {
                run.title = edited.title.clone();
                run.renamed_manually = true;
            }
        }
    }

    /// Routes the user's answer into the turn that asked (spec §9.8, fork F8).
    ///
    /// A reply for a turn that is no longer in flight is **dropped**: the user
    /// can press a key at the exact moment a turn is cancelled and the next one
    /// starts, and unblocking the new turn's call with the old turn's answer
    /// would run a tool nobody looked at. Same guard as `AppEvent::TokenUsage`'s
    /// `generation_id`.
    pub(super) fn handle_confirm_tool(
        &mut self,
        generation_id: Uuid,
        call_id: String,
        decision: ToolDecision,
    ) {
        let Some((id, tx)) = &self.confirm else {
            return;
        };
        if *id != generation_id {
            tracing::debug!(reply_for = %generation_id, in_flight = %id,
                "dropped a tool confirmation from a finished turn");
            return;
        }
        let _ = tx.send((call_id, decision));
    }
}

/// `/continue`: the turn's first assistant message finishes the seed in place
/// (fork F8) — same id, same bubble, no seam — instead of opening a message of
/// its own. A turn that continues nothing passes through untouched.
fn land_continuation(chat: &mut crate::entities::chat::Chat, res: &mut GenResult) {
    let Some(seed_id) = res.continuation else {
        return;
    };
    let Some(pos) = res
        .messages
        .iter()
        .position(|m| m.role == MessageRole::Assistant)
    else {
        return;
    };
    let round = res.messages.remove(pos);
    match chat.messages.iter_mut().rfind(|m| m.id == seed_id) {
        Some(seed) => merge_continuation(seed, round),
        // The seed vanished mid-turn (edited away by hand): keep the round as
        // its own message rather than lose the text.
        None => res.messages.insert(pos, round),
    }
}

/// The effects of a turn the caller applies once the `chat` borrow ends.
#[derive(Default)]
struct Landed {
    /// An attachment needs the whole orchestrator (index prune, background indexing,
    /// the feed note), which cannot be had while `chat` is borrowed.
    attached: Vec<crate::entities::attachment::Attachment>,
    /// A stored file's listing goes through the same path a background run's landing
    /// takes ([`Orchestrator::list_stored_files`]), so the two cannot drift.
    stored: Vec<crate::entities::chat_file::ChatFile>,
}

/// Applies one turn's tool effects to `chat`: identity in place, and what needs the
/// orchestrator collected for the caller.
fn apply_effects(chat: &mut crate::entities::chat::Chat, effects: Vec<ChatEffect>) -> Landed {
    let mut landed = Landed::default();
    for effect in effects {
        match effect {
            ChatEffect::SetSystemMessage(s) => chat.system_message = s,
            ChatEffect::SetSamplingOverride(s) => chat.sampling_override = Some(*s),
            ChatEffect::AddAttachment(a) => landed.attached.push(*a),
            ChatEffect::AddChatFile(f) => landed.stored.push(*f),
        }
    }
    landed
}

/// Which limit ended a turn — the two are enforced together and the message has
/// to name the right one, or it sends the user to a setting that was not the
/// problem (docs/lessons.md §4).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RoundLimit {
    /// `max_tool_rounds` (spec §6.3) — the budget for *external* work.
    Tools,
    /// `workspace.max_rounds` (spec §9.12) — the budget for work inside the
    /// attached project, which is exempt from the one above.
    Workspace,
}

/// Parameters for launching the generation task (the agentic loop).
struct GenSpawn {
    backend: Arc<dyn EngineBackend>,
    registry: Arc<ToolRegistry>,
    ctx: ToolContext,
    request: ChatRequest,
    cancel: CancellationToken,
    id: Uuid,
    chat_id: Uuid,
    max_rounds: u32,
    /// How many rounds this turn may spend entirely inside the attached project
    /// (`config.workspace.max_rounds`; 0 — no limit). Separate from
    /// `max_rounds` because the `code_*` family is exempt from that one, and
    /// "exempt" is not "unbounded" (spec §9.12).
    workspace_max_rounds: u32,
    /// A sub-agent run's limits (`config.tools`, spec §9.3.2).
    subagent: SubagentLimits,
    /// The turn's session budget — the permits of the active engine section's
    /// `sessions` (spec §11.6) over the KV pool the streams share when one is
    /// known ([`super::pool`]), shared with the turn's `ToolContext` so a
    /// tool's own engine request counts too. One permit, and the turn's loops
    /// take turns exactly as they did before the setting existed.
    sessions: Arc<SessionBudget>,
    /// Width of a round's concurrent tool group — the active section's
    /// `concurrent_calls` (spec §6.3). One: the sequential round.
    concurrent_calls: u32,
    /// The chat's rolling summary when one is in force (`Chat::compaction_view`)
    /// — the folded half of the dialogue director's conversation brief
    /// (spec §9.13, fork F6); the unfolded half is the request's own tail.
    compaction_summary: Option<String>,
    /// Effectively allowed tools (protection against calling a disabled one).
    allowed: Vec<ToolId>,
    /// The `tool-image-N` numbers the chat has already spent, read off its messages while
    /// the chat was borrowed. See [`ToolImageNames`].
    image_names: ToolImageNames,
    /// The profile's "self-model" (a snapshot at the start of the turn) + injection
    /// parameters/flags. Injection into the system prompt is done in the task (needs
    /// async embedding for relevance-based selection of observations). See
    /// docs/history/narrative-as-notes.md (Tier 2).
    self_model: Option<crate::entities::self_model::SelfModel>,
    self_model_params: crate::entities::self_model::SelfModelParams,
    inject_enabled: bool,
    maintenance_protocol: bool,
    /// The last user message — the query for relevance-based injection of observations.
    last_user: String,
    /// Engine mode and model name — a snapshot for `Message.metadata` (spec §8.3).
    engine_mode: ServerMode,
    /// [`Orchestrator::continuation_supported`], read once when the turn starts:
    /// what `Finished.continuable` and the interruption notes promise, so neither
    /// can name `/continue` where the command would refuse.
    continuation_supported: bool,
    /// What the endpoint published about the model's sampling fields, for the
    /// same snapshot (docs/history/gateway-capabilities.md §4, G3(ii)).
    endpoint_sampling_fields: Option<std::sync::Arc<[String]>>,
    model_name: Option<String>,
    /// Interface language (axis B) — for error messages shown to a human.
    ui_loc: &'static crate::shared::i18n::Locale,
    /// `tools.confirm_dangerous` — when off, nothing is asked and no tool is
    /// gated, so the loop behaves exactly as it did before the feature (spec
    /// §9.8). Snapshotted at the start of the turn, like the other config.
    confirm_dangerous: bool,
    /// Limits for an image a tool returned (`config.images`): the same downscale
    /// ceiling and byte cap a user's `/image attach` gets, so third-party pixels
    /// cannot cost more than the user's own (spec §9.10).
    image_cfg: crate::shared::config::ImageSettings,
    /// The user's answers to [`AppEvent::ToolConfirmRequest`], routed in by the
    /// orchestrator. The **only** channel in the codebase that runs orchestrator
    /// → task; everything else (`title_tx`, `imp_done`, the background-task done
    /// channel) runs the other way. See docs/history/tool-confirmation.md §3, fork F8.
    confirm_rx: UnboundedReceiver<(String, ToolDecision)>,
    /// `compaction.enabled` — read only to pick *which* advice a context-overflow
    /// error gives (spec §6.7): with compression on it names `/compact`, with it
    /// off it names the setting. Pointing at a command that would refuse is the
    /// dead end this project has closed three times.
    compaction_enabled: bool,
    /// The message this turn continues (`/continue`, spec §6.4): its text feeds
    /// the echo filter on the first round, its id rides `GenResult` so the
    /// orchestrator folds the round into it in place.
    continuation: Option<ContinuationSeed>,
    /// The app started this turn itself, on a background run's task
    /// notification (spec §9.3.2): nobody typed anything, and the whole new
    /// input is the note. Measured on the gate model, such a turn can spend
    /// its entire reply cap in `reasoning_content` and land empty
    /// (docs/research/background-dialogues.md §3, fork F11), so it gets the
    /// one-shot muted re-ask a dialogue's line gets.
    woken: bool,
    evt_tx: UnboundedSender<AppEvent>,
    done_tx: UnboundedSender<GenMessage>,
    /// The background-run slots (see [`TurnShared::background`]).
    background: Arc<BackgroundSlots>,
}

/// What the confirmation round trip owns, behind [`TurnShared::confirm`]'s
/// lock: the reply receiver and the "approved for this turn" set. One lock
/// for both, held for the whole ask-and-wait, is what makes the popup one
/// question at a time when several loops of the turn run at once
/// (docs/research/parallel-subagents.md §4.3).
struct ConfirmState {
    /// The user's answers to [`AppEvent::ToolConfirmRequest`], routed in by
    /// the orchestrator — the one channel that runs orchestrator → task.
    rx: UnboundedReceiver<(String, ToolDecision)>,
    /// Tools the user approved "for the rest of this turn" (fork F4). The turn
    /// is the natural unit — it is the scope of one user request and it ends by
    /// itself, so nothing outlives it and no standing permission accumulates.
    /// Shared by every loop of the turn for the same reason: same turn, same
    /// request.
    allowed_for_turn: HashSet<ToolId>,
}

/// Everything [`confirm_call`] needs that does not change between calls.
struct ConfirmGate<'a> {
    /// `tools.confirm_dangerous`. When `false` the gate is a no-op and never
    /// even asks the registry — the whole feature is switchable off (spec §9.8).
    enabled: bool,
    registry: &'a ToolRegistry,
    evt_tx: &'a UnboundedSender<AppEvent>,
    cancel: &'a CancellationToken,
    id: Uuid,
    /// Agent-scaffold language: the refusal text is read by the **model**
    /// (axis A), unlike the popup, which the user reads.
    loc: &'static crate::shared::i18n::Locale,
    /// The turn's snapshot, for the one question the popup cannot answer from the
    /// arguments alone: which of the chat's files a `python_exec` call would copy into the
    /// sandbox (docs/history/sandbox-file-exchange.md §12 T6).
    ctx: &'a ToolContext,
}

/// Asks the user before a dangerous tool call, if the feature is on.
///
/// Returns `None` when the call may proceed, or `Some(text)` — the result to
/// hand the model instead of running it. Approving "for the turn" is recorded in
/// `allowed_for_turn`, so the same tool is not asked about again before the turn
/// ends.
///
/// Waiting is bounded only by cancellation (fork F6): `Esc` and `Quit` both fire
/// the turn's token, so a popup left open cannot wedge the task forever. A
/// closed channel — the orchestrator dropped the sender because the turn is over
/// — reads as a refusal rather than as approval.
async fn confirm_call(
    gate: ConfirmGate<'_>,
    call: &ApiToolCall,
    confirm: &tokio::sync::Mutex<ConfirmState>,
) -> Option<String> {
    // Taken before the check and held through the answer: a sibling loop that
    // reaches a dangerous call meanwhile waits here, so at most one popup is
    // ever open and an "allow for this turn" given to the first covers the
    // second before it asks. Cancellation inside the wait releases it.
    let mut state = confirm.lock().await;
    let ConfirmState {
        rx: confirm_rx,
        allowed_for_turn,
    } = &mut *state;
    let needs_ask = gate.enabled
        && !allowed_for_turn.contains(call.name.as_str())
        && gate
            .registry
            .get(&call.name)
            .is_some_and(|tool| tool.danger());
    if !needs_ask {
        return None;
    }
    // What this call would hand the sandbox, resolved with the list the call itself
    // resolves against (§12 T6): the popup's compact view of the arguments drops arrays,
    // so `files` — the argument that decides what leaves the chat — is invisible without
    // this, and a set resolved twice could disagree with what goes in.
    let inputs = (call.name == crate::features::tools::PYTHON_EXEC_ID).then(|| {
        use crate::features::chat_inputs::NamedFiles;
        // An argument that cannot be read names nothing, and the call it belongs to will be
        // refused before it runs — so the popup asks about the code alone rather than
        // inventing a file list for it.
        let named = match serde_json::from_str::<serde_json::Value>(&call.arguments)
            .as_ref()
            .map(crate::features::chat_inputs::named_files)
        {
            Ok(NamedFiles::Named(named)) => named,
            Ok(NamedFiles::Malformed) | Err(_) => Vec::new(),
        };
        // The turn's list — the same one `stage` will resolve against. Derived afresh,
        // this popup could name a different set than the call ends up staging, which is
        // the one thing it exists to prevent (fork F12).
        crate::features::chat_inputs::for_confirm(&gate.ctx.inputs, &named, gate.ctx.python_net)
    });
    let _ = gate.evt_tx.send(AppEvent::ToolConfirmRequest {
        generation_id: gate.id,
        call_id: call.id.clone(),
        name: call.name.clone(),
        arguments: call.arguments.clone(),
        inputs,
    });
    let decision = tokio::select! {
        _ = gate.cancel.cancelled() => None,
        reply = wait_for_decision(confirm_rx, &call.id) => reply,
    };
    match decision {
        Some(ToolDecision::AllowForTurn) => {
            allowed_for_turn.insert(call.name.clone());
            None
        }
        Some(ToolDecision::Allow) => None,
        Some(ToolDecision::Deny) => Some(gate.loc.tf("loop.tool_denied", &[("name", &call.name)])),
        // Cancelled, or the channel closed with the question unanswered.
        None => Some(gate.loc.t("loop.tool_cancelled").to_string()),
    }
}

/// The answer to **this** call, skipping any that arrive for another one.
///
/// A mismatch is possible whenever the model made several calls in one round and
/// the user answered them out of order; answering the wrong call would run a tool
/// the user never looked at, so the id is checked rather than assumed.
async fn wait_for_decision(
    confirm_rx: &mut UnboundedReceiver<(String, ToolDecision)>,
    call_id: &str,
) -> Option<ToolDecision> {
    loop {
        let (id, decision) = confirm_rx.recv().await?;
        if id == call_id {
            return Some(decision);
        }
        tracing::debug!(reply_for = %id, waiting_for = %call_id,
            "dropped a tool confirmation meant for another call");
    }
}

/// Accumulator for a single stream round.
struct RoundOutput {
    text: String,
    thoughts: String,
    /// The references to the reasoning (Anthropic's signature / OpenAI's reasoning
    /// items), in order: needed to resend the thinking blocks on an assistant turn
    /// with a tool call in the same turn. Empty for backends with no extended
    /// thinking (llama.cpp) or when there were no "thoughts"; several on Responses
    /// ([`ThinkingAccumulator`]).
    thinking: Vec<ThinkingRef>,
    calls: Vec<ApiToolCall>,
    reason: FinishReason,
    /// Tokens generated in the round: the exact value from the server's `usage`, else
    /// the count of streamed deltas (an approximation — for llama-server one delta ≈
    /// one token).
    tokens: u64,
    /// The prompt's processing as the engine measured it (llama.cpp's `timings`;
    /// `None` elsewhere) — the slow-prefill note's sample
    /// (docs/research/slow-prefill-detection.md §3.1).
    prefill: Option<crate::shared::api::contract::Prefill>,
    /// The **exact** prompt size the server reported for this round, from `usage`.
    /// `None` when the provider reported none — and then it stays `None` rather
    /// than falling back to the byte estimate: auto-compaction reads this, and
    /// the estimate's error changes sign by content type (§9a M9 of the
    /// research), i.e. it is unsafe precisely on the tool-heavy chats that
    /// overflow first. See sub-decision S2.
    prompt_tokens: Option<u32>,
    /// Reasoning tokens ("thoughts") for the round from `usage` (`0` — the provider
    /// doesn't separate them).
    reasoning_tokens: u32,
}

/// Launches the client-side agentic-loop task (spec §6.3): stream → on
/// `finish_reason=ToolCalls` execute tools → a new request, up to
/// `max_rounds`. Effects and new messages are returned to the orchestrator.
fn spawn_generation(spawn: GenSpawn) {
    let GenSpawn {
        backend,
        registry,
        ctx,
        mut request,
        cancel,
        confirm_dangerous,
        image_cfg,
        confirm_rx,
        id,
        chat_id,
        max_rounds,
        workspace_max_rounds,
        subagent,
        sessions,
        concurrent_calls,
        allowed,
        image_names,
        self_model,
        self_model_params,
        inject_enabled,
        maintenance_protocol,
        last_user,
        engine_mode,
        continuation_supported,
        endpoint_sampling_fields,
        model_name,
        ui_loc,
        compaction_enabled,
        compaction_summary,
        continuation,
        woken,
        evt_tx,
        done_tx,
        background,
    } = spawn;

    tokio::spawn(async move {
        // Injecting the "self-model" into the system prompt (in the task — needs
        // async embedding of the last message for relevance-based selection of
        // observations; Tier 2). With injection disabled, `inject_self_model`
        // returns system as is.
        {
            let recent = injection_recent(
                &ctx.storage,
                ctx.embedder.as_ref(),
                ctx.profile_id,
                inject_enabled,
                &last_user,
                &self_model_params,
            )
            .await;
            request.system = inject_self_model(
                request.system.take(),
                self_model.as_ref(),
                inject_enabled,
                maintenance_protocol,
                &self_model_params,
                chrono::Utc::now(),
                &recent,
                ctx.loc,
            );
        }
        // Prompt-token estimate (after self-model injection) — the exact count will
        // come from the server's `usage` and replace the estimate. See spec §11.1.
        let _ = evt_tx.send(AppEvent::TokenUsage {
            generation_id: id,
            completion: 0,
            context: Some(estimate_prompt_tokens(&request)),
            context_exact: false,
            reasoning: None,
        });

        let shared = TurnShared {
            background,
            backend,
            registry,
            confirm_dangerous,
            image_cfg,
            confirm: tokio::sync::Mutex::new(ConfirmState {
                rx: confirm_rx,
                allowed_for_turn: HashSet::new(),
            }),
            counters: TurnCounters::default(),
            id,
            max_rounds,
            workspace_max_rounds,
            subagent,
            sessions,
            concurrent_calls,
            engine_mode,
            continuation_supported,
            endpoint_sampling_fields,
            model_name,
            ui_loc,
            evt_tx: evt_tx.clone(),
            done_tx: done_tx.clone(),
            compaction_enabled,
            compaction_summary,
        };
        let mut turn = TurnLoop {
            shared: &shared,
            ctx,
            request,
            cancel,
            // Asked on the first result that carries an image, and not again.
            vision: None,
            images_withheld: 0,
            image_names,
            allowed,
            messages: Vec::new(),
            effects: Vec::new(),
            deleted: Vec::new(),
            round: 0,
            workspace_rounds: 0,
            total_tokens: 0,
            total_reasoning: 0,
            last_usage: None,
            pending_new_bubble: false,
            woken,
            depth: 0,
            run_id: None,
            ended_by_limit: None,
            persona: None,
            echo_seed: continuation.as_ref().map(|c| c.text.clone()),
        };
        let reason = turn.run().await;

        // Whether `/continue` would resume what this turn leaves behind — the
        // interruption notes name the command only when it will actually work
        // (fork F9; text derived from state, docs/lessons.md §4). A tool-result
        // tail resumes the loop; an assistant tail needs visible text; a turn
        // that filed nothing left nothing new — unless it was itself a
        // continuation, whose seed still stands.
        let tail_continuable = match turn.messages.last() {
            Some(m) if m.role == MessageRole::Tool => true,
            Some(m) if m.role == MessageRole::Assistant => !m.text.is_empty(),
            _ => continuation.is_some(),
        };
        let continuable = turn.shared.continuation_supported
            && matches!(
                reason,
                FinishReason::Cancelled | FinishReason::Error | FinishReason::Length
            )
            && tail_continuable;
        let _ = evt_tx.send(AppEvent::Finished {
            generation_id: id,
            reason,
            continuable,
        });
        let _ = done_tx.send(GenMessage::Done(GenResult {
            id,
            chat_id,
            messages: turn.messages,
            effects: turn.effects,
            deleted: turn.deleted,
            usage: turn.last_usage,
            continuation: continuation.map(|c| c.message_id),
            images_withheld: turn.images_withheld,
        }));
    });
}

/// What every loop of one turn shares: the engine, the registry, the UI
/// channel, the progress channel, the confirmation round trip and the limits. Owned by the generation
/// task, one per turn; the turn's own loop borrows it, and a **child** loop — a
/// sub-agent run (docs/research/subagent-chats.md §3.2) — borrows it from its
/// parent for the duration of the call, which is sound because the parent is
/// suspended inside `execute_call` while the child runs. Split out of
/// [`TurnLoop`] so that a nested loop is the same type over the same shared
/// part, not a second loop with its own copy of these behaviours.
struct TurnShared {
    backend: Arc<dyn EngineBackend>,
    registry: Arc<ToolRegistry>,
    confirm_dangerous: bool,
    image_cfg: crate::shared::config::ImageSettings,
    /// The dangerous-call confirmation round trip (spec §9.8), one question
    /// at a time — see [`ConfirmState`].
    confirm: tokio::sync::Mutex<ConfirmState>,
    /// The turn's running token totals across every loop of it — what the
    /// status bar shows (docs/research/parallel-subagents.md §4.4). Each loop
    /// still keeps its own count for its record; this is the sum, kept where
    /// concurrent loops can all add to it.
    counters: TurnCounters,
    /// The turn's generation id: every streamed event and every confirmation
    /// request carries it, a child's included — the popup and the reply
    /// routing know one turn, not one loop.
    id: Uuid,
    max_rounds: u32,
    workspace_max_rounds: u32,
    /// A sub-agent run's limits (spec §9.3.2).
    subagent: SubagentLimits,
    /// The turn's session budget (docs/research/parallel-subagents.md §4.2):
    /// a permit is held for the duration of one request stream and for nothing
    /// else — a round's tool execution, a popup waiting for the user, a child's
    /// web fetch hold no session. Every loop of the turn, the turn's own
    /// included, streams under it; sized from the active engine section's
    /// `sessions`. With one permit the loops take turns as they always did.
    /// Under a shared KV pool a stream also reserves what it will occupy and
    /// waits for room (docs/research/admission-by-budget.md §4.1). Shared
    /// (`Arc`) with the turn's `ToolContext`: a tool's own engine request —
    /// `fetch_url`'s page summary — takes a permit of the same budget
    /// (docs/research/concurrent-tools.md §4.5).
    sessions: Arc<SessionBudget>,
    /// Width of a round's concurrent tool group (spec §6.3,
    /// docs/research/concurrent-tools.md §4.2–§4.4): how many of a segment's
    /// marked calls are alive at once. One: no segment is formed and every
    /// call takes the sequential path, bit for bit.
    concurrent_calls: u32,
    engine_mode: ServerMode,
    /// See [`GenSpawn::continuation_supported`].
    continuation_supported: bool,
    /// What the endpoint published about the model's sampling fields, when it
    /// published anything: the turn's metadata snapshot must not record a field
    /// the endpoint drops (docs/history/gateway-capabilities.md §4, G3(ii)).
    endpoint_sampling_fields: Option<std::sync::Arc<[String]>>,
    model_name: Option<String>,
    ui_loc: &'static crate::shared::i18n::Locale,
    evt_tx: UnboundedSender<AppEvent>,
    /// The progress channel to the orchestrator — the same one the result
    /// goes on, so progress and result arrive in order ([`GenMessage`]).
    done_tx: UnboundedSender<GenMessage>,
    /// `compaction.enabled` — picks which advice a context-overflow error gives
    /// (see [`GenSpawn::compaction_enabled`]).
    compaction_enabled: bool,
    /// The chat's rolling summary, for the dialogue director's brief
    /// (see [`GenSpawn::compaction_summary`]).
    compaction_summary: Option<String>,
    /// How many background runs are out, against the cap
    /// (`tools.subagent_background_max`) — owned by the orchestrator, taken
    /// by the loop that starts a run, released by the run that ends
    /// (docs/research/background-subagents.md §4.8).
    background: Arc<BackgroundSlots>,
}

/// The turn-wide token totals ([`TurnShared::counters`]): every loop adds its
/// streamed deltas as they arrive and corrects to the server's exact `usage`
/// at the round's end, so the bar's number grows monotonically whichever loop
/// produced the token.
#[derive(Default)]
struct TurnCounters {
    tokens: std::sync::atomic::AtomicU64,
    reasoning: std::sync::atomic::AtomicU32,
}

/// One round's token report from [`stream_round`] to its [`RoundSink`]: the
/// turn's totals for the status bar, the loop's own cumulative count for a
/// transcript's counter, the exact context when the server said.
struct TokenReport {
    turn_completion: u64,
    own_completion: u64,
    turn_reasoning: Option<u32>,
    own_reasoning: Option<u32>,
    context: Option<u64>,
    context_exact: bool,
}

/// One agentic loop's state: the turn's own, or a sub-agent's run inside it.
/// Moved verbatim out of [`spawn_generation`]'s async block (Sonar S3776): the
/// loop itself is [`Self::run`], one tool round is [`Self::tool_round`], one call
/// — [`Self::execute_call`] / [`Self::resolve_call_result`]. The struct follows
/// the module's parameter-struct pattern ([`GenSpawn`], [`ConfirmGate`]); it
/// still never touches `Chat` — results go back through [`GenResult`].
struct TurnLoop<'a> {
    /// Borrowed immutably by every loop of the turn — the parent's and any
    /// number of children running at once (the mutable parts sit behind
    /// their own locks and atomics, see [`TurnShared`]).
    shared: &'a TurnShared,
    ctx: ToolContext,
    request: ChatRequest,
    /// This loop's cancellation: the turn's token for the turn's own loop; a
    /// child token for a sub-agent, so a run timeout ends the child alone while
    /// `Esc` on the turn ends both.
    cancel: CancellationToken,
    /// What the engine answered about images, asked at most once per loop
    /// ([`TurnLoop::vision`]).
    vision: Option<VisionSupport>,
    /// How many images the request carried that the engine takes none of, and so went as
    /// markers instead ([`withhold_images`]). The orchestrator tells the user once
    /// per chat (docs/research/history-images-no-vision.md, fork W1(a)).
    images_withheld: usize,
    /// The `tool-image-N` numbers this chat has spent — seeded from the images it already
    /// carries and grown as the turn produces more. See [`ToolImageNames`].
    image_names: ToolImageNames,
    allowed: Vec<ToolId>,
    /// New domain messages accumulated across the loop's rounds.
    messages: Vec<Message>,
    /// Tool effects accumulated across the loop's rounds.
    effects: Vec<ChatEffect>,
    /// Discarded by the "rewrite" tool (for the deleted archive).
    deleted: Vec<Message>,
    round: u32,
    /// Rounds spent entirely on the attached project. Exempt from
    /// `max_tool_rounds`, bounded by `workspace.max_rounds`.
    workspace_rounds: u32,
    /// Cumulative reply-token counter across all agentic-loop rounds — the
    /// live indicator keeps growing from round to round.
    total_tokens: u64,
    /// Cumulative reasoning tokens ("thoughts") across rounds.
    total_reasoning: u32,
    /// The exact size of the most recent round, when the server reported one.
    /// Written by [`Self::stream`], so neither call site can forget it.
    last_usage: Option<TurnUsage>,
    /// The next domain assistant message starts a new bubble (after
    /// `send_followup_message`). See spec §9.3.
    pending_new_bubble: bool,
    /// The turn the app started itself on a task notification — the one
    /// turn allowed a muted re-ask when its first round comes back empty
    /// (see [`GenSpawn::woken`]).
    woken: bool,
    /// Nesting level: `0` for the turn's own loop, `1` for a sub-agent's run.
    /// [`Self::run_subagent`] refuses below the top — the belt under the braces
    /// of an allowed set that never offers `call_subagent` there.
    depth: u8,
    /// The run this loop is: `None` for the turn's own loop, whose stream
    /// reaches the feed; the run's id for a sub-agent's, whose stream goes to
    /// the orchestrator as progress under that id — its text would land in
    /// the parent's bubble — while only the turn's token total passes to the
    /// bar (see [`RoundSink`]). What every progress step of the loop is keyed by.
    run_id: Option<Uuid>,
    /// Which budget ended this loop, when one did — the parent reads it to
    /// record a sub-agent's outcome as `RoundLimit` rather than `Completed`.
    ended_by_limit: Option<RoundLimit>,
    /// A sub-agent's display name for the status-bar chip
    /// (`AppEvent::SubagentProgress`); `None` on the turn's own loop, which
    /// reports nothing of the kind.
    persona: Option<String>,
    /// The continuation seed's text, consumed by the **first** round's stream:
    /// llama.cpp echoes the prefill back, and the filter keeps it off the
    /// screen and out of the round (`/continue`, research §4d). `None` on an
    /// ordinary turn, on every later round, and on a sub-agent's loop.
    echo_seed: Option<std::sync::Arc<str>>,
}

/// The limits of one sub-agent run, snapshotted from `config.tools` with the
/// rest of the turn's configuration (spec §9.3.2, docs/research/subagent-chats.md §3.12).
#[derive(Debug, Clone, Copy)]
struct SubagentLimits {
    /// The per-round reply cap, min'ed with the effective `max_tokens` —
    /// a dialogue participant's line rides the same cap (spec §9.13).
    max_tokens: usize,
    /// The whole run — every round and tool call of it.
    run_timeout: std::time::Duration,
    /// The whole dialogue run (`run_dialogue`) — every participant line and
    /// director checkpoint of it. Its own knob: the honest default differs
    /// from the sub-agent's by an order of magnitude (spec §9.13).
    dialogue_run_timeout: std::time::Duration,
    /// How many of one round's sub-agents run at once
    /// (`tools.subagent_parallel`; docs/research/parallel-subagents.md §4.2).
    parallel: u32,
}

impl SubagentLimits {
    fn from_config(tools: &crate::shared::config::ToolSettings) -> Self {
        Self {
            max_tokens: tools.subagent_max_tokens,
            run_timeout: std::time::Duration::from_secs(tools.subagent_run_timeout_secs),
            dialogue_run_timeout: std::time::Duration::from_secs(tools.dialogue_run_timeout_secs),
            parallel: tools.subagent_parallel,
        }
    }
}

/// Where one loop's events go. The turn's own loop sends everything to the
/// screen; a sub-agent's loop sends its stream to the **orchestrator** as
/// progress (docs/history/subagent-live.md §8) — it is the transcript's
/// stream, not the parent's — except the token counter, which also goes on
/// to the status bar re-based on the parent's, with its `context` half
/// dropped: the child's prompt size is not the conversation's, and the bar
/// shows one number (research §3.5).
struct RoundSink<'a> {
    evt_tx: &'a UnboundedSender<AppEvent>,
    done_tx: &'a UnboundedSender<GenMessage>,
    turn: Uuid,
    /// `None` on the turn's own loop, whose stream goes to the screen
    /// directly and to the orchestrator as a mirror; `Some(run id)` on a
    /// sub-agent's, whose stream goes to the orchestrator only, keyed by the
    /// run — several can be in flight at once.
    child: Option<Uuid>,
    /// A dialogue's streams grow the open transcript **per message**, not per
    /// token (research §3.7): the token-level partial has no speaker side yet,
    /// and half the lines land on the `User` side — streaming them into the
    /// assistant-side partial would draw every other line in the wrong bubble.
    /// `true` drops a child's stream steps and keeps only the token counter;
    /// the filed messages (`ChildRoundFiled`) carry the transcript's growth.
    mute_steps: bool,
}

impl RoundSink<'_> {
    fn send(&self, event: AppEvent) {
        let progress = match self.child {
            None => {
                // The turn's own loop: the screen gets every event as it
                // always did; the orchestrator mirrors the round's steps.
                let step = stream_step(&event);
                let _ = self.evt_tx.send(event);
                match step {
                    Some(step) => TurnProgress::OwnStep(step),
                    None => return,
                }
            }
            // A retry or an error inside the run: the parent's result text
            // says how the run ended; nothing to draw meanwhile.
            Some(run) => {
                if self.mute_steps {
                    return;
                }
                match stream_step(&event) {
                    Some(step) => TurnProgress::ChildStep { run, step },
                    None => return,
                }
            }
        };
        let _ = self.done_tx.send(GenMessage::Progress {
            id: self.turn,
            progress,
        });
    }

    /// The token counter: the turn's totals go to the status bar from every
    /// loop (one number, whichever loop produced the token); a child's own
    /// count goes to the orchestrator for its transcript's counter.
    fn tokens(&self, r: TokenReport) {
        match self.child {
            None => {
                let _ = self.evt_tx.send(AppEvent::TokenUsage {
                    generation_id: self.turn,
                    completion: r.turn_completion,
                    context: r.context,
                    context_exact: r.context_exact,
                    reasoning: r.turn_reasoning,
                });
            }
            Some(run) => {
                // The child's prompt size is not the conversation's: the
                // bar shows one number, so the `context` half is dropped.
                let _ = self.evt_tx.send(AppEvent::TokenUsage {
                    generation_id: self.turn,
                    completion: r.turn_completion,
                    context: None,
                    context_exact: false,
                    reasoning: r.turn_reasoning,
                });
                let _ = self.done_tx.send(GenMessage::Progress {
                    id: self.turn,
                    progress: TurnProgress::ChildTokens {
                        run,
                        completion: r.own_completion,
                        reasoning: r.own_reasoning,
                    },
                });
            }
        }
    }
}

/// The mirrored shape of a feed event, when it is one of the round's steps.
fn stream_step(event: &AppEvent) -> Option<StreamStep> {
    Some(match event {
        AppEvent::Chunk { text, .. } => StreamStep::Chunk(text.clone()),
        AppEvent::Thoughts { text, .. } => StreamStep::Thoughts(text.clone()),
        AppEvent::ToolCallStarted {
            call_id,
            name,
            arguments,
            ..
        } => StreamStep::ToolStarted {
            call_id: call_id.clone(),
            name: name.clone(),
            arguments: arguments.clone(),
        },
        AppEvent::ToolCall {
            call_id,
            name,
            arguments,
            result,
            images,
            ..
        } => StreamStep::ToolCall {
            call_id: call_id.clone(),
            name: name.clone(),
            arguments: arguments.clone(),
            result: result.clone(),
            images: *images,
        },
        AppEvent::AssistantContinue { .. } => StreamStep::Continue,
        AppEvent::AssistantRewrite { .. } => StreamStep::Rewrite,
        _ => return None,
    })
}

impl TurnLoop<'_> {
    /// The kind of request this loop's rounds are, for the budget's ratio
    /// (docs/research/title-impersonation-usage.md §3.1): the turn's own,
    /// or a child run's — a persona's prompt and the turn's tools, a
    /// population of its own.
    fn shape(&self) -> crate::shared::session_budget::Shape {
        if self.depth == 0 {
            crate::shared::session_budget::Shape::Turn
        } else {
            crate::shared::session_budget::Shape::Run
        }
    }

    /// Is the tool in the turn's effectively allowed set (profile ∩ global
    /// switches)?
    fn allowed_has(&self, name: &str) -> bool {
        self.allowed.iter().any(|t| t == name)
    }

    /// Tells the status bar where a sub-agent run stands (spec §9.3.2): the
    /// round about to start, or the tool it is entering. Sent **around** the
    /// muted sink — this is the one event of a child's that is meant for the
    /// parent's screen. A no-op on the turn's own loop.
    fn report_progress(&self, tool: Option<&str>) {
        let (Some(name), Some(run)) = (&self.persona, self.run_id) else {
            return;
        };
        // `tool_round` counts the round before it executes the calls, so a
        // tool belongs to the round already counted; a stream opens the next.
        let counted = self.round + self.workspace_rounds;
        let round = if tool.is_some() { counted } else { counted + 1 };
        let progress = crate::app::events::SubagentProgress {
            name: name.clone(),
            round,
            tool: tool.map(str::to_string),
            kind: crate::app::events::RunProgressKind::Subagent,
        };
        // The same position to the orchestrator, for the run's mirror and
        // the tasks screen (spec §11.10) — one value, two readers.
        self.progress(TurnProgress::ChildProgress {
            run,
            progress: progress.clone(),
        });
        let _ = self.shared.evt_tx.send(AppEvent::SubagentProgress {
            generation_id: self.shared.id,
            run,
            progress: Some(progress),
        });
    }

    /// Sends one step of the turn to the orchestrator (see [`TurnProgress`]).
    fn progress(&self, progress: TurnProgress) {
        let _ = self.shared.done_tx.send(GenMessage::Progress {
            id: self.shared.id,
            progress,
        });
    }

    /// A filed round, reported as the parent's or the sub-agent's by depth.
    fn report_progress_filed(&self, messages: Vec<Message>) {
        self.progress(match self.run_id {
            None => TurnProgress::RoundFiled(messages),
            Some(run) => TurnProgress::ChildRoundFiled { run, messages },
        });
    }

    /// This loop's event sink (see [`RoundSink`]).
    fn sink(&self) -> RoundSink<'_> {
        RoundSink {
            evt_tx: &self.shared.evt_tx,
            done_tx: &self.shared.done_tx,
            turn: self.shared.id,
            child: self.run_id,
            mute_steps: false,
        }
    }

    /// The agentic loop itself: stream → on `finish_reason=ToolCalls` execute
    /// tools → a new request, up to `max_rounds`. Returns the turn's finish
    /// reason.
    /// One round through [`stream_round`], recording what it cost.
    ///
    /// Both call sites go through here so the usage cannot be recorded at one of
    /// them and forgotten at the other — the round-limit branch runs its own
    /// final round, and it is the one whose size the next turn actually starts
    /// from.
    async fn stream(&mut self) -> RoundOutput {
        // The continuation seed is the first round's alone: it filters the
        // server's echo of the prefill (research §4d, §7.1).
        let echo = self.echo_seed.take().map(EchoFilter::new);
        // What this stream will occupy of a shared KV pool
        // (docs/research/admission-by-budget.md §4.2): the calibrated estimate
        // of the request, floored by the last round's exact size plus what it
        // generated (the history only grows), plus the reply cap — which a
        // child and a summary always carry, and the turn's own stream may not
        // (then it reserves the pool: it never overlaps another stream anyway).
        let estimate = estimate_prompt_tokens(&self.request);
        let floor = self.last_usage.map_or(0, TurnUsage::next_prompt_estimate);
        let need = self.shared.sessions.price(
            self.shape(),
            estimate,
            floor,
            self.request.sampling.max_tokens.map(|m| m as u64),
        );
        // A session for the stream, and only for the stream: the permit and
        // the reservation are dropped with this block, before the round's
        // tools run.
        let out = {
            let Some(_session) = self.shared.sessions.acquire(need, &self.cancel).await else {
                return cancelled_round();
            };
            stream_round(
                &self.shared.backend,
                self.request.clone(),
                &self.cancel,
                self.shared.id,
                &self.sink(),
                &self.shared.counters,
                self.total_tokens,
                self.total_reasoning,
                self.shared.ui_loc,
                self.shared.compaction_enabled,
                self.shared.continuation_supported,
                echo,
            )
            .await
        };
        // The prefill was consumed by the round that carried it: later rounds
        // end with tool results (nothing to continue), and re-suppressing
        // thinking there would change rounds that continue nothing.
        self.request.continue_final = false;
        if let Some(prompt_tokens) = out.prompt_tokens {
            // The exact size next to the estimate made for the same request:
            // the estimator's correction for every later reservation of the
            // turn (admission-by-budget §4.3).
            self.shared
                .sessions
                .record_usage(self.shape(), estimate, prompt_tokens as u64);
            // The turn keeps its largest prefill sample: a session's first
            // round processes the prompt cold, later rounds ride the cache
            // (docs/research/slow-prefill-detection.md §3.1).
            let mut prefill = self.last_usage.as_ref().and_then(|u| u.prefill);
            crate::shared::api::contract::Prefill::keep_larger(&mut prefill, out.prefill);
            self.last_usage = Some(TurnUsage {
                prompt_tokens,
                completion_tokens: out.tokens,
                prefill,
            });
        }
        out
    }

    async fn run(&mut self) -> FinishReason {
        // A chat that got an image while a model that sees was selected replays it on every
        // turn, and an engine that takes none refuses the whole request for it — a `500`
        // from llama.cpp without a projector, a `404` from a gateway's router, every turn
        // (docs/research/history-images-no-vision.md §2.1). So on the engine's "no" the
        // request's images go as markers. A request without images asks nothing.
        if self.request.messages.iter().any(|m| !m.images.is_empty())
            && self.vision().await == VisionSupport::Unsupported
        {
            self.images_withheld += withhold_images(&mut self.request.messages, self.ctx.loc);
        }
        let mut muted_retry_left = self.woken;
        loop {
            self.report_progress(None);
            let mut out = self.stream().await;
            self.total_tokens += out.tokens;
            self.total_reasoning += out.reasoning_tokens;

            // A turn the app started on a task notification can spend its
            // whole cap thinking and say nothing — measured 2 in 5 on the
            // gate model (docs/research/background-dialogues.md §3). The
            // recovery is the dialogue's (spec §9.13): one re-ask with
            // thinking muted, whose tokens count like any other round's. A
            // second empty reply is reported honestly.
            if muted_retry_left
                && out.calls.is_empty()
                && out.text.trim().is_empty()
                && out.reason != FinishReason::Cancelled
            {
                muted_retry_left = false;
                self.request.sampling.reasoning_budget = Some(0);
                self.report_progress(None);
                out = self.stream().await;
                self.total_tokens += out.tokens;
                self.total_reasoning += out.reasoning_tokens;
            }

            // A round with tool calls — execute and continue the loop.
            if out.reason == FinishReason::ToolCalls && !out.calls.is_empty() {
                if let Some(reason) = self.tool_round(out).await {
                    return reason;
                }
                continue;
            }

            // The final round (Stop/Length/Cancelled/Error, or no calls).
            if let Some(mut m) = finalize_message(
                &out,
                &self.ctx.effective_sampling,
                self.shared.engine_mode,
                &self.shared.model_name,
                self.shared.endpoint_sampling_fields.as_deref(),
            ) {
                m.new_bubble = self.pending_new_bubble;
                self.messages.push(m);
            }
            return out.reason;
        }
    }

    /// Which budget, if either, the turn has run out of — the ordinary one, or
    /// the workspace ceiling that keeps an exempt loop from running forever.
    ///
    /// `workspace.max_rounds == 0` means the user switched the second one off.
    /// That is a supported choice rather than an oversight, and what remains
    /// underneath it is `Esc`, the per-command timeout and the one-at-a-time
    /// gate (spec §9.12).
    fn budget_exhausted(&self) -> Option<RoundLimit> {
        if self.round >= self.shared.max_rounds {
            return Some(RoundLimit::Tools);
        }
        if self.shared.workspace_max_rounds > 0
            && self.workspace_rounds >= self.shared.workspace_max_rounds
        {
            return Some(RoundLimit::Workspace);
        }
        None
    }

    /// Whether a call by this name spends a round of the `max_tool_rounds`
    /// budget — the tool's own answer (`Tool::counts_toward_round_limit`).
    ///
    /// An unknown name counts: it is about to become a "no such tool" result,
    /// and a model inventing tool names is exactly the loop the limit is for.
    fn counts_toward_round_limit(&self, name: &str) -> bool {
        self.shared
            .registry
            .get(name)
            .is_none_or(|tool| tool.counts_toward_round_limit())
    }

    /// The turn's round budget is spent: one final round **without tools**.
    ///
    /// DON'T execute new calls — ask the model instead to sum up what's already
    /// been gathered. Otherwise (the previous behavior) the round would only
    /// contain an intent to call more tools with empty text →
    /// `finalize_message` returned `None`, and the user got no reply at all,
    /// even though enough data had accumulated over the previous rounds. Tools
    /// are removed from the request, so the model must answer with text (the
    /// stream goes into the feed).
    ///
    /// Returns the finish reason of that final round (usually `Stop`; on user
    /// cancellation/a stream error — `Cancelled`/`Error`), not an artificial
    /// `Stop`.
    async fn final_round(&mut self, limit: RoundLimit) -> FinishReason {
        // Name the limit that actually fired: quoting `max_tool_rounds` at
        // someone whose turn was ended by the *project* budget points them
        // at the wrong setting (docs/lessons.md §4).
        let (key, n) = match limit {
            RoundLimit::Tools => ("loop.round_limit_reached", self.shared.max_rounds),
            RoundLimit::Workspace => (
                "loop.workspace_round_limit_reached",
                self.shared.workspace_max_rounds,
            ),
        };
        self.sink().send(AppEvent::Error(
            self.ctx.loc.tf(key, &[("max_rounds", &n.to_string())]),
        ));
        self.ended_by_limit = Some(limit);
        self.request.tools.clear();
        // The final round's token counter is emitted by `stream_round` itself
        // (from `base = total_*`); after that the turn ends, no need to accumulate.
        let final_out = self.stream().await;
        if let Some(mut m) = finalize_message(
            &final_out,
            &self.ctx.effective_sampling,
            self.shared.engine_mode,
            &self.shared.model_name,
            self.shared.endpoint_sampling_fields.as_deref(),
        ) {
            m.new_bubble = self.pending_new_bubble;
            self.messages.push(m);
        }
        final_out.reason
    }

    /// Files the round's messages: on `rewrite` the round is discarded into the
    /// deleted archive, otherwise it is appended, with `followup` opening the
    /// next assistant message as its own bubble.
    fn file_round(
        &mut self,
        mut am: Message,
        tool_msgs: Vec<Message>,
        rewrite: bool,
        followup: bool,
    ) {
        if rewrite {
            // Discard the round: assistant + tool messages → the deleted archive.
            // The live feed clears the current bubble for the rewritten reply.
            // `pending_new_bubble` is deliberately left alone (the final round absorbs it).
            self.deleted.push(am);
            self.deleted.extend(tool_msgs);
            self.sink().send(AppEvent::AssistantRewrite {
                generation_id: self.shared.id,
            });
            return;
        }
        // assistant BEFORE this round's tool messages.
        am.new_bubble = std::mem::take(&mut self.pending_new_bubble);
        // The orchestrator's in-flight mirror of this round
        // (docs/subagent-live.md §3.1): the parent's rounds rebuild its feed
        // after a switch back; a sub-agent's grow its open transcript.
        let filed: Vec<Message> = std::iter::once(am.clone())
            .chain(tool_msgs.iter().cloned())
            .collect();
        self.report_progress_filed(filed);
        self.messages.push(am);
        self.messages.extend(tool_msgs);
        if followup {
            // The next assistant message — as a separate bubble.
            self.pending_new_bubble = true;
            self.sink().send(AppEvent::AssistantContinue {
                generation_id: self.shared.id,
            });
        }
    }

    /// One round that ended in tool calls: the round-limit final round, the
    /// control-tool recognition, executing every call, and assembling the
    /// round's domain messages. `Some(reason)` ends the turn; `None` — run the
    /// next round.
    async fn tool_round(&mut self, out: RoundOutput) -> Option<FinishReason> {
        if let Some(limit) = self.budget_exhausted() {
            return Some(self.final_round(limit).await);
        }
        // A round spent entirely inside the attached project does not cost the
        // budget (spec §9.12). The limit exists to stop a model looping on
        // *external* work, where every round is a request and possibly money;
        // a code fix is read → change → check, and eight rounds end it halfway.
        // A round is counted when **any** call in it counts, so mixing a
        // `web_search` into a round of reads still spends one — the exemption
        // cannot be used as a way round the limit.
        if out
            .calls
            .iter()
            .any(|c| self.counts_toward_round_limit(&c.name))
        {
            self.round += 1;
        } else {
            // Exempt, but still counted: see `workspace.max_rounds`.
            self.workspace_rounds += 1;
        }

        // Conversation control tools (spec §9.3) are recognized only if
        // they're actually enabled in the profile — otherwise a plain
        // refusal below. `rewrite` discards the current round; `followup`
        // starts a new bubble.
        let rewrite = out
            .calls
            .iter()
            .any(|c| c.name == control::REWRITE_CURRENT_ID && self.allowed_has(&c.name));
        let followup = out
            .calls
            .iter()
            .any(|c| c.name == control::SEND_FOLLOWUP_ID && self.allowed_has(&c.name));

        // The assistant turn with calls — into the request history (also
        // needed for inference in the next continuation/rewrite round). With
        // extended thinking (Anthropic) or reasoning items (OpenAI Responses)
        // we attach the thinking blocks, in order: an assistant turn with
        // tool_use in the same turn is required to carry them, otherwise the
        // next request → 400. They exist only if the model actually returned
        // "thoughts"; other backends ignore the field. The round's thoughts
        // text rides on the first block — Anthropic's one block resends its
        // text with the signature, Responses sends only id + ciphertext.
        let thinking: Vec<ThinkingBlock> = out
            .thinking
            .iter()
            .enumerate()
            .map(|(i, r)| ThinkingBlock {
                text: if i == 0 {
                    out.thoughts.clone()
                } else {
                    String::new()
                },
                signature: r.signature.clone(),
                id: r.id.clone(),
            })
            .collect();
        self.request.messages.push(
            ApiMessage::assistant_tool_calls(out.text.clone(), out.calls.clone())
                .with_thinking_blocks(thinking),
        );
        let (records, tool_msgs) = self.execute_round(&out.calls, rewrite).await;

        // The round's domain assistant message (text + thoughts + tool blocks).
        let mut am = Message::assistant(out.text.clone());
        if !out.thoughts.is_empty() {
            am.thoughts = Some(out.thoughts.clone());
        }
        am.tool_calls = records;

        self.file_round(am, tool_msgs, rewrite, followup);
        // An attachment a tool produced this round (a video transcript,
        // spec §9.9) is mirrored into the turn's snapshot, so
        // `attachment_read`/`attachment_search` find it in the **next
        // round** — which is when the model, having just been told it
        // exists, will ask for it. Without this the tool result would be
        // an instruction the turn cannot carry out: the effect itself is
        // applied to `Chat` by the orchestrator only when the turn ends
        // (docs/history/youtube-transcript.md §3 F1).
        //
        // Once per round, not per call: within a round the model has
        // already issued its calls, so finer granularity would buy
        // nothing. The loop still never touches `Chat` — this is its own
        // snapshot.
        sync_attachments(&mut self.ctx, &self.effects);
        sync_files(&mut self.ctx, &self.effects);
        // …and the numbered list over them, last, because it reads both. It re-derives
        // rather than re-numbers: `#N` and the `/w/in` name the pinned block promised
        // outlive the round they were promised in (fork F12, §12 T2–T3). Only for a turn
        // that has such a list — for any other, building one would be pure cost.
        if self.ctx.stages_files {
            self.ctx.sync_inputs();
        }

        // The turn was cancelled while tools were executing — what's
        // accumulated is already saved above, don't start the next round.
        if self.cancel.is_cancelled() {
            return Some(FinishReason::Cancelled);
        }
        None
    }

    /// Executes a round's calls and returns its records and tool messages, in
    /// the model's order. Three phases (docs/research/parallel-subagents.md
    /// §4.1): the ordinary calls resolve in the model's order, as they always
    /// did, while the round's `call_subagent` calls — its parallel group — are
    /// only announced and prepared ([`Self::resolve_round`]); the group runs,
    /// at most `tools.subagent_parallel` children at once, each card closing
    /// as its run lands ([`Self::run_group`]); the request history and the
    /// round's records are written in the model's order, so what the model
    /// and the chat see is exactly what a sequential round would have left.
    async fn execute_round(
        &mut self,
        calls: &[ApiToolCall],
        rewrite: bool,
    ) -> (Vec<ToolCallRecord>, Vec<Message>) {
        let (mut results, group, mut announced) = self.resolve_round(calls, rewrite).await;
        if !group.is_empty() {
            for (i, done) in self.run_group(group).await {
                self.effects.extend(done.effects);
                self.keep_tool_sample(done.prefill);
                // The card closes as its run lands, whatever the order.
                self.announce_result(&calls[i], &done.result.text, 0);
                announced[i] = true;
                results[i] = Some(done.result);
            }
        }
        let mut records: Vec<ToolCallRecord> = Vec::new();
        let mut tool_msgs: Vec<Message> = Vec::new();
        for (i, call) in calls.iter().enumerate() {
            let result = results[i]
                .take()
                .expect("every call of the round resolves in one of the phases");
            self.record_call(
                call,
                result,
                rewrite,
                announced[i],
                &mut records,
                &mut tool_msgs,
            )
            .await;
        }
        (records, tool_msgs)
    }

    /// Phase one: every ordinary call resolved in the model's order — a
    /// **segment** of consecutive concurrent-marked calls as one group at its
    /// position ([`Self::run_segment`], docs/research/concurrent-tools.md
    /// §4.2), everything else one at a time; every sub-agent call announced
    /// (its card opens) and prepared as a [`ChildSpec`], or refused on the
    /// spot when the call is malformed. The third value says which cards a
    /// segment already closed as its results landed.
    ///
    /// The loop itself answers two questions and nothing else: which of the
    /// three kinds the call at `i` is, and where the next one starts. What
    /// each kind *does* is a method of its own — the shape docs/lessons.md
    /// §10 prescribes for a dispatch whose arms carry preconditions.
    async fn resolve_round(
        &mut self,
        calls: &[ApiToolCall],
        rewrite: bool,
    ) -> (Vec<Option<CallResult>>, Vec<(usize, ChildSpec)>, Vec<bool>) {
        let mut results: Vec<Option<CallResult>> = calls.iter().map(|_| None).collect();
        let mut group: Vec<(usize, ChildSpec)> = Vec::new();
        let mut announced = vec![false; calls.len()];
        let mut i = 0;
        while i < calls.len() {
            let call = &calls[i];
            if self.is_group_call(call, rewrite) {
                self.queue_group_call(call, i, &mut group, &mut results);
                i += 1;
            } else if self.is_background_call(call, rewrite) {
                results[i] = Some(self.resolve_background_call(call));
                i += 1;
            } else {
                let end = self.segment_end(calls, i, rewrite);
                self.resolve_ordinary(&calls[i..end], i, rewrite, &mut results, &mut announced)
                    .await;
                i = end;
            }
        }
        (results, group, announced)
    }

    /// A member of the round's parallel group: the card opens and the
    /// [`ChildSpec`] joins the group under the call's own index, or a
    /// malformed call is refused on the spot and never reaches the group
    /// (docs/research/parallel-subagents.md §4.1).
    fn queue_group_call(
        &mut self,
        call: &ApiToolCall,
        at: usize,
        group: &mut Vec<(usize, ChildSpec)>,
        results: &mut [Option<CallResult>],
    ) {
        self.announce_call(call);
        match self.child_spec(&Self::call_args(call)) {
            Ok(spec) => group.push((at, spec)),
            Err(refusal) => results[at] = Some(refusal),
        }
    }

    /// A background run starts now and answers at once — its card opens and
    /// closes within the round, like any call's
    /// (docs/research/background-subagents.md §4.2, and
    /// docs/research/background-dialogues.md §4.2 for the scene's twin).
    fn resolve_background_call(&mut self, call: &ApiToolCall) -> CallResult {
        self.announce_call(call);
        self.report_progress(Some(&call.name));
        let args = Self::call_args(call);
        if call.name == crate::features::tools::dialogue::START_DIALOGUE_ID {
            self.start_background_dialogue(&args)
        } else {
            self.start_background(&args)
        }
    }

    /// Everything that is not a sub-agent call, at index `at` of the round:
    /// `span` is either the one call, resolved where it stands, or a segment
    /// of two or more run at once ([`Self::run_segment`]). The segment's
    /// results arrive in the model's order, so its effects land in that order
    /// too (fork F6): a sequential round and a concurrent one leave the same
    /// `Chat`. A segment closes its cards as the results land, which is what
    /// it marks in `announced`.
    async fn resolve_ordinary(
        &mut self,
        span: &[ApiToolCall],
        at: usize,
        rewrite: bool,
        results: &mut [Option<CallResult>],
        announced: &mut [bool],
    ) {
        if span.len() == 1 {
            results[at] = Some(self.resolve_call(&span[0], rewrite).await);
            return;
        }
        for (j, done) in self.run_segment(span).await {
            self.effects.extend(done.effects);
            self.keep_tool_sample(done.prefill);
            results[at + j] = Some(done.result);
            announced[at + j] = true;
        }
    }

    /// Whether `call` may be a member of a concurrent segment: a round not
    /// being discarded, a name the profile offers, and a tool whose author
    /// marked it (`Tool::concurrent`, docs/research/concurrent-tools.md §4.1).
    /// A control call, a sub-agent, a disabled name or a writer is none of
    /// these and resolves at its own position, as it always did.
    fn is_concurrent_call(&self, call: &ApiToolCall, rewrite: bool) -> bool {
        !rewrite
            && !control::is_control_tool(&call.name)
            && self.allowed_has(&call.name)
            && self.shared.registry.is_concurrent(&call.name)
    }

    /// The end (exclusive) of the segment that starts at `start`: the first
    /// later index whose call is not a concurrent member, or the round's end.
    /// At a width of one no segment is ever formed — `start + 1` — so the
    /// default of a local engine takes the sequential path bit for bit
    /// (docs/research/concurrent-tools.md §4.4).
    fn segment_end(&self, calls: &[ApiToolCall], start: usize, rewrite: bool) -> usize {
        if self.shared.concurrent_calls <= 1 {
            return start + 1;
        }
        let members = calls[start..]
            .iter()
            .take_while(|c| self.is_concurrent_call(c, rewrite))
            .count();
        start + members.max(1)
    }

    /// Runs a segment of concurrent calls (docs/research/concurrent-tools.md
    /// §4.3): every member's card opens first, the invocations run as futures
    /// inside this task — at most `concurrent_calls` of them polled at once —
    /// each card closing as its result lands, and the results come back in
    /// the model's order, with the index each had in the segment. The
    /// confirmation gate is not consulted: a marked tool is never dangerous,
    /// which a registry test pins.
    async fn run_segment(&self, calls: &[ApiToolCall]) -> Vec<(usize, CallDone)> {
        let names: Vec<&str> = calls.iter().map(|c| c.name.as_str()).collect();
        self.report_progress(Some(&names.join(", ")));
        for call in calls {
            self.announce_call(call);
        }
        let width = self.shared.concurrent_calls.max(1) as usize;
        // The futures are made by calling the `async fn` directly rather than
        // inside an `async move` closure: the closure form captures `&self`
        // under a higher-ranked lifetime the spawned task cannot name
        // ("implementation of `FnOnce` is not general enough").
        let members: Vec<_> = calls
            .iter()
            .enumerate()
            .map(|(j, call)| self.invoke_member(j, call))
            .collect();
        let mut done: Vec<(usize, CallDone)> = futures_util::stream::iter(members)
            .buffer_unordered(width)
            .collect()
            .await;
        done.sort_by_key(|(j, _)| *j);
        done
    }

    /// A tool's own request as part of the turn's largest prefill sample
    /// (docs/research/page-summary-usage.md §3.2): the page summary's stream
    /// is a stream of the turn (spec §9.3.1), so its timing competes with the
    /// rounds' for the one note. Folded into the round that carried it — a
    /// round always precedes its tools — and dropped where no round reported
    /// a usage, since a provider without one sends no timing either.
    fn keep_tool_sample(&mut self, sample: Option<crate::shared::api::contract::Prefill>) {
        if let Some(usage) = &mut self.last_usage {
            crate::shared::api::contract::Prefill::keep_larger(&mut usage.prefill, sample);
        }
    }

    /// One member of a segment: the invocation under the same `select!` with
    /// the turn's cancellation token the sequential path uses, the outcome
    /// mapped the same way, and the card closed as the result lands. The card
    /// carries the tool's own image count — none of the marked tools returns
    /// images, and the record keeps the prepared count as always. Returns the
    /// member's index in the segment with its result.
    async fn invoke_member(&self, j: usize, call: &ApiToolCall) -> (usize, CallDone) {
        let args = Self::call_args(call);
        let invoked = tokio::select! {
            _ = self.cancel.cancelled() => None,
            res = self.shared.registry.invoke(&call.name, &self.ctx, args) => Some(res),
        };
        let done = match invoked {
            None => CallDone {
                result: self.ctx.loc.t("loop.tool_cancelled").to_string().into(),
                effects: Vec::new(),
                prefill: None,
            },
            Some(Ok(outcome)) => CallDone {
                result: CallResult {
                    text: outcome.result,
                    images: outcome.images,
                    subagent: None,
                },
                effects: outcome.effects,
                prefill: outcome.prefill,
            },
            Some(Err(err)) => CallDone {
                result: self
                    .ctx
                    .loc
                    .tf(
                        "loop.tool_error",
                        &[("name", &call.name), ("err", &err.to_string())],
                    )
                    .into(),
                effects: Vec::new(),
                prefill: None,
            },
        };
        self.announce_result(call, &done.result.text, done.result.images.len());
        (j, done)
    }

    /// Phase two: the group's children as futures inside this task, at most
    /// `tools.subagent_parallel` polled at once, yielded in completion order
    /// with the index each had in the round.
    async fn run_group(&self, group: Vec<(usize, ChildSpec)>) -> Vec<(usize, CallDone)> {
        let width = self.shared.subagent.parallel.max(1) as usize;
        let shared = self.shared;
        let loc = self.ctx.loc;
        futures_util::stream::iter(
            group
                .into_iter()
                .map(|(i, spec)| async move { (i, run_child(shared, loc, spec).await) }),
        )
        .buffer_unordered(width)
        .collect()
        .await
    }

    /// One call's arguments as the tools take them. A no-argument call gives an
    /// empty argument string — stored as an empty OBJECT, not `Null`: otherwise
    /// serializing the history entry gives `"null"`, and strict providers
    /// (Anthropic) expect an object in `input` (see shared/api/anthropic/wire.rs).
    /// An object is also safer for invoke (deserializing a struct from `null`
    /// panics).
    fn call_args(call: &ApiToolCall) -> serde_json::Value {
        serde_json::from_str(&call.arguments).unwrap_or_else(|_| serde_json::json!({}))
    }

    /// Opens a call's card before it runs (spec §11.3).
    fn announce_call(&self, call: &ApiToolCall) {
        self.sink().send(AppEvent::ToolCallStarted {
            generation_id: self.shared.id,
            call_id: call.id.clone(),
            name: call.name.clone(),
            arguments: call.arguments.clone(),
        });
    }

    /// Closes a call's card with its result.
    fn announce_result(&self, call: &ApiToolCall, result: &str, images: usize) {
        self.sink().send(AppEvent::ToolCall {
            generation_id: self.shared.id,
            call_id: call.id.clone(),
            name: call.name.clone(),
            arguments: call.arguments.clone(),
            result: result.to_string(),
            images,
        });
    }

    /// Resolves one ordinary call of the round: the card opens, the result
    /// comes from [`Self::resolve_call_result`] (gates, confirmation, the
    /// invocation). A control call and a call skipped by a rewrite never get
    /// a card.
    async fn resolve_call(&mut self, call: &ApiToolCall, rewrite: bool) -> CallResult {
        let args = Self::call_args(call);
        let is_control = control::is_control_tool(&call.name);
        self.report_progress(Some(&call.name));
        if !is_control && !rewrite {
            self.announce_call(call);
        }
        self.resolve_call_result(call, &args, is_control, rewrite)
            .await
    }

    /// Whether the engine takes images — asked **once per loop**, bounded, and interruptible.
    ///
    /// The answer is a property of the server and the model behind it, so it cannot change
    /// inside a turn; asking, though, is a real HTTP round trip on the turn's critical path.
    /// `OpenAiClient::vision` fetches `/props` and nothing memoizes it, so a turn whose
    /// rounds each returned an image paid the round trip each time — up to `max_tool_rounds`
    /// of them.
    ///
    /// Two ways it could stop the turn outright, both closed here. The engine client sets a
    /// **connect** timeout and no request timeout — right for a stream that may take
    /// minutes, wrong for a probe — so a server that accepted the connection and then
    /// stalled the response waited for ever. And this was a bare `await`, outside the loop's
    /// cancellation: `Esc` could not end it, and the turn sat in `Cancelling`.
    ///
    /// A probe that does not answer in time is [`VisionSupport::Unknown`], which is already
    /// the answer for everything that is not llama.cpp, so nothing about what gets sent
    /// changes — the turn simply stops waiting to find out.
    async fn vision(&mut self) -> VisionSupport {
        if let Some(known) = self.vision {
            return known;
        }
        let answer = tokio::select! {
            biased;
            () = self.cancel.cancelled() => VisionSupport::Unknown,
            answered = tokio::time::timeout(VISION_PROBE, self.ctx.engine.vision()) => {
                answered.unwrap_or(VisionSupport::Unknown)
            }
        };
        self.vision = Some(answer);
        answer
    }

    /// Records one resolved call: the tool message into the request history,
    /// the record and the domain tool message for the round — and closes the
    /// card, unless the round already did as the result landed (`announced`,
    /// the parallel group's case).
    async fn record_call(
        &mut self,
        call: &ApiToolCall,
        result: CallResult,
        rewrite: bool,
        announced: bool,
        records: &mut Vec<ToolCallRecord>,
        tool_msgs: &mut Vec<Message>,
    ) {
        let CallResult {
            text: mut result,
            images,
            subagent,
        } = result;
        let is_control = control::is_control_tool(&call.name);
        // Nothing the model cannot take is sent, and nothing withheld goes unsaid
        // (docs/history/sandbox-file-exchange.md §11 S8): a result that promised an image the
        // model never receives gets a chart described that it has not seen (§10). What
        // became of each image is said here and only here, since only here is it known.
        let offered = images.len();
        let entries: Vec<Option<String>> = images.iter().map(|i| i.entry.clone()).collect();
        let (images, fates) = if offered > 0 && self.vision().await == VisionSupport::Unsupported {
            (Vec::new(), vec![ImageFate::NoVision; offered])
        } else {
            // Decoded and downscaled here, once, so the same prepared bytes go into the
            // request and into the stored message — the object the model sees and the
            // object the chat keeps must be one (spec §9.10).
            let (prepared, taken) = prepare_tool_images(
                images,
                self.shared.image_cfg,
                std::mem::take(&mut self.image_names),
            )
            .await;
            self.image_names = taken;
            let fates = prepared
                .iter()
                .map(|p| match p {
                    Some(_) => ImageFate::Shown,
                    None => ImageFate::Dropped,
                })
                .collect();
            (prepared.into_iter().flatten().collect(), fates)
        };
        say_image_fates(&mut result, self.ctx.loc, &entries, &fates);
        // A UI tool block — only for regular executed calls (the internal
        // followup/rewrite ones, and ones skipped during a rewrite, don't get one).
        if !is_control && !rewrite && !announced {
            self.announce_result(call, &result, images.len());
        }
        self.request.messages.push(
            ApiMessage::tool(&call.id, &result).with_images(
                images
                    .iter()
                    .enumerate()
                    .map(|(i, image)| {
                        crate::shared::api::ApiImage::new(
                            image.mime.clone(),
                            &image.data,
                            Some(self.ctx.loc.tf(
                                "prompt.images.label",
                                &[("n", &(i + 1).to_string()), ("name", &image.name)],
                            )),
                        )
                    })
                    .collect(),
            ),
        );
        records.push(ToolCallRecord {
            id: call.id.clone(),
            name: call.name.clone(),
            arguments: Self::call_args(call),
            result: Some(result.clone()),
            // The thought signature (Gemini 3) is persisted — needed on history replay.
            thought_signature: call.thought_signature.clone(),
            images: images.len(),
            subagent,
        });
        tool_msgs.push(tool_message(call, result).with_images(images));
    }

    /// One call's result text: the disabled/control/rewrite gates, the
    /// confirmation round-trip (spec §9.8), and the invocation under a
    /// `select!` with the turn's cancellation token — moved verbatim from the
    /// loop body.
    async fn resolve_call_result(
        &mut self,
        call: &ApiToolCall,
        args: &serde_json::Value,
        is_control: bool,
        rewrite: bool,
    ) -> CallResult {
        if !self.allowed_has(&call.name) {
            // Protection: the tool is disabled globally/in the profile.
            self.ctx
                .loc
                .tf("loop.tool_disabled", &[("name", &call.name)])
                .into()
        } else if is_control {
            // A control tool: the result is "permission" (the model will
            // see it in the next round). Executed by the loop, not
            // through the registry.
            control::control_permission_text(&call.name, self.ctx.loc).into()
        } else if rewrite {
            // This round is being discarded — side-effect tools aren't executed.
            self.ctx.loc.t("loop.rewrite_skipped").to_string().into()
        } else if let Some(refusal) = confirm_call(
            ConfirmGate {
                enabled: self.shared.confirm_dangerous,
                registry: &self.shared.registry,
                evt_tx: &self.shared.evt_tx,
                cancel: &self.cancel,
                id: self.shared.id,
                loc: self.ctx.loc,
                ctx: &self.ctx,
            },
            call,
            &self.shared.confirm,
        )
        .await
        {
            // Declined, or the turn was cancelled while the popup was
            // open. Either way the loop carries on and the model is
            // told (fork F5) — ending the turn here would throw away
            // the text already streamed.
            refusal.into()
        } else if call.name == CALL_SUBAGENT_ID {
            // A loop-executed tool (spec §9.3.2): the sub-agent is a nested
            // loop over this turn's shared part, not a registry call.
            self.run_subagent(args).await
        } else if call.name == START_SUBAGENT_ID {
            // Reached only below the top of the turn (the round's own calls
            // resolve in `resolve_round`): refused there, no nesting.
            self.start_background(args)
        } else if call.name == crate::features::tools::dialogue::START_DIALOGUE_ID {
            // Reached only below the top of the turn, like its sibling above.
            self.start_background_dialogue(args)
        } else if call.name == crate::features::tools::dialogue::RUN_DIALOGUE_ID {
            // The second loop-executed tool (spec §9.13): a directed dialogue
            // of two personas, driven by this loop over the same shared part.
            self.run_dialogue(args).await
        } else {
            // Execution under a `select!` with the cancellation token: Esc
            // doesn't wait for a long-running tool (MCP/network) to finish.
            // Tools that read `ctx.cancel` terminate themselves (MCP sends
            // the server notifications/cancelled); this is a safety net
            // for the rest.
            let invoked = tokio::select! {
                _ = self.cancel.cancelled() => None,
                res = self.shared.registry.invoke(&call.name, &self.ctx, args.clone()) => Some(res),
            };
            match invoked {
                None => self.ctx.loc.t("loop.tool_cancelled").to_string().into(),
                Some(Ok(outcome)) => {
                    self.effects.extend(outcome.effects);
                    self.keep_tool_sample(outcome.prefill);
                    CallResult {
                        text: outcome.result,
                        images: outcome.images,
                        subagent: None,
                    }
                }
                Some(Err(err)) => self
                    .ctx
                    .loc
                    .tf(
                        "loop.tool_error",
                        &[("name", &call.name), ("err", &err.to_string())],
                    )
                    .into(),
            }
        }
    }
}

impl TurnLoop<'_> {
    /// Runs a sub-agent (spec §9.3.2, docs/research/subagent-chats.md
    /// §3.2–§3.4) — the single-call path, reached only where a
    /// `call_subagent` meets the loop outside a round's parallel group: a loop
    /// below the top, which refuses the name whatever the allowed set says.
    /// A round's own calls go through [`Self::child_spec`] and [`run_child`]
    /// as a group in [`Self::tool_round`].
    async fn run_subagent(&mut self, args: &serde_json::Value) -> CallResult {
        match self.child_spec(args) {
            Err(refusal) => refusal,
            Ok(spec) => {
                let done = run_child(self.shared, self.ctx.loc, spec).await;
                self.effects.extend(done.effects);
                done.result
            }
        }
    }

    /// Whether a call of this round belongs to its parallel group
    /// (docs/research/parallel-subagents.md §4.1): a `call_subagent` the
    /// profile offers, at the top of the turn, in a round that is not being
    /// discarded. Everything else — every other tool, a nested loop's
    /// refusal, a switched-off tool's refusal — takes the ordinary path.
    fn is_group_call(&self, call: &ApiToolCall, rewrite: bool) -> bool {
        call.name == CALL_SUBAGENT_ID && self.depth == 0 && !rewrite && self.allowed_has(&call.name)
    }

    /// Whether a call of this round starts a **background** run —
    /// `start_subagent` (docs/research/background-subagents.md §4.1) or
    /// `start_dialogue` (background-dialogues.md §4.2): the same three
    /// conditions as the group's, for the twins the profile offers only
    /// when `tools.subagent_background` is on.
    fn is_background_call(&self, call: &ApiToolCall, rewrite: bool) -> bool {
        (call.name == START_SUBAGENT_ID
            || call.name == crate::features::tools::dialogue::START_DIALOGUE_ID)
            && self.depth == 0
            && !rewrite
            && self.allowed_has(&call.name)
    }

    /// Starts a background run (docs/research/background-subagents.md
    /// §4.2): the spec a group child would get, over a token of its own —
    /// not the turn's, so `Esc` ends the turn and not the run — handed to
    /// the orchestrator as progress to spawn outside this task. The call's
    /// result is the *started* line with the transcript's address, and the
    /// record lands with the turn carrying a placeholder run the landing
    /// fills in. Refused past the cap (`tools.subagent_background_max`),
    /// with the number, and below the top of the turn.
    fn start_background(&mut self, args: &serde_json::Value) -> CallResult {
        let loc = self.ctx.loc;
        let spec = match self.child_spec_with(args, START_SUBAGENT_ID, CancellationToken::new()) {
            Ok(spec) => spec,
            Err(refusal) => return refusal,
        };
        if let Err(out) = self.shared.background.take() {
            return loc
                .tf(
                    "tool.start_subagent.result.too_many",
                    &[("n", &out.to_string())],
                )
                .into();
        }
        let placeholder = SubagentRun {
            id: spec.run_id,
            kind: RunKind::Subagent,
            title: spec.parsed.initial_title(),
            renamed_manually: false,
            name: spec.parsed.name.clone(),
            created_at: chrono::Utc::now(),
            finished_at: None,
            system_message: spec.parsed.system_message.clone(),
            sampling_override: None,
            messages: vec![spec.user.clone()],
            outcome: None,
            tokens: 0,
            participants: Vec::new(),
            background: true,
        };
        let address = crate::features::chat_links::uri(spec.run_id);
        let text = loc.tf(
            "tool.start_subagent.result.started",
            &[
                ("name", &spec.parsed.initial_title()),
                ("address", &address),
            ],
        );
        self.progress(TurnProgress::BackgroundStart(Box::new(BackgroundStart {
            spec: RunSpec::Subagent(Box::new(spec)),
            parts: SharedParts::of(self.shared),
        })));
        CallResult {
            text,
            images: Vec::new(),
            subagent: Some(Box::new(placeholder)),
        }
    }

    /// Starts a **background dialogue** (spec §9.13,
    /// docs/research/background-dialogues.md §4.2): the scene is parsed here
    /// so the model gets a straight refusal for a malformed call and the
    /// *started* line can name the transcript, the director's inputs are
    /// snapshotted (fork F3 — the persona and the conversation brief as they
    /// are at the call), and the run leaves the turn as progress. The record
    /// lands with the turn as a `kind: Dialogue` placeholder the landing
    /// fills in. Refused past the shared cap (`tools.subagent_background_max`,
    /// fork F7) and below the top of the turn.
    fn start_background_dialogue(&mut self, args: &serde_json::Value) -> CallResult {
        use crate::features::tools::dialogue::{self, START_DIALOGUE_ID};
        let loc = self.ctx.loc;
        let parsed = match dialogue::DialogueArgs::parse(args, loc) {
            Ok(parsed) => parsed,
            Err(err) => {
                return loc
                    .tf(
                        "loop.tool_error",
                        &[("name", START_DIALOGUE_ID), ("err", &err.to_string())],
                    )
                    .into();
            }
        };
        if self.depth > 0 {
            return loc
                .tf("loop.tool_disabled", &[("name", START_DIALOGUE_ID)])
                .into();
        }
        if let Err(out) = self.shared.background.take() {
            return loc
                .tf(
                    "tool.start_subagent.result.too_many",
                    &[("n", &out.to_string())],
                )
                .into();
        }
        // The participants' lines run under the chat's sampling; the scene
        // caps each of them itself, exactly as the foreground driver does.
        let spec = DialogueSpec {
            run_id: Uuid::new_v4(),
            persona: self.ctx.system_message.clone(),
            brief: conversation_brief(
                self.shared.compaction_summary.as_deref(),
                &self.request.messages,
                loc,
            ),
            sampling: self.ctx.effective_sampling.clone(),
            cancel: CancellationToken::new(),
            loc,
            args: parsed,
        };
        let placeholder = spec.placeholder();
        let text = loc.tf(
            "tool.start_dialogue.result.started",
            &[
                ("name", &placeholder.title),
                ("address", &crate::features::chat_links::uri(spec.run_id)),
            ],
        );
        self.progress(TurnProgress::BackgroundStart(Box::new(BackgroundStart {
            spec: RunSpec::Dialogue(Box::new(spec)),
            parts: SharedParts::of(self.shared),
        })));
        CallResult {
            text,
            images: Vec::new(),
            subagent: Some(Box::new(placeholder)),
        }
    }

    /// Everything a child needs, built by the parent before the child starts
    /// (research §3.3): the parsed call; the turn's tools minus the withheld
    /// ones, in the turn's order, with their schemas; the request over the
    /// parent's environment under the child's persona and reply cap; a context
    /// of its own; a cancellation token under the parent's, so `Esc` on the
    /// turn ends the child while a timeout ends the child alone. `Err` is the
    /// result to hand the model instead of a run: a malformed call, or a loop
    /// below the top — no nesting, twice over (research §3.2).
    fn child_spec(&self, args: &serde_json::Value) -> Result<ChildSpec, CallResult> {
        self.child_spec_with(args, CALL_SUBAGENT_ID, self.cancel.child_token())
    }

    /// [`Self::child_spec`] for either delegation tool: `tool` names the
    /// caller in a refusal, `cancel` is the run's token — a child of the
    /// turn's for a group child, a fresh one for a background run.
    fn child_spec_with(
        &self,
        args: &serde_json::Value,
        tool: &str,
        cancel: CancellationToken,
    ) -> Result<ChildSpec, CallResult> {
        let loc = self.ctx.loc;
        let parsed = SubagentArgs::parse(args, loc).map_err(|err| {
            CallResult::from(loc.tf(
                "loop.tool_error",
                &[("name", tool), ("err", &err.to_string())],
            ))
        })?;
        if self.depth > 0 {
            return Err(loc.tf("loop.tool_disabled", &[("name", tool)]).into());
        }
        let limits = self.shared.subagent;
        // A background run has no one to ask: while the user wants every
        // dangerous call confirmed, it is not offered those tools at all, so it
        // plans without them instead of acting unasked
        // (docs/research/safe-defaults.md D7).
        let unconfirmable = tool == START_SUBAGENT_ID && self.shared.confirm_dangerous;
        let allowed: Vec<ToolId> = self
            .allowed
            .iter()
            .filter(|t| !withheld_from_subagent(t))
            .filter(|t| {
                !(unconfirmable
                    && self
                        .shared
                        .registry
                        .get(t)
                        .is_some_and(|tool| tool.danger()))
            })
            .cloned()
            .collect();
        let schemas = self.shared.registry.schemas_for(&allowed, loc);
        // The reply cap on top of the effective sampling, as the tool-less
        // version applied it.
        let mut sampling = self.ctx.effective_sampling.clone();
        sampling.max_tokens = Some(
            sampling
                .max_tokens
                .map_or(limits.max_tokens, |m| m.min(limits.max_tokens)),
        );
        // The child's context is the parent's — environment, scope, journal —
        // under its own persona and knobs, with no folded history to read back
        // and the token the caller chose (see `child_spec_with`).
        let mut ctx = self.ctx.clone();
        ctx.system_message = parsed.system_message.clone();
        ctx.effective_sampling = sampling.clone();
        ctx.last_user_message_at = Some(chrono::Utc::now());
        ctx.history = None;
        ctx.cancel = cancel.clone();
        // Which attached files have an index — the attachment block names
        // `attachment_search` only for those (spec §9.7), same as the parent.
        let indexed: Vec<Uuid> = if ctx.attachments.is_empty() {
            Vec::new()
        } else {
            ctx.storage
                .db()
                .attachment_indexed_ids(ctx.chat_id)
                .unwrap_or_default()
        };
        // The chat's files as the child sees them (§12 T13): its context is the parent's,
        // so the list is the same one — and the block is built for a child that actually
        // offers the tool, which the parent's turn may have withheld.
        // Literally the parent's list, not a re-derivation of it: the child's context is
        // the parent's clone, so `stage` will resolve against `ctx.inputs`, and a block
        // numbered afresh here would be telling the child a different `#N` than the one
        // its own tool honours (fork F12).
        let inputs: &[crate::features::chat_inputs::ChatInput] = if ctx.stages_files
            && allowed
                .iter()
                .any(|t| t == crate::features::tools::PYTHON_EXEC_ID)
        {
            &ctx.inputs
        } else {
            &[]
        };
        let user = Message::user(parsed.message.clone());
        let request = build_request_in(
            &parsed.system_message,
            std::slice::from_ref(&user),
            &RequestEnv {
                attachments: &ctx.attachments,
                workspace: ctx.workspace.as_ref(),
                compaction: None,
            },
            sampling,
            schemas,
            &PromptContext {
                attachments: &ctx.attachment_cfg,
                // Only `enabled` is read, and only by the `&Chat` wrapper a
                // sub-agent does not go through: its compaction is `None` above.
                compaction: &crate::shared::config::CompactionSettings::default(),
                indexed: &indexed,
                files: inputs,
                // The child runs in the mode its parent's context carries.
                python_dirs: ctx.python_mode.dirs(),
                history_tools: false,
                offered_tools: &allowed,
                loc,
            },
        );
        Ok(ChildSpec {
            parsed,
            // The run's identity, minted before it runs: the list shows the
            // transcript under this id from the first round on, and the
            // landed record keeps it (docs/subagent-live.md §3.1).
            run_id: Uuid::new_v4(),
            allowed,
            request,
            ctx,
            cancel,
            user,
            limits,
            max_rounds: self.shared.max_rounds,
            depth: self.depth + 1,
        })
    }
}

/// What a child needs to run — see [`TurnLoop::child_spec`]. Owns everything
/// of its own, so several can be built by one parent and run at once — or
/// be carried out of the turn altogether (a background run,
/// [`BackgroundStart`]): opaque to the orchestrator, which only hands it
/// to [`spawn_background_run`].
pub(super) struct ChildSpec {
    parsed: SubagentArgs,
    run_id: Uuid,
    allowed: Vec<ToolId>,
    request: ChatRequest,
    ctx: ToolContext,
    cancel: CancellationToken,
    user: Message,
    limits: SubagentLimits,
    max_rounds: u32,
    depth: u8,
}

/// What a child leaves for its parent to record: the call's result (the
/// reply text with its trailer, and the run for the record) and the effects
/// addressed to the parent's chat (research §3.4).
struct CallDone {
    result: CallResult,
    effects: Vec<ChatEffect>,
    /// The engine's timing of a request the call made on its own — a page
    /// summary's — for the turn's largest sample (page-summary-usage §3.2).
    prefill: Option<crate::shared::api::contract::Prefill>,
}

/// A background run about to start (docs/research/background-subagents.md
/// §4.2): the child's spec over a token of its own, and the parts of the
/// turn's shared state a run needs — the engine, the registry, the limits —
/// as `Arc`s and copies, so the run owes the turn nothing once spawned.
pub(super) struct BackgroundStart {
    spec: RunSpec,
    parts: SharedParts,
}

/// What a background run *is* (docs/research/background-dialogues.md F5): a
/// sub-agent over its `ChildSpec`, or a directed scene over its own. The two
/// share every later step — the seat, the landing by id, the notification,
/// the stop — so only the start and the spawn branch.
pub(super) enum RunSpec {
    Subagent(Box<ChildSpec>),
    Dialogue(Box<DialogueSpec>),
}

/// A background dialogue's start (F3): the parsed scene plus the director's
/// inputs **snapshotted at the call** — the parent's persona and the folded
/// conversation brief — because a scene ending twenty minutes later has no
/// turn left to read them from.
pub(super) struct DialogueSpec {
    run_id: Uuid,
    args: crate::features::tools::dialogue::DialogueArgs,
    persona: String,
    brief: String,
    sampling: SamplingConfig,
    cancel: CancellationToken,
    loc: &'static crate::shared::i18n::Locale,
}

impl BackgroundStart {
    /// The run's id — minted with the spec, the placeholder's and the
    /// landed record's.
    pub(super) fn run_id(&self) -> Uuid {
        match &self.spec {
            RunSpec::Subagent(spec) => spec.run_id,
            RunSpec::Dialogue(spec) => spec.run_id,
        }
    }

    /// The run as it will land, before it runs: what the orchestrator's
    /// mirror starts from (the same shape `ChildStarted` carries).
    pub(super) fn placeholder(&self) -> SubagentRun {
        match &self.spec {
            RunSpec::Subagent(spec) => SubagentRun {
                id: spec.run_id,
                kind: RunKind::Subagent,
                title: spec.parsed.initial_title(),
                renamed_manually: false,
                name: spec.parsed.name.clone(),
                created_at: chrono::Utc::now(),
                finished_at: None,
                system_message: spec.parsed.system_message.clone(),
                sampling_override: None,
                messages: vec![spec.user.clone()],
                outcome: None,
                tokens: 0,
                participants: Vec::new(),
                background: true,
            },
            RunSpec::Dialogue(spec) => spec.placeholder(),
        }
    }
}

impl DialogueSpec {
    /// The scene as it will land before its first line: the opening the
    /// caller authored, the two personas, `kind: Dialogue` — the shape
    /// `DialogueCtx::run_parsed` reports through `ChildStarted`.
    fn placeholder(&self) -> SubagentRun {
        SubagentRun {
            id: self.run_id,
            kind: RunKind::Dialogue,
            title: self.args.initial_title(self.loc),
            renamed_manually: false,
            name: None,
            created_at: chrono::Utc::now(),
            finished_at: None,
            system_message: String::new(),
            sampling_override: None,
            messages: vec![if self.args.opening_by_a {
                Message::assistant(self.args.opening.clone())
            } else {
                Message::user(self.args.opening.clone())
            }],
            outcome: None,
            tokens: 0,
            participants: vec![
                crate::entities::subagent::Participant {
                    name: self.args.a.name.clone(),
                    system_message: self.args.a.system_message.clone(),
                },
                crate::entities::subagent::Participant {
                    name: self.args.b.name.clone(),
                    system_message: self.args.b.system_message.clone(),
                },
            ],
            background: true,
        }
    }
}

/// The cloneable half of [`TurnShared`] — what a background run takes with
/// it out of the turn.
struct SharedParts {
    backend: Arc<dyn EngineBackend>,
    registry: Arc<ToolRegistry>,
    image_cfg: crate::shared::config::ImageSettings,
    max_rounds: u32,
    workspace_max_rounds: u32,
    subagent: SubagentLimits,
    concurrent_calls: u32,
    engine_mode: ServerMode,
    continuation_supported: bool,
    /// The endpoint's published sampling fields, carried for the snapshot the
    /// dialogue's messages record (docs/history/gateway-capabilities.md §4, G3(ii)).
    endpoint_sampling_fields: Option<std::sync::Arc<[String]>>,
    model_name: Option<String>,
    ui_loc: &'static crate::shared::i18n::Locale,
    compaction_enabled: bool,
    compaction_summary: Option<String>,
    background: Arc<BackgroundSlots>,
}

impl SharedParts {
    fn of(shared: &TurnShared) -> Self {
        Self {
            backend: shared.backend.clone(),
            registry: shared.registry.clone(),
            image_cfg: shared.image_cfg,
            max_rounds: shared.max_rounds,
            workspace_max_rounds: shared.workspace_max_rounds,
            subagent: shared.subagent,
            concurrent_calls: shared.concurrent_calls,
            engine_mode: shared.engine_mode,
            continuation_supported: shared.continuation_supported,
            endpoint_sampling_fields: shared.endpoint_sampling_fields.clone(),
            model_name: shared.model_name.clone(),
            ui_loc: shared.ui_loc,
            compaction_enabled: shared.compaction_enabled,
            compaction_summary: shared.compaction_summary.clone(),
            background: shared.background.clone(),
        }
    }
}

/// How many background runs are out, against the cap
/// (`tools.subagent_background_max`, docs/research/background-subagents.md
/// §4.8). Owned by the orchestrator, shared with every turn: a loop takes a
/// slot when it starts a run, the run gives it back when it ends — so two
/// siblings of one round cannot both pass a cap of one.
#[derive(Debug)]
pub(super) struct BackgroundSlots {
    out: std::sync::atomic::AtomicU32,
    max: std::sync::atomic::AtomicU32,
}

impl BackgroundSlots {
    pub(super) fn new(max: u32) -> Self {
        Self {
            out: std::sync::atomic::AtomicU32::new(0),
            max: std::sync::atomic::AtomicU32::new(max.max(1)),
        }
    }

    /// The cap, as the settings say now (a settings edit lowers or raises
    /// it for the *next* start; runs already out are not ended).
    pub(super) fn set_max(&self, max: u32) {
        self.max
            .store(max.max(1), std::sync::atomic::Ordering::SeqCst);
    }

    /// Takes a slot, or says how many are out when none is free.
    fn take(&self) -> Result<(), u32> {
        use std::sync::atomic::Ordering::SeqCst;
        let max = self.max.load(SeqCst);
        let mut out = self.out.load(SeqCst);
        loop {
            if out >= max {
                return Err(out);
            }
            match self.out.compare_exchange(out, out + 1, SeqCst, SeqCst) {
                Ok(_) => return Ok(()),
                Err(seen) => out = seen,
            }
        }
    }

    fn release(&self) {
        use std::sync::atomic::Ordering::SeqCst;
        let _ = self
            .out
            .fetch_update(SeqCst, SeqCst, |n| Some(n.saturating_sub(1)));
    }
}

/// What a background run says to the orchestrator: its stream and rounds
/// while it runs (the same steps a turn's child sends, keyed by the run's
/// own generation id), and its end — the landed run, the result text the
/// notification quotes, and the effects for the parent chat.
pub(super) enum BackgroundMessage {
    Progress {
        generation: Uuid,
        progress: TurnProgress,
    },
    Done {
        generation: Uuid,
        run: Box<SubagentRun>,
        result: String,
        effects: Vec<ChatEffect>,
    },
}

/// What the orchestrator adds to a [`BackgroundStart`] to spawn it
/// (docs/research/background-subagents.md §4.2): the run's own generation
/// id, the app-wide session budget, and the channels.
pub(super) struct BackgroundSpawn {
    pub(super) generation: Uuid,
    pub(super) sessions: Arc<SessionBudget>,
    pub(super) evt_tx: UnboundedSender<AppEvent>,
    pub(super) bg_tx: UnboundedSender<BackgroundMessage>,
}

/// Spawns a background run as a task of its own: a [`TurnShared`] built
/// from the parts the turn handed over — no confirmation round trip (its
/// calls run as with `confirm_dangerous` off, research fork F3, the user's
/// decision), fresh counters, the app's budget — and the same [`run_child`]
/// a group child runs under, so everything a sub-agent is, a background
/// one is. Returns the run's cancellation token, which the orchestrator
/// keeps for `/subagents stop`, the deletion of the spawning exchange and
/// `Quit`.
pub(super) fn spawn_background_run(
    start: BackgroundStart,
    spawn: BackgroundSpawn,
) -> CancellationToken {
    let BackgroundStart { mut spec, parts } = start;
    let BackgroundSpawn {
        generation,
        sessions,
        evt_tx,
        bg_tx,
    } = spawn;
    let cancel = match &mut spec {
        RunSpec::Subagent(spec) => {
            // The run streams under the app's budget, like the turn it left.
            spec.ctx.sessions = Some(sessions.clone());
            spec.cancel.clone()
        }
        // A scene's own streams are priced by `DialogueCtx` against the same
        // budget (F4); its participants have no tools, so there is no tool
        // context to hand one to.
        RunSpec::Dialogue(spec) => spec.cancel.clone(),
    };
    // The run's progress goes on a channel of its own and is forwarded under
    // its generation id, so the orchestrator can tell it from the turn's;
    // its end follows on the same path, after the channel has closed, so
    // the landing never overtakes the last filed round.
    let (done_tx, mut done_rx) = tokio::sync::mpsc::unbounded_channel::<GenMessage>();
    let (end_tx, end_rx) = tokio::sync::oneshot::channel::<BackgroundMessage>();
    let forward = bg_tx;
    tokio::spawn(async move {
        while let Some(message) = done_rx.recv().await {
            if let GenMessage::Progress { progress, .. } = message {
                let _ = forward.send(BackgroundMessage::Progress {
                    generation,
                    progress,
                });
            }
        }
        if let Ok(end) = end_rx.await {
            let _ = forward.send(end);
        }
    });
    // Nothing ever asks: the gate is off, and the receiver is never read.
    let (_confirm_tx, confirm_rx) = tokio::sync::mpsc::unbounded_channel();
    let slots = parts.background.clone();
    let shared = TurnShared {
        backend: parts.backend,
        registry: parts.registry,
        confirm_dangerous: false,
        image_cfg: parts.image_cfg,
        confirm: tokio::sync::Mutex::new(ConfirmState {
            rx: confirm_rx,
            allowed_for_turn: HashSet::new(),
        }),
        counters: TurnCounters::default(),
        id: generation,
        max_rounds: parts.max_rounds,
        workspace_max_rounds: parts.workspace_max_rounds,
        subagent: parts.subagent,
        sessions,
        concurrent_calls: parts.concurrent_calls,
        engine_mode: parts.engine_mode,
        continuation_supported: parts.continuation_supported,
        endpoint_sampling_fields: parts.endpoint_sampling_fields.clone(),
        model_name: parts.model_name,
        ui_loc: parts.ui_loc,
        evt_tx,
        done_tx,
        compaction_enabled: parts.compaction_enabled,
        compaction_summary: parts.compaction_summary,
        background: parts.background,
    };
    tokio::spawn(async move {
        let (result, effects) = match spec {
            RunSpec::Subagent(spec) => {
                let loc = spec.ctx.loc;
                // A background run's landing offers no sample: the child's
                // stays with its loop (page-summary-usage §7).
                let CallDone {
                    result, effects, ..
                } = run_child(&shared, loc, *spec).await;
                (result, effects)
            }
            // The scene runs through the very same driver the turn's own
            // `run_dialogue` enters, over a context built from the snapshot
            // (docs/research/background-dialogues.md §4.2) — so a background
            // scene and a foreground one cannot drift apart.
            RunSpec::Dialogue(spec) => {
                let DialogueSpec {
                    run_id,
                    args,
                    persona,
                    brief,
                    sampling,
                    cancel,
                    loc,
                } = *spec;
                let result = DialogueCtx {
                    shared: &shared,
                    loc,
                    sampling,
                    persona,
                    brief,
                    cancel,
                    depth: 0,
                    run_id,
                }
                .run_parsed(args)
                .await;
                (result, Vec::new())
            }
        };
        slots.release();
        let run = result
            .subagent
            .expect("a background run always lands a run on its result");
        let _ = end_tx.send(BackgroundMessage::Done {
            generation,
            run,
            result: result.text,
            effects,
        });
        // Dropping the shared part closes the run's progress channel; the
        // forwarder then delivers the end above, last.
        drop(shared);
    });
    cancel
}

/// Runs one sub-agent over the turn's shared part: a child loop of the same
/// type as the turn's own, borrowing `shared` immutably and owning nothing of
/// its parent — which is what lets a round's group run several at once
/// (docs/research/parallel-subagents.md §4.1, §4.3). Reports the run's start
/// and end to the orchestrator, assembles the run and the result text.
async fn run_child(
    shared: &TurnShared,
    loc: &'static crate::shared::i18n::Locale,
    spec: ChildSpec,
) -> CallDone {
    let ChildSpec {
        parsed,
        run_id,
        allowed,
        request,
        ctx,
        cancel,
        user,
        limits,
        max_rounds,
        depth,
    } = spec;
    let started = chrono::Utc::now();
    let progress = |progress: TurnProgress| {
        let _ = shared.done_tx.send(GenMessage::Progress {
            id: shared.id,
            progress,
        });
    };
    progress(TurnProgress::ChildStarted(Box::new(SubagentRun {
        id: run_id,
        kind: RunKind::Subagent,
        title: parsed.initial_title(),
        renamed_manually: false,
        name: parsed.name.clone(),
        created_at: started,
        finished_at: None,
        system_message: parsed.system_message.clone(),
        sampling_override: None,
        messages: vec![user.clone()],
        outcome: None,
        tokens: 0,
        participants: Vec::new(),
        background: false,
    })));

    let mut child = TurnLoop {
        shared,
        ctx,
        request,
        cancel: cancel.clone(),
        // A child asks the same engine, and asks it for itself: its loop is its own.
        vision: None,
        images_withheld: 0,
        // A child's chat opens with the one user message, so that is all it can have spent.
        image_names: ToolImageNames::seeded(user.images.iter().map(|i| i.name.as_str())),
        allowed,
        // A child is never a woken turn: the notification reaches the parent.
        woken: false,
        messages: Vec::new(),
        effects: Vec::new(),
        deleted: Vec::new(),
        round: 0,
        workspace_rounds: 0,
        total_tokens: 0,
        total_reasoning: 0,
        last_usage: None,
        pending_new_bubble: false,
        depth,
        run_id: Some(run_id),
        ended_by_limit: None,
        persona: Some(parsed.initial_title()),
        // A sub-agent's run continues nothing — the seed is the turn's.
        echo_seed: None,
    };
    // Boxed: `run` → `tool_round` → here → `run` is a recursive async chain,
    // and the compiler needs one indirection in it.
    let finished = tokio::time::timeout(limits.run_timeout, Box::pin(child.run())).await;
    // A child the provider's filter stopped is stored as `Completed` — `RunOutcome`
    // is persisted, and a value of its own would be the chat-format change fork C2
    // declined — but its status line tells the parent model, which used to learn it
    // only from Gemini's in-text note (docs/research/content-filter-finish.md §3).
    let filtered = matches!(finished, Ok(FinishReason::Filtered));
    let outcome = match finished {
        Err(_) => {
            // The run's own token, so the parent's turn goes on.
            cancel.cancel();
            RunOutcome::TimedOut
        }
        Ok(FinishReason::Cancelled) => RunOutcome::Cancelled,
        Ok(FinishReason::Error) => RunOutcome::Failed,
        Ok(_) if child.ended_by_limit.is_some() => RunOutcome::RoundLimit,
        Ok(_) => RunOutcome::Completed,
    };
    // Everything the parent keeps, out of the child. Its own discarded drafts
    // (`rewrite_current_message`) are dropped: the archive's promise is
    // recovering what the *user* lost (research §3.6).
    let child_messages = std::mem::take(&mut child.messages);
    let child_effects = std::mem::take(&mut child.effects);
    let child_tokens = child.total_tokens;
    drop(child);
    // The chip goes with the run; the parent's turn is still generating.
    let _ = shared.evt_tx.send(AppEvent::SubagentProgress {
        generation_id: shared.id,
        run: run_id,
        progress: None,
    });
    let finished_at = chrono::Utc::now();
    progress(TurnProgress::ChildEnded {
        run: run_id,
        outcome,
        finished_at,
        tokens: child_tokens,
    });
    let mut run = SubagentRun {
        id: run_id,
        kind: RunKind::Subagent,
        title: parsed.initial_title(),
        renamed_manually: false,
        name: parsed.name.clone(),
        created_at: started,
        finished_at: Some(finished_at),
        system_message: parsed.system_message.clone(),
        sampling_override: None,
        messages: std::iter::once(user).chain(child_messages).collect(),
        outcome: Some(outcome),
        tokens: child_tokens,
        participants: Vec::new(),
        background: false,
    };
    // Effects go to the chat they describe (research §3.4): identity to the
    // run, environment to the parent — which mirrors an attachment into its
    // own snapshot at the round's end, as for any tool.
    let mut effects = Vec::new();
    for effect in child_effects {
        match effect {
            ChatEffect::SetSystemMessage(s) => run.system_message = s,
            ChatEffect::SetSamplingOverride(s) => run.sampling_override = Some(*s),
            a @ (ChatEffect::AddAttachment(_) | ChatEffect::AddChatFile(_)) => effects.push(a),
        }
    }

    // The model's result: the final reply and one line naming the transcript —
    // and, when the run did not complete, why (docs/lessons.md §4: a result
    // that says only "cannot" costs the next three turns).
    let address = crate::features::chat_links::uri(run.id);
    let body = run
        .final_reply()
        .map(str::to_string)
        .unwrap_or_else(|| loc.t("tool.call_subagent.result.empty").to_string());
    let status = match outcome {
        RunOutcome::Completed if filtered => loc.tf(
            "tool.call_subagent.result.filtered",
            &[("address", &address)],
        ),
        RunOutcome::Completed => loc.tf(
            "tool.call_subagent.result.transcript",
            &[("address", &address)],
        ),
        RunOutcome::Cancelled => loc.tf(
            "tool.call_subagent.result.cancelled",
            &[("address", &address)],
        ),
        RunOutcome::TimedOut => loc.tf(
            "tool.call_subagent.result.timeout",
            &[
                ("address", &address),
                ("secs", &limits.run_timeout.as_secs().to_string()),
            ],
        ),
        RunOutcome::Failed => loc.tf("tool.call_subagent.result.failed", &[("address", &address)]),
        RunOutcome::RoundLimit => loc.tf(
            "tool.call_subagent.result.round_limit",
            &[
                ("address", &address),
                ("max_rounds", &max_rounds.to_string()),
            ],
        ),
    };
    CallDone {
        result: CallResult {
            text: format!("{body}\n\n{status}"),
            images: Vec::new(),
            subagent: Some(Box::new(run)),
        },
        effects,
        // The child's own sample stays with its loop (page-summary-usage §7).
        prefill: None,
    }
}

/// How a dialogue loop ended, before it maps onto [`RunOutcome`]
/// (spec §9.13). `Cancelled` is the parent's `Esc` through the child token;
/// `Failed` names whose generation the engine gave nothing usable for — a
/// participant's line (empty even after the muted re-ask, research §5.1) or
/// a checkpoint the director's engine failed on.
enum DialogueEnd {
    Stopped {
        reason: String,
        summary: Option<String>,
    },
    Cap,
    Cancelled,
    Failed {
        who: String,
    },
}

/// One dialogue run's mutable state, owned **outside** the timed loop so a
/// timeout keeps the partial transcript (the future is dropped, the state
/// survives — the same shape `run_subagent` gets from its child loop).
struct DialogueState {
    /// The run's id — what its progress steps and chip are keyed by.
    run_id: Uuid,
    /// The run's title — the status-bar chip names the scene by it.
    title: String,
    /// The role-encoded transcript (research §3.5): participant `a` is
    /// `Assistant`, `b` is `User`, director interventions are `System`.
    transcript: Vec<Message>,
    /// Standing director notes per participant — each participant's system
    /// appendix from the moment it was issued (identity stays with the run,
    /// research §3.4).
    notes_a: Vec<String>,
    notes_b: Vec<String>,
    /// Generated lines, retried ones included — the `max_messages` meter.
    generated: usize,
    next_checkpoint: usize,
    /// How much of the transcript the director has been shown.
    rendered: usize,
    /// The director's persistent conversation: script increments as `user`
    /// turns, its verdicts as its own **text** turns — each call rendered
    /// `name(arguments)`, no `tool` result — which keeps its context
    /// append-only, the cache-friendly shape §5.1 of the dialogue research
    /// measured, and alternating on a template without a tool role, which
    /// Gemma 3's is (docs/research/dialogue-director-history.md §3.1).
    director_msgs: Vec<ApiMessage>,
    tokens: u64,
    reasoning: u32,
}

/// The director's conversation brief (fork F6): the chat's rolling summary
/// when one is in force, then the tail of the parent request's own
/// conversation — most recent turns within a fixed budget. Empty on a chat
/// with no history yet.
fn conversation_brief(
    summary: Option<&str>,
    messages: &[ApiMessage],
    loc: &'static crate::shared::i18n::Locale,
) -> String {
    const BRIEF_BUDGET: usize = 4000;
    let mut tail: Vec<String> = Vec::new();
    let mut spent = 0usize;
    for m in messages.iter().rev() {
        let label = match m.role {
            crate::shared::api::contract::ApiRole::User => loc.t("prompt.dialogue.role_user"),
            crate::shared::api::contract::ApiRole::Assistant => {
                loc.t("prompt.dialogue.role_assistant")
            }
            _ => continue,
        };
        let text = m.content.trim();
        if text.is_empty() {
            continue;
        }
        let line = format!("{label}: {text}");
        if spent + line.len() > BRIEF_BUDGET && !tail.is_empty() {
            break;
        }
        spent += line.len();
        tail.push(line);
        if spent > BRIEF_BUDGET {
            break;
        }
    }
    tail.reverse();
    let mut parts: Vec<String> = Vec::new();
    if let Some(s) = summary.map(str::trim).filter(|s| !s.is_empty()) {
        parts.push(s.to_string());
    }
    if !tail.is_empty() {
        parts.push(tail.join("\n"));
    }
    if parts.is_empty() {
        return String::new();
    }
    format!("{}\n{}", loc.t("prompt.dialogue.brief"), parts.join("\n\n"))
}

/// Everything a directed dialogue needs from the turn that staged it
/// (spec §9.13, docs/research/background-dialogues.md F6 — the user's
/// decision, 2026-09-05). The driver used to be a `TurnLoop` method and
/// reached into the loop for five unrelated things: the locale and sampling
/// of `ToolContext`, the parent chat's persona, the turn's live request tail
/// (from which the director's brief is folded) and the turn's cancellation
/// token. Naming them makes the scene runnable from anywhere that can
/// produce them — the live turn below, and a background task from a
/// snapshot — without the loop's other twenty fields coming along.
struct DialogueCtx<'a> {
    /// The turn's shared parts: the backend, the counters, the limits, the
    /// event and progress senders. Borrowed immutably, like every loop's.
    shared: &'a TurnShared,
    /// The profile's language — every prompt and result text of the scene.
    loc: &'static crate::shared::i18n::Locale,
    /// The sampling the participants' lines run under (the director's is
    /// derived from it: muted, with a small verdict cap).
    sampling: SamplingConfig,
    /// The parent chat's persona — the head of the director's system prompt
    /// (fork F6 of the dialogue track: the main agent directs).
    persona: String,
    /// The director's conversation brief, already folded
    /// ([`conversation_brief`]): the rolling summary plus the tail of the
    /// parent's own conversation.
    brief: String,
    /// The scene's own token — a child of the turn's for a foreground
    /// dialogue, so `Esc` ends both.
    cancel: CancellationToken,
    /// The nesting guard's input: `0` for a scene staged by the turn's own
    /// loop, which is the only depth that may stage one.
    depth: u8,
    /// The run's id, minted by whoever starts the scene: a foreground call
    /// mints it here, a background one mints it at the call so its *started*
    /// line can name the transcript's address before the scene begins
    /// (docs/research/background-dialogues.md §4.2).
    run_id: Uuid,
}

impl TurnLoop<'_> {
    /// Runs a directed dialogue (spec §9.13, docs/research/two-agent-dialogue.md)
    /// on behalf of the turn: names what the scene needs from this loop and
    /// hands it to [`DialogueCtx::run`], which is the driver.
    async fn run_dialogue(&mut self, args: &serde_json::Value) -> CallResult {
        DialogueCtx {
            shared: self.shared,
            loc: self.ctx.loc,
            sampling: self.ctx.effective_sampling.clone(),
            persona: self.ctx.system_message.clone(),
            brief: conversation_brief(
                self.shared.compaction_summary.as_deref(),
                &self.request.messages,
                self.ctx.loc,
            ),
            cancel: self.cancel.child_token(),
            depth: self.depth,
            run_id: Uuid::new_v4(),
        }
        .run(args)
        .await
    }
}

impl DialogueCtx<'_> {
    /// The dialogue's own status-bar chip (spec §9.13): which line is being
    /// written, or that the director is judging the scene — so a parent turn
    /// parked inside a long dialogue never reads as a stuck "generating"
    /// (docs/lessons.md §4). Worded by the screen; cleared with the run.
    fn dialogue_chip(
        &self,
        run: Uuid,
        title: &str,
        round: u32,
        kind: crate::app::events::RunProgressKind,
    ) {
        let progress = crate::app::events::SubagentProgress {
            name: title.to_string(),
            round,
            tool: None,
            kind,
        };
        // The scene's position to the orchestrator too — the tasks screen
        // reads it off the run's mirror (spec §11.10).
        self.progress(TurnProgress::ChildProgress {
            run,
            progress: progress.clone(),
        });
        let _ = self.shared.evt_tx.send(AppEvent::SubagentProgress {
            generation_id: self.shared.id,
            run,
            progress: Some(progress),
        });
    }

    /// Sends one step of the scene to the orchestrator, keyed by the turn
    /// that owns it — [`TurnLoop::progress`] for a scene.
    fn progress(&self, progress: TurnProgress) {
        let _ = self.shared.done_tx.send(GenMessage::Progress {
            id: self.shared.id,
            progress,
        });
    }

    /// The scene itself (spec §9.13, research §3.3): two persona contexts
    /// and a director context taking strictly sequential turns on one
    /// backend — at most one request of the scene in flight, the feature's
    /// VRAM contract (research §3.9). Returns the result text and the run
    /// for the record, exactly as `run_subagent` does.
    async fn run(&self, args: &serde_json::Value) -> CallResult {
        use crate::features::tools::dialogue::{self, RUN_DIALOGUE_ID};
        let loc = self.loc;
        let parsed = match dialogue::DialogueArgs::parse(args, loc) {
            Ok(a) => a,
            Err(err) => {
                return loc
                    .tf(
                        "loop.tool_error",
                        &[("name", RUN_DIALOGUE_ID), ("err", &err.to_string())],
                    )
                    .into();
            }
        };
        // No nesting, whatever the allowed set says — the same second lock
        // `run_subagent` keeps on its own door.
        if self.depth > 0 {
            return loc
                .tf("loop.tool_disabled", &[("name", RUN_DIALOGUE_ID)])
                .into();
        }
        self.run_parsed(parsed).await
    }

    /// The scene over already-parsed arguments — the seam a background start
    /// enters through, having parsed at the call to answer the model at once
    /// (docs/research/background-dialogues.md §4.2).
    async fn run_parsed(
        &self,
        parsed: crate::features::tools::dialogue::DialogueArgs,
    ) -> CallResult {
        use crate::features::tools::dialogue;
        let loc = self.loc;
        let started = chrono::Utc::now();
        let limits = self.shared.subagent;
        let a_label = parsed.label(true, loc);
        let b_label = parsed.label(false, loc);

        // Participants ride the chat's sampling under the shared per-line cap;
        // the director's checkpoints run with thinking muted (the probe's
        // empty-turn rule, research §5.1) and a small verdict cap.
        let mut sampling = self.sampling.clone();
        sampling.max_tokens = Some(
            sampling
                .max_tokens
                .map_or(limits.max_tokens, |m| m.min(limits.max_tokens)),
        );
        let mut muted = sampling.clone();
        muted.reasoning_budget = Some(0);
        let mut director_sampling = muted.clone();
        director_sampling.max_tokens = Some(512.min(limits.max_tokens));

        let direction = parsed
            .direction
            .clone()
            .unwrap_or_else(|| loc.t("prompt.dialogue.direction_default").to_string());
        let appendix = loc.tf(
            "prompt.dialogue.director",
            &[("a", &a_label), ("b", &b_label), ("direction", &direction)],
        );
        // The director is the main agent directing (fork F6): the parent
        // turn's own persona, the conversation brief, then the appendix. The
        // self-model injection stays top-turn-only (ADR 0010 F3).
        let director_system = [self.persona.as_str(), &self.brief, &appendix]
            .iter()
            .filter(|s| !s.trim().is_empty())
            .copied()
            .collect::<Vec<_>>()
            .join("\n\n");
        let verdict_schemas = dialogue::verdict_tools(loc, &a_label, &b_label);

        let participants = vec![
            crate::entities::subagent::Participant {
                name: parsed.a.name.clone(),
                system_message: parsed.a.system_message.clone(),
            },
            crate::entities::subagent::Participant {
                name: parsed.b.name.clone(),
                system_message: parsed.b.system_message.clone(),
            },
        ];
        let opening = if parsed.opening_by_a {
            Message::assistant(parsed.opening.clone())
        } else {
            Message::user(parsed.opening.clone())
        };
        let run_id = self.run_id;
        let cancel = self.cancel.clone();
        self.progress(TurnProgress::ChildStarted(Box::new(SubagentRun {
            id: run_id,
            kind: RunKind::Dialogue,
            title: parsed.initial_title(loc),
            renamed_manually: false,
            name: None,
            created_at: started,
            finished_at: None,
            system_message: appendix.clone(),
            sampling_override: None,
            messages: vec![opening.clone()],
            outcome: None,
            tokens: 0,
            participants: participants.clone(),
            background: false,
        })));

        let run = run_id;
        let mut st = DialogueState {
            run_id,
            title: parsed.initial_title(loc),
            transcript: vec![opening],
            notes_a: Vec::new(),
            notes_b: Vec::new(),
            generated: 0,
            next_checkpoint: parsed.moderate_every,
            rendered: 0,
            director_msgs: Vec::new(),
            tokens: 0,
            reasoning: 0,
        };
        let finished = tokio::time::timeout(
            limits.dialogue_run_timeout,
            Box::pin(self.dialogue_loop(
                &mut st,
                &parsed,
                (&a_label, &b_label),
                &director_system,
                &director_sampling,
                &verdict_schemas,
                &sampling,
                &muted,
                &cancel,
                run,
            )),
        )
        .await;
        let end = match finished {
            Err(_) => {
                // The run's own token, so the parent's turn goes on.
                cancel.cancel();
                None
            }
            Ok(end) => Some(end),
        };
        let outcome = match &end {
            None => RunOutcome::TimedOut,
            Some(DialogueEnd::Cancelled) => RunOutcome::Cancelled,
            Some(DialogueEnd::Failed { .. }) => RunOutcome::Failed,
            Some(DialogueEnd::Cap) => RunOutcome::RoundLimit,
            Some(DialogueEnd::Stopped { .. }) => RunOutcome::Completed,
        };
        // The chip goes with the run; the parent's turn is still generating.
        let _ = self.shared.evt_tx.send(AppEvent::SubagentProgress {
            generation_id: self.shared.id,
            run: run_id,
            progress: None,
        });
        let finished_at = chrono::Utc::now();
        self.progress(TurnProgress::ChildEnded {
            run: run_id,
            outcome,
            finished_at,
            tokens: st.tokens,
        });
        let run = SubagentRun {
            id: run_id,
            kind: RunKind::Dialogue,
            title: parsed.initial_title(loc),
            renamed_manually: false,
            name: None,
            created_at: started,
            finished_at: Some(finished_at),
            system_message: appendix,
            sampling_override: None,
            messages: st.transcript,
            outcome: Some(outcome),
            tokens: st.tokens,
            participants,
            background: false,
        };

        // The result closes the door (docs/lessons.md §4): how it ended, and
        // the one route to the words — the transcript's address.
        let generated = st.generated.to_string();
        let mut status = match &end {
            Some(DialogueEnd::Stopped { reason, summary }) => {
                let mut s = loc.tf(
                    "tool.run_dialogue.result.completed",
                    &[
                        ("a", &a_label),
                        ("b", &b_label),
                        ("messages", &generated),
                        ("reason", reason),
                    ],
                );
                if let Some(summary) = summary {
                    s.push('\n');
                    s.push_str(
                        &loc.tf("tool.run_dialogue.result.summary", &[("summary", summary)]),
                    );
                }
                s
            }
            Some(DialogueEnd::Cap) => loc.tf(
                "tool.run_dialogue.result.cap",
                &[
                    ("a", &a_label),
                    ("b", &b_label),
                    ("max_messages", &parsed.max_messages.to_string()),
                ],
            ),
            Some(DialogueEnd::Cancelled) => loc.t("tool.run_dialogue.result.cancelled").to_string(),
            Some(DialogueEnd::Failed { who }) => {
                loc.tf("tool.run_dialogue.result.failed", &[("who", who)])
            }
            None => loc.tf(
                "tool.run_dialogue.result.timeout",
                &[("secs", &limits.dialogue_run_timeout.as_secs().to_string())],
            ),
        };
        status.push_str("\n\n");
        status.push_str(&loc.tf(
            "tool.run_dialogue.result.transcript",
            &[("address", &crate::features::chat_links::uri(run.id))],
        ));
        CallResult {
            text: status,
            images: Vec::new(),
            subagent: Some(Box::new(run)),
        }
    }

    /// The dialogue's main loop (research §3.3): participant turns in strict
    /// alternation, a director checkpoint every `moderate_every` generated
    /// lines, until the director stops it or the cap fires.
    #[allow(clippy::too_many_arguments)] // one internal seam; a struct would re-group what DialogueState already holds
    async fn dialogue_loop(
        &self,
        st: &mut DialogueState,
        parsed: &crate::features::tools::dialogue::DialogueArgs,
        labels: (&str, &str),
        director_system: &str,
        director_sampling: &SamplingConfig,
        verdict_schemas: &[crate::shared::api::contract::ToolSchema],
        sampling: &SamplingConfig,
        muted: &SamplingConfig,
        cancel: &CancellationToken,
        run: Uuid,
    ) -> DialogueEnd {
        use crate::features::tools::dialogue;
        loop {
            if st.generated >= parsed.max_messages {
                return DialogueEnd::Cap;
            }
            if st.generated >= st.next_checkpoint {
                st.next_checkpoint += parsed.moderate_every;
                match self
                    .dialogue_checkpoint(
                        st,
                        parsed,
                        labels,
                        director_system,
                        director_sampling,
                        verdict_schemas,
                        sampling,
                        muted,
                        cancel,
                        run,
                    )
                    .await
                {
                    Ok(Some((reason, summary))) => {
                        return DialogueEnd::Stopped { reason, summary };
                    }
                    Ok(None) => continue,
                    Err(end) => return end,
                }
            }
            let speaker_a =
                dialogue::next_speaker_a(&st.transcript).unwrap_or(!parsed.opening_by_a);
            let line = match self
                .dialogue_line(
                    st, parsed, labels, speaker_a, None, sampling, muted, cancel, run,
                )
                .await
            {
                Ok(line) => line,
                Err(end) => return end,
            };
            self.progress(TurnProgress::ChildRoundFiled {
                run: st.run_id,
                messages: vec![line.clone()],
            });
            st.transcript.push(line);
            st.generated += 1;
        }
    }

    /// One participant's line: the derived view (research §3.2), one streamed
    /// generation, and the muted re-ask when the reply came back empty — the
    /// all-thinking spiral the probe measured (research §5.1).
    #[allow(clippy::too_many_arguments)]
    async fn dialogue_line(
        &self,
        st: &mut DialogueState,
        parsed: &crate::features::tools::dialogue::DialogueArgs,
        labels: (&str, &str),
        speaker_a: bool,
        one_shot: Option<&str>,
        sampling: &SamplingConfig,
        muted: &SamplingConfig,
        cancel: &CancellationToken,
        run: Uuid,
    ) -> Result<Message, DialogueEnd> {
        use crate::features::tools::dialogue;
        let loc = self.loc;
        let persona = if speaker_a { &parsed.a } else { &parsed.b };
        let notes = if speaker_a { &st.notes_a } else { &st.notes_b };
        let who = if speaker_a { labels.0 } else { labels.1 };
        let (system, messages) = dialogue::participant_view(
            &st.transcript,
            speaker_a,
            &persona.system_message,
            notes,
            one_shot,
            &dialogue::ViewText {
                scene: parsed.scene.as_deref(),
                begins: loc.t("prompt.dialogue.begins"),
                note_prefix: loc.t("prompt.dialogue.note_prefix"),
            },
        );
        let request = |s: SamplingConfig| ChatRequest {
            system: Some(system.clone()),
            messages: messages.clone(),
            sampling: s,
            tools: Vec::new(),
            ..Default::default()
        };
        // The coming stream's side, for the open transcript (stage 2): the
        // line's tokens draw in the speaker's own bubble.
        let role = if speaker_a {
            MessageRole::Assistant
        } else {
            MessageRole::User
        };
        self.progress(TurnProgress::ChildLineStarted {
            run: st.run_id,
            role,
        });
        self.dialogue_chip(
            st.run_id,
            &st.title,
            (st.generated + 1) as u32,
            crate::app::events::RunProgressKind::DialogueLine,
        );
        let mut out = self
            .dialogue_stream(request(sampling.clone()), cancel, st, run, true)
            .await;
        match out.reason {
            FinishReason::Cancelled => return Err(DialogueEnd::Cancelled),
            FinishReason::Error => {
                return Err(DialogueEnd::Failed {
                    who: who.to_string(),
                });
            }
            _ => {}
        }
        if out.text.trim().is_empty() {
            // The whole cap went into reasoning — re-ask once with thinking
            // muted; a second empty reply fails the run honestly. The re-ask
            // is the same line starting over: the open transcript's partial
            // resets with it.
            self.progress(TurnProgress::ChildLineStarted {
                run: st.run_id,
                role,
            });
            out = self
                .dialogue_stream(request(muted.clone()), cancel, st, run, true)
                .await;
            match out.reason {
                FinishReason::Cancelled => return Err(DialogueEnd::Cancelled),
                FinishReason::Error => {
                    return Err(DialogueEnd::Failed {
                        who: who.to_string(),
                    });
                }
                _ => {}
            }
            if out.text.trim().is_empty() {
                return Err(DialogueEnd::Failed {
                    who: who.to_string(),
                });
            }
        }
        let Some(mut m) = finalize_message(
            &out,
            &self.sampling,
            self.shared.engine_mode,
            &self.shared.model_name,
            self.shared.endpoint_sampling_fields.as_deref(),
        ) else {
            return Err(DialogueEnd::Failed {
                who: who.to_string(),
            });
        };
        if !speaker_a {
            // The role-encoded transcript (research §3.5): b's side is `User`.
            m.role = MessageRole::User;
        }
        Ok(m)
    }

    /// One director checkpoint: the incremental script, the verdict request
    /// (thinking muted), and the verdicts applied in call order
    /// (research §3.3–§3.4). `Ok(Some(..))` — the director stopped the
    /// dialogue; `Ok(None)` — it goes on. A reply with no tool call counts as
    /// `continue` — the dialogue proceeds toward its cap rather than stalling.
    #[allow(clippy::too_many_arguments)]
    async fn dialogue_checkpoint(
        &self,
        st: &mut DialogueState,
        parsed: &crate::features::tools::dialogue::DialogueArgs,
        labels: (&str, &str),
        director_system: &str,
        director_sampling: &SamplingConfig,
        verdict_schemas: &[crate::shared::api::contract::ToolSchema],
        sampling: &SamplingConfig,
        muted: &SamplingConfig,
        cancel: &CancellationToken,
        run: Uuid,
    ) -> Result<Option<(String, Option<String>)>, DialogueEnd> {
        use crate::features::tools::dialogue::{self, Verdict};
        let loc = self.loc;
        let user = self.dialogue_script(st, labels);
        st.director_msgs.push(ApiMessage::user(user));
        let request = ChatRequest {
            system: Some(director_system.to_string()),
            messages: st.director_msgs.clone(),
            sampling: director_sampling.clone(),
            tools: verdict_schemas.to_vec(),
            ..Default::default()
        };
        self.dialogue_chip(
            st.run_id,
            &st.title,
            st.generated as u32,
            crate::app::events::RunProgressKind::DialogueDirector,
        );
        let out = self.dialogue_stream(request, cancel, st, run, false).await;
        match out.reason {
            FinishReason::Cancelled => return Err(DialogueEnd::Cancelled),
            FinishReason::Error => {
                return Err(DialogueEnd::Failed {
                    who: loc.t("tool.run_dialogue.director_label").to_string(),
                });
            }
            _ => {}
        }
        // The verdicts stay in the director's own conversation, so it
        // remembers what it already directed (research §3.2) — as its own
        // text turn rather than a tool-call turn with a `tool` result: a
        // template without a tool role renders that result as a second user
        // turn in a row and Gemma 3's refuses the pair
        // (docs/research/dialogue-director-history.md §3.1).
        st.director_msgs
            .push(ApiMessage::assistant(dialogue::verdict_turn(
                &out.text, &out.calls,
            )));
        let (verdicts, _unknown) = dialogue::parse_verdicts(&out.calls);
        for verdict in verdicts {
            match verdict {
                Verdict::Continue => {}
                Verdict::Stop { reason, summary } => {
                    self.dialogue_stop(st, &reason, summary.as_deref());
                    return Ok(Some((reason, summary)));
                }
                Verdict::Note { to_a, to_b, text } => {
                    self.dialogue_note(st, labels, (to_a, to_b), text);
                }
                Verdict::Retry { note } => {
                    self.dialogue_retry(
                        st,
                        parsed,
                        labels,
                        note.as_deref(),
                        sampling,
                        muted,
                        cancel,
                        run,
                    )
                    .await?;
                }
                Verdict::Rewrite { text } => self.dialogue_rewrite(st, labels, text),
            }
        }
        Ok(None)
    }

    /// The incremental script one checkpoint shows the director
    /// (research §3.3): the transcript lines it has not seen yet, each
    /// labelled by its speaker, under the opening or the continuation header.
    /// Advances `rendered` — interventions are excluded, since the director's
    /// own tool-call turns already carry them.
    fn dialogue_script(&self, st: &mut DialogueState, labels: (&str, &str)) -> String {
        let loc = self.loc;
        let new_lines: Vec<String> = st.transcript[st.rendered..]
            .iter()
            .filter(|m| m.role != MessageRole::System)
            .map(|m| {
                let who = if m.role == MessageRole::Assistant {
                    labels.0
                } else {
                    labels.1
                };
                format!("{who}: {}", m.text)
            })
            .collect();
        st.rendered = st.transcript.len();
        let header = if st.director_msgs.is_empty() {
            loc.t("prompt.dialogue.script_opening")
        } else {
            loc.t("prompt.dialogue.script_more")
        };
        format!(
            "{header}\n\n{}\n\n{}",
            new_lines.join("\n\n"),
            loc.t("prompt.dialogue.ask")
        )
    }

    /// The `Stop` verdict's intervention row — the reason, and the director's
    /// closing summary when it wrote one.
    fn dialogue_stop(&self, st: &mut DialogueState, reason: &str, summary: Option<&str>) {
        let loc = self.loc;
        let line = match summary {
            Some(s) => loc.tf(
                "tool.run_dialogue.stop_line_summary",
                &[("reason", reason), ("summary", s)],
            ),
            None => loc.tf("tool.run_dialogue.stop_line", &[("reason", reason)]),
        };
        self.dialogue_intervention(st, line);
    }

    /// The `Note` verdict: a standing direction filed as an intervention row
    /// and appended to each addressed participant's notes — identity stays
    /// with the run from the moment it was issued (research §3.4).
    fn dialogue_note(
        &self,
        st: &mut DialogueState,
        labels: (&str, &str),
        to: (bool, bool),
        text: String,
    ) {
        let loc = self.loc;
        let (to_a, to_b) = to;
        let whom = match to {
            (true, false) => labels.0.to_string(),
            (false, true) => labels.1.to_string(),
            _ => format!("{}, {}", labels.0, labels.1),
        };
        self.dialogue_intervention(
            st,
            loc.tf(
                "tool.run_dialogue.note_line",
                &[("to", &whom), ("text", &text)],
            ),
        );
        if to_a {
            st.notes_a.push(text.clone());
        }
        if to_b {
            st.notes_b.push(text);
        }
    }

    /// The `Retry` verdict: discard the last line and generate it again, with
    /// the director's note as a one-shot instruction. A no-op when there is
    /// nothing generated to retry or the `max_messages` cap leaves no slot for
    /// the regeneration.
    #[allow(clippy::too_many_arguments)]
    async fn dialogue_retry(
        &self,
        st: &mut DialogueState,
        parsed: &crate::features::tools::dialogue::DialogueArgs,
        labels: (&str, &str),
        note: Option<&str>,
        sampling: &SamplingConfig,
        muted: &SamplingConfig,
        cancel: &CancellationToken,
        run: Uuid,
    ) -> Result<(), DialogueEnd> {
        let loc = self.loc;
        // Only a generated line can be retried, and the retry's regeneration
        // spends a `max_messages` slot of its own.
        if st.generated == 0 || st.generated >= parsed.max_messages {
            return Ok(());
        }
        let Some(last) = st
            .transcript
            .iter()
            .rposition(|m| m.role != MessageRole::System)
        else {
            return Ok(());
        };
        let speaker_a = st.transcript[last].role == MessageRole::Assistant;
        let who = if speaker_a { labels.0 } else { labels.1 };
        // A discard cannot be expressed by appending: the open transcript
        // gets the full replacement (stage 2), with the intervention row
        // saying what happened.
        st.transcript.remove(last);
        let line = match note {
            Some(n) => loc.tf(
                "tool.run_dialogue.retry_line_note",
                &[("who", who), ("note", n)],
            ),
            None => loc.tf("tool.run_dialogue.retry_line", &[("who", who)]),
        };
        st.transcript.push(Message::new(MessageRole::System, line));
        st.rendered = st.transcript.len();
        self.progress(TurnProgress::ChildTranscript {
            run: st.run_id,
            messages: st.transcript.clone(),
        });
        let line = self
            .dialogue_line(
                st, parsed, labels, speaker_a, note, sampling, muted, cancel, run,
            )
            .await?;
        self.progress(TurnProgress::ChildRoundFiled {
            run: st.run_id,
            messages: vec![line.clone()],
        });
        st.transcript.push(line);
        st.generated += 1;
        Ok(())
    }

    /// The `Rewrite` verdict: the director's final cut replaces the last
    /// line's words in place. A no-op when there is no line to rewrite.
    fn dialogue_rewrite(&self, st: &mut DialogueState, labels: (&str, &str), text: String) {
        let loc = self.loc;
        let Some(last) = st
            .transcript
            .iter()
            .rposition(|m| m.role != MessageRole::System)
        else {
            return;
        };
        let who = if st.transcript[last].role == MessageRole::Assistant {
            labels.0
        } else {
            labels.1
        };
        let line = loc.tf("tool.run_dialogue.rewrite_line", &[("who", who)]);
        // The final cut replaces the words; the original's thoughts described
        // a line that no longer exists. An in-place edit cannot be expressed
        // by appending: the open transcript gets the full replacement
        // (stage 2).
        st.transcript[last].text = text;
        st.transcript[last].thoughts = None;
        st.transcript.push(Message::new(MessageRole::System, line));
        st.rendered = st.transcript.len();
        self.progress(TurnProgress::ChildTranscript {
            run: st.run_id,
            messages: st.transcript.clone(),
        });
    }

    /// Files one director intervention as a `System` entry of the transcript
    /// (rendered as a note row, research §3.4) and mirrors it live.
    fn dialogue_intervention(&self, st: &mut DialogueState, text: String) {
        let m = Message::new(MessageRole::System, text);
        self.progress(TurnProgress::ChildRoundFiled {
            run: st.run_id,
            messages: vec![m.clone()],
        });
        st.transcript.push(m);
        // The director already knows what it did — its own tool-call turn
        // carries it — so interventions are not re-rendered into the script.
        st.rendered = st.transcript.len();
    }

    /// One streamed dialogue generation through the child sink, with the
    /// run's tokens accounted. `steps` — whether the stream's tokens reach
    /// the open transcript (a participant's line does, stage 2 of the track;
    /// a director checkpoint stays muted — its deliberation is not a line).
    ///
    /// The stream takes a session permit and a pool reservation like every
    /// other (`TurnLoop::stream`, spec §6.3): the scene's "one request in
    /// flight" was an invariant of running *inside* a turn, and a background
    /// scene has no turn to be inside — so the admission guard is what keeps
    /// it (docs/research/background-dialogues.md R3, fork F4). Nothing is
    /// priced at one session with no pool, which is the behaviour every
    /// foreground scene had before.
    async fn dialogue_stream(
        &self,
        request: ChatRequest,
        cancel: &CancellationToken,
        st: &mut DialogueState,
        run: Uuid,
        steps: bool,
    ) -> RoundOutput {
        let sink = RoundSink {
            evt_tx: &self.shared.evt_tx,
            done_tx: &self.shared.done_tx,
            turn: self.shared.id,
            child: Some(run),
            mute_steps: !steps,
        };
        // Each context is its own conversation, so there is no last-round
        // floor to raise the estimate with — the request is priced as it is.
        let need = self.shared.sessions.price(
            crate::shared::session_budget::Shape::Run,
            estimate_prompt_tokens(&request),
            0,
            request.sampling.max_tokens.map(|m| m as u64),
        );
        let Some(_session) = self.shared.sessions.acquire(need, cancel).await else {
            return cancelled_round();
        };
        let out = stream_round(
            &self.shared.backend,
            request,
            cancel,
            self.shared.id,
            &sink,
            &self.shared.counters,
            st.tokens,
            st.reasoning,
            self.shared.ui_loc,
            self.shared.compaction_enabled,
            false,
            None,
        )
        .await;
        st.tokens += out.tokens;
        st.reasoning += out.reasoning_tokens;
        out
    }
}

/// What one tool call produced for the model: its result text, any images it
/// returned (spec §9.10), and — for `call_subagent` — the run for the record.
/// Every gate and refusal path yields text alone — only a real invocation can
/// produce pixels or a transcript, which is what `From<String>` keeps cheap to express.
struct CallResult {
    text: String,
    images: Vec<crate::features::tools::ToolImage>,
    subagent: Option<Box<SubagentRun>>,
}

impl From<String> for CallResult {
    fn from(text: String) -> Self {
        Self {
            text,
            images: Vec::new(),
            subagent: None,
        }
    }
}

/// The stem every tool image's name is built on.
const TOOL_IMAGE_PREFIX: &str = "tool-image-";

/// Hands out `tool-image-N.<ext>` names, skipping every `N` the chat has already used.
///
/// A tool image is named for the **chat**, not for the call that produced it. Numbered per
/// call, two rounds each returning one chart both produced `tool-image-1.png`, and a name
/// two items share resolves to nothing (`Resolved::Shared`, §12 T2) — so the model naming
/// its own chart in the next call's `files` got a refusal instead of the file, and the
/// round was spent on finding that out.
#[derive(Debug, Default)]
struct ToolImageNames(std::collections::HashSet<u32>);

impl ToolImageNames {
    /// Seeds from the names a chat's images already carry. Anything that is not
    /// `tool-image-<number>.<ext>` claims no number — a user's `chart.png` is not in the
    /// family, and a user's own `tool-image-2.png` is.
    fn seeded<'a>(names: impl Iterator<Item = &'a str>) -> Self {
        Self(names.filter_map(Self::number_of).collect())
    }

    /// `tool-image-7.png` → `7`; any other name → `None`.
    fn number_of(name: &str) -> Option<u32> {
        let stem = name.rsplit_once('.').map_or(name, |(s, _)| s);
        stem.strip_prefix(TOOL_IMAGE_PREFIX)?.parse().ok()
    }

    /// The next free name. The number is taken whatever the extension: `tool-image-1.png`
    /// and `tool-image-1.jpg` are two different names to `resolve`, and two names one
    /// digit apart to a reader.
    fn next(&mut self, mime: &str) -> String {
        let mut n = 1;
        while !self.0.insert(n) {
            n += 1;
        }
        format!("{TOOL_IMAGE_PREFIX}{n}.{}", ext_of(mime))
    }
}

/// Decodes, downscales and re-encodes the images a tool returned, on the blocking pool.
///
/// The same preparation a user's `/image attach` gets, for the same reasons (spec §9.10):
/// third-party pixels must not cost more than the user's own, and a provider that takes
/// only png/jpeg must not be handed a webp. An image that fails to decode, or is over
/// `images.max_bytes`, is **dropped** — a half-broken picture is not something the model
/// can act on — as a `None` in its place, so the caller can say which one it was
/// (docs/history/sandbox-file-exchange.md §11 S8).
///
/// Names come from `taken`, which is handed back so the turn keeps them: naming happens
/// **after** the drop, so a result whose first image failed to decode does not hand the
/// second a number the model's own label contradicts.
async fn prepare_tool_images(
    images: Vec<crate::features::tools::ToolImage>,
    cfg: crate::shared::config::ImageSettings,
    mut taken: ToolImageNames,
) -> (
    Vec<Option<crate::entities::message_image::MessageImage>>,
    ToolImageNames,
) {
    if images.is_empty() {
        return (Vec::new(), taken);
    }
    // A task that never came back prepared nothing, and every image is said as dropped.
    let offered = images.len();
    tokio::task::spawn_blocking(move || {
        use base64::Engine as _;
        let b64 = base64::engine::general_purpose::STANDARD;
        let prepared = images
            .into_iter()
            .map(|image| {
                let raw = b64.decode(&image.data).ok()?;
                if raw.len() as u64 > cfg.max_bytes {
                    tracing::warn!(bytes = raw.len(), "tool image over the size cap, dropped");
                    return None;
                }
                let prepared =
                    crate::features::image_prepare::prepare(&raw, cfg.downscale_px).ok()?;
                Some(crate::entities::message_image::MessageImage::new(
                    taken.next(prepared.mime),
                    format!("tool:{}", Uuid::new_v4()),
                    prepared.mime,
                    prepared.width,
                    prepared.height,
                    b64.encode(&prepared.bytes),
                ))
            })
            .collect();
        (prepared, taken)
    })
    .await
    .unwrap_or_else(|_| {
        (
            std::iter::repeat_with(|| None).take(offered).collect(),
            ToolImageNames::default(),
        )
    })
}

/// Appends a note to a tool's result, a blank line after what the tool said.
fn push_note(result: &mut String, note: &str) {
    if !result.is_empty() {
        result.push_str("\n\n");
    }
    result.push_str(note);
}

/// What became of one image a tool offered.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ImageFate {
    /// It goes to the model with the result.
    Shown,
    /// The engine reports it takes no images, so none of the result's went.
    NoVision,
    /// The preparation dropped it: over `images.max_bytes`, or undecodable.
    Dropped,
}

/// Says what became of each image a call offered, in the result the model reads — the one
/// place that says it, because only the loop knows (spec §9.10).
///
/// An image the tool named on a line of its result (`ToolImage::entry`) is said at the end
/// of that line: " — shown to you below", or not shown and why. The tool used to write
/// "shown" itself, and on an engine without vision the loop's note below then contradicted
/// it in the same result. An image no line names — MCP's — is counted into one note per
/// reason, as before; a shown one needs no note, the image itself follows.
pub(super) fn say_image_fates(
    result: &mut String,
    loc: &crate::shared::i18n::Locale,
    entries: &[Option<String>],
    fates: &[ImageFate],
) {
    let (mut no_vision, mut dropped) = (0usize, 0usize);
    for (entry, fate) in entries.iter().zip(fates) {
        let suffix = match fate {
            ImageFate::Shown => "loop.image_shown",
            ImageFate::NoVision => "loop.image_not_shown_no_vision",
            ImageFate::Dropped => "loop.image_not_shown_dropped",
        };
        if let Some(line) = entry {
            if end_line(result, line, loc.t(suffix)) {
                continue;
            }
            tracing::warn!(line = %line, "a tool image's line is not in its result");
        }
        match fate {
            ImageFate::Shown => {}
            ImageFate::NoVision => no_vision += 1,
            ImageFate::Dropped => dropped += 1,
        }
    }
    for (n, key) in [
        (no_vision, "loop.images_no_vision"),
        (dropped, "loop.images_dropped"),
    ] {
        if n > 0 {
            push_note(result, &loc.tf(key, &[("n", &n.to_string())]));
        }
    }
}

/// Appends `suffix` to the **last** line of `text` that is exactly `line`, and says whether
/// there was one. The last, because a tool lists its files after the console output: code
/// that printed the same words must not have them claimed for its chart.
pub(super) fn end_line(text: &mut String, line: &str, suffix: &str) -> bool {
    let mut start = 0;
    let mut found = None;
    for piece in text.split_inclusive('\n') {
        if piece.strip_suffix('\n').unwrap_or(piece) == line {
            found = Some(start + line.len());
        }
        start += piece.len();
    }
    let Some(end) = found else {
        return false;
    };
    text.insert_str(end, suffix);
    true
}

/// The file extension matching a prepared image's MIME type.
fn ext_of(mime: &str) -> &'static str {
    if mime == "image/jpeg" { "jpg" } else { "png" }
}

/// Rebuilds the turn's attachment snapshot from the `AddAttachment` effects the
/// round produced, applying the same dedupe-by-source rule the orchestrator will
/// apply when it persists them — so what the model can read now and what ends up
/// in the chat file are the same set.
///
/// A no-op in the overwhelming majority of rounds (no such effect), so it checks
/// before rebuilding rather than cloning the list every round.
pub(super) fn sync_attachments(ctx: &mut ToolContext, effects: &[ChatEffect]) {
    let added: Vec<&crate::entities::attachment::Attachment> = effects
        .iter()
        .filter_map(|e| match e {
            ChatEffect::AddAttachment(a) => Some(a.as_ref()),
            _ => None,
        })
        .collect();
    if added.is_empty() {
        return;
    }
    let mut list: Vec<crate::entities::attachment::Attachment> = ctx.attachments.to_vec();
    for a in added {
        if list.iter().any(|x| x.id == a.id) {
            continue; // already mirrored by an earlier round
        }
        list.retain(|x| x.source != a.source);
        list.push(a.clone());
    }
    ctx.attachments = list.into();
}

/// Rebuilds the turn's stored-file snapshot from the `AddChatFile` effects so far, with
/// the rule the landing applies (a name already listed stays as it is) — so the next
/// round's `python_exec` versions its names against the files this turn already made
/// (docs/history/sandbox-file-exchange.md §11 S5). A no-op in a round without such an effect.
pub(super) fn sync_files(ctx: &mut ToolContext, effects: &[ChatEffect]) {
    let added: Vec<&crate::entities::chat_file::ChatFile> = effects
        .iter()
        .filter_map(|e| match e {
            ChatEffect::AddChatFile(f) => Some(f.as_ref()),
            _ => None,
        })
        .collect();
    if added.is_empty() {
        return;
    }
    let mut list: Vec<crate::entities::chat_file::ChatFile> = ctx.files.to_vec();
    for f in added {
        if !list
            .iter()
            .any(|x| crate::entities::chat_file::same_name(&x.name, &f.name))
        {
            list.push(f.clone());
        }
    }
    ctx.files = list.into();
}

/// The feed note for a failed turn.
///
/// One helper for **both** failure paths — the pre-stream `Err` and the in-stream
/// [`ChatChunk::Error`] — so the two can never drift into describing the same
/// condition differently.
///
/// - The conversation outgrew the window: say what to do about it rather than
///   handing back raw provider JSON in a generic wrapper. Which advice depends on
///   the switch — naming `/compact` while compression is off would send the user to
///   a command that refuses (spec §6.7, sub-decision S4).
/// - `partial` — text or "thoughts" already reached the screen, so the reply is a
///   fragment rather than a failure to answer. Saying only "generation error"
///   there leaves the user guessing whether what they can see is the whole
///   answer, which is the defect class this project keeps re-learning
///   (docs/lessons.md §4): name what happened *and* the way to a whole reply.
fn engine_error_note(
    err: &str,
    compaction_enabled: bool,
    partial: bool,
    continuable: bool,
    ui_loc: &'static crate::shared::i18n::Locale,
) -> String {
    ui_loc.tf(
        engine_error_key(err, compaction_enabled, partial, continuable),
        &[("err", err)],
    )
}

/// Which of the five things to tell the user — split out from
/// [`engine_error_note`] so the decision can be tested as a decision, without
/// asserting on localized prose. `continuable` — the mode can resume the kept
/// partial (`/continue`), so the note names the route that picks up where the
/// cut happened rather than only the one that starts over (fork F9).
pub(super) fn engine_error_key(
    err: &str,
    compaction_enabled: bool,
    partial: bool,
    continuable: bool,
) -> &'static str {
    match (
        crate::features::compaction::is_context_overflow(err),
        compaction_enabled,
        partial,
        continuable,
    ) {
        (true, true, _, _) => "ui.err.context_overflow",
        (true, false, _, _) => "ui.err.context_overflow_off",
        (false, _, true, true) => "ui.err.generation_interrupted_continuable",
        (false, _, true, false) => "ui.err.generation_interrupted",
        (false, _, false, _) => "ui.err.generation_failed",
    }
}

/// Streams a single request, relaying `Text`/`Thoughts` to the UI, accumulating
/// tool calls and the token counter. `base_tokens`/`base_reasoning` — tokens/
/// reasoning tokens accumulated by previous rounds; the UI counter grows
/// cumulatively. Returns the accumulated round.
#[allow(clippy::too_many_arguments)]
async fn stream_round(
    backend: &Arc<dyn EngineBackend>,
    request: ChatRequest,
    cancel: &CancellationToken,
    id: Uuid,
    sink: &RoundSink<'_>,
    counters: &TurnCounters,
    own_base_tokens: u64,
    own_base_reasoning: u32,
    ui_loc: &'static crate::shared::i18n::Locale,
    compaction_enabled: bool,
    continuation_supported: bool,
    mut echo: Option<EchoFilter>,
) -> RoundOutput {
    let mut text = String::new();
    let mut thoughts = String::new();
    let mut thinking = ThinkingAccumulator::default();
    let mut acc = ToolCallAccumulator::default();
    let mut reason = FinishReason::Stop;
    // Live count: the number of reply deltas (≈ tokens). If it arrives, the exact
    // value from the server's `usage` replaces the approximation.
    let mut streamed: u64 = 0;
    let mut usage_tokens: Option<u64> = None;
    // The exact prompt size, when the server reports one. Deliberately without an
    // estimate fallback — see `RoundOutput::prompt_tokens`.
    let mut usage_prompt: Option<u32> = None;
    // The engine's own clock over the prompt (llama.cpp's `timings`), for
    // the slow-prefill note (docs/research/slow-prefill-detection.md §3.1).
    let mut usage_prefill: Option<crate::shared::api::contract::Prefill> = None;
    // The round's reasoning tokens (from `usage`; `0` — the provider doesn't separate them).
    let mut round_reasoning: u32 = 0;

    // The reply counter: `context: None` leaves the prior conversation estimate
    // untouched (emitted by start_generation); the exact `context` only comes from the server's usage.
    // Each delta is counted into the turn's total as it arrives; the exact
    // `usage` corrects the total at the end (see the `Usage` arm).
    let emit_completion = |streamed: u64| {
        use std::sync::atomic::Ordering::Relaxed;
        counters.tokens.fetch_add(1, Relaxed);
        sink.tokens(TokenReport {
            turn_completion: counters.tokens.load(Relaxed),
            own_completion: own_base_tokens + streamed,
            turn_reasoning: None,
            own_reasoning: None,
            context: None,
            context_exact: false,
        });
    };

    match backend.chat_stream(request, cancel.clone()).await {
        Ok(mut stream) => {
            while let Some(chunk) = stream.next().await {
                match chunk {
                    ChatChunk::Text(t) => {
                        // A continuation round strips the server's echo of the
                        // prefill: the withheld bytes are already on screen and
                        // in the seed message (research §4d).
                        let visible = strip_echo(echo.as_mut(), t);
                        streamed += 1;
                        emit_completion(streamed);
                        relay_text(visible, &mut text, sink, id);
                    }
                    ChatChunk::Thoughts(t) => {
                        thoughts.push_str(&t);
                        streamed += 1;
                        sink.send(AppEvent::Thoughts {
                            generation_id: id,
                            text: t,
                        });
                        emit_completion(streamed);
                    }
                    // A reference to the reasoning (Anthropic signature / OpenAI
                    // reasoning item) — not shown in the UI, accumulated for resending
                    // on tool use: one entry per reasoning item on Responses (a reply
                    // may carry several), one block on Anthropic (`ThinkingAccumulator`).
                    ChatChunk::ThoughtsSignature(r) => thinking.push(r),
                    ChatChunk::ToolCall(delta) => acc.push(delta),
                    ChatChunk::Usage(u) => {
                        // The exact count from the server: both the reply and the
                        // conversation (prompt) — replaces the delta-based approximation
                        // and the conversation estimate. Reasoning tokens ("thoughts") —
                        // cumulative across rounds (base + current).
                        use std::sync::atomic::Ordering::Relaxed;
                        let exact = u.completion_tokens as u64;
                        usage_tokens = Some(exact);
                        usage_prompt = Some(u.prompt_tokens);
                        usage_prefill = u.prefill.or(usage_prefill);
                        round_reasoning = u.reasoning_tokens;
                        // Correct the turn's total from the delta count to the
                        // server's figure — the two differ by whatever a delta
                        // carried that was not exactly one token.
                        if exact >= streamed {
                            counters.tokens.fetch_add(exact - streamed, Relaxed);
                        } else {
                            counters.tokens.fetch_sub(streamed - exact, Relaxed);
                        }
                        counters.reasoning.fetch_add(u.reasoning_tokens, Relaxed);
                        sink.tokens(TokenReport {
                            turn_completion: counters.tokens.load(Relaxed),
                            own_completion: own_base_tokens + exact,
                            turn_reasoning: Some(counters.reasoning.load(Relaxed)),
                            own_reasoning: Some(own_base_reasoning + u.reasoning_tokens),
                            context: Some(u.prompt_tokens as u64),
                            context_exact: true,
                        });
                    }
                    // The engine is waiting before another attempt (spec §6.8). Not
                    // a failure yet, so nothing is recorded — only shown, and only
                    // while it lasts.
                    ChatChunk::Retry {
                        attempt,
                        max,
                        delay,
                    } => {
                        sink.send(AppEvent::Retrying {
                            generation_id: id,
                            attempt,
                            max,
                            // Rounded up: a chip reading "in 0 s" while it waits
                            // would be its own small lie.
                            delay_secs: delay.as_secs().max(1),
                        });
                    }
                    // A failure that arrived *after* the stream opened. Before this
                    // arm the reply simply stopped — the partial text was kept and
                    // persisted with nothing on screen saying why, so an overloaded
                    // provider looked like a model that had finished talking
                    // (docs/research/cloud-retry-backoff.md §1.2).
                    ChatChunk::Error { message, .. } => {
                        let partial = !text.is_empty() || !thoughts.is_empty();
                        // `/continue` resumes visible text, not a bare thought
                        // (fork F4) — so the note names it only for one.
                        let continuable = continuation_supported && !text.is_empty();
                        sink.send(AppEvent::Error(engine_error_note(
                            &message,
                            compaction_enabled,
                            partial,
                            continuable,
                            ui_loc,
                        )));
                        // The client always yields `Finished(Error)` next; setting the
                        // reason here keeps this correct even if one ever stops.
                        reason = FinishReason::Error;
                    }
                    ChatChunk::Finished(r) => {
                        reason = r;
                        break;
                    }
                }
            }
        }
        Err(err) => {
            let err = err.to_string();
            sink.send(AppEvent::Error(engine_error_note(
                &err,
                compaction_enabled,
                false,
                false,
                ui_loc,
            )));
            reason = FinishReason::Error;
        }
    }

    RoundOutput {
        text,
        thoughts,
        thinking: thinking.finish(),
        calls: acc.finish(),
        reason,
        tokens: usage_tokens.unwrap_or(streamed),
        prompt_tokens: usage_prompt,
        prefill: usage_prefill,
        reasoning_tokens: round_reasoning,
    }
}

/// The continuation echo filter over one text delta ([`stream_round`]'s `Text`
/// arm): with no filter armed the delta passes through whole.
fn strip_echo(echo: Option<&mut EchoFilter>, t: String) -> String {
    match echo {
        Some(f) => f.push(&t),
        None => t,
    }
}

/// Accumulates a visible text delta and relays it to the feed; an empty one (a
/// chunk the echo filter withheld whole) sends nothing.
fn relay_text(visible: String, text: &mut String, sink: &RoundSink<'_>, id: Uuid) {
    if visible.is_empty() {
        return;
    }
    text.push_str(&visible);
    sink.send(AppEvent::Chunk {
        generation_id: id,
        text: visible,
    });
}

/// Client-side estimate of the prompt's token count (the whole conversation) for
/// the live indicator before the server's exact `usage.prompt_tokens` arrives,
/// and for the session budget's reservations (admission-by-budget §4.2).
/// Accounts for the system message, message texts, tool-call arguments in
/// the history, and the tool schemas as the wire sends them — the largest
/// part of a turn's prompt (measured: 24 schemas, 18 116 bytes, about 4270
/// tokens against 85 for the rest of a fresh chat's request —
/// docs/research/roll-usage-calibration.md §2.1), counted as one part at
/// the text's bytes-per-token; the budget's calibration absorbs the
/// difference.
pub(super) fn estimate_prompt_tokens(req: &ChatRequest) -> u64 {
    let tools = (!req.tools.is_empty()).then(|| crate::shared::api::openai::tools_json(&req.tools));
    let mut parts: Vec<&str> = Vec::with_capacity(req.messages.len() + 1);
    for m in &req.messages {
        parts.push(m.content.as_str());
        for tc in &m.tool_calls {
            parts.push(tc.arguments.as_str());
        }
    }
    if let Some(t) = &tools {
        parts.push(t.as_str());
    }
    estimate_prompt(req.system.as_deref(), parts)
}

/// Blends relevant and recent self-notes for relevance-based injection
/// (Tier 2): first the relevant ones (in decreasing order of closeness, up to
/// `n`), then **the freshest observation is guaranteed** (continuity of "what I
/// just noticed") — bumping the last relevant one out if there's no room.
/// Dedup by id. A pure function — testable.
pub(super) fn blend_self_notes(
    relevant: Vec<crate::entities::note::Note>,
    fresh: &[crate::entities::note::Note],
    n: usize,
) -> Vec<crate::entities::note::Note> {
    let mut out: Vec<crate::entities::note::Note> = Vec::new();
    let mut seen: std::collections::HashSet<Uuid> = std::collections::HashSet::new();
    for r in relevant {
        if out.len() >= n {
            break;
        }
        if seen.insert(r.id) {
            out.push(r);
        }
    }
    if let Some(f) = fresh.first()
        && !seen.contains(&f.id)
    {
        if out.len() >= n && !out.is_empty() {
            out.pop();
        }
        out.push(f.clone());
    }
    out
}

/// Gathers observations (self-notes) for injection into the system prompt (Tier 2):
/// **relevant** to the latest reply + a guaranteed freshest observation, with a fallback to
/// plain recency when the embedder is unavailable/the query is empty. Empty if injection is
/// disabled. Async (embedding the query) — that's why it's factored out of the sync handler into
/// the generation task. Tested over a temp store + `MockEmbedder`.
pub(super) async fn injection_recent(
    storage: &crate::shared::storage::Storage,
    embedder: &dyn crate::shared::api::Embedder,
    profile_id: Uuid,
    inject_enabled: bool,
    last_user: &str,
    params: &crate::entities::self_model::SelfModelParams,
) -> Vec<crate::entities::self_model::NarrativeSegment> {
    if !inject_enabled {
        return Vec::new();
    }
    use crate::features::tools::notes;
    let n = params.narrative_in_prompt;
    let fresh = notes::self_notes_recent(storage, profile_id, params.max_narrative);
    // Observations relevant to the latest reply; empty → fall back to recency.
    let relevant = notes::self_notes_relevant(storage, embedder, profile_id, last_user, n).await;
    let picked = if relevant.is_empty() {
        fresh
    } else {
        blend_self_notes(relevant, &fresh, n)
    };
    picked
        .into_iter()
        .map(|nt| crate::entities::self_model::NarrativeSegment {
            id: nt.id,
            text: nt.content,
            created_at: nt.created_at,
        })
        .collect()
}

/// Mixes the "self-model" into the turn's system prompt (SelfModel MVP, see
/// docs/history/self-model-mvp.md): a compact render of the current model (if non-empty) plus,
/// when `maintenance_protocol` is on, a persona-neutral maintenance protocol. Returns
/// the previous `system` unchanged if injection is disabled (the profile hasn't enabled
/// `get_self_model`) or there's nothing to mix in (an empty model and the protocol is off).
/// The protocol is mixed in even for an empty model — to get the model to start maintaining it.
/// A pure function — testable with no engine.
#[allow(clippy::too_many_arguments)]
pub(super) fn inject_self_model(
    system: Option<String>,
    model: Option<&crate::entities::self_model::SelfModel>,
    enabled: bool,
    maintenance_protocol: bool,
    params: &crate::entities::self_model::SelfModelParams,
    now: chrono::DateTime<chrono::Utc>,
    recent: &[crate::entities::self_model::NarrativeSegment],
    loc: &crate::shared::i18n::Locale,
) -> Option<String> {
    if !enabled {
        return system;
    }
    // Observations (self-notes) can exist without the model blob — then we render
    // an empty model with observations. `render_for_prompt` returns None only if it's empty
    // both structurally and in observations.
    let empty;
    let m = match model {
        Some(m) => m,
        None => {
            empty = crate::entities::self_model::SelfModel::new(uuid::Uuid::nil());
            &empty
        }
    };
    let block = m.render_for_prompt(
        params.prompt_cap,
        params.narrative_in_prompt,
        now,
        recent,
        loc,
    );
    // Gather the parts to mix in: the model render (if any) + the protocol (if enabled).
    let mut parts: Vec<String> = Vec::new();
    if let Some(b) = block {
        parts.push(b);
    }
    if maintenance_protocol {
        // The maintenance protocol is assembled from the shared POLICY_CORE (stage 6) — the same
        // rules as the background auto-reflection.
        parts.push(crate::features::tools::self_model::maintenance_protocol(
            loc,
        ));
        // A data-aware note: if the self-description has grown past its target —
        // a concrete hint to shorten it (the static protocol becomes specific once
        // the summary is actually bloated). See docs/summary-as-snapshot.md (stage 2).
        if let Some(hint) = m.summary_fill_hint(params.summary_target_chars, loc) {
            parts.push(format!("({hint})"));
        }
    }
    if parts.is_empty() {
        return system; // nothing to mix in
    }
    let inject = parts.join("\n\n");
    Some(match system {
        Some(s) => format!("{s}\n\n{inject}"),
        None => inject,
    })
}

/// A domain tool message (role `Tool`) tied to the call.
fn tool_message(call: &ApiToolCall, result: String) -> Message {
    let mut m = Message::new(MessageRole::Tool, result);
    m.tool_call_id = Some(call.id.clone());
    m.tool_name = Some(call.name.clone());
    m
}

/// The turn's final assistant message (if there's text/thoughts) with a metadata
/// snapshot: the engine mode, model name, and sampling, **pared down to the fields
/// available in that mode** (the engine wouldn't accept an unavailable field — spec §8.3).
/// The round's finish reason is recorded too (`MessageFinish`, spec §6.4) — it is
/// what lets `/continue` tell an interrupted reply from a completed one.
fn finalize_message(
    out: &RoundOutput,
    sampling: &SamplingConfig,
    mode: ServerMode,
    model: &Option<String>,
    endpoint_fields: Option<&[String]>,
) -> Option<Message> {
    if out.text.is_empty() && out.thoughts.is_empty() {
        return None;
    }
    let mut m = Message::assistant(out.text.clone());
    if !out.thoughts.is_empty() {
        m.thoughts = Some(out.thoughts.clone());
    }
    m.metadata = Some(MessageMetadata {
        // G3(ii): the snapshot records what was *applied*, so it must not name a
        // field the endpoint drops — that is the same lie as the settings screen
        // showing it, and this is the copy that survives into the chat file
        // (docs/history/gateway-capabilities.md §4).
        sampling: sampling.retain_supported(mode.cloud_provider(), endpoint_fields),
        mode,
        model: model.clone(),
        finish: Some(match out.reason {
            FinishReason::Length => MessageFinish::Length,
            FinishReason::Cancelled => MessageFinish::Cancelled,
            FinishReason::Error => MessageFinish::Error,
            // `ToolCalls` reaches here only with an empty call list (a claim
            // with nothing behind it) — the round ended like a plain stop.
            // `Filtered` is stored as a stop too: `/continue` refuses it, which is
            // right, since resuming meets the same filter, and a value of its own
            // would be a chat-format change for a record nothing reads
            // (docs/research/content-filter-finish.md, fork C2).
            FinishReason::Stop | FinishReason::ToolCalls | FinishReason::Filtered => {
                MessageFinish::Stop
            }
        }),
    });
    Some(m)
}

/// Folds the continuation round's first assistant message into the seed
/// message it continues, in place (`/continue`, fork F8): the text is appended
/// byte-exactly — the seam is the model's own, already echo-stripped — the
/// thoughts are joined, tool calls extend, and the metadata becomes the
/// round's, except the model name, which stays the seed's unless the
/// continuation outgrew what it continued (fork F7). The message keeps its id
/// and timestamp: it is the same reply, finished later.
pub(super) fn merge_continuation(seed: &mut Message, round: Message) {
    let seed_len = seed.text.len();
    seed.text.push_str(&round.text);
    if let Some(t) = round.thoughts {
        match &mut seed.thoughts {
            Some(existing) => {
                existing.push_str("\n\n");
                existing.push_str(&t);
            }
            None => seed.thoughts = Some(t),
        }
    }
    seed.tool_calls.extend(round.tool_calls);
    let kept_model = seed.metadata.as_ref().and_then(|md| md.model.clone());
    let outgrown = round.text.len() > seed_len;
    if let Some(mut md) = round.metadata {
        if !outgrown && kept_model.is_some() {
            md.model = kept_model;
        }
        seed.metadata = Some(md);
    }
}

/// A round that never streamed: cancelled while waiting for a session, or for
/// room in the pool (`SessionBudget::acquire`). Nothing was produced, nothing
/// was counted, and the loop lands what it already has.
fn cancelled_round() -> RoundOutput {
    RoundOutput {
        text: String::new(),
        thoughts: String::new(),
        thinking: Vec::new(),
        calls: Vec::new(),
        reason: FinishReason::Cancelled,
        tokens: 0,
        prompt_tokens: None,
        prefill: None,
        reasoning_tokens: 0,
    }
}

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

    /// The round a loop lands when cancelled before it could stream: nothing
    /// produced, nothing counted (the budget's own waits are tested with it,
    /// `shared::session_budget`).
    #[test]
    fn a_round_cancelled_while_waiting_is_empty() {
        let round = cancelled_round();
        assert_eq!(round.reason, FinishReason::Cancelled);
        assert_eq!((round.tokens, round.prompt_tokens), (0, None));
        assert!(round.text.is_empty() && round.calls.is_empty());
    }
}