mindfork 0.17.0

A terminal AI chat written in Rust: local models via llama.cpp, or OpenAI, Anthropic, Gemini, Grok and OpenRouter 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
//! Global application configuration (`settings.json`). See spec §12.1.
//! Versioned via the `schema_version` field for future migrations.

use serde::{Deserialize, Serialize};

use crate::entities::sampling::SamplingConfig;
use crate::shared::embed_prefix::EmbedConvention;
use crate::shared::gguf::display_name;
use crate::shared::secrets::{ExternalSlot, SecretKey};

/// Current config schema version.
pub const SCHEMA_VERSION: u32 = 5;

/// Inference-engine connection mode. Local (`Managed`/`External`) and cloud
/// providers (`OpenAi`/`Gemini`) are equal-footing variants of a single selector
/// (flat taxonomy, [ADR 0004](decisions/0004-engine-contract-multi-provider.md)).
/// Claude is added in Phase 2 (a separate `/v1/messages` protocol).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ServerMode {
    /// The app itself launches a child `llama-server` process.
    #[default]
    Managed,
    /// Connecting to an already-running OpenAI-compatible server (any: llama.cpp,
    /// vLLM, LM Studio…). Sampling fields are sent as-is (lenient dialect).
    External,
    /// OpenAI cloud (`platform.openai.com`). Strict OpenAI dialect + Bearer key.
    #[serde(rename = "openai")]
    OpenAi,
    /// Google Gemini cloud via an OpenAI-compatible endpoint. Strict dialect + key.
    Gemini,
    /// Anthropic cloud (`platform.claude.com`). A separate Messages API protocol
    /// (`/v1/messages`), `x-api-key`. See ADR 0004, Phase 2.
    Claude,
    /// xAI cloud (`console.x.ai`), the Grok models. Plain OpenAI Chat Completions
    /// (`OpenAiClient`) — the only cloud whose OpenAI-compatible path also carries
    /// reasoning (`delta.reasoning_content`) and needs no thinking-signature
    /// round-trip. See docs/research/grok-xai-provider.md.
    Grok,
    /// The OpenRouter gateway (`openrouter.ai`): one key in front of every
    /// vendor's models, spoken to as Chat Completions (`OpenAiClient`) in the
    /// gateway's own dialect. A mode of its own rather than a URL typed into
    /// `external`, so that the local server and the gateway each keep their
    /// settings and one key serves every slot. See
    /// docs/research/openrouter-mode.md.
    #[serde(rename = "openrouter")]
    OpenRouter,
}

/// Inference cloud provider. `OpenAi`/`Gemini` speak the OpenAI protocol,
/// `Claude` — the Anthropic Messages API. Carries a default base URL.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CloudProvider {
    OpenAi,
    Gemini,
    Claude,
    Grok,
    OpenRouter,
}

impl CloudProvider {
    /// Every provider, in the order the per-provider arrays taken by
    /// [`cloud_ref`]/[`cloud_mut`] are indexed (and the order the settings UI
    /// cycles through them).
    pub const ALL: [CloudProvider; 5] = [
        CloudProvider::OpenAi,
        CloudProvider::Gemini,
        CloudProvider::Claude,
        CloudProvider::Grok,
        CloudProvider::OpenRouter,
    ];

    /// Position in [`Self::ALL`]. Adding a provider then costs one array element
    /// per settings struct instead of another positional argument on
    /// [`cloud_ref`]/[`cloud_mut`] (which a fourth provider would have grown to
    /// six).
    fn index(self) -> usize {
        match self {
            CloudProvider::OpenAi => 0,
            CloudProvider::Gemini => 1,
            CloudProvider::Claude => 2,
            CloudProvider::Grok => 3,
            CloudProvider::OpenRouter => 4,
        }
    }
    /// Base URL for **embeddings**/compat access (an OpenAI-compatible
    /// endpoint). For Gemini this is the compat path `…/v1beta/openai` (RAG
    /// embeddings go through it, `OpenAiClient`). Overridable via the `url` field.
    pub fn base_url(self) -> &'static str {
        match self {
            CloudProvider::OpenAi => "https://api.openai.com/v1",
            CloudProvider::Gemini => "https://generativelanguage.googleapis.com/v1beta/openai",
            // The Anthropic client appends `/v1/messages` itself, hence no suffix.
            CloudProvider::Claude => "https://api.anthropic.com",
            // xAI has no embedding models at all (docs/research/grok-xai-provider.md
            // §2.7) — this URL only serves as the chat base, which is the same path.
            CloudProvider::Grok => "https://api.x.ai/v1",
            // One base for chat, embeddings, the catalogue and the key check
            // (docs/research/openrouter-mode.md §3.1).
            CloudProvider::OpenRouter => "https://openrouter.ai/api/v1",
        }
    }

    /// Base URL for **chat** (the client's native protocol). For Gemini — `…/v1beta`
    /// (the native `GeminiClient` appends `/models/{model}:streamGenerateContent`),
    /// unlike the embeddings compat path ([`base_url`](Self::base_url)). For OpenAI
    /// (Responses) and Claude it matches `base_url`. Overridable via the `url` field.
    pub fn chat_base_url(self) -> &'static str {
        match self {
            CloudProvider::Gemini => "https://generativelanguage.googleapis.com/v1beta",
            CloudProvider::OpenAi
            | CloudProvider::Claude
            | CloudProvider::Grok
            | CloudProvider::OpenRouter => self.base_url(),
        }
    }

    /// Stable provider string key — indexes stored API keys
    /// (`AppConfig::api_keys`, see `shared::secrets`). The key is **shared** across
    /// chat, impersonation, and embeddings for this provider. Values persist in
    /// `settings.json` — do not rename.
    pub fn key(self) -> &'static str {
        match self {
            CloudProvider::OpenAi => "openai",
            CloudProvider::Gemini => "gemini",
            CloudProvider::Claude => "claude",
            CloudProvider::Grok => "grok",
            CloudProvider::OpenRouter => "openrouter",
        }
    }

    /// The provider's name as the UI spells it — a brand, the same word in every
    /// locale. Settings rows that hold a key say **whose** key it is (spec
    /// §11.6): one key serves chat, impersonation, embeddings and speech of one
    /// provider (ADR 0008), and those four slots may point at four different
    /// providers at once. Not [`key`](Self::key) — that spelling is persisted
    /// storage and must not be prettified.
    pub fn display_name(self) -> &'static str {
        match self {
            CloudProvider::OpenAi => "OpenAI",
            CloudProvider::Gemini => "Gemini",
            CloudProvider::Claude => "Claude",
            CloudProvider::Grok => "Grok",
            CloudProvider::OpenRouter => "OpenRouter",
        }
    }
}

impl ServerMode {
    /// Cloud provider for this mode (`None` — local managed/external).
    pub fn cloud_provider(self) -> Option<CloudProvider> {
        match self {
            ServerMode::OpenAi => Some(CloudProvider::OpenAi),
            ServerMode::Gemini => Some(CloudProvider::Gemini),
            ServerMode::Claude => Some(CloudProvider::Claude),
            ServerMode::Grok => Some(CloudProvider::Grok),
            ServerMode::OpenRouter => Some(CloudProvider::OpenRouter),
            ServerMode::Managed | ServerMode::External => None,
        }
    }

    /// Stable string key for storage and tool results — the serde spelling of
    /// the variant (pinned by `server_mode_key_matches_serde`). Values persist
    /// in `data.db` (`llm_history.mode`, spec §9.14) — do not rename.
    pub fn key(self) -> &'static str {
        match self {
            ServerMode::Managed => "managed",
            ServerMode::External => "external",
            ServerMode::OpenAi => "openai",
            ServerMode::Gemini => "gemini",
            ServerMode::Claude => "claude",
            ServerMode::Grok => "grok",
            ServerMode::OpenRouter => "openrouter",
        }
    }

    /// The inverse of [`Self::key`] (`None` — not a mode this build knows).
    pub fn from_key(key: &str) -> Option<Self> {
        ServerMode::ALL.into_iter().find(|m| m.key() == key)
    }

    /// Every mode, in the settings UI's order.
    pub const ALL: [ServerMode; 7] = [
        ServerMode::Managed,
        ServerMode::External,
        ServerMode::OpenAi,
        ServerMode::Gemini,
        ServerMode::Claude,
        ServerMode::Grok,
        ServerMode::OpenRouter,
    ];

    /// Whether `/continue` can resume a partial reply in this mode and, for
    /// Anthropic, on this model — i.e. the server continues a trailing
    /// assistant message in place (assistant prefill / continue-final-message).
    /// The single source of truth for the command's gate and the interruption
    /// notes, mirroring
    /// [`supported_sampling_fields`](crate::entities::sampling::supported_sampling_fields).
    ///
    /// Measured per provider in docs/research/continue-generation.md §2/§7.1:
    /// llama.cpp continues by default and vLLM via the explicit fields (both
    /// behind managed/external); Gemini continues a trailing `model` turn
    /// (measured live — undocumented, so the probe stays in the smoke set);
    /// Anthropic continues on models up to the 4.5 generation and returns a
    /// `400` from 4.6 on ("This model does not support assistant message
    /// prefill", pinned in `continue_probe`) — see
    /// [`anthropic_model_continues`]; OpenAI cannot; Grok measurably restarts.
    ///
    /// `catalogued` — the endpoint published a catalogue entry for the model,
    /// which is what a gateway does and a llama.cpp never does. Through a
    /// gateway the answer belongs to the route it picks, and measured per route
    /// only Anthropic ≤ 4.5 and Gemini continue — every open-weight route and
    /// OpenAI restart, which the echo filter would glue onto the partial
    /// (docs/history/gateway-images-and-continue.md §1.3, fork H2). Without a catalogue
    /// `external` answers as it always did.
    ///
    /// `OpenRouter` is that gateway by name, so it asks the slug whether or not
    /// the catalogue has answered yet: there is no llama.cpp behind this mode
    /// for silence to mean (docs/research/openrouter-mode.md §2.3).
    pub fn supports_continuation(self, model: Option<&str>, catalogued: bool) -> bool {
        match self {
            ServerMode::OpenRouter => model.is_some_and(gateway_model_continues),
            ServerMode::External if catalogued => model.is_some_and(gateway_model_continues),
            ServerMode::Managed | ServerMode::External | ServerMode::Gemini => true,
            ServerMode::Claude => model.is_some_and(anthropic_model_continues),
            ServerMode::OpenAi | ServerMode::Grok => false,
        }
    }
}

/// Whether an Anthropic model still accepts assistant prefill: every model up
/// to the 4.5 generation does, everything from 4.6 on rejects it, and the
/// removal is forward-going — so this is an *allowlist by version*, not a
/// blocklist by name, and an id whose generation cannot be read refuses
/// (capability is asked, never guessed — the images-feature discipline).
///
/// The generation is read off the id's first two short numeric segments:
/// `claude-haiku-4-5` and `claude-sonnet-4-5-20250929` → 4.5 (a date segment
/// is longer than two digits and is skipped), `claude-3-5-sonnet-20241022` →
/// 3.5, `claude-opus-5` → 5.0, `claude-fable-5` → 5.0.
fn anthropic_model_continues(model: &str) -> bool {
    let mut nums = model
        .split(['-', '.', '@'])
        .filter(|s| !s.is_empty() && s.len() <= 2 && s.bytes().all(|b| b.is_ascii_digit()))
        .filter_map(|s| s.parse::<u32>().ok());
    let Some(major) = nums.next() else {
        return false;
    };
    let minor = nums.next().unwrap_or(0);
    major < 4 || (major == 4 && minor <= 5)
}

/// Whether a gateway slug (`vendor/model`) names a family whose direct mode
/// continues a partial reply — the spec §6.4 table applied to the vendor half,
/// because a gateway exposes no capability of its own here. An Anthropic model
/// asks [`anthropic_model_continues`]; a Google Gemini continues; every other
/// vendor, and a slug with no vendor, refuses rather than being guessed at. A
/// `:variant` suffix (`:batch`, `:thinking`) is dropped first: left on, it would
/// hide the minor version (`4.6:batch` reads as 4.0).
fn gateway_model_continues(slug: &str) -> bool {
    let slug = slug.split(':').next().unwrap_or_default();
    let Some((vendor, model)) = slug.split_once('/') else {
        return false;
    };
    if vendor.eq_ignore_ascii_case("anthropic") {
        anthropic_model_continues(model)
    } else if vendor.eq_ignore_ascii_case("google") {
        model.to_ascii_lowercase().starts_with("gemini")
    } else {
        false
    }
}

/// Default number of GPU layers (`-ngl`): everything on GPU.
pub const DEFAULT_GPU_LAYERS: i32 = 99;
/// Default context size (`-c`).
pub const DEFAULT_CONTEXT_SIZE: u32 = 8192;
/// Default number of request streams the app keeps open against one engine at
/// a time (`sessions`, spec §11.6; docs/research/parallel-subagents.md §4.2).
/// One — the main agent and its sub-agents take turns, exactly as before the
/// setting existed.
pub const DEFAULT_SESSIONS: u32 = 1;
/// Default width of a round's concurrent tool group on a **local** engine
/// (`concurrent_calls` of `managed`/`external`, spec §6.3;
/// docs/research/concurrent-tools.md §4.4, fork F3): one — the sequential
/// round, bit for bit, until the user raises it. The machine the user is
/// sitting at, sharing one context pool with every stream of the turn.
pub const DEFAULT_CONCURRENT_CALLS_LOCAL: u32 = 1;
/// The same on a **cloud** provider: four — the reads and page fetches the
/// model issues in one reply overlap out of the box; someone else's fleet.
pub const DEFAULT_CONCURRENT_CALLS_CLOUD: u32 = 4;

/// FlashAttention mode (`--flash-attn`) for the managed llama.cpp server. `Auto` —
/// the flag isn't passed (llama.cpp decides on its own, its default); `On`/`Off` — forced.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FlashAttn {
    #[default]
    Auto,
    On,
    Off,
}

impl FlashAttn {
    /// All variants in UI-cycle order (for the Choice popup and the cycle).
    pub const ALL: [FlashAttn; 3] = [FlashAttn::Auto, FlashAttn::On, FlashAttn::Off];

    /// Value for `--flash-attn`; `None` (Auto) — don't pass the flag.
    pub fn as_arg(self) -> Option<&'static str> {
        match self {
            FlashAttn::Auto => None,
            FlashAttn::On => Some("on"),
            FlashAttn::Off => Some("off"),
        }
    }

    /// UI label (Choice field).
    pub fn label(self) -> &'static str {
        match self {
            FlashAttn::Auto => "auto",
            FlashAttn::On => "on",
            FlashAttn::Off => "off",
        }
    }

    /// Cyclic iteration honoring direction (`dir` = +1/-1).
    pub fn cycle(self, dir: i32) -> Self {
        let idx = Self::ALL.iter().position(|x| *x == self).unwrap_or(0) as i32;
        let n = Self::ALL.len() as i32;
        Self::ALL[(((idx + dir) % n + n) % n) as usize]
    }
}

/// Speculative-decoding type (`--spec-type`) for the managed llama.cpp server.
/// `None` — off (the flag isn't passed). `draft-*` types need a draft model
/// (`-md`) — for MTP models (e.g. `mtp-gemma-4-12B-it.gguf`) that's `draft-mtp`;
/// `ngram-*` need no separate model (the draft comes from the context history).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum SpecType {
    #[default]
    None,
    DraftSimple,
    DraftEagle3,
    DraftMtp,
    NgramSimple,
    NgramMapK,
    NgramMapK4v,
    NgramMod,
    NgramCache,
}

impl SpecType {
    /// All variants in UI-cycle order (for the Choice popup and the cycle).
    pub const ALL: [SpecType; 9] = [
        SpecType::None,
        SpecType::DraftSimple,
        SpecType::DraftEagle3,
        SpecType::DraftMtp,
        SpecType::NgramSimple,
        SpecType::NgramMapK,
        SpecType::NgramMapK4v,
        SpecType::NgramMod,
        SpecType::NgramCache,
    ];

    /// Value for `--spec-type`; `None` — don't pass the flag (off).
    pub fn as_arg(self) -> Option<&'static str> {
        match self {
            SpecType::None => Option::None,
            SpecType::DraftSimple => Some("draft-simple"),
            SpecType::DraftEagle3 => Some("draft-eagle3"),
            SpecType::DraftMtp => Some("draft-mtp"),
            SpecType::NgramSimple => Some("ngram-simple"),
            SpecType::NgramMapK => Some("ngram-map-k"),
            SpecType::NgramMapK4v => Some("ngram-map-k4v"),
            SpecType::NgramMod => Some("ngram-mod"),
            SpecType::NgramCache => Some("ngram-cache"),
        }
    }

    /// Whether the type needs a separate draft model (`-md`): only `draft-*`.
    pub fn needs_draft_model(self) -> bool {
        matches!(
            self,
            SpecType::DraftSimple | SpecType::DraftEagle3 | SpecType::DraftMtp
        )
    }

    /// UI label (Choice field).
    pub fn label(self) -> &'static str {
        self.as_arg().unwrap_or("none")
    }

    /// Cyclic iteration honoring direction (`dir` = +1/-1).
    pub fn cycle(self, dir: i32) -> Self {
        let idx = Self::ALL.iter().position(|x| *x == self).unwrap_or(0) as i32;
        let n = Self::ALL.len() as i32;
        Self::ALL[(((idx + dir) % n + n) % n) as usize]
    }
}

/// Settings for the local managed `llama-server` (llama.cpp): the app launches
/// it as a child process. Its own sub-section in every engine, so switching modes
/// doesn't lose these values. See docs/install.md §3.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ManagedSettings {
    /// Path to the `llama-server` binary.
    pub binary: Option<String>,
    /// Path to the GGUF model (`-m`).
    pub model_path: Option<String>,
    /// Path to the multimodal projector (`--mmproj`) — the second GGUF that ships
    /// next to a vision model's weights and turns image pixels into the tokens the
    /// language model reads. Without it `llama-server` loads a text-only model and
    /// reports `modalities.vision: false` on `/props`, which is exactly how the app
    /// learns it cannot take images (spec §9.10). Changing it restarts the server.
    pub mmproj: Option<String>,
    /// GPU layers (`-ngl`).
    pub gpu_layers: i32,
    /// Context size (`-c`).
    pub context_size: u32,
    /// The server's batch (`-b`, with `-ub min(n, 512)`): how many prompt
    /// tokens one pass processes before the server looks at its queue — the
    /// batch a stopped or displaced stream holds its slot for
    /// (docs/research/cpu-batch.md §4). `None` — auto: 256 when `gpu_layers`
    /// is 0 (the engine runs on the CPU by the user's own setting; measured:
    /// a quarter of the wait for a seventh of the prompt processing),
    /// otherwise the flag is not passed and the server's default stands.
    pub batch_size: Option<u32>,
    /// Simultaneous request streams the app may keep open against this server
    /// (spec §11.6). Above 1 the server is launched with `-np N --kv-unified`:
    /// N slots sharing the one context pool `-c` sizes — the shape llama.cpp
    /// itself picks when `-np` is not given (four slots, unified), so the pool
    /// costs the same memory whatever this says
    /// (docs/research/parallel-subagents.md §4.7, fork F4). At 1 the launch
    /// line is exactly what it was before the field existed.
    pub sessions: u32,
    /// How many of a round's concurrent tool calls — the reads and page
    /// fetches the model issues in one reply — run at once (spec §6.3,
    /// docs/research/concurrent-tools.md §4.4). Default 1 on a local engine:
    /// the sequential round, bit for bit.
    pub concurrent_calls: u32,
    /// Use the model's built-in chat template (`--jinja`) — needed for correct
    /// formatting and tool calling.
    pub jinja: bool,
    /// Reasoning format (`--reasoning-format`, e.g. `auto`); `None` — leave unset.
    pub reasoning_format: Option<String>,
    /// Don't use mmap when loading the model (`--no-mmap`): weights load into RAM
    /// entirely. Helps on network/slow disks. Off by default.
    pub no_mmap: bool,
    /// FlashAttention (`--flash-attn`): attention optimization. Default `Auto`.
    pub flash_attn: FlashAttn,
    /// Speculative-decoding type (`--spec-type`). Off by default.
    pub spec_type: SpecType,
    /// Draft model for speculative decoding (`-md`/`--model-draft`).
    /// Needed for `draft-*` types; for MTP models — the path to the matching GGUF.
    pub draft_model: Option<String>,
    /// Draft-model GPU layers (`-ngld`); `None` — auto (flag not passed).
    pub draft_gpu_layers: Option<i32>,
    /// How many tokens to draft per step (`--spec-draft-n-max`); `None` —
    /// llama.cpp's default (3).
    pub draft_n_max: Option<u32>,
    /// Minimum draft tokens per step (`--spec-draft-n-min`); `None` — default (0).
    pub draft_n_min: Option<u32>,
    /// Bind interface (`--host`), e.g. `127.0.0.1` or `0.0.0.0`.
    pub host: String,
    pub port: u16,
    /// Raw `llama-server` arguments appended to the line the fields above build
    /// (spec §3.4) — for what has no field: `--n-cpu-moe 20`, `-ot …=CPU`, `-t 8`.
    /// Edited as one command line (`shared::cmdline`); a flag one of these fields
    /// writes, or one that would lock the app out, arm the server with tools or
    /// have it fetch models, is refused (`shared::api::llama_args`,
    /// docs/research/managed-extra-args.md). Changing it restarts the server.
    pub extra_args: Vec<String>,
}

impl Default for ManagedSettings {
    fn default() -> Self {
        Self {
            binary: None,
            model_path: None,
            mmproj: None,
            gpu_layers: DEFAULT_GPU_LAYERS,
            context_size: DEFAULT_CONTEXT_SIZE,
            batch_size: None,
            sessions: DEFAULT_SESSIONS,
            concurrent_calls: DEFAULT_CONCURRENT_CALLS_LOCAL,
            jinja: true,
            reasoning_format: None,
            no_mmap: false,
            flash_attn: FlashAttn::default(),
            spec_type: SpecType::default(),
            draft_model: None,
            draft_gpu_layers: None,
            draft_n_max: None,
            draft_n_min: None,
            host: "127.0.0.1".to_string(),
            port: 8000,
            extra_args: Vec::new(),
        }
    }
}

/// External-mode settings: connecting to an already-running OpenAI-compatible
/// server (any: llama.cpp, vLLM, LM Studio…).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ExternalSettings {
    /// Server URL (e.g. `http://127.0.0.1:8000/v1`).
    pub url: Option<String>,
    /// Model name for a multi-model server (optional).
    pub model_name: Option<String>,
    /// Simultaneous request streams the app may keep open against this server
    /// (spec §11.6). Typed, never discovered: a llama.cpp behind the URL
    /// reports its slot count on `/props`, which the settings screen shows as
    /// a hint next to this field, but what the app actually opens is what is
    /// written here (docs/research/parallel-subagents.md fork F8). Default 1.
    pub sessions: u32,
    /// Width of a round's concurrent tool group (spec §6.3,
    /// docs/research/concurrent-tools.md §4.4). Default 1 — a local engine.
    pub concurrent_calls: u32,
    /// Env-variable name carrying a Bearer key (optional) — for an OpenAI-compatible
    /// proxy/gateway that requires authorization. Stores the **name**, not the secret
    /// (ADR 0004). `None`/empty — no authorization (a local `llama-server` doesn't need it).
    ///
    /// A **fallback**, since docs/history/external-api-key.md: the key can also be entered
    /// in settings and kept machine-encrypted under this slot's
    /// [`crate::shared::secrets::ExternalSlot`], and a stored key wins over the
    /// variable named here (ADR 0008 §3, F2).
    pub api_key_env: Option<String>,
}

impl Default for ExternalSettings {
    fn default() -> Self {
        Self {
            url: None,
            model_name: None,
            sessions: DEFAULT_SESSIONS,
            concurrent_calls: DEFAULT_CONCURRENT_CALLS_LOCAL,
            api_key_env: None,
        }
    }
}

/// Settings for a single cloud provider (OpenAI/Gemini/Claude/Grok). Stored
/// separately per provider so switching providers doesn't lose the other's values.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct CloudSettings {
    /// Provider's model name (`gpt-4o`, `gemini-2.5-pro`, `claude-opus-4-8`, `grok-4.5`).
    pub model_name: Option<String>,
    /// Env-variable name carrying the API key (e.g. `OPENAI_API_KEY`). Stores
    /// the **name**, not the secret itself — the key is read from the environment (ADR 0004).
    pub api_key_env: Option<String>,
    /// Override of the provider's base URL (optional); `None` — the provider's default.
    pub url: Option<String>,
    /// Simultaneous request streams the app may keep open against this
    /// provider (spec §11.6) — the user's statement of what their tier allows;
    /// a `429` when it is optimistic is absorbed by the retry decorator
    /// (docs/research/parallel-subagents.md §4.8). Default 1.
    pub sessions: u32,
    /// Width of a round's concurrent tool group (spec §6.3,
    /// docs/research/concurrent-tools.md §4.4). Default 4 on a cloud: the
    /// reads and page fetches of one reply overlap out of the box.
    pub concurrent_calls: u32,
}

impl Default for CloudSettings {
    fn default() -> Self {
        Self {
            model_name: None,
            api_key_env: None,
            url: None,
            sessions: DEFAULT_SESSIONS,
            concurrent_calls: DEFAULT_CONCURRENT_CALLS_CLOUD,
        }
    }
}

/// Chat inference-server settings. A sub-section per mode/provider
/// (managed/external/openai/gemini/claude/grok), so switching modes doesn't lose
/// the other's values. Transport — OpenAI-compatible HTTP (except Claude —
/// Messages API). See docs/install.md §3, ADR 0004.
/// Every environment variable the settings name as the source of a key — whatever it is
/// called. Model-driven children have these removed along with the credential-shaped names
/// ([`crate::shared::child_env`], docs/research/safe-defaults.md D5): a user who pointed a
/// slot at `MY_OPENAI` named a secret, and no pattern would know.
pub fn named_key_env_vars(cfg: &AppConfig) -> Vec<String> {
    let engine = |e: &EngineSettings| {
        [
            e.external.api_key_env.clone(),
            e.openai.api_key_env.clone(),
            e.gemini.api_key_env.clone(),
            e.claude.api_key_env.clone(),
            e.grok.api_key_env.clone(),
            e.openrouter.api_key_env.clone(),
        ]
    };
    let imp = &cfg.impersonation_engine;
    let embed = &cfg.embed;
    engine(&cfg.engine)
        .into_iter()
        .chain([
            imp.external.api_key_env.clone(),
            imp.openai.api_key_env.clone(),
            imp.gemini.api_key_env.clone(),
            imp.claude.api_key_env.clone(),
            imp.grok.api_key_env.clone(),
            imp.openrouter.api_key_env.clone(),
            embed.external.api_key_env.clone(),
            embed.openai.api_key_env.clone(),
            embed.gemini.api_key_env.clone(),
            embed.claude.api_key_env.clone(),
            embed.grok.api_key_env.clone(),
            embed.openrouter.api_key_env.clone(),
            cfg.tts.openai.api_key_env.clone(),
            cfg.tts.gemini.api_key_env.clone(),
            cfg.tts.openrouter.api_key_env.clone(),
            cfg.tts.external.api_key_env.clone(),
            cfg.tools.web_tavily_key_env.clone(),
            cfg.video.api_key_env.clone(),
            cfg.video.openrouter.api_key_env.clone(),
        ])
        .flatten()
        .map(|n| n.trim().to_string())
        .filter(|n| !n.is_empty())
        .collect()
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct EngineSettings {
    pub mode: ServerMode,
    pub managed: ManagedSettings,
    pub external: ExternalSettings,
    pub openai: CloudSettings,
    pub gemini: CloudSettings,
    pub claude: CloudSettings,
    pub grok: CloudSettings,
    pub openrouter: CloudSettings,
}

impl EngineSettings {
    /// Active provider's cloud settings (`None` — local managed/external).
    pub fn cloud(&self) -> Option<&CloudSettings> {
        cloud_ref(
            self.mode.cloud_provider(),
            [
                &self.openai,
                &self.gemini,
                &self.claude,
                &self.grok,
                &self.openrouter,
            ],
        )
    }

    /// Active provider's mutable cloud settings (`None` — local).
    pub fn cloud_mut(&mut self) -> Option<&mut CloudSettings> {
        cloud_mut(
            self.mode.cloud_provider(),
            [
                &mut self.openai,
                &mut self.gemini,
                &mut self.claude,
                &mut self.grok,
                &mut self.openrouter,
            ],
        )
    }

    /// How many request streams the active mode lets a turn keep open at once
    /// (`sessions` of the active section, spec §11.6). Never below 1: a zero
    /// typed into the field would be a turn that can never start a stream.
    pub fn active_sessions(&self) -> u32 {
        let n = match self.mode {
            ServerMode::Managed => self.managed.sessions,
            ServerMode::External => self.external.sessions,
            ServerMode::OpenAi
            | ServerMode::Gemini
            | ServerMode::Claude
            | ServerMode::Grok
            | ServerMode::OpenRouter => self.cloud().map_or(DEFAULT_SESSIONS, |c| c.sessions),
        };
        n.max(1)
    }

    /// Width of a round's concurrent tool group for the current mode
    /// (`concurrent_calls` of the active section, spec §6.3;
    /// docs/research/concurrent-tools.md §4.4). Never below 1: one is the
    /// sequential round, and a zero would mean no call could ever run.
    pub fn active_concurrent_calls(&self) -> u32 {
        let n = match self.mode {
            ServerMode::Managed => self.managed.concurrent_calls,
            ServerMode::External => self.external.concurrent_calls,
            ServerMode::OpenAi
            | ServerMode::Gemini
            | ServerMode::Claude
            | ServerMode::Grok
            | ServerMode::OpenRouter => self
                .cloud()
                .map_or(DEFAULT_CONCURRENT_CALLS_CLOUD, |c| c.concurrent_calls),
        };
        n.max(1)
    }

    /// Active model name for the current mode (for the `Message.metadata` snapshot
    /// and the feed caption). Managed — the GGUF's base name without the path/`.gguf`
    /// extension and, for a multi-file model, without its `-00001-of-00003` part
    /// tail ([`display_name`]); external/cloud — the configured `model_name`.
    /// `None` if unset.
    pub fn active_model_name(&self) -> Option<String> {
        match self.mode {
            ServerMode::Managed => self.managed.model_path.as_deref().and_then(display_name),
            ServerMode::External => self.external.model_name.clone().filter(|m| !m.is_empty()),
            ServerMode::OpenAi
            | ServerMode::Gemini
            | ServerMode::Claude
            | ServerMode::Grok
            | ServerMode::OpenRouter => self
                .cloud()
                .and_then(|c| c.model_name.clone())
                .filter(|m| !m.is_empty()),
        }
    }
}

/// Active cloud sub-structure by provider (a shared helper for all engines).
/// `all` is indexed by [`CloudProvider::index`], i.e. it must be given in
/// [`CloudProvider::ALL`] order.
fn cloud_ref(
    provider: Option<CloudProvider>,
    all: [&CloudSettings; CloudProvider::ALL.len()],
) -> Option<&CloudSettings> {
    Some(all[provider?.index()])
}

fn cloud_mut(
    provider: Option<CloudProvider>,
    all: [&mut CloudSettings; CloudProvider::ALL.len()],
) -> Option<&mut CloudSettings> {
    let idx = provider?.index();
    all.into_iter().nth(idx)
}

/// Which stored secret a settings section's **active mode** reads: one contract
/// instead of a "mode → secret" mapping re-derived at each call site — the
/// orchestrator resolves the key with it, the settings screen addresses its field
/// with it, so a row cannot speak for a different secret than the server uses.
/// Implemented by the four sections that can point at either a cloud provider or an
/// external server. See docs/history/external-api-key.md §5.2.
pub trait SecretSlot {
    /// The active mode's cloud provider (`None` — a local or `shared` mode).
    fn provider(&self) -> Option<CloudProvider>;

    /// This section's own external slot, when the active mode is `external`.
    fn external_slot(&self) -> Option<ExternalSlot>;

    /// The secret to read: in a cloud mode the provider's key, **shared** with that
    /// provider's other sections (ADR 0008 §3); in `external` this section's own,
    /// since its URL is a server of the user's choosing; `None` when the mode needs
    /// no key at all — a managed server is a local process, and impersonation's
    /// `shared` runs on the assistant's engine and therefore on its key.
    ///
    /// The two answers are mutually exclusive by construction ([`Self::provider`] is
    /// `Some` exactly for the cloud modes); should an implementation ever return
    /// both, the provider wins, so no key is produced for a server that isn't running.
    fn secret_key(&self) -> Option<SecretKey> {
        match (self.provider(), self.external_slot()) {
            (Some(p), _) => Some(SecretKey::Provider(p)),
            (None, Some(slot)) => Some(SecretKey::External(slot)),
            (None, None) => None,
        }
    }
}

impl SecretSlot for EngineSettings {
    fn provider(&self) -> Option<CloudProvider> {
        self.mode.cloud_provider()
    }
    fn external_slot(&self) -> Option<ExternalSlot> {
        (self.mode == ServerMode::External).then_some(ExternalSlot::Chat)
    }
}

impl SecretSlot for ImpersonationEngineSettings {
    fn provider(&self) -> Option<CloudProvider> {
        self.mode.cloud_provider()
    }
    fn external_slot(&self) -> Option<ExternalSlot> {
        (self.mode == ImpersonationMode::External).then_some(ExternalSlot::Impersonation)
    }
}

impl SecretSlot for EmbedSettings {
    fn provider(&self) -> Option<CloudProvider> {
        self.mode.cloud_provider()
    }
    fn external_slot(&self) -> Option<ExternalSlot> {
        (self.mode == ServerMode::External).then_some(ExternalSlot::Embed)
    }
}

impl SecretSlot for TtsSettings {
    fn provider(&self) -> Option<CloudProvider> {
        self.mode.cloud_provider()
    }
    fn external_slot(&self) -> Option<ExternalSlot> {
        (self.mode == TtsMode::External).then_some(ExternalSlot::Tts)
    }
}

/// Impersonation-server mode (writing a message on the user's behalf).
/// Differs from [`ServerMode`] by a third variant, `Shared`. See spec §11.8.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ImpersonationMode {
    /// Use the same engine as for assistant replies (any mode), but
    /// with sampling from the "Impersonation" subsection.
    #[default]
    Shared,
    /// Bring up a separate child `llama-server` process.
    Managed,
    /// Connect to a separate remote OpenAI-compatible server.
    External,
    /// OpenAI cloud (separate from the assistant).
    #[serde(rename = "openai")]
    OpenAi,
    /// Google Gemini cloud via an OpenAI-compatible endpoint.
    Gemini,
    /// Anthropic cloud (Claude, Messages API).
    Claude,
    /// xAI cloud (Grok, OpenAI Chat Completions).
    Grok,
    /// The OpenRouter gateway — on the key every slot of this provider
    /// shares, with a model of its own.
    #[serde(rename = "openrouter")]
    OpenRouter,
}

impl ImpersonationMode {
    /// Cloud provider for this mode (`None` — shared/managed/external).
    pub fn cloud_provider(self) -> Option<CloudProvider> {
        match self {
            ImpersonationMode::OpenAi => Some(CloudProvider::OpenAi),
            ImpersonationMode::Gemini => Some(CloudProvider::Gemini),
            ImpersonationMode::Claude => Some(CloudProvider::Claude),
            ImpersonationMode::Grok => Some(CloudProvider::Grok),
            ImpersonationMode::OpenRouter => Some(CloudProvider::OpenRouter),
            ImpersonationMode::Shared
            | ImpersonationMode::Managed
            | ImpersonationMode::External => None,
        }
    }
}

/// Default port for the managed impersonation server (a separate instance).
pub const DEFAULT_IMPERSONATION_PORT: u16 = 8002;

/// Impersonation-server settings. Sub-sections are identical to [`EngineSettings`],
/// but the mode is [`ImpersonationMode`] (adds `shared`). In `shared` mode the
/// sub-sections aren't used — the assistant's chat server is used instead. See spec §11.8.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ImpersonationEngineSettings {
    pub mode: ImpersonationMode,
    pub managed: ManagedSettings,
    pub external: ExternalSettings,
    pub openai: CloudSettings,
    pub gemini: CloudSettings,
    pub claude: CloudSettings,
    pub grok: CloudSettings,
    pub openrouter: CloudSettings,
}

impl Default for ImpersonationEngineSettings {
    fn default() -> Self {
        Self {
            mode: ImpersonationMode::Shared,
            // A separate managed impersonation instance listens on its own port.
            managed: ManagedSettings {
                port: DEFAULT_IMPERSONATION_PORT,
                ..Default::default()
            },
            external: ExternalSettings::default(),
            openai: CloudSettings::default(),
            gemini: CloudSettings::default(),
            claude: CloudSettings::default(),
            grok: CloudSettings::default(),
            openrouter: CloudSettings::default(),
        }
    }
}

impl ImpersonationEngineSettings {
    /// Active provider's cloud settings (`None` — shared/managed/external).
    pub fn cloud(&self) -> Option<&CloudSettings> {
        cloud_ref(
            self.mode.cloud_provider(),
            [
                &self.openai,
                &self.gemini,
                &self.claude,
                &self.grok,
                &self.openrouter,
            ],
        )
    }

    /// Active provider's mutable cloud settings (`None` — local).
    pub fn cloud_mut(&mut self) -> Option<&mut CloudSettings> {
        cloud_mut(
            self.mode.cloud_provider(),
            [
                &mut self.openai,
                &mut self.gemini,
                &mut self.claude,
                &mut self.grok,
                &mut self.openrouter,
            ],
        )
    }
}

/// Default embedding-server port.
pub const DEFAULT_EMBED_PORT: u16 = 8001;

/// Managed embedding-server settings: the same `llama-server` with `--embeddings`.
/// The embedding server has no chat-template/host/no_mmap — the supervisor
/// fixes those, hence fewer fields than [`ManagedSettings`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ManagedEmbedSettings {
    /// Path to the `llama-server` binary.
    pub binary: Option<String>,
    /// Path to the GGUF embedding model (`-m`).
    pub model_path: Option<String>,
    /// GPU layers (`-ngl`).
    pub gpu_layers: i32,
    pub port: u16,
    /// Raw `llama-server` arguments for the embedding server — as
    /// [`ManagedSettings::extra_args`], judged against this section's fields
    /// (a model and a port), so `-c`, `-ngl` and `--pooling` are this field's
    /// to set.
    pub extra_args: Vec<String>,
}

impl Default for ManagedEmbedSettings {
    fn default() -> Self {
        Self {
            binary: None,
            model_path: None,
            gpu_layers: DEFAULT_GPU_LAYERS,
            port: DEFAULT_EMBED_PORT,
            extra_args: Vec::new(),
        }
    }
}

/// Settings for the dedicated embedding server used by RAG (ADR 0002). A separate
/// process/port; when unconfigured (`UnavailableEmbedder`) — RAG returns an error.
/// A sub-section per mode/provider (like [`EngineSettings`]); cloud embeddings
/// exist for OpenAI/Gemini (not Anthropic and not xAI — RAG turns off). See ADR 0004.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct EmbedSettings {
    pub mode: ServerMode,
    pub managed: ManagedEmbedSettings,
    pub external: ExternalSettings,
    pub openai: CloudSettings,
    pub gemini: CloudSettings,
    pub claude: CloudSettings,
    pub grok: CloudSettings,
    pub openrouter: CloudSettings,
    /// How the active model expects its input to be marked (`query:`/`passage:`
    /// and relatives). Independent of the mode — it is a property of the *model*,
    /// not of where it runs. Default [`EmbedConvention::None`], and switching it
    /// is a change of vector space: the guard detects it and offers `/reindex`
    /// (docs/research/embedding-input-prefixes.md).
    pub convention: EmbedConvention,
}

impl EmbedSettings {
    /// Active provider's cloud settings (`None` — local managed/external).
    pub fn cloud(&self) -> Option<&CloudSettings> {
        cloud_ref(
            self.mode.cloud_provider(),
            [
                &self.openai,
                &self.gemini,
                &self.claude,
                &self.grok,
                &self.openrouter,
            ],
        )
    }

    /// Active provider's mutable cloud settings (`None` — local).
    pub fn cloud_mut(&mut self) -> Option<&mut CloudSettings> {
        cloud_mut(
            self.mode.cloud_provider(),
            [
                &mut self.openai,
                &mut self.gemini,
                &mut self.claude,
                &mut self.grok,
                &mut self.openrouter,
            ],
        )
    }

    /// Active embedding model's name for the current mode — **display metadata**
    /// for the "the embedding model changed" message (see
    /// [`crate::shared::embed_identity`]). Mirrors
    /// [`EngineSettings::active_model_name`]; managed embeddings have no
    /// `model_name` field, so the name comes from the GGUF path (same
    /// [`display_name`], part tail and all).
    ///
    /// Never used to *decide* whether the model changed — the canary vector does
    /// that. A name is too easy to leave stale: an external server picks the
    /// model itself, and the same path can come to point at a different file.
    pub fn active_model_name(&self) -> Option<String> {
        match self.mode {
            ServerMode::Managed => self.managed.model_path.as_deref().and_then(display_name),
            ServerMode::External => self.external.model_name.clone().filter(|m| !m.is_empty()),
            ServerMode::OpenAi
            | ServerMode::Gemini
            | ServerMode::Claude
            | ServerMode::Grok
            | ServerMode::OpenRouter => self
                .cloud()
                .and_then(|c| c.model_name.clone())
                .filter(|m| !m.is_empty()),
        }
    }
}

/// Default per-round reply token limit of a sub-agent (`call_subagent`, spec
/// §9.3.2). A sub-agent that has just done three searches writes a longer
/// answer than a one-shot opinion, hence wider than the 1024 of the tool-less
/// version; the settings step 1→2 lifts a stored old default to this.
pub const DEFAULT_SUBAGENT_MAX_TOKENS: usize = 4096;
/// Default time limit for a **whole** sub-agent run (seconds) — every round and
/// every tool call of it. One knob, since the run is unattended inside a turn.
pub const DEFAULT_SUBAGENT_RUN_TIMEOUT_SECS: u64 = 600;
/// Default number of a round's sub-agents allowed to run at once
/// (`tools.subagent_parallel`): one, i.e. the sequential behaviour the tool
/// shipped with (docs/research/parallel-subagents.md §4.2).
pub const DEFAULT_SUBAGENT_PARALLEL: u32 = 1;
/// Default cap on the sub-agent runs out in the **background** at once
/// (`tools.subagent_background_max`, spec §9.3.2,
/// docs/research/background-subagents.md §4.8): a `start_subagent` past it is
/// refused with a result that names the cap.
pub const DEFAULT_SUBAGENT_BACKGROUND_MAX: u32 = 2;
/// Default time limit for a whole dialogue run (`run_dialogue`, spec §9.13).
/// An order of magnitude above the sub-agent's on purpose: a 16-message
/// dialogue on a local thinking model is ~25 sequential requests, measured at
/// up to ~8 minutes in the stage-0 probe (two-agent-dialogue.md §5.2).
pub const DEFAULT_DIALOGUE_RUN_TIMEOUT_SECS: u64 = 1800;
/// Default code-execution timeout in the Wasmer sandbox (seconds). More generous
/// than the local interpreter's (10s): WASM interpretation is ~2–5× slower than native.
/// See docs/research/python-wasmer-sandbox.md.
pub const DEFAULT_PYTHON_WASM_TIMEOUT_SECS: u64 = 30;

/// Which `web_search` backend to prefer (spec §9.3.1,
/// docs/research/web-search-keyed-providers.md).
///
/// The keyless scraping chain is never removed — it is the last fallback under
/// every value, and the whole behaviour under [`Self::Auto`] with no key stored
/// is byte-identical to the version before keyed providers existed.
/// It is deliberately a choice rather than a toggle: [`SearchSlot`] is a set,
/// and the day a second provider ships this gains a variant instead of a new
/// setting — the stored `"auto"`/`"freeonly"` values keep round-tripping.
///
/// [`SearchSlot`]: crate::shared::secrets::SearchSlot
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum WebProvider {
    /// Every keyed provider that has a key, then the keyless chain. Default:
    /// with no key configured this *is* the old behaviour, and configuring a
    /// key is the whole opt-in.
    #[default]
    Auto,
    /// Ignore stored keys entirely and use only the keyless chain. For someone
    /// who has a key configured for another purpose and does not want
    /// `web_search` spending it.
    FreeOnly,
}

impl WebProvider {
    /// All variants in UI-cycle order (for the Choice popup and the cycle).
    pub const ALL: [WebProvider; 2] = [WebProvider::Auto, WebProvider::FreeOnly];

    /// Cyclic iteration honoring direction (`dir` = +1/-1).
    pub fn cycle(self, dir: i32) -> Self {
        let idx = Self::ALL.iter().position(|x| *x == self).unwrap_or(0) as i32;
        let n = Self::ALL.len() as i32;
        Self::ALL[(((idx + dir) % n + n) % n) as usize]
    }
}

/// `python_exec` execution mode: an isolated Wasmer/WASIX sandbox (by
/// default — no access to machine files, pre-installed packages) or the local
/// system interpreter (previous behavior). See
/// docs/research/python-wasmer-sandbox.md (Phase 0 → the `wasmer` sidecar).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PythonMode {
    /// An isolated sandbox on the bundled `wasmer` (sidecar). Default.
    #[default]
    Wasmer,
    /// The local system interpreter (`python`/`python3`), no isolation.
    Local,
}

impl PythonMode {
    /// All variants in UI-cycle order (for the Choice popup and the cycle).
    pub const ALL: [PythonMode; 2] = [PythonMode::Wasmer, PythonMode::Local];

    /// Where a call reads the files staged for it and writes what it wants kept, **as the
    /// model is told** (docs/history/sandbox-file-exchange.md §14 V2). Both modes run with the job
    /// directory as the working directory, so a relative `in/`/`out/` works in either;
    /// what differs is the form the prompt uses — the guest sees that directory mounted at
    /// `/w`, the host process sees it as its cwd. One source for the tool's description
    /// and for the pinned block, so the two cannot name different folders.
    pub fn dirs(self) -> (&'static str, &'static str) {
        match self {
            PythonMode::Wasmer => ("/w/in", "/w/out"),
            PythonMode::Local => ("in", "out"),
        }
    }

    /// Cyclic iteration honoring direction (`dir` = +1/-1).
    pub fn cycle(self, dir: i32) -> Self {
        let idx = Self::ALL.iter().position(|x| *x == self).unwrap_or(0) as i32;
        let n = Self::ALL.len() as i32;
        Self::ALL[(((idx + dir) % n + n) % n) as usize]
    }
}

// UI label — `screens::settings::helpers::python_mode_label` (interface language,
// axis B; mirrors `theme_label` for `Theme` — kept next to the other settings-screen
// label helpers rather than on the type itself).

/// Global "master switches" for external tools (security/privacy,
/// spec §9.4, §13.2). Effective set = `Profile.enabled_tools ∩ globally enabled`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ToolSettings {
    /// The web tools — `web_search`, `fetch_url`, `youtube_watch`. **Off by
    /// default.**
    ///
    /// It shipped on until 0.9.9, which made this the one subsystem that
    /// contradicted the app's own promise: the search engines the chain queries
    /// are picked by *us*, not by the user, so a fresh install could send a
    /// query derived from the conversation to a destination nobody chose. Every
    /// other outbound address in the app is one the user configured. See
    /// [docs/research/code-signing.md](../../docs/research/code-signing.md) §3.2
    /// and PRIVACY.md §3.3; an existing `settings.json` keeps whatever it
    /// already says, so this changes new installations only.
    pub web_enabled: bool,
    /// Fetch result pages, extract text, and reorder by
    /// relevance (`web_search`, spec §9.3.1). Enabled by default; gives the model
    /// page content, but adds latency (fetching up to `max_results` pages).
    /// The call's `fetch_content` argument overrides this value.
    pub web_fetch_content: bool,
    /// Whether tools that follow **model-chosen** URLs (`fetch_url`, and the page fetches
    /// `web_search` makes) may reach local and private addresses. **Off**: such a URL
    /// routinely comes from a page the model just read, and on a developer's machine the
    /// private ranges are where unauthenticated services live (spec §9.3,
    /// docs/research/fetch-url-address-policy.md). Turning it on is for someone whose
    /// model should read an internal wiki; it does not affect `/image attach <url>`,
    /// which the *user* types, or the engine addresses in settings.
    #[serde(default)]
    pub web_allow_private: bool,
    /// Which `web_search` backend to prefer (spec §9.3.1). The keyless
    /// scraping chain is always the last fallback and the no-key default, so a
    /// configuration with no key behaves exactly as before this setting existed.
    #[serde(default)]
    pub web_provider: WebProvider,
    /// Env-variable name carrying the Tavily API key. Stores the **name**, not
    /// the secret (ADR 0004); a key entered in settings and kept
    /// machine-encrypted under [`crate::shared::secrets::SearchSlot::Tavily`]
    /// **wins** over the variable named here (ADR 0008 §3, and the same
    /// precedence `api_key_env` already has).
    ///
    /// **`None` by default**, and that is the whole point. It used to default to
    /// `"TAVILY_API_KEY"` — the vendor's own documented name, chosen so that an
    /// existing shell "already worked" — which meant a key exported for some
    /// unrelated tool silently routed the model's searches to that vendor and
    /// spent its credits, with no decision made anywhere in this app. Naming
    /// the variable is now the decision, typed into the settings field, which
    /// is where it belongs.
    #[serde(default)]
    pub web_tavily_key_env: Option<String>,
    /// Python execution. Off by default (the tool's master gate).
    pub python_enabled: bool,
    /// `python_exec` execution mode: the Wasmer sandbox (default) or the local
    /// interpreter. See [`PythonMode`].
    pub python_mode: PythonMode,
    /// Path to the Python interpreter (`None` → system `python3`/`python`).
    /// Used only in [`PythonMode::Local`] mode.
    pub python_path: Option<String>,
    /// Allow network access inside the Wasmer sandbox (`--net`). Enabled by default
    /// — the main value of a pre-installed `requests`; but code in the sandbox will
    /// be able to reach the network. [`PythonMode::Local`] mode doesn't use this field
    /// (network is always available there). See docs/research/python-wasmer-sandbox.md §7.
    pub python_net_enabled: bool,
    /// Execution timeout in the Wasmer sandbox (seconds). Local mode keeps its own
    /// (shorter) timeout. See [`DEFAULT_PYTHON_WASM_TIMEOUT_SECS`].
    pub python_wasm_timeout_secs: u64,
    /// Hard OS-level memory limit for the Wasmer sandbox (MB; `None`/0 — no limit).
    /// Protects the host from OOM on a runaway script: exceeding it kills the
    /// `wasmer` process (not graceful — V8 fails with "Fatal out of memory"). **Windows
    /// only** (Job Object); not applied on Unix (rlimit is unreliable with V8, ADR
    /// 0005). Minimum ~1024 (less — the sandbox may fail to start: V8+CPython
    /// needs ~768 MB). Unlimited by default (defense in depth on top of the timeout
    /// and wasm32's ~4 GB).
    pub python_wasm_memory_mb: Option<u64>,
    /// Hard OS-level memory limit for each local interpreter process in
    /// [`PythonMode::Local`] (MB; `None`/0 — no limit). Its own field rather than the
    /// sandbox's, because the two floors are far apart: V8 and CPython need ~768 MB before
    /// the sandbox starts, native CPython tens of MB. An allocation past it fails, so the
    /// script sees a `MemoryError`. **Windows only** (Job Object), and not isolation — see
    /// `LocalSandbox::with_memory_limit`. Unlimited by default.
    pub python_local_memory_mb: Option<u64>,
    /// Access to local files (`fs_read`/`fs_write`/`fs_list`). Off by
    /// default (the tool can read/overwrite any file — privacy/
    /// security, like Python). See spec §9.3, §13.2.
    pub fs_enabled: bool,
    /// "Sandbox" directory for file tools (`None` → no restriction).
    /// If set, all paths must lie inside it (protection against `..` escape).
    pub fs_root: Option<String>,
    /// A sub-agent's per-round reply token limit (`call_subagent`), min'ed
    /// with the effective `max_tokens`.
    pub subagent_max_tokens: usize,
    /// Time limit for a whole sub-agent run (seconds): rounds and tool calls
    /// together. Replaced `subagent_timeout_secs` (one request) when the
    /// sub-agent gained tools — settings step 1→2 carries a changed value over.
    pub subagent_run_timeout_secs: u64,
    /// Time limit for a whole dialogue run (`run_dialogue`, spec §9.13):
    /// every participant line and director checkpoint of it.
    pub dialogue_run_timeout_secs: u64,
    /// How long a quit waits for the app's own background tasks — a
    /// reflection, a consolidation, a compaction roll — to land, so a task
    /// caught mid-work finishes its tool call and its window is decided
    /// exactly (docs/research/quit-settle-roll-and-cap.md §3.2). `None`, the
    /// default, waits until every task has landed (each is bounded by its
    /// own run time limit); a number is the cap in seconds, `0` deciding at
    /// once by the task's state.
    #[serde(default)]
    pub quit_settle_secs: Option<u32>,
    /// How many of one round's sub-agents may run at once when the model
    /// delegates several tasks in one reply (spec §9.3.2,
    /// docs/research/parallel-subagents.md §4.2). The rest start as siblings
    /// finish. At 1 — the default — the round's sub-agents run one after
    /// another, in the model's order, as they always have. Their request
    /// streams share the engine's `sessions` budget.
    pub subagent_parallel: u32,
    /// Offer `start_subagent` — a sub-agent run that outlives the turn which
    /// started it, its result delivered as a task notification in a later
    /// turn (spec §9.3.2, docs/research/background-subagents.md). **Off** by
    /// default: the tool is absent from the catalog and nothing about a turn
    /// changes. A background run never asks for a confirmation: the profile's
    /// tool set is the control (research fork F3, user's decision).
    pub subagent_background: bool,
    /// When a background run ends while its chat is open and idle, start a
    /// turn at once so the assistant reports the result (research §4.4);
    /// off — the notification waits for the next message.
    pub subagent_background_wake: bool,
    /// How many background runs may be out at once; a `start_subagent` past
    /// the cap is refused with a result that says so (research §4.8).
    pub subagent_background_max: u32,
    /// Ask the user before the agentic loop runs a tool marked dangerous
    /// (`Tool::danger()` — spec §9.8). Off by default: opt-in, so the loop
    /// behaves exactly as before until the user turns it on.
    pub confirm_dangerous: bool,
    /// Let an image returned by an MCP tool reach the model (spec §9.10, fork F3 of
    /// docs/research/mcp-tool-images.md). **On** by default: a user who enabled a
    /// screenshot server wants its screenshots, and the server is already behind a
    /// double opt-in. Separate from that opt-in because pixels carry a hazard text does
    /// not — instructions painted into an image are invisible to the user, and the
    /// DATA framing that fences a text block has no image analogue (spec §13.4). Off
    /// keeps the server and its text results, and the placeholder still says an image
    /// was returned.
    pub mcp_images: bool,
    /// Show the model an image `python_exec` saved to `/w/out` — its own chart — after
    /// the call (docs/history/sandbox-file-exchange.md F5, §11 S8). **On** by default: looking at
    /// the chart is how a model checks what it drew. Off stops paying for the image
    /// tokens; the files are still saved, and the result tells the model it has not seen
    /// them. Separate from [`Self::mcp_images`], whose pixels come from third-party code.
    pub python_images: bool,
}

impl Default for ToolSettings {
    fn default() -> Self {
        Self {
            web_enabled: false,
            web_fetch_content: true,
            web_allow_private: false,
            web_provider: WebProvider::default(),
            web_tavily_key_env: None,
            python_enabled: false,
            python_mode: PythonMode::default(),
            python_path: None,
            python_net_enabled: true,
            python_wasm_timeout_secs: DEFAULT_PYTHON_WASM_TIMEOUT_SECS,
            python_wasm_memory_mb: None,
            python_local_memory_mb: None,
            fs_enabled: false,
            fs_root: None,
            subagent_max_tokens: DEFAULT_SUBAGENT_MAX_TOKENS,
            subagent_run_timeout_secs: DEFAULT_SUBAGENT_RUN_TIMEOUT_SECS,
            dialogue_run_timeout_secs: DEFAULT_DIALOGUE_RUN_TIMEOUT_SECS,
            quit_settle_secs: None,
            subagent_parallel: DEFAULT_SUBAGENT_PARALLEL,
            subagent_background: false,
            subagent_background_wake: true,
            subagent_background_max: DEFAULT_SUBAGENT_BACKGROUND_MAX,
            confirm_dangerous: false,
            mcp_images: true,
            python_images: true,
        }
    }
}

/// Default per-command timeout for the workspace command slots, in seconds.
/// A cold `cargo build` of a real project is minutes, not seconds.
pub const DEFAULT_WORKSPACE_TIMEOUT_SECS: u64 = 300;
/// Default ceiling on characters kept **per stream** from one command.
pub const DEFAULT_WORKSPACE_OUTPUT_CHARS: usize = 10_000;
/// Default ceiling on rounds a turn may spend entirely inside the attached
/// project. Far above any real fix; see [`WorkspaceSettings::max_rounds`].
pub const DEFAULT_WORKSPACE_MAX_ROUNDS: u32 = 500;

/// The code workspace (spec §9.12): how the build/run/test commands are run,
/// and how long the model may work inside the project.
///
/// Its own group rather than four more fields on [`ToolSettings`]: that struct
/// already carries sixteen, and these belong to a capability whose gate is a
/// *project*, not a switch.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct WorkspaceSettings {
    /// How long one `code_build`/`code_run`/`code_test` may run before the
    /// process **tree** is killed. Whatever it printed up to that point is kept
    /// and returned with the timeout note — the opposite of the Python sandbox,
    /// which discards partial output: a build's first errors are the answer,
    /// and throwing them away because the build was slow would waste the wait.
    pub command_timeout_secs: u64,
    /// Ceiling on characters kept from each of stdout and stderr. What is over
    /// it is cut from the **middle**, keeping head and tail (design fork F12):
    /// a compiler puts its first errors at the top and its summary at the
    /// bottom, and a tail-only cut loses the errors.
    pub output_limit_chars: usize,
    /// How many rounds one turn may spend entirely inside the project before
    /// the loop ends it anyway. **0 — no limit.**
    ///
    /// The `code_*` family is exempt from `max_tool_rounds` by design (the limit
    /// exists to stop a model looping on *external* work), and "exempt" is not
    /// "unbounded": a model repeating one call leaves a turn that never ends,
    /// which is a measured failure mode of local models rather than a
    /// hypothetical one. So there is a number, it is editable, and it can be
    /// switched off by someone who wants that — `Esc`, the per-command timeout
    /// and the one-at-a-time gate stay underneath either way.
    pub max_rounds: u32,
}

impl Default for WorkspaceSettings {
    fn default() -> Self {
        Self {
            command_timeout_secs: DEFAULT_WORKSPACE_TIMEOUT_SECS,
            output_limit_chars: DEFAULT_WORKSPACE_OUTPUT_CHARS,
            max_rounds: DEFAULT_WORKSPACE_MAX_ROUNDS,
        }
    }
}

/// Default target ("soft") RAG chunk size in characters.
pub const DEFAULT_CHUNK_TARGET_CHARS: usize = 800;
/// Default overlap between adjacent RAG chunks in characters.
pub const DEFAULT_CHUNK_OVERLAP_CHARS: usize = 150;
/// Default hard ceiling for an indivisible RAG chunk run in characters.
pub const DEFAULT_CHUNK_MAX_CHARS: usize = 1200;

/// Knowledge-base (RAG) chunking settings. Affect slicing at indexing time
/// (`/rag add`, the `rag_add` tool) and reindexing (`/rag rebuild`). Sizes are in
/// characters (not bytes — correct for Cyrillic/Unicode). See spec §9.3.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct RagSettings {
    /// Target ("soft") chunk size: units are packed up to it.
    pub chunk_target_chars: usize,
    /// Overlap between adjacent chunks: the previous one's tail repeats at the start of the next.
    pub chunk_overlap_chars: usize,
    /// Hard ceiling for an indivisible run (a very long word/line with no punctuation).
    pub chunk_max_chars: usize,
}

impl Default for RagSettings {
    fn default() -> Self {
        Self {
            chunk_target_chars: DEFAULT_CHUNK_TARGET_CHARS,
            chunk_overlap_chars: DEFAULT_CHUNK_OVERLAP_CHARS,
            chunk_max_chars: DEFAULT_CHUNK_MAX_CHARS,
        }
    }
}

/// Default per-file inline budget for chat attachments, in estimated tokens.
/// Above it the file switches to by-reference mode (metadata + excerpt) instead
/// of being refused. Conservative on purpose: silently overflowing an 8k local
/// model's context is a far worse failure than showing an excerpt.
pub const DEFAULT_ATTACH_MAX_FILE_TOKENS: usize = 4000;
/// Default total inline budget for one chat's attachments, in estimated tokens.
pub const DEFAULT_ATTACH_MAX_TOTAL_TOKENS: usize = 8000;
/// Default excerpt size shown for a by-reference attachment, in estimated tokens.
pub const DEFAULT_ATTACH_EXCERPT_TOKENS: usize = 300;
/// Default page size for `attachment_read`, in estimated tokens. Big enough to be
/// worth a round trip, small enough that a few pages don't blow an 8k context.
pub const DEFAULT_ATTACH_PAGE_TOKENS: usize = 1500;

/// Chat file-attachment settings (`/file attach`, docs/file-attachments.md).
/// Budgets are in **estimated tokens** (`shared::tokens`) — characters mislead
/// across scripts, and tokens are what the status bar shows.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct AttachmentSettings {
    /// Per-file inline budget: a bigger file goes by reference.
    pub max_file_tokens: usize,
    /// Total inline budget for one chat: once it is used up, further files go
    /// by reference (already-attached ones are never demoted).
    pub max_total_tokens: usize,
    /// How much of a by-reference file's head to show in the pinned block.
    pub excerpt_tokens: usize,
    /// Page size for the `attachment_read` tool — how much of a by-reference
    /// file one call returns.
    pub page_tokens: usize,
}

impl Default for AttachmentSettings {
    fn default() -> Self {
        Self {
            max_file_tokens: DEFAULT_ATTACH_MAX_FILE_TOKENS,
            max_total_tokens: DEFAULT_ATTACH_MAX_TOTAL_TOKENS,
            excerpt_tokens: DEFAULT_ATTACH_EXCERPT_TOKENS,
            page_tokens: DEFAULT_ATTACH_PAGE_TOKENS,
        }
    }
}

/// Default cap on how many images one message may carry (spec §9.10, fork F7).
/// Every image is re-sent on every later turn, so the cap bounds a *standing* cost
/// rather than one upload.
pub const DEFAULT_IMAGE_MAX_COUNT: usize = 8;
/// Default hard ceiling on a single image file, in bytes — the strictest provider
/// limit (Anthropic's 10 MB base64), checked before decoding so a decompression
/// bomb never reaches the decoder.
pub const DEFAULT_IMAGE_MAX_BYTES: u64 = 10 * 1024 * 1024;
/// Default long-edge ceiling in pixels: Anthropic's standard-resolution tier, and
/// comfortably above the ~256-token encoder budgets measured on the local stack,
/// Gemini and xAI (docs/research/multimodal-images.md §2).
pub const DEFAULT_IMAGE_DOWNSCALE_PX: u32 = 1568;
/// How many images one tool result may show the model — an MCP server's (fork F2 of
/// docs/research/mcp-tool-images.md) and the charts a `python_exec` call saved
/// (docs/history/sandbox-file-exchange.md §11 S8). Every image a result carries rides **every**
/// later turn of the conversation, so the ceiling bounds a standing cost, not one reply.
/// Extras are dropped and **said out loud** in the result: a silent cap reads as "the
/// tool returned four images" when it returned fifty.
pub const MAX_TOOL_RESULT_IMAGES: usize = 4;

/// Image-attachment settings (`/image attach`, spec §9.10).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ImageSettings {
    /// How many images one message may carry.
    pub max_count: usize,
    /// Files above this size are refused (measured before decoding).
    pub max_bytes: u64,
    /// Long-edge ceiling; a larger image is downscaled once, at attach time.
    /// `0` disables downscaling — format normalization still happens, because the
    /// provider matrix depends on it (fork F3).
    pub downscale_px: u32,
}

impl Default for ImageSettings {
    fn default() -> Self {
        Self {
            max_count: DEFAULT_IMAGE_MAX_COUNT,
            max_bytes: DEFAULT_IMAGE_MAX_BYTES,
            downscale_px: DEFAULT_IMAGE_DOWNSCALE_PX,
        }
    }
}

/// Whether conversation history compression is active by default. **On** — what
/// it prevents (a hard 400 from the engine, or a silent context shift that
/// evicts the system prompt first) is strictly worse than what it does, and the
/// feed divider keeps it visible. Fork F10,
/// docs/research/history-compression.md §8.
pub const DEFAULT_COMPACTION_ENABLED: bool = true;
/// Default length limit for the rolling summary, **in words**. Measured: a bare
/// `max_tokens` cap truncates the summary mid-sentence instead of making the
/// model prioritize, and given room the summary grows with every roll — a stated
/// word limit fixes both (§9a of the research).
pub const DEFAULT_COMPACTION_SUMMARY_WORDS: usize = 250;
/// Default size of the conversation tail kept **verbatim**, in estimated tokens.
/// Everything before the nearest exchange boundary older than this is what a
/// compaction folds into the summary.
pub const DEFAULT_COMPACTION_TAIL_TOKENS: usize = 2048;
/// Default share of the context window at which a compaction starts, in percent.
/// Deliberately well below the wall: the roll runs in the background (~10-12 s on
/// the reference stack), so the remaining quarter is what lets the user keep
/// typing while it works — and it doubles as the reply reserve, which is why
/// there is no second knob for that (sub-decision S5).
pub const DEFAULT_COMPACTION_THRESHOLD_PCT: u8 = 75;
/// Default page size for `history_read`, in estimated tokens. Smaller than the
/// attachment page (1500): this reader exists for conversations that are already
/// pressing against their window, so a page has to be affordable there.
pub const DEFAULT_COMPACTION_PAGE_TOKENS: usize = 800;

/// Conversation history compression (a rolling summary of the older part of a
/// chat). See docs/research/history-compression.md and spec §6.7.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct CompactionSettings {
    /// Master switch. When off the feature is **inert**: no summary is spliced
    /// into the request (the full history is sent, exactly as before the feature
    /// existed), `/compact` refuses, and the feed shows no boundary. A summary
    /// already stored on a chat is kept, not discarded — `messages` are never
    /// touched, so off → on → off is lossless in both directions.
    pub enabled: bool,
    /// Length limit for the summary, in words, stated in the prompt itself.
    pub summary_words: usize,
    /// How much of the conversation tail stays verbatim (estimated tokens).
    pub tail_tokens: usize,
    /// Share of the context window at which a compaction starts automatically,
    /// in percent. `0` disables the automatic trigger while leaving `/compact`
    /// available.
    pub threshold_pct: u8,
    /// The context window to measure against, in tokens, when the engine cannot
    /// be asked. `None`/`0` — resolve it instead: `managed.context_size` for a
    /// managed server, else the engine's own answer
    /// ([`EngineBackend::context_budget`](crate::shared::api::EngineBackend::context_budget)
    /// — llama.cpp's `/props`). With no source at all the automatic trigger stays
    /// inactive; `/compact` still works, it needs no budget.
    pub context_tokens: Option<usize>,
    /// Page size for `history_read`, in estimated tokens: how much of the
    /// compacted-away conversation one call returns. Its own knob rather than
    /// the attachment one (S14) — an 8k user and a 200k user need materially
    /// different pages, and this feature's users are the ones with the least
    /// room to spare.
    pub page_tokens: usize,
}

impl Default for CompactionSettings {
    fn default() -> Self {
        Self {
            enabled: DEFAULT_COMPACTION_ENABLED,
            summary_words: DEFAULT_COMPACTION_SUMMARY_WORDS,
            tail_tokens: DEFAULT_COMPACTION_TAIL_TOKENS,
            threshold_pct: DEFAULT_COMPACTION_THRESHOLD_PCT,
            context_tokens: None,
            page_tokens: DEFAULT_COMPACTION_PAGE_TOKENS,
        }
    }
}

/// Default storage ceiling for the self-model narrative (insights).
pub const DEFAULT_SELF_MODEL_MAX_NARRATIVE: usize = 50;
/// Default number of fresh insights to inject into the system prompt.
pub const DEFAULT_SELF_MODEL_NARRATIVE_IN_PROMPT: usize = 3;
/// Default character ceiling for rendering the self-model into the system prompt.
///
/// Raised 1200 → 4000 (docs/history/self-model-injection-budget.md, decision D5): measured
/// on a real profile, the four sections wanted 5359 characters, so at 1200 the
/// description and goals took everything and the interlocutor model and the
/// observations were never injected at all. The per-section budgets fix the
/// starvation; this gives them room to be worth having. **An existing
/// `settings.json` pins its own value** — the field is always serialized, so this
/// only affects fresh installs.
pub const DEFAULT_SELF_MODEL_PROMPT_CAP: usize = 4000;
/// Whether to inject a persona-neutral "self-model maintenance protocol" by default.
pub const DEFAULT_SELF_MODEL_MAINTENANCE_PROTOCOL: bool = true;
/// Default number of closed goals to keep in the structure (the oldest beyond this
/// are folded into a narrative scar and removed — the closed-goal ceiling).
pub const DEFAULT_SELF_MODEL_MAX_CLOSED_GOALS: usize = 10;
/// Default target size of the self-description (summary) in characters. Beyond it
/// tools and the maintenance protocol softly suggest shortening the description (this
/// is a gate, not a ceiling — data isn't truncated). See docs/summary-as-snapshot.md (stage 2).
pub const DEFAULT_SELF_MODEL_SUMMARY_TARGET: usize = 1000;

/// Self-model settings (SelfModel): narrative sizes and the injection volume into
/// the system prompt. See [docs/history/self-model-mvp.md] and spec §9.3.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct SelfModelSettings {
    /// How many insights to keep in the narrative (old ones are evicted on add).
    pub max_narrative: usize,
    /// How many fresh insights to inject into the system prompt.
    pub narrative_in_prompt: usize,
    /// Character ceiling for the compact model render injected into the system prompt.
    pub prompt_cap: usize,
    /// How many closed (completed/no-longer-relevant) goals to keep in the structure;
    /// the oldest beyond this are folded into a narrative scar and removed.
    pub max_closed_goals: usize,
    /// Target size of the self-description (summary) in characters: beyond it, tools and
    /// the maintenance protocol softly suggest shortening the description. A gate, not a
    /// ceiling — data isn't truncated. See docs/summary-as-snapshot.md (stage 2).
    pub summary_target_chars: usize,
    /// Auto-reflection: run background reflection every N assistant replies in a
    /// chat (the model updates the "self-model" itself). `0` — off (default).
    /// Fires only in profiles with self-model tools enabled.
    pub auto_reflect_every: usize,
    /// Self-model auto-consolidation ("sleep"): run background consolidation every
    /// N assistant replies in a chat (the model merges duplicate observations, shrinks
    /// a bloated description, links contradictions on its own). `0` — off (default).
    /// Separate from `auto_reflect_every` (its own toggle is more precise — self-model
    /// and notes gates/data are already kept apart). Fires only in profiles with
    /// self-model tools enabled. See docs/history/self-model-consolidation.md (stage A1).
    pub auto_consolidate_every: usize,
    /// Whether to inject a persona-neutral "self-model maintenance protocol" into the
    /// system prompt (when to record changes, "transient — into observations",
    /// "accuracy over agreeableness"). Stabilizes tool usage independent of the
    /// profile's persona. On by default; applies only when the profile has enabled
    /// self-model tools.
    pub maintenance_protocol: bool,
}

impl Default for SelfModelSettings {
    fn default() -> Self {
        Self {
            max_narrative: DEFAULT_SELF_MODEL_MAX_NARRATIVE,
            narrative_in_prompt: DEFAULT_SELF_MODEL_NARRATIVE_IN_PROMPT,
            prompt_cap: DEFAULT_SELF_MODEL_PROMPT_CAP,
            max_closed_goals: DEFAULT_SELF_MODEL_MAX_CLOSED_GOALS,
            summary_target_chars: DEFAULT_SELF_MODEL_SUMMARY_TARGET,
            auto_reflect_every: 0,
            auto_consolidate_every: 0,
            maintenance_protocol: DEFAULT_SELF_MODEL_MAINTENANCE_PROTOCOL,
        }
    }
}

/// Notes settings: auto-consolidation ("sleep"). See docs/history/notes-connectivity.md (Tier 3).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct NotesSettings {
    /// Auto-consolidation: run background "sleep" consolidation every N assistant
    /// replies in a chat (the model merges duplicates / rewrites stale ones /
    /// links related ones on its own). `0` — off (default). Fires only in
    /// profiles with note tools enabled.
    pub auto_consolidate_every: usize,
    /// Whether to show "about self" (`@self`) observations in general `note_recall` —
    /// marked `[about self]`. **Off** by default: memory about oneself ≠ memory about
    /// the interlocutor (Tier 1 decision). The toggle gives "full output mixing"
    /// (Tier 3, Path 2) to validate whether that's safe; when off, self-notes stay
    /// hidden, as before. See docs/history/narrative-as-notes.md (Tier 3, Path 2).
    pub recall_includes_self: bool,
}

/// TUI theme. Real application in widgets — at M9 (`shared/theme.rs`);
/// here it just stores the user's choice.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Theme {
    /// Follow the **terminal** (default).
    ///
    /// Role colors are named ANSI, so their shades are whatever the terminal's
    /// palette says. The two things that cannot be expressed that way — light
    /// or dark code-block greys, and the "keycap"/selection backdrop — follow
    /// the background the terminal reports over OSC 11 at startup
    /// (`shared/osc11`, spec §11.6). A terminal that does not answer (legacy
    /// conhost, a pipe) falls back to dark, which is what those hosts are.
    #[default]
    Auto,
    Dark,
    Light,
}

/// The **colour mode** — how the interface is drawn, one level above the theme
/// (`interface.theme_mode`, spec §11.6, docs/history/theme-modes.md).
///
/// Deliberately **not** `Deserialize`: the field is read through
/// [`lenient_theme_mode`], because a value this binary does not know must not
/// fail the parse. `settings.json` is read as a whole, so one unparsable value
/// fails the file — the app refuses to start on it
/// (`features::data_migration`), and before that refusal existed it cost the
/// user the whole configuration — and this enum grows (`mono` joined it a
/// stage after `full`), which is exactly how an older binary meets such a
/// value. For the same reason the modes are a field of their own rather than
/// new values of [`Theme`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ThemeMode {
    /// Foregrounds over the **terminal's own** background (default): what the
    /// app has always done. The palette is [`Theme`]'s.
    #[default]
    System,
    /// The app paints its own background — the theme's canvas — and its own
    /// text colour under every cell (`shared/ui.rs::paint_canvas`), so the
    /// contrast is the theme's to guarantee. The theme is
    /// [`InterfaceSettings::full_theme`].
    Full,
    /// No colours and no text attributes: the terminal's own two colours, and
    /// nothing else (`shared/ui.rs::strip_styles`). What styling alone used to
    /// say is said by a glyph; reverse video is kept for the two things that
    /// have none to fall back on — a text selection and a search match. No
    /// theme applies. The mode `NO_COLOR` starts the app in
    /// ([`ThemeMode::for_environment`]).
    Mono,
}

/// The mode in effect when the settings name none — decided by the
/// environment, once, at start-up ([`set_environment_mode`]). Process-wide
/// for the reason `shared/theme.rs::DETECTED_BACKGROUND` is: one fact about
/// the process, read from render paths. Never set in a test binary, where it
/// reads as [`ThemeMode::System`] whatever the environment holds — the tests
/// take the `_under` seams of [`InterfaceSettings`] instead.
static ENVIRONMENT_MODE: std::sync::OnceLock<ThemeMode> = std::sync::OnceLock::new();

/// Records the environment's colour mode. Called once, from start-up; later
/// calls are ignored.
pub fn set_environment_mode(mode: ThemeMode) {
    let _ = ENVIRONMENT_MODE.set(mode);
}

impl ThemeMode {
    /// Every mode, in the order the settings row cycles through them.
    pub const ALL: [ThemeMode; 3] = [ThemeMode::System, ThemeMode::Full, ThemeMode::Mono];

    /// The name a mode has in `settings.json`.
    pub fn name(self) -> &'static str {
        match self {
            ThemeMode::System => "system",
            ThemeMode::Full => "full",
            ThemeMode::Mono => "mono",
        }
    }

    /// The mode the environment asks for: monochrome when `NO_COLOR` is set
    /// to anything but an empty string (no-color.org — the value itself means
    /// nothing), the system mode otherwise. `no_color` is the variable as the
    /// process found it.
    pub fn for_environment(no_color: Option<&std::ffi::OsStr>) -> Self {
        match no_color {
            Some(value) if !value.is_empty() => ThemeMode::Mono,
            _ => ThemeMode::System,
        }
    }

    /// The mode in effect when none was chosen — see [`ENVIRONMENT_MODE`].
    pub fn environment_default() -> Self {
        ENVIRONMENT_MODE.get().copied().unwrap_or_default()
    }

    /// The mode by its `settings.json` name; `None` for one this binary does
    /// not know.
    pub fn from_name(name: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|m| m.name() == name)
    }

    /// The next mode in [`Self::ALL`], in direction `dir`, wrapping.
    pub fn cycle(self, dir: i32) -> Self {
        let n = Self::ALL.len() as i32;
        let at = Self::ALL.iter().position(|m| *m == self).unwrap_or(0) as i32;
        Self::ALL[(at + dir).rem_euclid(n) as usize]
    }
}

/// Reads `interface.theme_mode`: a mode's name, or nothing. Anything else — a
/// name from a newer version, a number — reads as "not chosen" and says so in
/// the log, instead of failing the whole file (see [`ThemeMode`]).
fn lenient_theme_mode<'de, D>(de: D) -> Result<Option<ThemeMode>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let raw = serde_json::Value::deserialize(de)?;
    let mode = raw.as_str().and_then(ThemeMode::from_name);
    if mode.is_none() && !raw.is_null() {
        tracing::warn!(
            value = %raw,
            "interface.theme_mode is not a colour mode this version knows — following the default"
        );
    }
    Ok(mode)
}

/// The full mode's default theme (`interface.full_theme`).
pub const DEFAULT_FULL_THEME: &str = "dark";

/// When the automatic chat titling runs (`interface.auto_title`, spec §11.2):
/// the model names a new conversation by itself, once, on its first exchange —
/// unless the chat was renamed manually (`Chat::renamed_manually`). One
/// tri-state rather than a switch plus a trigger (the `clipboard_osc52` shape):
/// no dead "off but a trigger picked" state, one settings row.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AutoTitleMode {
    /// After the user's first message — the cloud-chat-UI timing: the title
    /// appears while the reply streams, from the question alone. On a
    /// single-slot local server the extra request contends with the reply
    /// (which is why it is not the default).
    AfterUserMessage,
    /// After the assistant's first reply (default): the reply is what
    /// disambiguates a terse opening, so the name is measurably better, and
    /// the engine is idle by then.
    #[default]
    AfterAssistantReply,
    /// Never automatically; the chat-list action still works.
    Off,
}

/// The order the **self-model screen** (`F3`) lists observations in
/// (`interface.self_model_note_order`, spec §17.7). A display rule only: the
/// snapshot the screen receives is capped by recency (`self_model.max_narrative`)
/// whichever way it is then read.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NoteOrder {
    /// Newest observation first (default): the narrative grows at its end, and
    /// what the assistant noticed last is what a person opens the screen to read
    /// — putting it under the header saves scrolling past the whole history.
    #[default]
    NewestFirst,
    /// Oldest first — the narrative read forward, as the story of how the
    /// self-model got here.
    OldestFirst,
}

/// Interface settings (theme, spellcheck, dictionaries). See spec §11.6.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct InterfaceSettings {
    /// The **system** mode's palette. Untouched by the colour modes: see
    /// [`ThemeMode`] for why they are not new values here.
    pub theme: Theme,
    /// The colour mode, **when one was chosen** (spec §11.6). Absent — and
    /// left out of the file — means "the default", which is what lets the
    /// default depend on the environment (`NO_COLOR` makes it monochrome)
    /// without overriding a choice made here. Read through [`Self::mode`],
    /// written through [`Self::set_mode`].
    #[serde(
        deserialize_with = "lenient_theme_mode",
        skip_serializing_if = "Option::is_none"
    )]
    pub theme_mode: Option<ThemeMode>,
    /// The **full** mode's theme, by name: `dark` and `light` are built in
    /// (`shared/theme.rs::FULL_THEMES`). A name rather than an enum, so a
    /// theme this binary does not have is kept in the file and falls back to
    /// `dark` on screen, instead of failing the parse.
    pub full_theme: String,
    /// Whether input spellcheck is enabled (dictionaries load from `dictionaries/`).
    pub spellcheck_enabled: bool,
    /// Base names of the selected dictionaries (e.g. `en_US`, `ru_RU`). Empty —
    /// use all found in the directory.
    pub selected_dictionaries: Vec<String>,
    /// Ask for confirmation before regenerating (`Ctrl+R`) and deleting the
    /// last exchange (`Ctrl+E`) — both operations are irreversible in the UI. Off
    /// by default (the shortcuts fire immediately). See spec §11.7.
    pub confirm_destructive_keys: bool,
    /// Compatibility mode for old terminal emulators (conhost Windows 10
    /// and the like): instead of emoji and rare Unicode characters — glyphs from a
    /// safe set (WGL4/ASCII), straight borders instead of rounded, an ASCII spinner,
    /// dimming popup backgrounds by color instead of `DIM`. Off by default.
    /// See spec §11.6 and [`crate::shared::theme::GlyphSet`].
    pub terminal_compat: bool,
    /// Horizontal separators between Markdown-table rows in the feed
    /// (`├───┼───┤`, a "grid" look). Off by default (a compact look — a separator
    /// only below the header); enabling it gives a "grid" look. See spec §11.4.
    pub table_row_separators: bool,
    /// Render ```mermaid blocks in the feed as a diagram (Unicode/ASCII graphics,
    /// the `mermaid-text` crate) instead of the source. Only flowchart/sequence
    /// (whitelist); on any failure (didn't parse / didn't fit the width / a type
    /// outside the whitelist) — a hard fallback to the source as a code block, same
    /// as with the toggle off. Thanks to the fallback, **on** by default (the worst
    /// case = prior behavior). See spec §11.4 and
    /// docs/research/mermaid-ascii-rendering.md.
    pub render_mermaid: bool,
    /// Show the model's name next to the assistant's role header in the feed,
    /// taken from the message's own metadata snapshot (`MessageMetadata::model`)
    /// — so a reloaded conversation names the model that actually wrote each
    /// answer, not the one currently selected. **Off** by default: most chats
    /// run on one model, where the line would be the same noise on every bubble.
    /// See spec §11.3, §11.6.
    pub show_model_name: bool,
    /// **Interface** language (axis B, docs/i18n-ui.md) — text for the human
    /// (status bar, settings, help, feed role headers). **Independent** of the
    /// agent language (`Profile.language`, axis A): a Russian UI + English-speaking
    /// agents is a legitimate combination. Defaults to `Ru` (an old `settings.json`
    /// with no field); on a fresh install — from `defaults.json` (`main.rs`). Reuses
    /// `i18n::Lang` (the UI language is "which bundle to read `ui.*` keys from").
    pub language: crate::shared::i18n::Lang,
    /// Whether a copy is also handed to the **terminal's** clipboard over
    /// OSC 52 — the clipboard of the machine the user is sitting at, which over
    /// SSH is not the one `arboard` writes (and on a headless box there is none
    /// to write). `Auto` by default: nothing changes for a local session. See
    /// [`crate::shared::osc52`] and docs/history/osc52-clipboard.md.
    pub clipboard_osc52: crate::shared::osc52::Osc52Mode,
    /// Automatic chat titling: when the model names a new conversation by
    /// itself (spec §11.2, docs/history/auto-chat-title.md). On by default,
    /// firing after the first reply; `Off` leaves only the chat-list action.
    pub auto_title: AutoTitleMode,
    /// The order observations are listed in on the self-model screen (`F3`,
    /// spec §17.7). `NewestFirst` by default — the last thing the assistant
    /// noticed is the one a person opens that screen for.
    pub self_model_note_order: NoteOrder,
    /// How many text rows the chat's input box grows to before it scrolls
    /// (spec §11.5). A wish, not a guarantee: the box also never takes more
    /// than half the window, so the feed stays in view. Read through
    /// [`Self::input_rows_ceiling`], which also bounds a hand-edited value.
    pub input_max_rows: u16,
}

/// The input box's default row ceiling — the value that was hard-coded before
/// `interface.input_max_rows` existed (spec §11.5).
pub const DEFAULT_INPUT_MAX_ROWS: u16 = 6;
/// The largest ceiling the setting accepts: past it the half-window cap
/// decides on any real terminal anyway.
pub const INPUT_MAX_ROWS_LIMIT: u16 = 50;

impl InterfaceSettings {
    /// `input_max_rows` brought into `1..=INPUT_MAX_ROWS_LIMIT` — a `0` or a
    /// huge number typed into `settings.json` by hand must not collapse the
    /// box or reach the layout unbounded.
    pub fn input_rows_ceiling(&self) -> u16 {
        self.input_max_rows.clamp(1, INPUT_MAX_ROWS_LIMIT)
    }

    /// The colour mode in effect: the chosen one, or the environment's
    /// ([`ThemeMode::environment_default`]).
    pub fn mode(&self) -> ThemeMode {
        self.mode_under(ThemeMode::environment_default())
    }

    /// Chooses a colour mode. The default is stored as **absence**, so going
    /// back to it — cycling the row round, or resetting it — returns to
    /// following the environment rather than pinning today's value of it.
    pub fn set_mode(&mut self, mode: ThemeMode) {
        self.set_mode_under(mode, ThemeMode::environment_default());
    }

    /// [`Self::mode`] for an explicitly given environment default. The seam
    /// exists for the tests: the real default lives in a process-wide
    /// `OnceLock`, which cannot hold two values in one test binary.
    pub(crate) fn mode_under(&self, default: ThemeMode) -> ThemeMode {
        self.theme_mode.unwrap_or(default)
    }

    /// [`Self::set_mode`] for an explicitly given environment default.
    pub(crate) fn set_mode_under(&mut self, mode: ThemeMode, default: ThemeMode) {
        self.theme_mode = (mode != default).then_some(mode);
    }
}

impl Default for InterfaceSettings {
    fn default() -> Self {
        Self {
            theme: Theme::default(),
            theme_mode: None,
            full_theme: DEFAULT_FULL_THEME.to_string(),
            spellcheck_enabled: true,
            selected_dictionaries: Vec::new(),
            confirm_destructive_keys: false,
            terminal_compat: false,
            table_row_separators: false,
            render_mermaid: true,
            show_model_name: false,
            language: crate::shared::i18n::Lang::default(),
            clipboard_osc52: crate::shared::osc52::Osc52Mode::default(),
            auto_title: AutoTitleMode::default(),
            self_model_note_order: NoteOrder::default(),
            input_max_rows: DEFAULT_INPUT_MAX_ROWS,
        }
    }
}

/// Default timeout for one MCP-server tool call (seconds).
pub const DEFAULT_MCP_TOOL_TIMEOUT_SECS: u64 = 60;
/// Default character ceiling for an MCP-tool result (clipping prompt input — a
/// precedent from Claude Code: a cap of ~25k tokens). See docs/research/plugin-system.md §4.4.
pub const DEFAULT_MCP_MAX_RESULT_CHARS: usize = 20_000;

/// Configuration of a single MCP server (a stdio subprocess,
/// docs/research/plugin-system.md §4.4). Servers are added by editing
/// `settings.json` (decision point R6); the settings UI shows statuses and toggles.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct McpServerConfig {
    /// Short identifier (slug `[a-z0-9-]`, ≤32) — part of the tool id
    /// `mcp__<id>__<tool>`. Empty/invalid — the server doesn't start.
    pub id: String,
    /// The launch command. `.bat`/`.cmd` are forbidden (BatBadBut, CVE-2024-24576);
    /// `npx` servers on Windows — `cmd /c npx …` or a direct exe path.
    pub command: String,
    /// Command arguments.
    pub args: Vec<String>,
    /// Child environment: variable → **name** of the source variable in the app's
    /// own environment (the secret itself isn't written to `settings.json` — the
    /// `api_key_env` precedent, decision point R8). A missing source — a warn in the log, skipped.
    pub env: std::collections::BTreeMap<String, String>,
    /// Whether the server is enabled (a disabled one doesn't start, its tools are unavailable).
    pub enabled: bool,
    /// Timeout for one tool call (seconds). The startup handshake keeps its own
    /// timeout (a client constant).
    pub tool_timeout_secs: u64,
    /// Tool-result clip (characters) — a limit on prompt input.
    pub max_result_chars: usize,
    /// TOFU pin of the tool catalog (sha256 over names+descriptions+schemas): set
    /// automatically on the server's first startup; on a **catalog change**
    /// (a rug-pull detector, tool poisoning), tools aren't registered until
    /// the user reconfirms the new catalog in settings. Written by the
    /// app (not editable in the UI); manually removing the field = resetting trust.
    /// See docs/research/plugin-system.md §4.5 (R7).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pinned_catalog: Option<String>,
}

impl Default for McpServerConfig {
    fn default() -> Self {
        Self {
            id: String::new(),
            command: String::new(),
            args: Vec::new(),
            env: std::collections::BTreeMap::new(),
            enabled: true,
            tool_timeout_secs: DEFAULT_MCP_TOOL_TIMEOUT_SECS,
            max_result_chars: DEFAULT_MCP_MAX_RESULT_CHARS,
            pinned_catalog: None,
        }
    }
}

/// MCP-host settings (plugin tools, docs/research/plugin-system.md §4).
/// The master switch is **off by default** (like Python): an MCP server is an
/// arbitrary user-privileged program; enabling it is a deliberate opt-in,
/// and tools are additionally opt-in per profile (double opt-in, decision point R7).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct McpSettings {
    /// MCP-host master switch.
    pub enabled: bool,
    /// List of servers (edited in `settings.json`).
    pub servers: Vec<McpServerConfig>,
}

/// Default OpenAI speech model (the current dedicated TTS; `tts-1*` is
/// legacy). See docs/research/tts.md §3.1.
pub const DEFAULT_TTS_OPENAI_MODEL: &str = "gpt-4o-mini-tts";
/// Default OpenAI voice. `onyx` — a deep male voice, **verified by a live spike**
/// (docs/research/tts.md §13.9): correct stress, no drift; `marin`/`cedar` are
/// recommended expressive alternatives (not auditioned in the spike).
pub const DEFAULT_TTS_OPENAI_VOICE: &str = "onyx";
/// Default Gemini speech model (Gemini has no GA TTS models — all are
/// preview; we take flash: cheaper and has a free tier). See docs/research/tts.md §3.2.
pub const DEFAULT_TTS_GEMINI_MODEL: &str = "gemini-2.5-flash-preview-tts";
/// Default Gemini voice (from 30 prebuilt voices).
pub const DEFAULT_TTS_GEMINI_VOICE: &str = "Kore";

/// Default model for video understanding (`youtube_watch`). A flash-class model
/// is enough: the task is description, not reasoning, and video is billed per
/// second of footage — see docs/research/youtube-integration.md §3.3. A **current**
/// generation on purpose: a default model is a thing that rots (`gemini-2.5-flash-lite`
/// already 404s for new users), so it should be one with life left in it.
pub const DEFAULT_VIDEO_MODEL: &str = "gemini-3.5-flash";
/// Default ceiling on the length of a video the tool will watch (minutes).
/// ~164k prompt tokens on the default model (measured ≈91 tok/s, §3.3) — enough
/// for a talk, and a bound on what one tool call can spend.
pub const DEFAULT_VIDEO_MAX_MINUTES: u32 = 30;

/// Frame sampling detail for video understanding (`generationConfig.mediaResolution`).
///
/// **Measured 2026-08-01 on YouTube URLs, and it is not what the docs imply**: on
/// **Gemini 3.x** (checked on 3.1-flash-lite, 3.5-flash, 3.6-flash) the parameter
/// is a **no-op** — an identical 20 s clip costs 1820 prompt tokens either way
/// (≈91 tok/s), with audio folded into the video bucket rather than reported
/// separately. On **2.5** it does what the docs say: ≈103 tok/s at `Low`
/// (video 71 + audio 32) against ≈295 at `Medium`.
///
/// Kept as a setting anyway — it is real on the 2.5-class models, and the API
/// documents the parameter generally, so a future model may honour it again. The
/// field's hint says where it currently does nothing, rather than promising a
/// 3× saving that a 3.x user will not get. See
/// docs/research/youtube-integration.md §3.3.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum MediaResolution {
    /// `MEDIA_RESOLUTION_LOW` — the default here: on a 2.5-class model it is ~3×
    /// cheaper and still enough to say what is happening on screen; on 3.x it
    /// makes no difference.
    #[default]
    Low,
    /// `MEDIA_RESOLUTION_MEDIUM` — the provider's default detail. On a 2.5-class
    /// model it reads small on-screen text better at ~3× the tokens; on 3.x it
    /// changes nothing.
    Medium,
}

impl MediaResolution {
    pub const ALL: [MediaResolution; 2] = [MediaResolution::Low, MediaResolution::Medium];

    /// The API value for `generationConfig.mediaResolution`.
    pub fn as_arg(self) -> &'static str {
        match self {
            MediaResolution::Low => "MEDIA_RESOLUTION_LOW",
            MediaResolution::Medium => "MEDIA_RESOLUTION_MEDIUM",
        }
    }

    pub fn cycle(self, dir: i32) -> Self {
        let i = Self::ALL.iter().position(|v| *v == self).unwrap_or(0) as i32;
        let n = Self::ALL.len() as i32;
        Self::ALL[(i + dir).rem_euclid(n) as usize]
    }
}

/// Who watches the video. Gemini is the family that takes a YouTube link, and it
/// is reached two ways: by Google's own API, or through the OpenRouter gateway —
/// for a user whose one key is the gateway's
/// (docs/research/openrouter-mode.md §4.5, fork F10).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum VideoProvider {
    /// Google's own `generateContent`: a segment is clipped by the provider and
    /// only the segment is charged.
    #[default]
    Gemini,
    /// The gateway's `chat/completions` with a `video_url` part: no segment
    /// bounds and no resolution are carried — the whole video is read and
    /// charged, and a segment is named in words.
    #[serde(rename = "openrouter")]
    OpenRouter,
}

impl VideoProvider {
    pub const ALL: [VideoProvider; 2] = [VideoProvider::Gemini, VideoProvider::OpenRouter];

    /// UI label (Choice field), and the settings file's own spelling.
    pub fn label(self) -> &'static str {
        match self {
            VideoProvider::Gemini => "gemini",
            VideoProvider::OpenRouter => "openrouter",
        }
    }

    /// The provider whose stored key the slot reads (ADR 0008).
    pub fn cloud_provider(self) -> CloudProvider {
        match self {
            VideoProvider::Gemini => CloudProvider::Gemini,
            VideoProvider::OpenRouter => CloudProvider::OpenRouter,
        }
    }

    pub fn cycle(self, dir: i32) -> Self {
        let i = Self::ALL.iter().position(|v| *v == self).unwrap_or(0) as i32;
        let n = Self::ALL.len() as i32;
        Self::ALL[(i + dir).rem_euclid(n) as usize]
    }
}

/// The video slot's section for the OpenRouter gateway. It has **no default
/// model**: a default that names a model ages (docs/research/model-picker.md
/// §1), and the gateway's list of models that take video is one keypress away.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct VideoGatewaySettings {
    /// The model's slug on the gateway (`google/gemini-3.5-flash`).
    pub model_name: Option<String>,
    /// Base URL override; empty → the gateway's own.
    pub url: Option<String>,
    /// Env-variable name with the gateway's key — a fallback when none is stored.
    pub api_key_env: Option<String>,
}

/// Video understanding (`youtube_watch`, docs/research/youtube-integration.md).
/// A slot of its own, independent of the chat engine: only Gemini ingests video
/// at all, so a user on a local model or on Claude still gets this — the tool
/// calls the provider out of band, exactly like TTS (ADR 0009). The API key is
/// **not** here: it is the provider key shared with chat/embeddings (ADR 0008).
/// All fields `#[serde(default)]` → old `settings.json` reads without migration:
/// the fields a file has always held — `model_name`, `url`, `api_key_env` — are
/// Gemini's, where they were, and the gateway's are a section beside them, so
/// that neither model is retyped on a switch.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct VideoSettings {
    /// Who watches. `gemini` unless chosen otherwise.
    pub provider: VideoProvider,
    /// The gateway's section, read when `provider` is `openrouter`.
    pub openrouter: VideoGatewaySettings,
    /// Gemini model name. Empty → the tool reports itself unconfigured.
    pub model_name: Option<String>,
    /// Base URL override (`…/v1beta`); empty → the provider's own.
    pub url: Option<String>,
    /// Env-variable name with the key — a fallback when nothing is stored in
    /// settings (the same pattern as the engine and TTS sections).
    pub api_key_env: Option<String>,
    /// Frame sampling detail. Gemini's own API reads it; the gateway carries no
    /// such field (three spellings tried, none honoured).
    pub media_resolution: MediaResolution,
    /// Refuse videos longer than this many minutes (`0` — no ceiling).
    pub max_minutes: u32,
}

impl VideoSettings {
    /// The stored secret the slot reads: the chosen provider's one key.
    pub fn secret_key(&self) -> crate::shared::secrets::SecretKey {
        crate::shared::secrets::SecretKey::Provider(self.provider.cloud_provider())
    }
}

impl Default for VideoSettings {
    fn default() -> Self {
        Self {
            provider: VideoProvider::default(),
            openrouter: VideoGatewaySettings::default(),
            model_name: Some(DEFAULT_VIDEO_MODEL.into()),
            url: None,
            api_key_env: None,
            media_resolution: MediaResolution::default(),
            max_minutes: DEFAULT_VIDEO_MAX_MINUTES,
        }
    }
}

/// Speech (TTS) mode — an independent "server slot", like embeddings
/// (ADR 0002): Anthropic has no TTS at all, so the speech provider is
/// configured separately from the chat engine. A local engine (managed sidecar) is
/// **future work**: a live spike (docs/research/tts.md §13) showed local engines are
/// either NO-GO for Russian (Qwen3-TTS/Supertonic 3) or need their own Rust
/// frontend (vosk-tts); the primary path is the cloud (OpenAI), external for offline.
/// See docs/research/tts.md §8.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TtsMode {
    /// OpenAI cloud (`POST /v1/audio/speech`).
    #[default]
    OpenAi,
    /// Google Gemini cloud (native `generateContent` with `responseModalities:["AUDIO"]`).
    Gemini,
    /// The OpenRouter gateway (`POST /audio/speech`): some twenty speech models
    /// of a dozen vendors behind the key every slot of this provider shares.
    /// See docs/research/openrouter-mode.md §4.4, fork F9.
    #[serde(rename = "openrouter")]
    OpenRouter,
    /// Any local/third-party OpenAI-compatible TTS server (Kokoro-FastAPI,
    /// speaches, LocalAI, …). See docs/research/tts.md §3.4.
    External,
}

impl TtsMode {
    /// All variants in UI-cycle order (Choice field): the clouds, then the
    /// server of the user's own.
    pub const ALL: [TtsMode; 4] = [
        TtsMode::OpenAi,
        TtsMode::Gemini,
        TtsMode::OpenRouter,
        TtsMode::External,
    ];

    /// UI label (Choice field).
    pub fn label(self) -> &'static str {
        match self {
            TtsMode::OpenAi => "openai",
            TtsMode::Gemini => "gemini",
            TtsMode::OpenRouter => "openrouter",
            TtsMode::External => "external",
        }
    }

    /// The mode's cloud provider (`None` — external). Indexes the shared
    /// stored API key (ADR 0008): a key entered for chat is available to TTS too.
    pub fn cloud_provider(self) -> Option<CloudProvider> {
        match self {
            TtsMode::OpenAi => Some(CloudProvider::OpenAi),
            TtsMode::Gemini => Some(CloudProvider::Gemini),
            TtsMode::OpenRouter => Some(CloudProvider::OpenRouter),
            TtsMode::External => None,
        }
    }

    /// Cyclic iteration honoring direction (`dir` = +1/-1).
    pub fn cycle(self, dir: i32) -> Self {
        let idx = Self::ALL.iter().position(|x| *x == self).unwrap_or(0) as i32;
        let n = Self::ALL.len() as i32;
        Self::ALL[(((idx + dir) % n + n) % n) as usize]
    }
}

/// Cloud speech-provider settings (OpenAI/Gemini). Stored separately
/// per provider so switching modes doesn't lose the other's values (like
/// [`CloudSettings`] for the engine).
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct TtsCloudSettings {
    /// The provider's TTS model name.
    pub model_name: Option<String>,
    /// The assistant's voice (names differ per provider).
    pub voice: Option<String>,
    /// The **user's** voice for multi-message speech (`/tts all`, `/tts N`):
    /// when set, user turns are read in it, and the assistant's — in `voice`.
    /// `None` → all turns in one voice `voice` (the default behavior).
    pub user_voice: Option<String>,
    /// Natural-language instructions on tone/language/speed. For OpenAI this is
    /// the `instructions` field (and the only working way to set speed —
    /// `speed` is de facto ignored by `gpt-4o-mini-tts`); for Gemini — a prefix
    /// to the request text. See docs/research/tts.md §3.
    pub instructions: Option<String>,
    /// Env-variable name carrying the API key (a fallback if no key was entered in settings).
    pub api_key_env: Option<String>,
    /// Override of the provider's base URL (optional).
    pub url: Option<String>,
}

/// Settings for an external (local/third-party) OpenAI-compatible TTS server.
/// The common-denominator parameter set for such servers is `model`+`input`+`voice`+
/// `response_format`+`speed`, where `voice` differs per server and many
/// ignore `model` → we send only what's set. See docs/research/tts.md §3.4.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct TtsExternalSettings {
    /// Server URL (e.g. `http://127.0.0.1:8880/v1`).
    pub url: Option<String>,
    /// Model name (optional — many servers ignore it).
    pub model_name: Option<String>,
    /// Assistant's voice — a free-text field (names depend on the server).
    pub voice: Option<String>,
    /// The **user's** voice for multi-message speech (see the identically-named field
    /// [`TtsCloudSettings::user_voice`]). `None` → one voice `voice`.
    pub user_voice: Option<String>,
    /// Env-variable name carrying a Bearer key (optional; a local server doesn't need it).
    pub api_key_env: Option<String>,
}

/// Settings for speaking chat messages aloud (the `/tts` command, spec §11.9).
/// All via `#[serde(default)]` — old `settings.json` files read without migration.
/// See docs/research/tts.md §8.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct TtsSettings {
    /// Speech provider.
    pub mode: TtsMode,
    pub openai: TtsCloudSettings,
    pub gemini: TtsCloudSettings,
    /// The gateway's section. It has **no default model**: a default that names
    /// a model ages (docs/research/model-picker.md §1), and the gateway's list
    /// is one keypress away. `instructions` is not a field of the gateway's
    /// speech route and is never sent there.
    pub openrouter: TtsCloudSettings,
    pub external: TtsExternalSettings,
    /// Speech speed (where supported). Ignored by `gpt-4o-mini-tts` — there
    /// speed is requested via words in `instructions` — and by some of the
    /// gateway's models (measured on two, docs/research/openrouter-mode.md §4.4).
    pub speed: f32,
    /// Speak role prefixes ("User."/"Assistant.") — in **all**
    /// command variants, including a bare `/tts` (user's decision, R6).
    pub speak_roles: bool,
    /// Stop speech when switching chats.
    pub stop_on_chat_switch: bool,
    /// Stop speech when a reply starts generating.
    pub stop_on_generation_start: bool,
}

impl Default for TtsSettings {
    fn default() -> Self {
        Self {
            mode: TtsMode::default(),
            openai: TtsCloudSettings {
                model_name: Some(DEFAULT_TTS_OPENAI_MODEL.into()),
                voice: Some(DEFAULT_TTS_OPENAI_VOICE.into()),
                ..Default::default()
            },
            gemini: TtsCloudSettings {
                model_name: Some(DEFAULT_TTS_GEMINI_MODEL.into()),
                voice: Some(DEFAULT_TTS_GEMINI_VOICE.into()),
                ..Default::default()
            },
            openrouter: TtsCloudSettings::default(),
            external: TtsExternalSettings::default(),
            speed: 1.0,
            speak_roles: false,
            // Stop on chat switch — yes; on generation start — no
            // (user's decision, R8).
            stop_on_chat_switch: true,
            stop_on_generation_start: false,
        }
    }
}

impl TtsSettings {
    /// Active cloud provider's settings (`None` — external).
    pub fn cloud(&self) -> Option<&TtsCloudSettings> {
        match self.mode.cloud_provider()? {
            CloudProvider::OpenAi => Some(&self.openai),
            CloudProvider::Gemini => Some(&self.gemini),
            CloudProvider::OpenRouter => Some(&self.openrouter),
            // Neither has a TTS API (and `TtsMode` has no variant for them
            // anyway — these arms exist only to keep the match exhaustive).
            CloudProvider::Claude | CloudProvider::Grok => None,
        }
    }

    /// Active mode's voices: `(assistant, user)`. Blank fields → `None`.
    /// The user's voice is used by multi-message speech (`/tts all`); at
    /// `None`, user turns are read in the assistant's voice.
    pub fn active_voices(&self) -> (Option<&str>, Option<&str>) {
        fn nonblank(v: &Option<String>) -> Option<&str> {
            v.as_deref().map(str::trim).filter(|s| !s.is_empty())
        }
        let (voice, user) = match self.cloud() {
            Some(c) => (&c.voice, &c.user_voice),
            None => (&self.external.voice, &self.external.user_voice),
        };
        (nonblank(voice), nonblank(user))
    }

    /// Active cloud provider's mutable settings (`None` — external).
    pub fn cloud_mut(&mut self) -> Option<&mut TtsCloudSettings> {
        match self.mode.cloud_provider()? {
            CloudProvider::OpenAi => Some(&mut self.openai),
            CloudProvider::Gemini => Some(&mut self.gemini),
            CloudProvider::OpenRouter => Some(&mut self.openrouter),
            // Neither has a TTS API (and `TtsMode` has no variant for them
            // anyway — these arms exist only to keep the match exhaustive).
            CloudProvider::Claude | CloudProvider::Grok => None,
        }
    }
}

/// What to include when copying the whole chat conversation to the clipboard (`F5`,
/// spec §11.2). By default only message text is copied (`Default` — all flags
/// `false`); optionally "thoughts" (CoT), tool-call parameters
/// (name + arguments), and their results are added.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct CopySettings {
    /// Include the assistant's "thoughts" (CoT) block.
    pub copy_thoughts: bool,
    /// Include tool-call parameters (tool name + arguments).
    pub copy_tool_calls: bool,
    /// Include tool-call results (responses).
    pub copy_tool_results: bool,
}

/// An impersonation profile — the **user** persona the model writes a reply on
/// behalf of (`Ctrl+U`, spec §11.8): its own name and system message. Assistant
/// profiles reference one by id ([`crate::entities::profile::Profile::impersonation_profile_id`]);
/// an unset/dangling reference falls back to the shared default text.
///
/// Lives in `settings.json` (not `profiles.json`) — impersonation is configured
/// globally, next to its engine (`impersonation_engine`) and sampling
/// (`impersonation_sampling`); the list is edited on the settings screen through
/// the usual config-save path, with no separate storage artifact.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ImpersonationProfile {
    pub id: uuid::Uuid,
    pub name: String,
    /// The system message describing the user persona. Empty → the shared default.
    #[serde(default)]
    pub system_message: String,
}

impl ImpersonationProfile {
    /// A new impersonation profile with a fresh id.
    pub fn new(name: impl Into<String>, system_message: impl Into<String>) -> Self {
        Self {
            id: uuid::Uuid::new_v4(),
            name: name.into(),
            system_message: system_message.into(),
        }
    }
}

/// What is set once for the OpenRouter gateway, whichever slot speaks to it —
/// unlike a model or a key's variable, which each slot's own section holds.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct OpenRouterSettings {
    /// Send the two attribution headers — `HTTP-Referer` and
    /// `X-OpenRouter-Title` — with every request to the gateway. They name the
    /// **application**, never the user, and are what the gateway's public
    /// rankings count by; PRIVACY.md says what they hold. On by default, and a
    /// switch because it is the one thing this app says about itself to a
    /// provider (docs/research/openrouter-mode.md, fork F5).
    pub attribution: bool,
}

impl Default for OpenRouterSettings {
    fn default() -> Self {
        Self { attribution: true }
    }
}

/// Global application configuration.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct AppConfig {
    pub schema_version: u32,
    pub default_sampling: SamplingConfig,
    /// Sampling for impersonation mode (writing a message on the user's behalf).
    /// Applies in every impersonation-server mode (including `shared`). See spec §11.8.
    pub impersonation_sampling: SamplingConfig,
    /// Chat inference-server settings (managed llama.cpp or any OpenAI external).
    pub engine: EngineSettings,
    /// Impersonation-server settings (shared/managed/external). See spec §11.8.
    pub impersonation_engine: ImpersonationEngineSettings,
    /// Impersonation profiles (the user personas) — each with its own name and
    /// system message; an assistant profile picks one by id. Empty → every
    /// impersonation uses the shared default text. See spec §11.8.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub impersonation_profiles: Vec<ImpersonationProfile>,
    /// Dedicated embedding-server settings (RAG, ADR 0002).
    pub embed: EmbedSettings,
    /// What is provider-wide about the OpenRouter gateway.
    pub openrouter: OpenRouterSettings,
    /// Round limit for the client-side agentic loop (spec §6.3).
    pub max_tool_rounds: u32,
    /// Global switches for external tools.
    pub tools: ToolSettings,
    /// The code workspace attached to a chat (spec §9.12): command execution
    /// and the project round budget.
    #[serde(default)]
    pub workspace: WorkspaceSettings,
    /// Knowledge-base (RAG) chunking settings.
    pub rag: RagSettings,
    /// Chat file-attachment budgets (`/file attach`).
    pub attachments: AttachmentSettings,
    /// Image-attachment limits (`/image attach`, spec §9.10).
    pub images: ImageSettings,
    /// Conversation history compression (rolling summary, `/compact`).
    pub compaction: CompactionSettings,
    /// Self-model settings (narrative, prompt-injection volume).
    pub self_model: SelfModelSettings,
    /// Notes settings (auto-consolidation "sleep").
    pub notes: NotesSettings,
    /// Interface settings (theme, spellcheck, dictionaries).
    pub interface: InterfaceSettings,
    /// What to include when copying the chat conversation to the clipboard (`F5`).
    pub copy: CopySettings,
    /// MCP host: plugin tools via external MCP servers (stdio).
    pub mcp: McpSettings,
    /// Speaking chat messages aloud (the `/tts` command, spec §11.9).
    pub tts: TtsSettings,
    /// Video understanding for `youtube_watch` (spec §9.9).
    pub video: VideoSettings,
    /// Last-open chat — restored on the next launch. Written by the
    /// orchestrator (not editable via the settings screen). `None` — no memory
    /// (first launch/the chat was deleted) → the most recent one opens.
    pub last_active_chat: Option<uuid::Uuid>,
    /// Stored API keys for cloud providers — **one entry per machine**,
    /// encrypted with a machine key (Windows DPAPI / Linux HKDF(machine-id)+AEAD).
    /// The config stays portable: a foreign entry won't decrypt (the key gets
    /// re-entered via its own entry), returning to the original machine re-reads its entry.
    /// Written by the orchestrator (`AppCommand::SetApiKey`), not editable in the UI —
    /// the settings screen sends the key itself, not this structure. See `shared::secrets`.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub api_keys: Vec<crate::shared::secrets::ApiKeyEntry>,
}

impl Default for AppConfig {
    fn default() -> Self {
        Self {
            schema_version: SCHEMA_VERSION,
            // The budget covers the **reasoning** as well, on every provider that
            // charges for it that way — which the shipped 2048 predated. Measured
            // on `gemini-2.5-pro` with thinking on, a school arithmetic question:
            // 1697 tokens of thinking left 347 for the answer and the reply came
            // back `MAX_TOKENS`, cut mid-explanation; the same question at 16384
            // finished at 1444 + 750 and stopped on its own
            // (docs/research/robustness-and-defaults.md F5). A cap is not a target,
            // so the wider one generates nothing extra — it only stops taking the
            // end off. Anthropic, where the field is required, keeps its own 4096
            // fallback for sampling that names no limit.
            default_sampling: SamplingConfig {
                max_tokens: Some(16384),
                thinking: Some(true),
                ..Default::default()
            },
            // Impersonation writes a short reply on the user's behalf — "thoughts"
            // would only eat the budget — a modest token limit.
            impersonation_sampling: SamplingConfig {
                max_tokens: Some(1024),
                thinking: Some(false),
                ..Default::default()
            },
            engine: EngineSettings::default(),
            impersonation_engine: ImpersonationEngineSettings::default(),
            impersonation_profiles: Vec::new(),
            embed: EmbedSettings::default(),
            openrouter: OpenRouterSettings::default(),
            max_tool_rounds: 8,
            tools: ToolSettings::default(),
            workspace: WorkspaceSettings::default(),
            rag: RagSettings::default(),
            attachments: AttachmentSettings::default(),
            images: ImageSettings::default(),
            compaction: CompactionSettings::default(),
            self_model: SelfModelSettings::default(),
            notes: NotesSettings::default(),
            interface: InterfaceSettings::default(),
            copy: CopySettings::default(),
            mcp: McpSettings::default(),
            tts: TtsSettings::default(),
            video: VideoSettings::default(),
            last_active_chat: None,
            api_keys: Vec::new(),
        }
    }
}

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

    /// The `/continue` capability matrix (spec §6.4) and the Anthropic version
    /// gate behind it: an allowlist by generation, refusing what it cannot
    /// read. Each row is a measured or documented fact from
    /// docs/research/continue-generation.md §2/§7.1.
    #[test]
    fn continuation_capability_is_per_mode_and_anthropic_generation() {
        for mode in [
            ServerMode::Managed,
            ServerMode::External,
            ServerMode::Gemini,
        ] {
            assert!(mode.supports_continuation(None, false), "{mode:?}");
        }
        for mode in [ServerMode::OpenAi, ServerMode::Grok] {
            assert!(
                !mode.supports_continuation(Some("anything"), false),
                "{mode:?}"
            );
        }
        // Anthropic: ≤4.5 continues (haiku-4-5 measured; dated ids and the
        // old 3.x naming parse the same way), 4.6+ and the 5 family reject
        // (opus-4-8 measured verbatim), and an unreadable id refuses.
        for ok in [
            "claude-haiku-4-5",
            "claude-sonnet-4-5-20250929",
            "claude-opus-4-5@20251101",
            "claude-3-5-sonnet-20241022",
            "claude-3-opus-20240229",
        ] {
            assert!(
                ServerMode::Claude.supports_continuation(Some(ok), false),
                "{ok} must continue"
            );
        }
        for no in [
            "claude-opus-4-6",
            "claude-opus-4-7",
            "claude-opus-4-8",
            "claude-sonnet-4-6",
            "claude-opus-5",
            "claude-sonnet-5",
            "claude-fable-5",
            "claude-mythos-5",
            "unknown-model",
        ] {
            assert!(
                !ServerMode::Claude.supports_continuation(Some(no), false),
                "{no} must refuse"
            );
        }
        assert!(
            !ServerMode::Claude.supports_continuation(None, false),
            "no model name — nothing to allow by"
        );
    }

    /// Through a gateway (`external` with a catalogue) `/continue` follows the
    /// route table measured in docs/history/gateway-images-and-continue.md §1.3: the
    /// slugs whose direct mode continues do, everything else refuses — and the
    /// same slugs on an `external` endpoint that published nothing keep the
    /// behaviour that shipped, since silence is not a claim.
    #[test]
    fn through_a_gateway_only_the_measured_families_continue() {
        let gateway = |slug: &str| ServerMode::External.supports_continuation(Some(slug), true);
        for ok in [
            "anthropic/claude-haiku-4.5",
            "anthropic/claude-3.7-sonnet",
            "anthropic/claude-3.7-sonnet:thinking",
            "anthropic/claude-haiku-4.5:batch",
            "google/gemini-2.5-flash",
            "Google/Gemini-3-Flash-Preview",
        ] {
            assert!(gateway(ok), "{ok} continues through a gateway");
        }
        for no in [
            // Measured: a `400` passed through.
            "anthropic/claude-sonnet-4.6",
            // The variant suffix must not hide the minor version.
            "anthropic/claude-sonnet-4.6:batch",
            "anthropic/claude-opus-5",
            // Measured restarts.
            "google/gemma-4-31b-it",
            "openai/gpt-4.1-mini",
            "qwen/qwen3.6-27b",
            "x-ai/grok-4.5",
            "mistralai/mistral-small-3.2-24b-instruct",
            // An alias or a router names no generation to allow by.
            "~anthropic/claude-haiku-latest",
            "openrouter/auto",
            // No vendor half: not a gateway slug at all.
            "claude-haiku-4-5",
        ] {
            assert!(!gateway(no), "{no} refuses through a gateway");
        }
        assert!(
            !ServerMode::External.supports_continuation(None, true),
            "a gateway with no model named has nothing to allow by"
        );
        for slug in ["google/gemma-4-31b-it", "openai/gpt-4.1-mini"] {
            assert!(
                ServerMode::External.supports_continuation(Some(slug), false),
                "without a catalogue {slug} answers as external always did"
            );
        }
        // Only `external` reads the catalogue: the other modes ignore the flag.
        assert!(ServerMode::Managed.supports_continuation(None, true));
        assert!(!ServerMode::OpenAi.supports_continuation(Some("x"), true));
    }

    #[test]
    fn default_has_current_schema_version() {
        assert_eq!(AppConfig::default().schema_version, SCHEMA_VERSION);
        assert_eq!(AppConfig::default().max_tool_rounds, 8);
    }

    /// Automatic titling is on by default and fires after the first reply
    /// (user's decision, docs/history/auto-chat-title.md §2); an old
    /// `settings.json` without the key reads the same — additive, no migration.
    #[test]
    fn auto_title_defaults_to_after_assistant_reply() {
        assert_eq!(
            AppConfig::default().interface.auto_title,
            AutoTitleMode::AfterAssistantReply
        );
        let old: InterfaceSettings = serde_json::from_str("{}").unwrap();
        assert_eq!(old.auto_title, AutoTitleMode::AfterAssistantReply);
    }

    /// Which secret each slot's mode reads. The four slots share the cloud key of a
    /// provider (ADR 0008 §3) but have **their own** external key, because their four
    /// `external` URLs are four independent servers — the whole point of
    /// docs/history/external-api-key.md F1. Managed needs no key, and impersonation's `shared`
    /// mode has none of its own: it runs on the assistant's engine.
    #[test]
    fn secret_key_follows_the_mode_of_each_slot() {
        let openai = Some(SecretKey::Provider(CloudProvider::OpenAi));
        let mut engine = EngineSettings::default();
        for (mode, want) in [
            (ServerMode::Managed, None),
            (
                ServerMode::External,
                Some(SecretKey::External(ExternalSlot::Chat)),
            ),
            (ServerMode::OpenAi, openai.clone()),
            (
                ServerMode::Claude,
                Some(SecretKey::Provider(CloudProvider::Claude)),
            ),
        ] {
            engine.mode = mode;
            assert_eq!(engine.secret_key(), want, "chat mode {mode:?}");
        }

        let mut imp = ImpersonationEngineSettings::default();
        for (mode, want) in [
            (ImpersonationMode::Shared, None),
            (ImpersonationMode::Managed, None),
            (
                ImpersonationMode::External,
                Some(SecretKey::External(ExternalSlot::Impersonation)),
            ),
            (ImpersonationMode::OpenAi, openai.clone()),
        ] {
            imp.mode = mode;
            assert_eq!(imp.secret_key(), want, "impersonation mode {mode:?}");
        }

        let mut embed = EmbedSettings {
            mode: ServerMode::External,
            ..Default::default()
        };
        assert_eq!(
            embed.secret_key(),
            Some(SecretKey::External(ExternalSlot::Embed))
        );
        embed.mode = ServerMode::OpenAi;
        assert_eq!(embed.secret_key(), openai.clone());

        let mut tts = TtsSettings {
            mode: TtsMode::External,
            ..Default::default()
        };
        assert_eq!(
            tts.secret_key(),
            Some(SecretKey::External(ExternalSlot::Tts))
        );
        tts.mode = TtsMode::OpenAi;
        assert_eq!(tts.secret_key(), openai);

        // No two slots address the same external key: a shared one would send a
        // gateway's Bearer token to whatever the other slots point at.
        let names: std::collections::BTreeSet<String> = ExternalSlot::ALL
            .into_iter()
            .map(|s| SecretKey::External(s).storage_name())
            .collect();
        assert_eq!(names.len(), ExternalSlot::ALL.len());
    }

    #[test]
    fn tts_active_voices_reads_mode_and_treats_blank_as_unset() {
        let mut tts = TtsSettings {
            mode: TtsMode::OpenAi,
            openai: TtsCloudSettings {
                voice: Some("onyx".into()),
                user_voice: Some("nova".into()),
                ..Default::default()
            },
            ..Default::default()
        };
        assert_eq!(tts.active_voices(), (Some("onyx"), Some("nova")));
        // Blank user voice → None (doesn't spin up a second engine).
        tts.openai.user_voice = Some("  ".into());
        assert_eq!(tts.active_voices(), (Some("onyx"), None));
        // Active mode external — reads its own fields, not openai's.
        tts.mode = TtsMode::External;
        tts.external.voice = Some("bella".into());
        assert_eq!(tts.active_voices(), (Some("bella"), None));
    }

    #[test]
    fn serde_roundtrip() {
        let c = AppConfig::default();
        let json = serde_json::to_string_pretty(&c).unwrap();
        let back: AppConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(c, back);
    }

    /// The container test environment seeds its `settings.json` from a **partial**
    /// document (`docker/lab/settings.seed.json`), which is legal only because this
    /// struct and every section it names carry `#[serde(default)]`. That is a
    /// contract nothing else enforces: rename a field here and the seed keeps
    /// parsing while quietly configuring nothing, so the lab would come up pointed
    /// at no server at all and look like a broken engine.
    ///
    /// Placeholders are substituted at container start; here they stand in as
    /// ordinary strings, which is exactly what makes the check cheap.
    /// See docs/research/docker-jupyter-env.md §5 (fork F4).
    #[test]
    fn docker_settings_seed_still_configures_what_it_claims() {
        const SEED: &str = include_str!("../../docker/lab/settings.seed.json");
        let c: AppConfig = serde_json::from_str(SEED).expect("the seed is valid AppConfig JSON");

        assert_eq!(c.engine.mode, ServerMode::External);
        assert_eq!(c.engine.external.url.as_deref(), Some("__CHAT_URL__"));
        assert_eq!(c.embed.mode, ServerMode::External);
        assert_eq!(c.embed.external.url.as_deref(), Some("__EMBED_URL__"));

        // Switching the engine to a cloud provider in the settings screen has to
        // work without typing anything: the seed names the variable each key
        // arrives in, and docker/compose.yaml passes those through.
        assert_eq!(
            c.engine.claude.api_key_env.as_deref(),
            Some("ANTHROPIC_API_KEY")
        );
        assert_eq!(
            c.engine.openai.api_key_env.as_deref(),
            Some("OPENAI_API_KEY")
        );
        // The gateway, in both slots the seed gives it: one variable, as one
        // key serves them.
        for section in [&c.engine.openrouter, &c.embed.openrouter] {
            assert_eq!(section.api_key_env.as_deref(), Some("OPENROUTER_API_KEY"));
            assert!(section.model_name.is_some());
        }

        // The container ships a real interpreter, so `python_exec` needs no
        // ~300 MB wasmer provisioning to work there.
        assert!(c.tools.python_enabled);
        assert_eq!(c.tools.python_mode, PythonMode::Local);

        // The MCP example server is pre-configured and scoped to the mounted work
        // directory, but **the master switch stays off**: an MCP server is an
        // arbitrary user-privileged program, and a convenience seed must not be
        // what turns the host on (double opt-in, docs/research/plugin-system.md R7).
        assert!(
            !c.mcp.enabled,
            "the MCP master switch must not be seeded on"
        );
        let fs = c.mcp.servers.first().expect("the example server");
        assert_eq!(fs.id, "fs");
        assert_eq!(fs.args, vec!["/home/jovyan/work".to_string()]);

        // `Auto`, which is also the app's own default: it asks the terminal for
        // its background at start-up and matches to it, and JupyterLab's terminal
        // answers — so the container no longer pins a polarity to work around a
        // theme that could not detect one. The start-up hook substitutes this
        // value by matching it **literally**, so the seed has to keep a real
        // `Theme` here rather than a placeholder — which is also what lets this
        // test parse the file at all, and what makes this assertion load-bearing:
        // change the value here and the hook stops substituting silently.
        assert_eq!(c.interface.theme, Theme::Auto);

        // Everything the seed does not mention must still be the default.
        assert_eq!(c.max_tool_rounds, AppConfig::default().max_tool_rounds);
    }

    /// `sessions` is read from the active section, and never below one: a zero
    /// typed into the field would be a turn that can never open a stream.
    #[test]
    fn active_sessions_follows_the_mode_and_never_drops_below_one() {
        let mut e = EngineSettings::default();
        assert_eq!(e.active_sessions(), 1);
        e.managed.sessions = 3;
        e.external.sessions = 0;
        e.grok.sessions = 5;
        e.mode = ServerMode::Managed;
        assert_eq!(e.active_sessions(), 3);
        e.mode = ServerMode::External;
        assert_eq!(e.active_sessions(), 1, "zero reads as one");
        e.mode = ServerMode::Grok;
        assert_eq!(e.active_sessions(), 5);
        e.mode = ServerMode::OpenAi;
        assert_eq!(e.active_sessions(), 1, "a provider left at its default");
        // A file written before the field existed reads as one everywhere.
        let mut old: EngineSettings = serde_json::from_str(
            r#"{"external":{"url":"http://h/v1"},"openai":{"model_name":"m"}}"#,
        )
        .unwrap();
        old.mode = ServerMode::External;
        assert_eq!(old.external.sessions, 1);
        assert_eq!(old.openai.sessions, 1);
        assert_eq!(old.active_sessions(), 1);
    }

    /// `concurrent_calls` is read from the active section like `sessions`,
    /// with a default per kind of engine (docs/research/concurrent-tools.md
    /// fork F3, the user's decision): one on a local engine — the sequential
    /// round — and four on a cloud. Never below one, and a file written before
    /// the field existed reads those defaults.
    #[test]
    fn active_concurrent_calls_follows_the_mode_with_a_default_per_kind() {
        let mut e = EngineSettings::default();
        assert_eq!(e.active_concurrent_calls(), 1, "managed is local");
        e.mode = ServerMode::External;
        assert_eq!(e.active_concurrent_calls(), 1, "external is local");
        e.mode = ServerMode::OpenAi;
        assert_eq!(
            e.active_concurrent_calls(),
            4,
            "a cloud overlaps by default"
        );
        e.mode = ServerMode::Claude;
        assert_eq!(e.active_concurrent_calls(), 4);
        e.grok.concurrent_calls = 0;
        e.mode = ServerMode::Grok;
        assert_eq!(e.active_concurrent_calls(), 1, "zero reads as one");
        e.managed.concurrent_calls = 3;
        e.mode = ServerMode::Managed;
        assert_eq!(e.active_concurrent_calls(), 3);
        let old: EngineSettings = serde_json::from_str(
            r#"{"external":{"url":"http://h/v1"},"gemini":{"model_name":"m"}}"#,
        )
        .unwrap();
        assert_eq!(
            old.external.concurrent_calls,
            DEFAULT_CONCURRENT_CALLS_LOCAL
        );
        assert_eq!(old.managed.concurrent_calls, DEFAULT_CONCURRENT_CALLS_LOCAL);
        assert_eq!(old.gemini.concurrent_calls, DEFAULT_CONCURRENT_CALLS_CLOUD);
        assert_eq!(old.openai.concurrent_calls, DEFAULT_CONCURRENT_CALLS_CLOUD);
    }

    #[test]
    fn active_model_name_by_mode() {
        // Managed — the GGUF's base name without the path or extension.
        let mut e = EngineSettings {
            mode: ServerMode::Managed,
            managed: ManagedSettings {
                model_path: Some("/models/gemma-4-it.gguf".into()),
                ..Default::default()
            },
            ..Default::default()
        };
        assert_eq!(e.active_model_name().as_deref(), Some("gemma-4-it"));
        // No path set → None.
        e.managed.model_path = None;
        assert_eq!(e.active_model_name(), None);
        // External — the model name as-is.
        e.mode = ServerMode::External;
        e.external.model_name = Some("qwen-3.6".into());
        assert_eq!(e.active_model_name().as_deref(), Some("qwen-3.6"));
        // Cloud — the name from the active cloud subsection.
        e.mode = ServerMode::OpenAi;
        e.openai.model_name = Some("gpt-4o".into());
        assert_eq!(e.active_model_name().as_deref(), Some("gpt-4o"));
        // An empty name is treated as unset.
        e.openai.model_name = Some(String::new());
        assert_eq!(e.active_model_name(), None);
    }

    #[test]
    fn server_mode_key_matches_serde() {
        // `key()` promises the serde spelling (it persists in `data.db`,
        // spec §9.14): a drift between the two would make stored history
        // rows unreadable, so pin them to each other, and pin the inverse.
        for mode in ServerMode::ALL {
            let serde_name = serde_json::to_value(mode).unwrap();
            assert_eq!(serde_name.as_str(), Some(mode.key()));
            assert_eq!(ServerMode::from_key(mode.key()), Some(mode));
        }
        assert_eq!(ServerMode::from_key("no-such-mode"), None);
    }

    #[test]
    fn mcp_server_config_roundtrip_and_partial_defaults() {
        // A partial server entry (as in a real settings.json) gets filled with
        // defaults: enabled=true, timeout/clip — constants.
        let c: AppConfig = serde_json::from_str(
            r#"{"mcp":{"enabled":true,"servers":[{
                "id":"fs","command":"cmd","args":["/c","npx","-y","srv"],
                "env":{"TOKEN":"MINDFORK_FS_TOKEN"}}]}}"#,
        )
        .unwrap();
        assert!(c.mcp.enabled);
        let s = &c.mcp.servers[0];
        assert_eq!(s.id, "fs");
        assert_eq!(s.command, "cmd");
        assert_eq!(s.args, vec!["/c", "npx", "-y", "srv"]);
        assert_eq!(
            s.env.get("TOKEN").map(String::as_str),
            Some("MINDFORK_FS_TOKEN")
        );
        assert!(s.enabled);
        assert_eq!(s.tool_timeout_secs, DEFAULT_MCP_TOOL_TIMEOUT_SECS);
        assert_eq!(s.max_result_chars, DEFAULT_MCP_MAX_RESULT_CHARS);
        // Round-trip: serializing → reading gives the same value.
        let json = serde_json::to_string(&c.mcp).unwrap();
        let back: McpSettings = serde_json::from_str(&json).unwrap();
        assert_eq!(back, c.mcp);
    }

    #[test]
    fn partial_json_fills_defaults() {
        let c: AppConfig = serde_json::from_str(r#"{"max_tool_rounds":4}"#).unwrap();
        assert_eq!(c.max_tool_rounds, 4);
        assert_eq!(c.schema_version, SCHEMA_VERSION);
        assert_eq!(c.engine.managed.port, 8000);
        assert_eq!(c.engine.managed.gpu_layers, DEFAULT_GPU_LAYERS);
        assert!(c.engine.managed.jinja);
        // Input prefixes default to "none": the feature must be inert until the
        // user opts in (docs/research/embedding-input-prefixes.md §7 R6).
        assert_eq!(c.embed.convention, EmbedConvention::None);
        // New sections get filled with defaults when absent from the file.
        assert_eq!(c.embed.managed.port, DEFAULT_EMBED_PORT);
        assert_eq!(c.tools.subagent_max_tokens, DEFAULT_SUBAGENT_MAX_TOKENS);
        assert_eq!(
            c.tools.subagent_run_timeout_secs,
            DEFAULT_SUBAGENT_RUN_TIMEOUT_SECS
        );
        assert_eq!(
            c.tools.dialogue_run_timeout_secs,
            DEFAULT_DIALOGUE_RUN_TIMEOUT_SECS
        );
        // Parallel sessions and sub-agents are opt-in: one stream and one run
        // at a time until the user says otherwise (docs/research/parallel-subagents.md R4).
        assert_eq!(c.engine.managed.sessions, DEFAULT_SESSIONS);
        assert_eq!(c.engine.external.sessions, DEFAULT_SESSIONS);
        assert_eq!(c.engine.claude.sessions, DEFAULT_SESSIONS);
        assert_eq!(c.tools.subagent_parallel, DEFAULT_SUBAGENT_PARALLEL);
        // Confirmation of dangerous tool calls is opt-in: off until turned on.
        assert!(!c.tools.confirm_dangerous);
        // History compression: on where it can act at all (fork F10), and the
        // stage-2 fields are additive — a `settings.json` written before they
        // existed reads them as defaults, no migration (ADR 0006 F12).
        assert!(c.compaction.enabled);
        assert_eq!(c.compaction.threshold_pct, DEFAULT_COMPACTION_THRESHOLD_PCT);
        // No explicit window: it is resolved (a managed server's `-c`, else the
        // engine's own answer), and where nothing can say, the automatic trigger
        // stays inactive rather than guessing.
        assert_eq!(c.compaction.context_tokens, None);
        // File tools are off by default (like Python).
        assert!(!c.tools.fs_enabled);
        assert_eq!(c.tools.fs_root, None);
        // Python: the tool is off, mode — the Wasmer sandbox, network in the
        // sandbox is on, the sandbox timeout is the default.
        assert!(!c.tools.python_enabled);
        assert_eq!(c.tools.python_mode, PythonMode::Wasmer);
        assert!(c.tools.python_net_enabled);
        assert_eq!(
            c.tools.python_wasm_timeout_secs,
            DEFAULT_PYTHON_WASM_TIMEOUT_SECS
        );
        // The sandbox memory limit is off by default (opt-in, Windows only).
        assert_eq!(c.tools.python_wasm_memory_mb, None);
        // So is the local interpreter's — its own field, and additive: a config written
        // before it existed reads with none, the sandbox's untouched.
        assert_eq!(c.tools.python_local_memory_mb, None);
        let old: AppConfig =
            serde_json::from_str(r#"{"tools": {"python_wasm_memory_mb": 2048}}"#).unwrap();
        assert_eq!(
            (
                old.tools.python_wasm_memory_mb,
                old.tools.python_local_memory_mb
            ),
            (Some(2048), None)
        );
        assert_eq!(c.rag.chunk_target_chars, DEFAULT_CHUNK_TARGET_CHARS);
        assert_eq!(c.self_model.max_narrative, DEFAULT_SELF_MODEL_MAX_NARRATIVE);
        assert_eq!(
            c.self_model.narrative_in_prompt,
            DEFAULT_SELF_MODEL_NARRATIVE_IN_PROMPT
        );
        assert_eq!(c.self_model.prompt_cap, DEFAULT_SELF_MODEL_PROMPT_CAP);
        assert_eq!(
            c.self_model.max_closed_goals,
            DEFAULT_SELF_MODEL_MAX_CLOSED_GOALS
        );
        assert_eq!(
            c.self_model.summary_target_chars,
            DEFAULT_SELF_MODEL_SUMMARY_TARGET
        );
        // The self-model maintenance protocol is on by default, auto-reflection and
        // self-model auto-consolidation are not.
        assert!(c.self_model.maintenance_protocol);
        assert_eq!(c.self_model.auto_reflect_every, 0);
        assert_eq!(c.self_model.auto_consolidate_every, 0);
        // Notes: auto-consolidation off, self-notes are hidden from recall (Tier 3, Path 2).
        assert_eq!(c.notes.auto_consolidate_every, 0);
        assert!(!c.notes.recall_includes_self);
        assert_eq!(c.rag.chunk_overlap_chars, DEFAULT_CHUNK_OVERLAP_CHARS);
        assert_eq!(c.rag.chunk_max_chars, DEFAULT_CHUNK_MAX_CHARS);
        assert!(c.interface.spellcheck_enabled);
        assert_eq!(c.interface.theme, Theme::Auto);
        // The self-model screen lists the newest observation first: it is the one
        // a person opens that screen to read (spec §17.7). An `interface` section
        // written before the key existed keeps that default rather than losing the
        // section's other values — the additive-field rule (AGENTS.md §3).
        assert_eq!(c.interface.self_model_note_order, NoteOrder::NewestFirst);
        let old: AppConfig = serde_json::from_str(r#"{"interface":{"theme":"dark"}}"#).unwrap();
        assert_eq!(old.interface.theme, Theme::Dark);
        assert_eq!(old.interface.self_model_note_order, NoteOrder::NewestFirst);
        // The input box keeps the six-row ceiling it had before the setting
        // existed (spec §11.5) — on a fresh config and under an old section alike.
        assert_eq!(c.interface.input_max_rows, DEFAULT_INPUT_MAX_ROWS);
        assert_eq!(DEFAULT_INPUT_MAX_ROWS, 6);
        assert_eq!(old.interface.input_max_rows, DEFAULT_INPUT_MAX_ROWS);
        // Old-terminal compatibility mode is off by default.
        assert!(!c.interface.terminal_compat);
        // Markdown-table row separators are off by default.
        assert!(!c.interface.table_row_separators);
        // Mermaid diagram rendering is on by default (a hard fallback to the source
        // makes enabling it safe: the worst case = prior behavior).
        assert!(c.interface.render_mermaid);
        // Interface language (axis B) defaults to Russian (an old settings.json with
        // no field; a fresh install sets it from defaults.json in main.rs).
        assert_eq!(c.interface.language, crate::shared::i18n::Lang::Ru);
        // Copying the conversation: text only by default (all flags off).
        assert!(!c.copy.copy_thoughts);
        assert!(!c.copy.copy_tool_calls);
        assert!(!c.copy.copy_tool_results);
        // MCP host: master switch off, no servers (double opt-in, R7).
        assert!(!c.mcp.enabled);
        assert!(c.mcp.servers.is_empty());
        // Speech (TTS): the default mode is OpenAI with a sensible model and
        // voice ("not configured" = no key), speed 1.0; of behavior only
        // stopping on chat switch is enabled (R6/R8).
        assert_eq!(c.tts.mode, TtsMode::OpenAi);
        assert_eq!(
            c.tts.openai.model_name.as_deref(),
            Some(DEFAULT_TTS_OPENAI_MODEL)
        );
        assert_eq!(
            c.tts.openai.voice.as_deref(),
            Some(DEFAULT_TTS_OPENAI_VOICE)
        );
        assert_eq!(
            c.tts.gemini.model_name.as_deref(),
            Some(DEFAULT_TTS_GEMINI_MODEL)
        );
        assert_eq!(c.tts.speed, 1.0);
        assert!(!c.tts.speak_roles);
        assert!(c.tts.stop_on_chat_switch);
        assert!(!c.tts.stop_on_generation_start);
        // Impersonation is filled with defaults when absent from the file.
        assert_eq!(c.impersonation_engine.mode, ImpersonationMode::Shared);
        assert_eq!(
            c.impersonation_engine.managed.port,
            DEFAULT_IMPERSONATION_PORT
        );
        assert_eq!(c.impersonation_sampling.thinking, Some(false));
        // Memory of the last-open chat: empty by default.
        assert_eq!(c.last_active_chat, None);
    }

    #[test]
    fn impersonation_sections_roundtrip() {
        let c = AppConfig {
            impersonation_engine: ImpersonationEngineSettings {
                mode: ImpersonationMode::Managed,
                managed: ManagedSettings {
                    binary: Some("llama-server".into()),
                    model_path: Some("persona.gguf".into()),
                    port: 8002,
                    ..Default::default()
                },
                ..Default::default()
            },
            impersonation_sampling: SamplingConfig {
                temperature: Some(0.8),
                max_tokens: Some(256),
                ..Default::default()
            },
            ..Default::default()
        };
        let json = serde_json::to_string_pretty(&c).unwrap();
        let back: AppConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(c, back);
    }

    #[test]
    fn impersonation_profiles_default_empty_and_roundtrip() {
        // Additive (`#[serde(default)]` + skip-if-empty): an old settings.json without
        // the field reads fine, and an empty list doesn't clutter the JSON.
        let old: AppConfig = serde_json::from_str(r#"{"max_tool_rounds":4}"#).unwrap();
        assert!(old.impersonation_profiles.is_empty());
        assert!(
            !serde_json::to_string(&old)
                .unwrap()
                .contains("impersonation_profiles")
        );

        let c = AppConfig {
            impersonation_profiles: vec![ImpersonationProfile::new("Юзер", "Ты — Владимир.")],
            ..Default::default()
        };
        let back: AppConfig = serde_json::from_str(&serde_json::to_string(&c).unwrap()).unwrap();
        assert_eq!(c, back);
    }

    #[test]
    fn impersonation_managed_default_port_is_8002() {
        let s = ImpersonationEngineSettings::default();
        assert_eq!(s.managed.port, DEFAULT_IMPERSONATION_PORT);
    }

    #[test]
    fn flash_attn_arg_and_cycle() {
        assert_eq!(FlashAttn::default(), FlashAttn::Auto);
        assert_eq!(FlashAttn::Auto.as_arg(), None);
        assert_eq!(FlashAttn::On.as_arg(), Some("on"));
        assert_eq!(FlashAttn::Off.as_arg(), Some("off"));
        // Cyclic iteration in both directions.
        assert_eq!(FlashAttn::Auto.cycle(1), FlashAttn::On);
        assert_eq!(FlashAttn::Auto.cycle(-1), FlashAttn::Off);
    }

    #[test]
    fn python_mode_default_cycle_and_serde() {
        assert_eq!(PythonMode::default(), PythonMode::Wasmer);
        // Cyclic iteration (two variants).
        assert_eq!(PythonMode::Wasmer.cycle(1), PythonMode::Local);
        assert_eq!(PythonMode::Local.cycle(1), PythonMode::Wasmer);
        assert_eq!(PythonMode::Wasmer.cycle(-1), PythonMode::Local);
        // serde — lowercase, round-trip.
        assert_eq!(
            serde_json::to_string(&PythonMode::Local).unwrap(),
            "\"local\""
        );
        let m: PythonMode = serde_json::from_str("\"wasmer\"").unwrap();
        assert_eq!(m, PythonMode::Wasmer);
        assert!(PythonMode::ALL.contains(&PythonMode::Local));
    }

    #[test]
    fn spec_type_arg_serde_and_draft_need() {
        assert_eq!(SpecType::default(), SpecType::None);
        assert_eq!(SpecType::None.as_arg(), None);
        assert_eq!(SpecType::DraftMtp.as_arg(), Some("draft-mtp"));
        assert_eq!(SpecType::NgramMapK4v.as_arg(), Some("ngram-map-k4v"));
        // The serde name matches the CLI value (kebab-case).
        assert_eq!(
            serde_json::to_string(&SpecType::DraftMtp).unwrap(),
            "\"draft-mtp\""
        );
        assert_eq!(
            serde_json::to_string(&SpecType::NgramMapK4v).unwrap(),
            "\"ngram-map-k4v\""
        );
        // A draft model is only needed by draft-* types.
        assert!(SpecType::DraftMtp.needs_draft_model());
        assert!(!SpecType::NgramSimple.needs_draft_model());
        assert!(!SpecType::None.needs_draft_model());
    }

    #[test]
    fn managed_spec_fields_roundtrip() {
        let c = AppConfig {
            engine: EngineSettings {
                mode: ServerMode::Managed,
                managed: ManagedSettings {
                    binary: Some("llama-server".into()),
                    model_path: Some("mtp-gemma-4-12B-it.gguf".into()),
                    flash_attn: FlashAttn::On,
                    spec_type: SpecType::DraftMtp,
                    draft_model: Some("mtp-gemma-4-12B-it.gguf".into()),
                    draft_gpu_layers: Some(99),
                    draft_n_max: Some(5),
                    draft_n_min: Some(1),
                    ..Default::default()
                },
                ..Default::default()
            },
            ..Default::default()
        };
        let json = serde_json::to_string_pretty(&c).unwrap();
        let back: AppConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(c, back);
    }

    /// The projector survives a save/load round trip, and — the load-bearing half —
    /// changing it makes `EngineSettings` **compare unequal**. That comparison is
    /// what the orchestrator uses to schedule a server restart, so a field excluded
    /// from it (a `#[serde(skip)]`, a hand-written `PartialEq`) would leave a
    /// changed projector running against a stale server: the setting would appear to
    /// take effect while images kept being refused (docs/lessons.md §3).
    #[test]
    fn managed_projector_roundtrips_and_a_change_is_visible_to_the_restart_check() {
        let c = AppConfig {
            engine: EngineSettings {
                mode: ServerMode::Managed,
                managed: ManagedSettings {
                    binary: Some("llama-server".into()),
                    model_path: Some("gemma-4-31B-it.gguf".into()),
                    mmproj: Some("mmproj-gemma-4-31B-it.gguf".into()),
                    ..Default::default()
                },
                ..Default::default()
            },
            ..Default::default()
        };
        let back: AppConfig = serde_json::from_str(&serde_json::to_string(&c).unwrap()).unwrap();
        assert_eq!(c, back);
        assert_eq!(
            back.engine.managed.mmproj.as_deref(),
            Some("mmproj-gemma-4-31B-it.gguf")
        );

        let mut changed = c.clone();
        changed.engine.managed.mmproj = Some("mmproj-other.gguf".into());
        assert_ne!(changed.engine, c.engine, "a changed projector must restart");
        let mut cleared = c.clone();
        cleared.engine.managed.mmproj = None;
        assert_ne!(cleared.engine, c.engine, "clearing it must restart too");
    }

    /// An older `settings.json` — written before the projector existed — still
    /// loads, with the field defaulting to "not set".
    #[test]
    fn a_config_without_the_projector_still_loads() {
        let json = r#"{"engine":{"mode":"managed","managed":{"model_path":"m.gguf"}}}"#;
        let c: AppConfig = serde_json::from_str(json).unwrap();
        assert_eq!(c.engine.managed.mmproj, None);
        assert_eq!(c.engine.managed.model_path.as_deref(), Some("m.gguf"));
    }

    #[test]
    fn per_provider_cloud_settings_are_independent() {
        // Each provider stores its own fields — switching modes doesn't lose the other's.
        let mut e = EngineSettings {
            mode: ServerMode::OpenAi,
            openai: CloudSettings {
                model_name: Some("gpt-4o".into()),
                api_key_env: Some("OPENAI_API_KEY".into()),
                ..Default::default()
            },
            gemini: CloudSettings {
                model_name: Some("gemini-2.5-pro".into()),
                api_key_env: Some("GEMINI_API_KEY".into()),
                ..Default::default()
            },
            ..Default::default()
        };
        // Active provider — OpenAI.
        assert_eq!(e.cloud().unwrap().model_name.as_deref(), Some("gpt-4o"));
        // Switching to Gemini exposes its own fields, OpenAI stays intact.
        e.mode = ServerMode::Gemini;
        assert_eq!(
            e.cloud().unwrap().model_name.as_deref(),
            Some("gemini-2.5-pro")
        );
        assert_eq!(e.openai.model_name.as_deref(), Some("gpt-4o"));
        // Local modes — no cloud.
        e.mode = ServerMode::Managed;
        assert!(e.cloud().is_none());
    }

    #[test]
    fn impersonation_mode_serializes_lowercase() {
        assert_eq!(
            serde_json::to_string(&ImpersonationMode::External).unwrap(),
            "\"external\""
        );
        assert_eq!(
            serde_json::to_string(&ImpersonationMode::Shared).unwrap(),
            "\"shared\""
        );
    }

    #[test]
    fn extended_sections_roundtrip() {
        let c = AppConfig {
            engine: EngineSettings {
                mode: ServerMode::Managed,
                managed: ManagedSettings {
                    binary: Some("llama-server".into()),
                    model_path: Some("gemma.gguf".into()),
                    gpu_layers: 50,
                    context_size: 4096,
                    jinja: true,
                    reasoning_format: Some("auto".into()),
                    ..Default::default()
                },
                ..Default::default()
            },
            embed: EmbedSettings {
                mode: ServerMode::External,
                external: ExternalSettings {
                    url: Some("http://127.0.0.1:8001/v1".into()),
                    ..Default::default()
                },
                ..Default::default()
            },
            tools: ToolSettings {
                python_enabled: true,
                subagent_max_tokens: 512,
                subagent_run_timeout_secs: 30,
                confirm_dangerous: true,
                ..Default::default()
            },
            interface: InterfaceSettings {
                theme: Theme::Dark,
                theme_mode: Some(ThemeMode::Full),
                full_theme: "light".into(),
                spellcheck_enabled: false,
                selected_dictionaries: vec!["en_US".into(), "ru_RU".into()],
                confirm_destructive_keys: true,
                terminal_compat: true,
                table_row_separators: true,
                render_mermaid: false,
                show_model_name: true,
                language: crate::shared::i18n::Lang::Ru,
                clipboard_osc52: crate::shared::osc52::Osc52Mode::Always,
                auto_title: AutoTitleMode::AfterUserMessage,
                self_model_note_order: NoteOrder::OldestFirst,
                input_max_rows: 12,
            },
            ..Default::default()
        };
        let json = serde_json::to_string_pretty(&c).unwrap();
        let back: AppConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(c, back);
    }

    /// `interface.input_max_rows` is read through a clamp: the settings row
    /// bounds what it stores, but `settings.json` is also edited by hand, and a
    /// `0` there would leave a box with no text row at all (spec §11.5).
    #[test]
    fn input_rows_ceiling_bounds_a_hand_edited_value() {
        let with = |rows: u16| InterfaceSettings {
            input_max_rows: rows,
            ..Default::default()
        };
        assert_eq!(with(0).input_rows_ceiling(), 1);
        assert_eq!(with(1).input_rows_ceiling(), 1);
        assert_eq!(with(17).input_rows_ceiling(), 17);
        assert_eq!(
            with(INPUT_MAX_ROWS_LIMIT).input_rows_ceiling(),
            INPUT_MAX_ROWS_LIMIT
        );
        assert_eq!(with(u16::MAX).input_rows_ceiling(), INPUT_MAX_ROWS_LIMIT);
        let hand: AppConfig =
            serde_json::from_str(r#"{"interface":{"input_max_rows":0}}"#).unwrap();
        assert_eq!(hand.interface.input_rows_ceiling(), 1);
    }

    /// The colour mode is **additive**: a file written before it existed reads
    /// as the system mode, with the theme it had (docs/history/theme-modes.md §4.1).
    #[test]
    fn a_settings_file_without_a_colour_mode_reads_as_system() {
        let old: AppConfig = serde_json::from_str(r#"{"interface":{"theme":"light"}}"#).unwrap();
        assert_eq!(old.interface.theme_mode, None);
        assert_eq!(old.interface.mode(), ThemeMode::System);
        assert_eq!(old.interface.theme, Theme::Light);
        assert_eq!(old.interface.full_theme, DEFAULT_FULL_THEME);
    }

    /// A mode that was never chosen is **not written**, and one that was is
    /// written by name. "Absent" has to survive a save, or the first save
    /// would pin today's default and a later default (`NO_COLOR`) would never
    /// apply to anyone.
    #[test]
    fn a_colour_mode_is_written_only_when_chosen() {
        let untouched = serde_json::to_value(InterfaceSettings::default()).unwrap();
        assert!(
            untouched.get("theme_mode").is_none(),
            "the default mode must stay out of the file: {untouched}"
        );
        assert_eq!(untouched["full_theme"], "dark");

        let mut chosen = InterfaceSettings::default();
        chosen.set_mode(ThemeMode::Full);
        let written = serde_json::to_value(&chosen).unwrap();
        assert_eq!(written["theme_mode"], "full");
        let back: InterfaceSettings = serde_json::from_value(written).unwrap();
        assert_eq!(back.mode(), ThemeMode::Full);

        // Going back to the default is going back to absence — through the
        // setter the settings row uses, not only on a fresh config.
        chosen.set_mode(ThemeMode::System);
        assert_eq!(chosen.theme_mode, None);
    }

    /// The reason the mode is parsed leniently. `settings.json` is read as a
    /// whole, so a value that fails the parse fails the file — a refusal to
    /// start today, **every** setting lost before the typed gate — and the
    /// enum grows: `mono` was such a value to the binary that only knew
    /// `full`. The control arm is `theme`, a plain enum, which does fail.
    #[test]
    fn a_colour_mode_from_a_newer_version_does_not_cost_the_config() {
        for foreign in [r#""sepia""#, r#""FULL""#, "7", "true", r#"{"a":1}"#] {
            let json = format!(
                r#"{{"max_tool_rounds":3,"interface":{{"theme":"dark","theme_mode":{foreign}}}}}"#
            );
            let c: AppConfig = serde_json::from_str(&json)
                .unwrap_or_else(|e| panic!("theme_mode={foreign} failed the parse: {e}"));
            assert_eq!(c.interface.mode(), ThemeMode::System, "{foreign}");
            // …and the rest of the file is what it said.
            assert_eq!(c.interface.theme, Theme::Dark, "{foreign}");
            assert_eq!(c.max_tool_rounds, 3, "{foreign}");
        }
        // A theme name this binary does not have is kept, not refused.
        let c: AppConfig =
            serde_json::from_str(r#"{"interface":{"full_theme":"gruvbox"}}"#).unwrap();
        assert_eq!(c.interface.full_theme, "gruvbox");
        // The control: an ordinary enum holding a foreign value fails the file,
        // which is what the lenient reader is there to avoid.
        assert!(serde_json::from_str::<AppConfig>(r#"{"interface":{"theme":"mono"}}"#).is_err());
    }

    /// The names are the file format, and the cycle is the settings row.
    #[test]
    fn colour_modes_have_stable_names_and_cycle_both_ways() {
        assert_eq!(ThemeMode::System.name(), "system");
        assert_eq!(ThemeMode::Full.name(), "full");
        assert_eq!(ThemeMode::Mono.name(), "mono");
        for mode in ThemeMode::ALL {
            assert_eq!(ThemeMode::from_name(mode.name()), Some(mode));
            assert_eq!(
                serde_json::to_value(mode).unwrap(),
                mode.name(),
                "what is written is what is read back"
            );
            assert_eq!(mode.cycle(1).cycle(-1), mode);
        }
        // `full` stays one step from `system`, where it was before `mono`
        // joined: a new mode goes to the end of the row.
        assert_eq!(ThemeMode::System.cycle(1), ThemeMode::Full);
        assert_eq!(ThemeMode::Full.cycle(1), ThemeMode::Mono);
        assert_eq!(ThemeMode::System.cycle(-1), ThemeMode::Mono, "wraps");
        assert_eq!(ThemeMode::from_name("sepia"), None);
    }

    /// `NO_COLOR` (no-color.org): set to anything but an empty string it asks
    /// for no colour, and the value itself means nothing — `0` and `false`
    /// included.
    #[test]
    fn no_color_asks_for_monochrome_unless_it_is_empty() {
        use std::ffi::OsStr;
        assert_eq!(ThemeMode::for_environment(None), ThemeMode::System);
        assert_eq!(
            ThemeMode::for_environment(Some(OsStr::new(""))),
            ThemeMode::System,
            "an empty NO_COLOR is an unset one"
        );
        for value in ["1", "0", "false", "yes", " "] {
            assert_eq!(
                ThemeMode::for_environment(Some(OsStr::new(value))),
                ThemeMode::Mono,
                "{value:?}"
            );
        }
        // Nothing sets the process-wide default in a test binary, so the
        // tests do not depend on the environment they are run in.
        assert_eq!(ThemeMode::environment_default(), ThemeMode::System);
    }

    /// Fork C (user's decision, 2026-09-27): the environment decides the mode
    /// nobody chose, and a mode chosen in settings wins over it — which takes
    /// `system` being *storable* once the default is something else.
    #[test]
    fn the_environment_decides_only_the_mode_nobody_chose() {
        let mono = ThemeMode::Mono;
        let mut i = InterfaceSettings::default();
        assert_eq!(i.mode_under(mono), ThemeMode::Mono, "nothing chosen");

        // Choosing `system` under `NO_COLOR` is a choice, and is written.
        i.set_mode_under(ThemeMode::System, mono);
        assert_eq!(i.theme_mode, Some(ThemeMode::System));
        assert_eq!(i.mode_under(mono), ThemeMode::System);
        assert_eq!(serde_json::to_value(&i).unwrap()["theme_mode"], "system");

        // Going back to the environment's mode is going back to absence, so
        // the file follows the environment again — here and without it.
        i.set_mode_under(ThemeMode::Mono, mono);
        assert_eq!(i.theme_mode, None);
        assert_eq!(i.mode_under(ThemeMode::System), ThemeMode::System);

        // A mode chosen without the variable holds when it appears.
        i.set_mode_under(ThemeMode::Full, ThemeMode::System);
        assert_eq!(i.mode_under(mono), ThemeMode::Full);
        i.set_mode_under(ThemeMode::Mono, ThemeMode::System);
        assert_eq!(i.theme_mode, Some(ThemeMode::Mono), "chosen, so written");
        assert_eq!(i.mode_under(ThemeMode::System), ThemeMode::Mono);
    }

    /// `cloud_ref`/`cloud_mut` index per-provider arrays by [`CloudProvider::index`],
    /// so a provider added to `ALL` without its index (or in the wrong slot) would
    /// silently hand back **another provider's** settings — a key and a model name
    /// from the wrong cloud, with no type error to catch it.
    #[test]
    fn provider_index_matches_its_slot_in_all() {
        for (i, p) in CloudProvider::ALL.into_iter().enumerate() {
            assert_eq!(p.index(), i, "{p:?} is not at its own index");
        }
        // …and the settings accessor really follows that order.
        let mut e = EngineSettings {
            grok: CloudSettings {
                model_name: Some("grok-4.5".into()),
                ..Default::default()
            },
            claude: CloudSettings {
                model_name: Some("claude-opus-4-8".into()),
                ..Default::default()
            },
            ..Default::default()
        };
        e.mode = ServerMode::Grok;
        assert_eq!(e.cloud().unwrap().model_name.as_deref(), Some("grok-4.5"));
        assert_eq!(e.active_model_name().as_deref(), Some("grok-4.5"));
        e.cloud_mut().unwrap().model_name = Some("grok-4.3".into());
        assert_eq!(e.grok.model_name.as_deref(), Some("grok-4.3"));
        assert_eq!(
            e.claude.model_name.as_deref(),
            Some("claude-opus-4-8"),
            "writing through cloud_mut hit the wrong provider"
        );
    }

    /// A `settings.json` written before the Grok mode existed must still load — the
    /// project's no-migration invariant (`#[serde(default)]` on every sub-section).
    #[test]
    fn config_without_grok_section_still_loads() {
        let old = r#"{"engine":{"mode":"openai","openai":{"model_name":"gpt-4o"}}}"#;
        let c: AppConfig = serde_json::from_str(old).unwrap();
        assert_eq!(c.engine.openai.model_name.as_deref(), Some("gpt-4o"));
        assert_eq!(c.engine.grok, CloudSettings::default());
        assert_eq!(c.impersonation_engine.grok, CloudSettings::default());
        assert_eq!(c.embed.grok, CloudSettings::default());
    }

    #[test]
    fn theme_serializes_lowercase() {
        assert_eq!(serde_json::to_string(&Theme::Dark).unwrap(), "\"dark\"");
    }

    #[test]
    fn cloud_modes_serialize_and_map_to_provider() {
        assert_eq!(
            serde_json::to_string(&ServerMode::OpenAi).unwrap(),
            "\"openai\""
        );
        assert_eq!(
            serde_json::to_string(&ServerMode::Gemini).unwrap(),
            "\"gemini\""
        );
        assert_eq!(
            ServerMode::OpenAi.cloud_provider(),
            Some(CloudProvider::OpenAi)
        );
        assert_eq!(
            ServerMode::Gemini.cloud_provider(),
            Some(CloudProvider::Gemini)
        );
        assert_eq!(ServerMode::Managed.cloud_provider(), None);
        assert_eq!(ServerMode::External.cloud_provider(), None);
        // Claude — cloud, but not the OpenAI protocol.
        assert_eq!(
            serde_json::to_string(&ServerMode::Claude).unwrap(),
            "\"claude\""
        );
        assert_eq!(
            ServerMode::Claude.cloud_provider(),
            Some(CloudProvider::Claude)
        );
        assert!(CloudProvider::Claude.base_url().contains("anthropic"));
        // Grok — cloud on the plain OpenAI Chat Completions protocol; chat and
        // embeddings share one base URL (no compat/native split as for Gemini).
        assert_eq!(
            serde_json::to_string(&ServerMode::Grok).unwrap(),
            "\"grok\""
        );
        assert_eq!(ServerMode::Grok.cloud_provider(), Some(CloudProvider::Grok));
        assert_eq!(CloudProvider::Grok.base_url(), "https://api.x.ai/v1");
        assert_eq!(
            CloudProvider::Grok.chat_base_url(),
            CloudProvider::Grok.base_url()
        );
        // Impersonation: the same cloud providers, other modes — None.
        assert_eq!(
            ImpersonationMode::OpenAi.cloud_provider(),
            Some(CloudProvider::OpenAi)
        );
        assert_eq!(ImpersonationMode::Shared.cloud_provider(), None);
        // Providers' base URLs.
        assert!(
            CloudProvider::OpenAi
                .base_url()
                .starts_with("https://api.openai.com")
        );
        assert!(
            CloudProvider::Gemini
                .base_url()
                .contains("generativelanguage")
        );
    }

    #[test]
    fn cloud_engine_settings_roundtrip() {
        let c = AppConfig {
            engine: EngineSettings {
                mode: ServerMode::OpenAi,
                openai: CloudSettings {
                    model_name: Some("gpt-4o".into()),
                    api_key_env: Some("OPENAI_API_KEY".into()),
                    ..Default::default()
                },
                ..Default::default()
            },
            ..Default::default()
        };
        let json = serde_json::to_string_pretty(&c).unwrap();
        let back: AppConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(c, back);
        // Sub-sections get filled with defaults when absent from the file.
        let old: AppConfig = serde_json::from_str(r#"{"engine":{"mode":"managed"}}"#).unwrap();
        assert_eq!(old.engine.openai.model_name, None);
        assert_eq!(old.engine.openai.api_key_env, None);
        assert_eq!(old.engine.managed.binary, None);
    }

    // ---------- the OpenRouter mode (docs/research/openrouter-mode.md) ----------

    /// Fork F3: the mode's name is storage — `settings.json`, every chat's
    /// `metadata.mode` and `data.db` hold it — so it is one word in both enums
    /// that carry it, and no neighbouring spelling reads as it: a typed parse
    /// that fell back would be an engine switched in silence
    /// (docs/research/settings-typed-parse.md).
    #[test]
    fn the_gateway_mode_is_one_word_in_both_enums_that_carry_it() {
        let written = |mode: serde_json::Value| mode.as_str().map(str::to_string);
        assert_eq!(
            written(serde_json::to_value(ServerMode::OpenRouter).unwrap()).as_deref(),
            Some("openrouter")
        );
        assert_eq!(
            written(serde_json::to_value(ImpersonationMode::OpenRouter).unwrap()).as_deref(),
            Some("openrouter")
        );
        assert_eq!(
            serde_json::from_str::<ServerMode>(r#""openrouter""#).ok(),
            Some(ServerMode::OpenRouter)
        );
        assert_eq!(
            serde_json::from_str::<ImpersonationMode>(r#""openrouter""#).ok(),
            Some(ImpersonationMode::OpenRouter)
        );
        assert_eq!(
            ServerMode::from_key("openrouter"),
            Some(ServerMode::OpenRouter)
        );
        for other in ["open_router", "open-router", "OpenRouter", "openrouter.ai"] {
            let json = format!("\"{other}\"");
            assert!(
                serde_json::from_str::<ServerMode>(&json).is_err(),
                "{other}"
            );
            assert!(
                serde_json::from_str::<ImpersonationMode>(&json).is_err(),
                "{other}"
            );
            assert_eq!(ServerMode::from_key(other), None, "{other}");
        }
    }

    /// The fifth provider sits where [`CloudProvider::ALL`] says, and in each of
    /// the three settings structs that position is the `openrouter` section,
    /// read and written. `provider_index_matches_its_slot_in_all` pins the
    /// index; this pins what the three hand-written arrays put **at** it, where
    /// a swap with the neighbour would hand the gateway xAI's model and key
    /// with no type error to catch it.
    #[test]
    fn each_slot_hands_the_gateway_mode_its_own_section() {
        const SLUG: &str = "anthropic/claude-haiku-4.5";
        const PICKED: &str = "google/gemini-3.5-flash";
        assert_eq!(
            CloudProvider::ALL.get(CloudProvider::OpenRouter.index()),
            Some(&CloudProvider::OpenRouter)
        );
        macro_rules! own_section {
            ($slot:literal, $settings:expr) => {{
                let mut s = $settings;
                s.grok.model_name = Some("grok-4.5".into());
                s.openrouter.model_name = Some(SLUG.into());
                let read = s.cloud().and_then(|c| c.model_name.clone());
                assert_eq!(read.as_deref(), Some(SLUG), "{}: read", $slot);
                s.cloud_mut().expect("a cloud mode").model_name = Some(PICKED.into());
                assert_eq!(
                    (
                        s.openrouter.model_name.as_deref(),
                        s.grok.model_name.as_deref()
                    ),
                    (Some(PICKED), Some("grok-4.5")),
                    "{}: written to the gateway's section and to no neighbour",
                    $slot
                );
                s
            }};
        }
        let engine = own_section!(
            "engine",
            EngineSettings {
                mode: ServerMode::OpenRouter,
                ..Default::default()
            }
        );
        assert_eq!(engine.active_model_name().as_deref(), Some(PICKED));
        assert_eq!(
            engine.secret_key(),
            Some(SecretKey::Provider(CloudProvider::OpenRouter))
        );
        let imp = own_section!(
            "impersonation",
            ImpersonationEngineSettings {
                mode: ImpersonationMode::OpenRouter,
                ..Default::default()
            }
        );
        assert_eq!(imp.secret_key(), engine.secret_key(), "one key, every slot");
        let embed = own_section!(
            "embed",
            EmbedSettings {
                mode: ServerMode::OpenRouter,
                ..Default::default()
            }
        );
        assert_eq!(embed.active_model_name().as_deref(), Some(PICKED));
        assert_eq!(embed.secret_key(), engine.secret_key());
    }

    /// A `settings.json` written before the mode existed still loads, every
    /// gateway section at its defaults — the no-migration invariant the Grok
    /// mode's test pins for its own sections. The schema step 3 → 4 changes no
    /// value (fork F3), so this is what a migrated file reads as.
    #[test]
    fn config_without_openrouter_sections_still_loads() {
        let old = r#"{"engine":{"mode":"grok","grok":{"model_name":"grok-4.5"}}}"#;
        let c: AppConfig = serde_json::from_str(old).unwrap();
        assert_eq!(c.engine.mode, ServerMode::Grok);
        assert_eq!(c.engine.grok.model_name.as_deref(), Some("grok-4.5"));
        assert_eq!(c.engine.openrouter, CloudSettings::default());
        assert_eq!(c.impersonation_engine.openrouter, CloudSettings::default());
        assert_eq!(c.embed.openrouter, CloudSettings::default());
        assert_eq!(c.openrouter, OpenRouterSettings::default());
    }

    /// Fork F5, adopted (b): the application is named to the gateway **until
    /// somebody turns that off** — so the default is on, a file that never
    /// heard of the switch reads as on, and an "off" that was written stays
    /// off through a save and a load.
    #[test]
    fn attribution_is_on_until_somebody_turns_it_off() {
        assert!(AppConfig::default().openrouter.attribution);
        for silent in ["{}", r#"{"openrouter":{}}"#] {
            let c: AppConfig =
                serde_json::from_str(silent).unwrap_or_else(|e| panic!("{silent} must load: {e}"));
            assert!(c.openrouter.attribution, "{silent}");
        }
        let off: AppConfig =
            serde_json::from_str(r#"{"openrouter":{"attribution":false}}"#).unwrap();
        assert!(!off.openrouter.attribution);
        let saved = serde_json::to_value(&off).unwrap();
        assert_eq!(saved["openrouter"]["attribution"], false, "{saved}");
        let back: AppConfig = serde_json::from_value(saved).unwrap();
        assert!(!back.openrouter.attribution, "off survives the round trip");
    }

    /// The file's own words for the mode: each slot keeps its gateway section
    /// under `openrouter`, beside the provider-wide one at the top level — the
    /// layout the settings migration, the docs and a hand-edited file rely on.
    #[test]
    fn a_config_on_the_gateway_round_trips_in_the_files_own_words() {
        let section = |model: &str, env: &str| CloudSettings {
            model_name: Some(model.into()),
            api_key_env: Some(env.into()),
            ..Default::default()
        };
        let mut c = AppConfig::default();
        c.engine.mode = ServerMode::OpenRouter;
        c.engine.openrouter = section("anthropic/claude-haiku-4.5", "CHAT_KEY");
        c.impersonation_engine.mode = ImpersonationMode::OpenRouter;
        c.impersonation_engine.openrouter = section("qwen/qwen3.6-27b", "IMP_KEY");
        c.embed.mode = ServerMode::OpenRouter;
        c.embed.openrouter = section("baai/bge-m3", "EMBED_KEY");
        c.openrouter.attribution = false;

        let json = serde_json::to_value(&c).unwrap();
        let said: Vec<serde_json::Value> = "/engine/mode /engine/openrouter/model_name \
            /impersonation_engine/mode /impersonation_engine/openrouter/api_key_env \
            /embed/mode /embed/openrouter/model_name /openrouter/attribution"
            .split_whitespace()
            .map(|path| json.pointer(path).cloned().unwrap_or_default())
            .collect();
        let written: serde_json::Value = serde_json::from_str(
            r#"["openrouter", "anthropic/claude-haiku-4.5", "openrouter", "IMP_KEY",
                "openrouter", "baai/bge-m3", false]"#,
        )
        .unwrap();
        assert_eq!(serde_json::Value::Array(said), written, "{json}");
        let back: AppConfig = serde_json::from_value(json).unwrap();
        assert_eq!(back, c);
    }

    /// A variable the user named as the gateway's key is a secret whatever it
    /// is called, in whichever slot it was typed — so all three reach the list
    /// that model-driven children are started without
    /// (docs/research/safe-defaults.md D5). A slot left out would hand a
    /// `python_exec` child the gateway's key.
    #[test]
    fn a_variable_named_for_the_gateways_key_is_kept_from_children() {
        let mut c = AppConfig::default();
        c.engine.openrouter.api_key_env = Some("MY_ROUTER_CHAT".into());
        c.impersonation_engine.openrouter.api_key_env = Some(" MY_ROUTER_IMP ".into());
        c.embed.openrouter.api_key_env = Some("MY_ROUTER_EMBED".into());
        let named = named_key_env_vars(&c);
        let missing: Vec<&str> = ["MY_ROUTER_CHAT", "MY_ROUTER_IMP", "MY_ROUTER_EMBED"]
            .into_iter()
            .filter(|name| !named.iter().any(|n| n == name))
            .collect();
        assert!(missing.is_empty(), "not named: {missing:?} in {named:?}");
    }

    /// `/continue` through the mode follows the routed vendor, as it does
    /// through `external` with a catalogue — and **without** one too: the mode
    /// is the gateway by name, so there is no llama.cpp for silence to mean
    /// (docs/research/openrouter-mode.md §2.3). Columns: the slug, whether it
    /// continues, why. One literal, not tuple rows (lessons §2).
    const GATEWAY_CONTINUES: &str = "
        anthropic/claude-haiku-4.5        yes | Anthropic up to 4.5 continues
        anthropic/claude-sonnet-4.6       no  | ...and refuses prefill from 4.6 on
        google/gemini-3.5-flash           yes | a Gemini continues
        openai/gpt-5.5                    no  | OpenAI restarts
        qwen/qwen3.6-27b                  no  | every open-weight route restarts
        anthropic/claude-haiku-4.5:nitro  yes | a variant answers as its base
        anthropic/claude-sonnet-4.6:nitro no  | ...and must not hide the minor version
    ";

    #[test]
    fn the_gateway_mode_asks_the_slug_whether_or_not_the_catalogue_answered() {
        let mut wrong = Vec::new();
        for row in GATEWAY_CONTINUES.lines().filter(|l| !l.trim().is_empty()) {
            let (columns, why) = row.split_once('|').unwrap();
            let c: Vec<&str> = columns.split_whitespace().collect();
            for catalogued in [false, true] {
                let got = ServerMode::OpenRouter.supports_continuation(Some(c[0]), catalogued);
                if got != (c[1] == "yes") {
                    wrong.push(format!(
                        "{} (catalogued: {catalogued}) — {}",
                        c[0],
                        why.trim()
                    ));
                }
            }
        }
        assert!(wrong.is_empty(), "{wrong:#?}");
        for catalogued in [false, true] {
            assert!(
                !ServerMode::OpenRouter.supports_continuation(None, catalogued),
                "no model named — nothing to allow by"
            );
        }
        // `external` is unchanged: the same slug is judged only once the
        // endpoint has said it is a gateway.
        assert!(ServerMode::External.supports_continuation(Some("openai/gpt-5.5"), false));
        assert!(!ServerMode::External.supports_continuation(Some("openai/gpt-5.5"), true));
    }

    /// Speech through the gateway (stage 3, docs/research/openrouter-mode.md
    /// §7): the mode is written `openrouter`, as in every other slot; it reads
    /// the provider's one key; and it keeps a section of its own, which the
    /// other modes' values do not leak into.
    #[test]
    fn the_speech_slot_has_a_gateway_mode_on_the_providers_key() {
        let tts: TtsSettings = serde_json::from_str(
            r#"{"mode":"openrouter",
                "openrouter":{"model_name":"x-ai/grok-voice-tts-1.0","voice":"eve"}}"#,
        )
        .expect("the mode is read");
        assert_eq!(tts.mode, TtsMode::OpenRouter);
        assert_eq!(
            serde_json::to_value(&tts).unwrap()["mode"],
            "openrouter",
            "and written back the same"
        );
        assert_eq!(TtsMode::OpenRouter.label(), "openrouter");
        assert_eq!(
            tts.secret_key(),
            Some(SecretKey::Provider(CloudProvider::OpenRouter)),
            "the key the chat slot stored serves speech too"
        );
        assert_eq!(tts.active_voices(), (Some("eve"), None));
        assert_eq!(
            tts.cloud().and_then(|c| c.model_name.as_deref()),
            Some("x-ai/grok-voice-tts-1.0")
        );
        // The section is its own: OpenAI's defaults are where they were.
        assert_eq!(
            tts.openai.model_name.as_deref(),
            Some(DEFAULT_TTS_OPENAI_MODEL)
        );
        for other in ["open_router", "OpenRouter", "openrouter.ai"] {
            let asked = format!(r#"{{"mode":"{other}"}}"#);
            assert!(
                serde_json::from_str::<TtsSettings>(&asked).is_err(),
                "{other} is not a mode"
            );
        }
    }

    /// No default model and no default voice: a default that names a model
    /// ages, and a voice belongs to a model. A speech slot switched to the
    /// gateway and left empty is "not configured", which `/tts` says.
    #[test]
    fn the_gateways_speech_section_starts_empty() {
        let tts = TtsSettings::default();
        assert_eq!(tts.openrouter, TtsCloudSettings::default());
        let written = serde_json::to_value(&tts).unwrap();
        assert!(written["openrouter"]["model_name"].is_null(), "{written}");
        // A file written before the section existed reads with it empty.
        let old: TtsSettings =
            serde_json::from_str(r#"{"mode":"gemini","gemini":{"voice":"Puck"}}"#).unwrap();
        assert_eq!(old.openrouter, TtsCloudSettings::default());
        assert_eq!(old.gemini.voice.as_deref(), Some("Puck"));
    }

    /// Every speech mode cycles through every other, both ways, and each cloud
    /// mode edits the section it reads.
    #[test]
    fn every_speech_mode_is_reached_by_cycling_and_edits_its_own_section() {
        for dir in [1, -1] {
            let mut seen = vec![TtsMode::default()];
            for _ in 1..TtsMode::ALL.len() {
                seen.push(seen.last().unwrap().cycle(dir));
            }
            for mode in TtsMode::ALL {
                assert!(seen.contains(&mode), "{mode:?} not reached with {dir}");
            }
            assert_eq!(seen.last().unwrap().cycle(dir), TtsMode::default());
        }
        for mode in TtsMode::ALL {
            let mut tts = TtsSettings {
                mode,
                ..Default::default()
            };
            let Some(section) = tts.cloud_mut() else {
                assert_eq!(mode, TtsMode::External, "{mode:?} has a section");
                continue;
            };
            section.voice = Some(format!("voice-of-{}", mode.label()));
            let named = format!("voice-of-{}", mode.label());
            assert_eq!(tts.active_voices().0, Some(named.as_str()));
            let sections = [&tts.openai, &tts.gemini, &tts.openrouter];
            let holding = sections
                .iter()
                .filter(|s| s.voice.as_deref() == Some(named.as_str()))
                .count();
            assert_eq!(holding, 1, "{mode:?} wrote to one section");
        }
    }

    // ---------- video through the gateway (docs/research/openrouter-mode.md, fork F10) ----------

    /// The selector is a new field and the gateway's section a new one beside
    /// Gemini's fields: a file written before either reads as it always did —
    /// Gemini, its model where it was — and what each provider holds survives
    /// a switch to the other and back.
    #[test]
    fn the_video_slot_chooses_its_provider_and_keeps_both_models() {
        let old: VideoSettings = serde_json::from_str(
            r#"{"model_name":"gemini-2.5-pro","api_key_env":"MY_GEMINI","max_minutes":45}"#,
        )
        .expect("a file of before the selector");
        assert_eq!(old.provider, VideoProvider::Gemini);
        assert_eq!(old.openrouter, VideoGatewaySettings::default());
        assert_eq!(old.model_name.as_deref(), Some("gemini-2.5-pro"));
        assert_eq!(
            old.secret_key(),
            SecretKey::Provider(CloudProvider::Gemini),
            "Gemini's key, as before"
        );

        let new: VideoSettings = serde_json::from_str(
            r#"{"provider":"openrouter","model_name":"gemini-2.5-pro",
                "openrouter":{"model_name":"google/gemini-3.5-flash","api_key_env":"MY_ROUTER"}}"#,
        )
        .expect("the selector is read");
        assert_eq!(new.provider, VideoProvider::OpenRouter);
        assert_eq!(
            new.secret_key(),
            SecretKey::Provider(CloudProvider::OpenRouter)
        );
        assert_eq!(
            new.openrouter.model_name.as_deref(),
            Some("google/gemini-3.5-flash")
        );
        assert_eq!(new.model_name.as_deref(), Some("gemini-2.5-pro"));
        let written = serde_json::to_value(&new).unwrap();
        assert_eq!(written["provider"], "openrouter");
        assert_eq!(written["openrouter"]["api_key_env"], "MY_ROUTER");

        for other in ["open_router", "OpenRouter", "google"] {
            let asked = format!(r#"{{"provider":"{other}"}}"#);
            assert!(
                serde_json::from_str::<VideoSettings>(&asked).is_err(),
                "{other} is not a provider"
            );
        }
    }

    /// No default model for the gateway — Gemini keeps the one it has — and the
    /// selector is reached both ways from either provider.
    #[test]
    fn the_gateways_video_section_starts_empty_and_the_selector_cycles() {
        let video = VideoSettings::default();
        assert_eq!(video.provider, VideoProvider::Gemini);
        assert_eq!(video.openrouter, VideoGatewaySettings::default());
        assert_eq!(video.model_name.as_deref(), Some(DEFAULT_VIDEO_MODEL));
        for dir in [1, -1] {
            assert_eq!(
                VideoProvider::Gemini.cycle(dir),
                VideoProvider::OpenRouter,
                "{dir}"
            );
            assert_eq!(
                VideoProvider::OpenRouter.cycle(dir),
                VideoProvider::Gemini,
                "{dir}"
            );
        }
        let labels: Vec<&str> = VideoProvider::ALL.into_iter().map(|p| p.label()).collect();
        assert_eq!(labels, ["gemini", "openrouter"]);
        for provider in VideoProvider::ALL {
            let written = serde_json::to_value(provider).unwrap();
            assert_eq!(
                written,
                provider.label(),
                "the label is the file's spelling"
            );
        }
    }

    /// The variable the video slot names for the gateway's key is a secret like
    /// the others — and Gemini's stays one.
    #[test]
    fn the_gateways_video_key_variable_is_named_among_the_secrets() {
        let mut c = AppConfig::default();
        c.video.api_key_env = Some("MY_GEMINI_VIDEO".into());
        c.video.openrouter.api_key_env = Some(" MY_ROUTER_VIDEO ".into());
        let named = named_key_env_vars(&c);
        for name in ["MY_GEMINI_VIDEO", "MY_ROUTER_VIDEO"] {
            assert!(named.contains(&name.to_string()), "{name}: {named:?}");
        }
    }

    /// The variable a speech slot names for the gateway's key is a secret like
    /// the others: removed from what a model-driven child inherits.
    #[test]
    fn the_gateways_speech_key_variable_is_named_among_the_secrets() {
        let mut c = AppConfig::default();
        c.tts.openrouter.api_key_env = Some(" MY_ROUTER_VOICE ".into());
        assert!(
            named_key_env_vars(&c).contains(&"MY_ROUTER_VOICE".to_string()),
            "{:?}",
            named_key_env_vars(&c)
        );
    }
}