llm-manager 1.10.0

Terminal UI for managing LLMs
Documentation
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
mod model_config;
mod presets;
mod profiles;
mod store;

use std::collections::HashSet;
use std::path::PathBuf;

use chrono::Local;
use serde::{Deserialize, Serialize};

#[allow(unused_imports)]
pub use model_config::{ModelConfigStore, display_from_key, key_from_display};

pub use profiles::ProfileStore;

use crate::models::{
    Backend, CacheType, CacheTypeK, CacheTypeV, Mirostat, NumMode, RopeScaling, Samplers, SplitMode,
};
use crate::tui::app::ActivePanel;
pub use presets::PresetStore;

/// Default system prompt used when no preset is selected.
pub const DEFAULT_SYSTEM_PROMPT: &str = "You are an expert software developer. Write clean, well-documented code. Explain your reasoning and suggest improvements.";

/// Resolve the base config directory with a safe fallback chain.
///
/// Prefers `dirs::config_dir()` (XDG on Linux, ~/Library/Application Support on macOS,
/// etc.), falls back to `~/.config`, and lastly `./.llm-manager` if both fail.
pub fn config_base_dir() -> PathBuf {
    if let Some(d) = dirs::config_dir() {
        return d;
    }
    if let Some(home) = dirs::home_dir() {
        return home.join(".config");
    }
    PathBuf::from(".").join(".llm-manager")
}

/// Count physical CPU cores on Linux (ignores hyperthreading).
/// Falls back to 1 if the file can't be read or parsing fails.
pub fn physical_cores() -> u32 {
    let content = match std::fs::read_to_string("/proc/cpuinfo") {
        Ok(c) => c,
        Err(_) => {
            return std::thread::available_parallelism()
                .map(|p| p.get() as u32)
                .unwrap_or(1);
        }
    };
    let mut seen = HashSet::new();
    let mut cur_phys: Option<&str> = None;
    let mut cur_core: Option<&str> = None;
    for line in content.lines() {
        if let Some((key, val)) = line.split_once(':') {
            let key = key.trim();
            let val = val.trim();
            match key {
                "physical id" => cur_phys = Some(val),
                "core id" => cur_core = Some(val),
                _ => {}
            }
            if let (Some(phys), Some(core)) = (cur_phys, cur_core) {
                seen.insert((phys, core));
            }
        }
    }
    seen.len().max(1) as u32
}

/// A remote RPC worker for distributed inference.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RpcWorker {
    #[serde(default)]
    pub selected: bool,
    #[serde(default)]
    pub name: String,
    pub ip: String,
    #[serde(default = "default_rpc_port")]
    pub port: u16,
}

fn default_rpc_port() -> u16 {
    50052
}

/// Global configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    pub models_dirs: Vec<PathBuf>,
    pub llama_server: PathBuf,
    pub default: DefaultParams,
    /// Per-model overrides (keyed by display_name/path relative to model dir, stored as YAML in models/).
    #[serde(default, skip)]
    pub model_overrides: ModelConfigStore,
    /// Named profiles of settings presets (stored as YAML in profiles/).
    #[serde(default, skip)]
    pub profiles: ProfileStore,
    /// System prompt presets (stored as YAML in presets/).
    #[serde(default, skip)]
    pub system_prompt_presets: PresetStore,
    /// RPC Workers for distributed inference.
    #[serde(default)]
    pub rpc_workers: Vec<RpcWorker>,
    /// Number of results per HuggingFace search query.
    #[serde(default = "default_search_limit")]
    pub search_limit: u32,
    /// The last focused panel position (for restoring on next launch).
    #[serde(default)]
    pub active_panel: crate::tui::app::ActivePanel,
    /// Left panel width percentage (20-80).
    #[serde(default = "default_left_pct")]
    pub left_pct: u16,
    /// Server Settings panel height in rows (3-20).
    #[serde(default = "default_server_settings_height")]
    pub server_settings_height: u16,
    /// UI language (en, fr, it). Falls back to en.
    #[serde(default = "default_language")]
    pub language: String,
    /// Whether the first-launch onboarding wizard has been completed.
    #[serde(default = "default_onboarding")]
    pub onboarding_complete: bool,
}

fn default_language() -> String {
    "en".to_string()
}

fn default_left_pct() -> u16 {
    55
}

fn default_server_settings_height() -> u16 {
    9
}

fn default_onboarding() -> bool {
    false
}

fn default_search_limit() -> u32 {
    50
}

/// A named profile of settings.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Profile {
    pub name: String,
    /// Brief description shown in the profile list.
    pub description: String,
    /// The settings for this profile.
    #[serde(default)]
    pub settings: ModelOverride,
}

impl Profile {
    /// Apply this profile's settings to a base ModelSettings.
    pub fn apply(&self, mut base: crate::models::ModelSettings) -> crate::models::ModelSettings {
        self.settings.apply(&mut base);
        base
    }
}

impl crate::config::store::NamedItem for Profile {
    fn name(&self) -> &str {
        &self.name
    }
}

/// A named system prompt preset.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemPromptPreset {
    pub name: String,
    pub description: String,
    pub content: String,
}

impl crate::config::store::NamedItem for SystemPromptPreset {
    fn name(&self) -> &str {
        &self.name
    }
}

/// Built-in system prompt presets.
pub fn builtin_system_prompt_presets() -> Vec<SystemPromptPreset> {
    vec![
        SystemPromptPreset {
            name: "General".into(),
            description: "General-purpose assistant".into(),
            content: "You are a helpful assistant.".into(),
        },
        SystemPromptPreset {
            name: "Coder".into(),
            description: "Expert software developer".into(),
            content: "You are an expert software developer. Write clean, well-documented code. Explain your reasoning and suggest improvements. Split code to avoid too big files. Always try to re-use existing code, avoid duplicate function. In case of reviewing code: every claim must have file:line reference. For kernel Every Kconfig symbol must be verified against actual Kconfig files. Every XML example must be validated against Relax NG schema. Every limitation must be verified against source code. Do NOT include claims you cannot verify. Use tables for structured data. Use code blocks for commands. Cross-reference between components. Workflows using SVG.".into(),
        },
        SystemPromptPreset {
            name: "Thinker".into(),
            description: "Analytical and thoughtful".into(),
            content: "You are a thoughtful and analytical AI assistant. Think carefully before answering. Provide well-reasoned responses with clear explanations. Do NOT include claims you cannot verify".into(),
        },
        SystemPromptPreset {
            name: "Mathematician".into(),
            description: "Expert in mathematics".into(),
            content: "You are an expert in mathematics. Provide clear, step-by-step solutions to mathematical problems. Show your reasoning and explain key concepts.".into(),
        },
    ]
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
pub struct ModelOverride {
    // Loading
    pub context_length: Option<u32>,
    pub batch_size: Option<u32>,
    pub ubatch_size: Option<u32>,
    pub cache_type_k: Option<CacheTypeK>,
    pub cache_type_v: Option<CacheTypeV>,
    pub keep: Option<i32>,
    pub swa_full: Option<bool>,
    pub mlock: Option<bool>,
    pub mmap: Option<bool>,
    pub numa: Option<NumMode>,
    pub uniform_cache: Option<bool>,
    pub system_prompt: Option<String>,
    pub system_prompt_preset_name: Option<String>,
    pub max_concurrent_predictions: Option<u32>,
    pub threads: Option<u32>,
    pub threads_batch: Option<u32>,
    pub parallel: Option<u32>,

    // GPU
    pub gpu_layers: Option<i32>,
    pub split_mode: Option<SplitMode>,
    pub tensor_split: Option<String>,
    pub main_gpu: Option<i32>,
    pub fit: Option<bool>,
    pub lora: Option<PathBuf>,
    pub lora_scaled: Option<(PathBuf, f32)>,
    pub rpc: Option<String>,
    pub embedding: Option<bool>,
    pub kv_cache_offload: Option<bool>,
    pub flash_attn: Option<bool>,
    pub jinja: Option<bool>,
    pub auto_chat_template: Option<bool>,
    pub chat_template: Option<String>,
    pub chat_template_kwargs: Option<String>,
    pub expert_count: Option<i32>,
    pub gpu_layers_mode: Option<crate::models::GpuLayersMode>,

    // Sampling
    pub seed: Option<i32>,
    pub temperature: Option<f32>,
    pub top_k: Option<i32>,
    pub top_p: Option<f32>,
    pub min_p: Option<f32>,
    pub typical_p: Option<f32>,
    pub mirostat: Option<Mirostat>,
    pub mirostat_lr: Option<f32>,
    pub mirostat_ent: Option<f32>,
    pub ignore_eos: Option<bool>,
    pub samplers: Option<Samplers>,

    // Repetition
    pub repeat_penalty: Option<f32>,
    pub repeat_last_n: Option<i32>,
    pub presence_penalty: Option<f32>,
    pub frequency_penalty: Option<f32>,
    pub dry_multiplier: Option<f32>,
    pub dry_base: Option<f32>,
    pub dry_allowed_length: Option<i32>,
    pub dry_penalty_last_n: Option<i32>,

    // RoPE
    pub rope_scaling: Option<RopeScaling>,
    pub rope_scale: Option<f32>,
    pub rope_freq_base: Option<f32>,
    pub rope_freq_scale: Option<f32>,
    pub rope_yarn_enabled: Option<bool>,

    // Server
    pub cache_prompt: Option<bool>,
    pub cache_reuse: Option<u32>,
    pub webui: Option<bool>,

    // Other
    pub max_tokens: Option<u32>,
    pub cache_type: Option<CacheType>,
    pub llama_cpp_version_cpu: Option<String>,
    pub llama_cpp_version_vulkan: Option<String>,
    pub llama_cpp_version_rocm: Option<String>,
    pub llama_cpp_version_rocm_lemonade: Option<String>,
    pub llama_cpp_version_cuda: Option<String>,
    pub spec_type: Option<String>,
    pub draft_tokens: Option<u32>,
    pub tags: Option<Vec<String>>,
}

/// Apply a scalar Copy field from override: `base.f = self.f.unwrap_or(base.f)`.
macro_rules! apply_scalar {
    ($self:ident, $base:ident, $($field:ident),+ $(,)?) => {
        $(
            $base.$field = $self.$field.unwrap_or($base.$field);
        )+
    };
}

/// Apply a Clone field from override: `if let Some(v) = &self.f { base.f = v.clone(); }`.
macro_rules! apply_clone {
    ($self:ident, $base:ident, $($field:ident),+ $(,)?) => {
        $(
            if let Some(v) = &$self.$field {
                $base.$field = v.clone();
            }
        )+
    };
}

/// Apply an Option<T> field from override: `if let Some(v) = &self.f { base.f = Some(v.clone()); }`.
macro_rules! apply_option {
    ($self:ident, $base:ident, $($field:ident),+ $(,)?) => {
        $(
            if let Some(v) = &$self.$field {
                $base.$field = Some(v.clone());
            }
        )+
    };
}

impl ModelOverride {
    pub fn from_settings(s: &crate::models::ModelSettings) -> Self {
        Self {
            context_length: Some(s.context_length),
            batch_size: Some(s.batch_size),
            ubatch_size: Some(s.ubatch_size),
            cache_type_k: s.cache_type_k,
            cache_type_v: s.cache_type_v,
            keep: Some(s.keep),
            swa_full: Some(s.swa_full),
            mlock: Some(s.mlock),
            mmap: Some(s.mmap),
            numa: Some(s.numa),
            uniform_cache: Some(s.uniform_cache),
            system_prompt: Some(s.system_prompt.clone()),
            system_prompt_preset_name: Some(s.system_prompt_preset_name.clone()),
            max_concurrent_predictions: s.max_concurrent_predictions,
            threads: Some(s.threads),
            threads_batch: Some(s.threads_batch),
            parallel: Some(s.parallel),
            gpu_layers: Some(match s.gpu_layers_mode {
                crate::models::GpuLayersMode::Auto => -2,
                crate::models::GpuLayersMode::Specific(n) => n as i32,
                crate::models::GpuLayersMode::All => -1,
            }),
            gpu_layers_mode: Some(s.gpu_layers_mode),
            split_mode: Some(s.split_mode),
            tensor_split: Some(s.tensor_split.clone()),
            main_gpu: Some(s.main_gpu),
            fit: Some(s.fit),
            lora: s.lora.clone(),
            lora_scaled: s.lora_scaled.clone(),
            rpc: Some(s.rpc.clone()),
            embedding: Some(s.embedding),
            kv_cache_offload: Some(s.kv_cache_offload),
            flash_attn: Some(s.flash_attn),
            jinja: Some(s.jinja),
            auto_chat_template: Some(s.auto_chat_template),
            chat_template: s.chat_template.clone(),
            chat_template_kwargs: s.chat_template_kwargs.clone(),
            expert_count: Some(s.expert_count),
            seed: Some(s.seed),
            temperature: Some(s.temperature),
            top_k: Some(s.top_k),
            top_p: Some(s.top_p),
            min_p: Some(s.min_p),
            typical_p: Some(s.typical_p),
            mirostat: Some(s.mirostat),
            mirostat_lr: Some(s.mirostat_lr),
            mirostat_ent: Some(s.mirostat_ent),
            ignore_eos: Some(s.ignore_eos),
            samplers: Some(s.samplers.clone()),
            repeat_penalty: Some(s.repeat_penalty),
            repeat_last_n: Some(s.repeat_last_n),
            presence_penalty: s.presence_penalty,
            frequency_penalty: s.frequency_penalty,
            dry_multiplier: Some(s.dry_multiplier),
            dry_base: Some(s.dry_base),
            dry_allowed_length: Some(s.dry_allowed_length),
            dry_penalty_last_n: Some(s.dry_penalty_last_n),
            rope_scaling: Some(s.rope_scaling),
            rope_scale: Some(s.rope_scale),
            rope_freq_base: Some(s.rope_freq_base),
            rope_freq_scale: Some(s.rope_freq_scale),
            rope_yarn_enabled: Some(s.rope_yarn_enabled),
            cache_prompt: Some(s.cache_prompt),
            cache_reuse: Some(s.cache_reuse),
            webui: Some(s.webui),
            max_tokens: s.max_tokens,
            cache_type: Some(s.cache_type),
            llama_cpp_version_cpu: s.llama_cpp_version_cpu.clone(),
            llama_cpp_version_vulkan: s.llama_cpp_version_vulkan.clone(),
            llama_cpp_version_rocm: s.llama_cpp_version_rocm.clone(),
            llama_cpp_version_rocm_lemonade: s.llama_cpp_version_rocm_lemonade.clone(),
            llama_cpp_version_cuda: s.llama_cpp_version_cuda.clone(),
            spec_type: Some(s.spec_type.clone()),
            draft_tokens: Some(s.draft_tokens),
            tags: Some(s.tags.clone()),
        }
    }

    /// Merge override into a base ModelSettings (in-place).
    pub fn apply(&self, base: &mut crate::models::ModelSettings) {
        // Override values always take precedence. For Option<T> fields,
        // the override value (even None) is explicitly set by the user.

        // Scalar Copy fields: base.f = self.f.unwrap_or(base.f)
        apply_scalar!(
            self,
            base,
            context_length,
            batch_size,
            ubatch_size,
            keep,
            swa_full,
            mlock,
            mmap,
            numa,
            uniform_cache,
            kv_cache_offload,
            threads,
            threads_batch,
            parallel,
            split_mode,
            main_gpu,
            fit,
            embedding,
            flash_attn,
            jinja,
            auto_chat_template,
            expert_count,
            seed,
            temperature,
            top_k,
            top_p,
            min_p,
            typical_p,
            mirostat,
            mirostat_lr,
            mirostat_ent,
            ignore_eos,
            repeat_penalty,
            repeat_last_n,
            dry_multiplier,
            dry_base,
            dry_allowed_length,
            dry_penalty_last_n,
            rope_scaling,
            rope_scale,
            rope_freq_base,
            rope_freq_scale,
            rope_yarn_enabled,
            cache_prompt,
            cache_reuse,
            webui,
            cache_type,
            draft_tokens,
            gpu_layers_mode,
        );

        // Cloneable fields: if let Some(v) = &self.f { base.f = v.clone(); }
        apply_clone!(
            self,
            base,
            system_prompt,
            system_prompt_preset_name,
            tensor_split,
            rpc,
            samplers,
            spec_type,
            tags,
        );

        // Option<T> fields: if let Some(v) = &self.f { base.f = Some(v.clone()); }
        apply_option!(
            self,
            base,
            lora,
            lora_scaled,
            chat_template,
            chat_template_kwargs,
            llama_cpp_version_cpu,
            llama_cpp_version_vulkan,
            llama_cpp_version_rocm,
            llama_cpp_version_rocm_lemonade,
            llama_cpp_version_cuda,
        );

        // Direct Option<T> assignment (same type in both structs) — only apply if Some
        if let Some(v) = self.cache_type_k {
            base.cache_type_k = Some(v);
        }
        if let Some(v) = self.cache_type_v {
            base.cache_type_v = Some(v);
        }
        if let Some(v) = self.presence_penalty {
            base.presence_penalty = Some(v);
        }
        if let Some(v) = self.frequency_penalty {
            base.frequency_penalty = Some(v);
        }
        base.max_tokens = self.max_tokens.or(base.max_tokens);

        // Special: max_concurrent_predictions uses or() for Option chaining
        base.max_concurrent_predictions = self
            .max_concurrent_predictions
            .or(base.max_concurrent_predictions);

        // Special: gpu_layers converts i32 legacy field to GpuLayersMode enum
        // Only applies when gpu_layers is explicitly set in the override.
        // -2 is sentinel for Auto (preserves round-trip from from_settings).
        if let Some(n) = self.gpu_layers {
            base.gpu_layers_mode = match n {
                -2 => crate::models::GpuLayersMode::Auto,
                n if n < 0 => crate::models::GpuLayersMode::All,
                n => crate::models::GpuLayersMode::Specific(n as u32),
            };
        }

        // FIELD ACCOUNTING (ModelOverride: 87 fields):
        // - apply_scalar: 53 fields
        // - apply_clone: 7 fields
        // - apply_option: 10 fields
        // - direct Option assign: 5 fields (cache_type_k, cache_type_v, presence_penalty,
        //   frequency_penalty, max_tokens)
        // - special: 1 field (max_concurrent_predictions)
        // - conditional: gpu_layers overrides gpu_layers_mode only when Some
        // - NOT in ModelSettings: 0 (all ModelOverride fields mapped above)
        //
        // ModelSettings fields NOT in ModelOverride (not overridable):
        // host, port, timeout, backend, platform, router_max_models, server_mode,
        // api_endpoint_enabled, api_endpoint_port
        //
        // When adding a field: ensure it appears in exactly one category above.
    }
}

/// Built-in profiles with sensible defaults for popular model families.
pub fn builtin_profiles() -> Vec<Profile> {
    vec![
        Profile {
            name: "Qwen".into(),
            description: "Optimized for Qwen models (dense)".into(),
            settings: ModelOverride {
                context_length: Some(131072),
                temperature: Some(0.7),
                top_k: Some(20),
                top_p: Some(0.95),
                max_tokens: Some(4096),
                presence_penalty: Some(0.0),
                uniform_cache: Some(true),
                jinja: Some(true),
                ..Default::default()
            },
        },
        Profile {
            name: "Qwen-MoE".into(),
            description: "Optimized for Qwen MoE models (35B-A3B)".into(),
            settings: ModelOverride {
                context_length: Some(131072),
                temperature: Some(0.8),
                top_k: Some(20),
                top_p: Some(0.95),
                max_tokens: Some(4096),
                presence_penalty: Some(1.5),
                uniform_cache: Some(true),
                jinja: Some(true),
                ..Default::default()
            },
        },
        Profile {
            name: "Qwen-Coding".into(),
            description: "Optimized for Qwen models in coding mode".into(),
            settings: ModelOverride {
                context_length: Some(131072),
                temperature: Some(0.6),
                top_k: Some(20),
                top_p: Some(0.95),
                max_tokens: Some(4096),
                presence_penalty: Some(0.0),
                uniform_cache: Some(true),
                jinja: Some(true),
                ..Default::default()
            },
        },
        Profile {
            name: "Gemma".into(),
            description: "Optimized for Gemma 2/4 models".into(),
            settings: ModelOverride {
                context_length: Some(131072),
                min_p: Some(0.1),
                temperature: Some(1.0),
                top_k: Some(65),
                top_p: Some(0.95),
                max_tokens: Some(4096),
                uniform_cache: Some(true),
                jinja: Some(true),
                ..Default::default()
            },
        },
        Profile {
            name: "Llama".into(),
            description: "Optimized for Llama 3.1/3.3 models".into(),
            settings: ModelOverride {
                context_length: Some(131072),
                temperature: Some(0.7),
                top_p: Some(0.9),
                repeat_penalty: Some(1.1),
                max_tokens: Some(4096),
                uniform_cache: Some(true),
                jinja: Some(true),
                ..Default::default()
            },
        },
        Profile {
            name: "Mistral".into(),
            description: "Optimized for Mistral 7B/NeMo models".into(),
            settings: ModelOverride {
                context_length: Some(131072),
                temperature: Some(0.7),
                top_k: Some(50),
                top_p: Some(0.9),
                max_tokens: Some(4096),
                uniform_cache: Some(true),
                jinja: Some(true),
                ..Default::default()
            },
        },
        Profile {
            name: "Phi".into(),
            description: "Optimized for Phi 3.5 Mini models".into(),
            settings: ModelOverride {
                context_length: Some(131072),
                temperature: Some(0.7),
                top_k: Some(50),
                top_p: Some(0.9),
                repeat_penalty: Some(1.1),
                max_tokens: Some(4096),
                uniform_cache: Some(true),
                ..Default::default()
            },
        },
    ]
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct DefaultParams {
    // Loading
    #[serde(default)]
    pub context_length: u32,
    #[serde(default)]
    pub threads: u32,
    #[serde(default)]
    pub threads_batch: u32,
    #[serde(default)]
    pub batch_size: u32,
    #[serde(default)]
    pub ubatch_size: u32,
    #[serde(default = "default_cache_type_k")]
    pub cache_type_k: Option<CacheTypeK>,
    #[serde(default = "default_cache_type_v")]
    pub cache_type_v: Option<CacheTypeV>,
    #[serde(default)]
    pub keep: i32,
    #[serde(default)]
    pub swa_full: bool,
    #[serde(default)]
    pub mlock: bool,
    #[serde(default)]
    pub mmap: bool,
    #[serde(default)]
    pub numa: NumMode,
    #[serde(default)]
    pub uniform_cache: bool,
    #[serde(default)]
    pub kv_cache_offload: bool,
    #[serde(default)]
    pub parallel: u32,
    #[serde(default)]
    pub max_concurrent_predictions: Option<u32>,
    #[serde(default)]
    pub system_prompt: String,
    #[serde(default = "default_system_prompt_preset_name")]
    pub system_prompt_preset_name: String,
    // GPU
    #[serde(default)]
    pub gpu_layers: i32,
    #[serde(default = "default_gpu_layers_mode")]
    pub gpu_layers_mode: crate::models::GpuLayersMode,
    #[serde(default)]
    pub split_mode: SplitMode,
    #[serde(default)]
    pub tensor_split: String,
    #[serde(default)]
    pub main_gpu: i32,
    #[serde(default)]
    pub fit: bool,
    #[serde(default)]
    pub lora: Option<PathBuf>,
    #[serde(default)]
    pub lora_scaled: Option<(PathBuf, f32)>,
    #[serde(default)]
    pub rpc: String,
    #[serde(default)]
    pub embedding: bool,
    #[serde(default)]
    pub flash_attn: bool,
    #[serde(default)]
    pub jinja: bool,
    #[serde(default)]
    pub auto_chat_template: bool,
    #[serde(default)]
    pub chat_template: Option<String>,
    #[serde(default)]
    pub chat_template_kwargs: Option<String>,
    #[serde(default)]
    pub expert_count: i32,

    // Sampling
    #[serde(default)]
    pub seed: i32,
    #[serde(default)]
    pub temperature: f32,
    #[serde(default)]
    pub top_k: i32,
    #[serde(default)]
    pub top_p: f32,
    #[serde(default)]
    pub min_p: f32,
    #[serde(default)]
    pub typical_p: f32,
    #[serde(default)]
    pub mirostat: Mirostat,
    #[serde(default)]
    pub mirostat_lr: f32,
    #[serde(default)]
    pub mirostat_ent: f32,
    #[serde(default)]
    pub ignore_eos: bool,
    #[serde(default)]
    pub samplers: Samplers,

    // Repetition
    #[serde(default)]
    pub repeat_penalty: f32,
    #[serde(default)]
    pub repeat_last_n: i32,
    #[serde(default = "default_presence_penalty")]
    pub presence_penalty: Option<f32>,
    #[serde(default = "default_frequency_penalty")]
    pub frequency_penalty: Option<f32>,
    #[serde(default)]
    pub dry_multiplier: f32,
    #[serde(default)]
    pub dry_base: f32,
    #[serde(default)]
    pub dry_allowed_length: i32,
    #[serde(default)]
    pub dry_penalty_last_n: i32,

    // RoPE
    #[serde(default)]
    pub rope_scaling: RopeScaling,
    #[serde(default)]
    pub rope_scale: f32,
    #[serde(default)]
    pub rope_freq_base: f32,
    #[serde(default)]
    pub rope_freq_scale: f32,
    #[serde(default)]
    pub rope_yarn_enabled: bool,

    // Server
    #[serde(default)]
    pub host: String,
    #[serde(default)]
    pub port: u16,
    #[serde(default)]
    pub timeout: u32,
    #[serde(default = "default_cache_prompt")]
    pub cache_prompt: bool,
    #[serde(default)]
    pub cache_reuse: u32,
    #[serde(default)]
    pub webui: bool,
    #[serde(default)]
    pub ws_server_enabled: bool,
    #[serde(default = "default_ws_server_port")]
    pub ws_server_port: u16,
    #[serde(default = "default_server_tls_enabled")]
    pub server_tls_enabled: bool,
    #[serde(default)]
    pub server_tls_cert: Option<String>,
    #[serde(default)]
    pub server_tls_key: Option<String>,
    #[serde(default)]
    pub router_max_models: u32,
    #[serde(default)]
    pub server_mode: crate::models::ServerMode,
    #[serde(default = "default_log_level")]
    pub log_level: String,

    // Other
    #[serde(default = "default_max_tokens")]
    pub max_tokens: Option<u32>,
    #[serde(default)]
    pub cache_type: CacheType,
    #[serde(default)]
    pub backend: Backend,
    /// Platform override: "linux", "windows", or "macos". If None, auto-detected.
    #[serde(default)]
    pub platform: Option<String>,
    #[serde(default)]
    pub llama_cpp_version_cpu: Option<String>,
    #[serde(default)]
    pub llama_cpp_version_vulkan: Option<String>,
    #[serde(default)]
    pub llama_cpp_version_rocm: Option<String>,
    #[serde(default)]
    pub llama_cpp_version_rocm_lemonade: Option<String>,
    #[serde(default)]
    pub llama_cpp_version_cuda: Option<String>,

    // API
    #[serde(default)]
    pub api_endpoint_enabled: bool,
    #[serde(default = "default_api_endpoint_port")]
    pub api_endpoint_port: u16,
    #[serde(default = "default_web_search_engine")]
    pub web_search_engine: String,
    #[serde(default)]
    pub web_search_engine_url: String,
    #[serde(default = "default_web_search_enabled")]
    pub web_search_enabled: bool,
    #[serde(default)]
    pub web_search_api_key: Option<String>,
    #[serde(default)]
    pub api_endpoint_key: Option<String>,
    #[serde(default)]
    pub spec_type: String,
    #[serde(default)]
    pub draft_tokens: u32,
    #[serde(default)]
    pub tags: Vec<String>,
}

fn default_api_endpoint_port() -> u16 {
    49222
}

fn default_web_search_engine() -> String {
    "searxng".to_string()
}

fn default_web_search_enabled() -> bool {
    false
}

fn default_system_prompt_preset_name() -> String {
    "General".to_string()
}

fn default_cache_type_k() -> Option<CacheTypeK> {
    None
}
fn default_cache_type_v() -> Option<CacheTypeV> {
    None
}
fn default_presence_penalty() -> Option<f32> {
    None
}
fn default_frequency_penalty() -> Option<f32> {
    None
}
fn default_max_tokens() -> Option<u32> {
    None
}
fn default_cache_prompt() -> bool {
    true
}
fn default_ws_server_port() -> u16 {
    49223
}

fn default_server_tls_enabled() -> bool {
    true
}

fn default_log_level() -> String {
    "trace".to_string()
}

fn default_gpu_layers_mode() -> crate::models::GpuLayersMode {
    crate::models::GpuLayersMode::Auto
}

impl Default for DefaultParams {
    fn default() -> Self {
        Self {
            // Loading
            context_length: 131072,
            threads: physical_cores(),
            threads_batch: 8,
            batch_size: 512,
            ubatch_size: 512,
            cache_type_k: None,
            cache_type_v: None,
            keep: 0,
            swa_full: false,
            mlock: false,
            mmap: true,
            numa: NumMode::None,
            uniform_cache: true,
            kv_cache_offload: true,
            parallel: 1,
            max_concurrent_predictions: None,
            system_prompt: DEFAULT_SYSTEM_PROMPT.to_string(),
            system_prompt_preset_name: "Coder".to_string(),

            // GPU
            gpu_layers: -1,
            gpu_layers_mode: crate::models::GpuLayersMode::Auto,
            split_mode: SplitMode::Layer,
            tensor_split: String::new(),
            main_gpu: 0,
            fit: true,
            lora: None,
            lora_scaled: None,
            rpc: String::new(),
            embedding: false,
            flash_attn: true,
            jinja: true,
            auto_chat_template: false,
            chat_template: None,
            chat_template_kwargs: None,
            expert_count: -1,

            // Sampling
            seed: -1,
            temperature: 0.8,
            top_k: 40,
            top_p: 0.95,
            min_p: 0.0,
            typical_p: 1.0,
            mirostat: Mirostat::Off,
            mirostat_lr: 0.1,
            mirostat_ent: 5.0,
            ignore_eos: false,
            samplers: Samplers::default(),

            // Repetition
            repeat_penalty: 1.1,
            repeat_last_n: 64,
            presence_penalty: None,
            frequency_penalty: None,
            dry_multiplier: 0.0,
            dry_base: 1.75,
            dry_allowed_length: 2,
            dry_penalty_last_n: -1,

            // RoPE
            rope_scaling: RopeScaling::None,
            rope_scale: 1.0,
            rope_freq_base: 0.0,
            rope_freq_scale: 1.0,
            rope_yarn_enabled: false,

            // Server
            host: "127.0.0.1".to_string(),
            port: 8080,
            timeout: 600,
            cache_prompt: true,
            cache_reuse: 0,
            webui: false,
            ws_server_enabled: false,
            ws_server_port: 49223,
            server_tls_enabled: true,
            server_tls_cert: None,
            server_tls_key: None,
            router_max_models: 4,
            server_mode: crate::models::ServerMode::Normal,
            log_level: "trace".to_string(),

            // Other
            max_tokens: None,
            cache_type: CacheType::F16,
            backend: {
                use crate::backend::hardware::{GpuVendor, detect_gpu_vendors};
                let vendors = detect_gpu_vendors();
                let mut result = Backend::Cpu;
                for v in &vendors {
                    if matches!(v, GpuVendor::Nvidia) {
                        result = Backend::Cuda;
                        break;
                    }
                    if matches!(v, GpuVendor::Amd) {
                        result = Backend::Rocm;
                        break;
                    }
                    if matches!(v, GpuVendor::Intel) {
                        result = Backend::Vulkan;
                        break;
                    }
                }
                result
            },
            platform: None,
            llama_cpp_version_cpu: None,
            llama_cpp_version_vulkan: None,
            llama_cpp_version_rocm: None,
            llama_cpp_version_rocm_lemonade: None,
            llama_cpp_version_cuda: None,
            api_endpoint_enabled: false,
            api_endpoint_port: 49222,
            api_endpoint_key: None,
            web_search_engine: "searxng".to_string(),
            web_search_engine_url: String::new(),
            web_search_enabled: false,
            web_search_api_key: None,
            spec_type: String::new(),
            draft_tokens: 0,
            tags: Vec::new(),
        }
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            models_dirs: vec![
                dirs::data_dir()
                    .unwrap_or_default()
                    .join("llm-manager")
                    .join("models"),
            ],
            llama_server: "llama-server".into(),
            default: DefaultParams::default(),
            model_overrides: ModelConfigStore::new(),
            profiles: Default::default(),
            system_prompt_presets: Default::default(),
            rpc_workers: Vec::new(),
            search_limit: default_search_limit(),
            active_panel: ActivePanel::Models,
            left_pct: 55,
            server_settings_height: 9,
            language: default_language(),
            onboarding_complete: false,
        }
    }
}

impl Config {
    pub fn config_path() -> PathBuf {
        config_base_dir().join("llm-manager").join("config.yaml")
    }

    /// Known top-level config keys.
    fn config_keys() -> &'static [&'static str] {
        &[
            "models_dirs",
            "llama_server",
            "default",
            "model_overrides",
            "profiles",
            "system_prompt_presets",
            "rpc_workers",
            "search_limit",
            "active_panel",
            "left_pct",
            "server_settings_height",
            "language",
            "onboarding_complete",
        ]
    }

    /// Known DefaultParams keys.
    fn default_params_keys() -> &'static [&'static str] {
        &[
            "context_length",
            "threads",
            "threads_batch",
            "batch_size",
            "ubatch_size",
            "cache_type_k",
            "cache_type_v",
            "keep",
            "swa_full",
            "mlock",
            "mmap",
            "numa",
            "uniform_cache",
            "kv_cache_offload",
            "parallel",
            "max_concurrent_predictions",
            "system_prompt",
            "system_prompt_preset_name",
            "gpu_layers",
            "gpu_layers_mode",
            "split_mode",
            "tensor_split",
            "main_gpu",
            "fit",
            "lora",
            "lora_scaled",
            "rpc",
            "embedding",
            "flash_attn",
            "jinja",
            "chat_template",
            "chat_template_kwargs",
            "expert_count",
            "seed",
            "temperature",
            "top_k",
            "top_p",
            "min_p",
            "typical_p",
            "mirostat",
            "mirostat_lr",
            "mirostat_ent",
            "ignore_eos",
            "samplers",
            "repeat_penalty",
            "repeat_last_n",
            "presence_penalty",
            "frequency_penalty",
            "dry_multiplier",
            "dry_base",
            "dry_allowed_length",
            "dry_penalty_last_n",
            "rope_scaling",
            "rope_scale",
            "rope_freq_base",
            "rope_freq_scale",
            "rope_yarn_enabled",
            "host",
            "port",
            "timeout",
            "cache_prompt",
            "cache_reuse",
            "webui",
            "ws_server_enabled",
            "ws_server_port",
            "server_tls_enabled",
            "server_tls_cert",
            "server_tls_key",
            "router_max_models",
            "server_mode",
            "log_level",
            "max_tokens",
            "cache_type",
            "backend",
            "platform",
            "llama_cpp_version_cpu",
            "llama_cpp_version_vulkan",
            "llama_cpp_version_rocm",
            "llama_cpp_version_rocm_lemonade",
            "llama_cpp_version_cuda",
            "api_endpoint_enabled",
            "api_endpoint_port",
            "api_endpoint_key",
            "web_search_engine",
            "web_search_engine_url",
            "web_search_enabled",
            "web_search_api_key",
            "spec_type",
            "draft_tokens",
            "tags",
            "auto_chat_template",
        ]
    }

    /// Known ModelOverride keys.
    fn model_override_keys() -> &'static [&'static str] {
        &[
            "context_length",
            "batch_size",
            "ubatch_size",
            "cache_type_k",
            "cache_type_v",
            "keep",
            "swa_full",
            "mlock",
            "mmap",
            "numa",
            "uniform_cache",
            "system_prompt",
            "system_prompt_preset_name",
            "max_concurrent_predictions",
            "threads",
            "threads_batch",
            "parallel",
            "gpu_layers",
            "split_mode",
            "tensor_split",
            "main_gpu",
            "fit",
            "lora",
            "lora_scaled",
            "rpc",
            "embedding",
            "kv_cache_offload",
            "flash_attn",
            "jinja",
            "auto_chat_template",
            "chat_template",
            "chat_template_kwargs",
            "expert_count",
            "gpu_layers_mode",
            "seed",
            "temperature",
            "top_k",
            "top_p",
            "min_p",
            "typical_p",
            "mirostat",
            "mirostat_lr",
            "mirostat_ent",
            "ignore_eos",
            "samplers",
            "repeat_penalty",
            "repeat_last_n",
            "presence_penalty",
            "frequency_penalty",
            "dry_multiplier",
            "dry_base",
            "dry_allowed_length",
            "dry_penalty_last_n",
            "rope_scaling",
            "rope_scale",
            "rope_freq_base",
            "rope_freq_scale",
            "rope_yarn_enabled",
            "cache_prompt",
            "cache_reuse",
            "webui",
            "max_tokens",
            "cache_type",
            "llama_cpp_version_cpu",
            "llama_cpp_version_vulkan",
            "llama_cpp_version_rocm",
            "llama_cpp_version_rocm_lemonade",
            "llama_cpp_version_cuda",
            "spec_type",
            "draft_tokens",
            "tags",
        ]
    }

    /// Known RpcWorker keys.
    fn rpc_worker_keys() -> &'static [&'static str] {
        &["selected", "name", "ip", "port"]
    }

    /// Validate unknown YAML keys against known field lists.
    pub fn validate_unknown_fields(value: &serde_yml::Value) -> Vec<ValidationWarning> {
        let mut warnings = Vec::new();
        Self::check_unknown_fields(value, "", Self::config_keys(), &mut warnings);
        warnings
    }

    fn check_unknown_fields(
        value: &serde_yml::Value,
        prefix: &str,
        known_keys: &'static [&'static str],
        warnings: &mut Vec<ValidationWarning>,
    ) {
        if let serde_yml::Value::Mapping(map) = value {
            for key in map.keys() {
                let key_str = key.as_str();
                if !known_keys.contains(&key_str) {
                    let field = if prefix.is_empty() {
                        key_str.to_string()
                    } else {
                        format!("{}.{}", prefix, key_str)
                    };
                    warnings.push(ValidationWarning {
                        field,
                        message: format!("Unknown config field: {}", key_str),
                        severity: ValidationSeverity::Warning,
                    });
                }
            }

            // Recurse into nested structures
            for (key, val) in map {
                let key_str = key.as_str();
                let new_prefix = if prefix.is_empty() {
                    key_str.to_string()
                } else {
                    format!("{}.{}", prefix, key_str)
                };

                match key_str {
                    "default" => {
                        Self::check_unknown_fields(
                            val,
                            &new_prefix,
                            Self::default_params_keys(),
                            warnings,
                        );
                    }
                    "model_overrides" => {
                        if let serde_yml::Value::Mapping(overrides) = val {
                            for (override_key, override_val) in overrides {
                                let k = override_key.as_str();
                                let override_prefix = format!("{}.{}", new_prefix, k);
                                Self::check_unknown_fields(
                                    override_val,
                                    &override_prefix,
                                    Self::model_override_keys(),
                                    warnings,
                                );
                            }
                        }
                    }
                    "rpc_workers" => {
                        if let serde_yml::Value::Sequence(items) = val {
                            for item in items {
                                Self::check_unknown_fields(
                                    item,
                                    &new_prefix,
                                    Self::rpc_worker_keys(),
                                    warnings,
                                );
                            }
                        }
                    }
                    _ => {
                        Self::check_unknown_fields(val, &new_prefix, known_keys, warnings);
                    }
                }
            }
        }
    }

    /// Validate config values and return a list of warnings for invalid entries.
    pub fn validate(&self) -> Vec<ValidationWarning> {
        let mut warnings = Vec::new();
        let default = &self.default;

        // Numeric range checks
        if default.context_length < 512 || default.context_length > 1048576 {
            warnings.push(ValidationWarning {
                field: "default.context_length".to_string(),
                message: format!(
                    "context_length {} is outside recommended range 512-1048576",
                    default.context_length
                ),
                severity: ValidationSeverity::Warning,
            });
        }
        if default.threads == 0 {
            warnings.push(ValidationWarning {
                field: "default.threads".to_string(),
                message: "threads must be greater than 0".to_string(),
                severity: ValidationSeverity::Warning,
            });
        }
        if default.temperature < 0.0 || default.temperature > 2.0 {
            warnings.push(ValidationWarning {
                field: "default.temperature".to_string(),
                message: format!(
                    "temperature {} is outside recommended range 0.0-2.0",
                    default.temperature
                ),
                severity: ValidationSeverity::Warning,
            });
        }
        if default.top_k < 0 {
            warnings.push(ValidationWarning {
                field: "default.top_k".to_string(),
                message: "top_k must be >= 0".to_string(),
                severity: ValidationSeverity::Warning,
            });
        }
        if default.top_p < 0.0 || default.top_p > 1.0 {
            warnings.push(ValidationWarning {
                field: "default.top_p".to_string(),
                message: format!(
                    "top_p {} is outside recommended range 0.0-1.0",
                    default.top_p
                ),
                severity: ValidationSeverity::Warning,
            });
        }
        if default.min_p < 0.0 || default.min_p > 1.0 {
            warnings.push(ValidationWarning {
                field: "default.min_p".to_string(),
                message: format!(
                    "min_p {} is outside recommended range 0.0-1.0",
                    default.min_p
                ),
                severity: ValidationSeverity::Warning,
            });
        }
        if default.typical_p < 0.0 || default.typical_p > 1.0 {
            warnings.push(ValidationWarning {
                field: "default.typical_p".to_string(),
                message: format!(
                    "typical_p {} is outside recommended range 0.0-1.0",
                    default.typical_p
                ),
                severity: ValidationSeverity::Warning,
            });
        }
        if default.repeat_penalty < 0.0 || default.repeat_penalty > 3.0 {
            warnings.push(ValidationWarning {
                field: "default.repeat_penalty".to_string(),
                message: format!(
                    "repeat_penalty {} is outside recommended range 0.0-3.0",
                    default.repeat_penalty
                ),
                severity: ValidationSeverity::Warning,
            });
        }
        if default.mirostat_lr < 0.0 || default.mirostat_lr > 1.0 {
            warnings.push(ValidationWarning {
                field: "default.mirostat_lr".to_string(),
                message: format!(
                    "mirostat_lr {} is outside recommended range 0.0-1.0",
                    default.mirostat_lr
                ),
                severity: ValidationSeverity::Warning,
            });
        }
        if default.mirostat_ent < 0.0 || default.mirostat_ent > 10.0 {
            warnings.push(ValidationWarning {
                field: "default.mirostat_ent".to_string(),
                message: format!(
                    "mirostat_ent {} is outside recommended range 0.0-10.0",
                    default.mirostat_ent
                ),
                severity: ValidationSeverity::Warning,
            });
        }
        if default.dry_multiplier < 0.0 {
            warnings.push(ValidationWarning {
                field: "default.dry_multiplier".to_string(),
                message: "dry_multiplier must be >= 0".to_string(),
                severity: ValidationSeverity::Warning,
            });
        }
        if default.dry_base <= 0.0 {
            warnings.push(ValidationWarning {
                field: "default.dry_base".to_string(),
                message: "dry_base must be > 0".to_string(),
                severity: ValidationSeverity::Warning,
            });
        }
        if default.rope_scale <= 0.0 {
            warnings.push(ValidationWarning {
                field: "default.rope_scale".to_string(),
                message: "rope_scale must be > 0".to_string(),
                severity: ValidationSeverity::Warning,
            });
        }
        if default.rope_freq_scale <= 0.0 {
            warnings.push(ValidationWarning {
                field: "default.rope_freq_scale".to_string(),
                message: "rope_freq_scale must be > 0".to_string(),
                severity: ValidationSeverity::Warning,
            });
        }
        if default.port == 0 {
            warnings.push(ValidationWarning {
                field: "default.port".to_string(),
                message: "port must be between 1 and 65535".to_string(),
                severity: ValidationSeverity::Error,
            });
        }
        if default.port < 1024 {
            warnings.push(ValidationWarning {
                field: "default.port".to_string(),
                message: format!("port {} is a privileged port (< 1024)", default.port),
                severity: ValidationSeverity::Warning,
            });
        }
        if default.api_endpoint_port == 0 {
            warnings.push(ValidationWarning {
                field: "default.api_endpoint_port".to_string(),
                message: "api_endpoint_port must be between 1 and 65535".to_string(),
                severity: ValidationSeverity::Error,
            });
        }
        if default.ws_server_port == 0 {
            warnings.push(ValidationWarning {
                field: "default.ws_server_port".to_string(),
                message: "ws_server_port must be between 1 and 65535".to_string(),
                severity: ValidationSeverity::Error,
            });
        }
        if default.timeout < 1 {
            warnings.push(ValidationWarning {
                field: "default.timeout".to_string(),
                message: "timeout must be at least 1 second".to_string(),
                severity: ValidationSeverity::Warning,
            });
        }
        if default.router_max_models == 0 {
            warnings.push(ValidationWarning {
                field: "default.router_max_models".to_string(),
                message: "router_max_models must be >= 1".to_string(),
                severity: ValidationSeverity::Warning,
            });
        }
        if let Some(max_tokens) = default.max_tokens {
            if max_tokens == 0 {
                warnings.push(ValidationWarning {
                    field: "default.max_tokens".to_string(),
                    message: "max_tokens must be > 0".to_string(),
                    severity: ValidationSeverity::Warning,
                });
            } else if max_tokens > 65536 {
                warnings.push(ValidationWarning {
                    field: "default.max_tokens".to_string(),
                    message: format!("max_tokens {} is very large (> 65536)", max_tokens),
                    severity: ValidationSeverity::Warning,
                });
            }
        }
        if default.context_length > 262144 {
            warnings.push(ValidationWarning {
                field: "default.context_length".to_string(),
                message: format!(
                    "context_length {} may cause high memory usage",
                    default.context_length
                ),
                severity: ValidationSeverity::Warning,
            });
        }
        if default.threads_batch > default.batch_size && default.batch_size > 0 {
            warnings.push(ValidationWarning {
                field: "default.threads_batch".to_string(),
                message: "threads_batch should not exceed batch_size".to_string(),
                severity: ValidationSeverity::Warning,
            });
        }

        // Path validation
        if let Some(lora) = &default.lora
            && !lora.exists()
        {
            warnings.push(ValidationWarning {
                field: "default.lora".to_string(),
                message: format!("lora path does not exist: {}", lora.display()),
                severity: ValidationSeverity::Warning,
            });
        }
        if let Some((lora, _)) = &default.lora_scaled
            && !lora.exists()
        {
            warnings.push(ValidationWarning {
                field: "default.lora_scaled".to_string(),
                message: format!("lora path does not exist: {}", lora.display()),
                severity: ValidationSeverity::Warning,
            });
        }
        if self.llama_server.is_absolute() && !self.llama_server.exists() {
            warnings.push(ValidationWarning {
                field: "llama_server".to_string(),
                message: format!(
                    "llama_server binary not found: {}",
                    self.llama_server.display()
                ),
                severity: ValidationSeverity::Warning,
            });
        }

        // Model override validation
        for model_name in self.model_overrides.keys() {
            if let Some(override_settings) = self.model_overrides.get(model_name.as_str()) {
                if let Some(lora) = &override_settings.lora
                    && !lora.exists()
                {
                    warnings.push(ValidationWarning {
                        field: format!("model_overrides.{}.lora", model_name),
                        message: format!("lora path does not exist: {}", lora.display()),
                        severity: ValidationSeverity::Warning,
                    });
                }
                if let Some((lora, _)) = &override_settings.lora_scaled
                    && !lora.exists()
                {
                    warnings.push(ValidationWarning {
                        field: format!("model_overrides.{}.lora_scaled", model_name),
                        message: format!("lora path does not exist: {}", lora.display()),
                        severity: ValidationSeverity::Warning,
                    });
                }
            }
        }

        // Cross-field validation
        if default.port == default.api_endpoint_port {
            warnings.push(ValidationWarning {
                field: "default.port".to_string(),
                message: format!(
                    "port conflict: server port and API endpoint port both set to {}",
                    default.port
                ),
                severity: ValidationSeverity::Warning,
            });
        }
        if default.port == default.ws_server_port {
            warnings.push(ValidationWarning {
                field: "default.port".to_string(),
                message: format!(
                    "port conflict: server port and WS server port both set to {}",
                    default.port
                ),
                severity: ValidationSeverity::Warning,
            });
        }
        if default.api_endpoint_port == default.ws_server_port {
            warnings.push(ValidationWarning {
                field: "default.api_endpoint_port".to_string(),
                message: format!(
                    "port conflict: API endpoint port and WS server port both set to {}",
                    default.api_endpoint_port
                ),
                severity: ValidationSeverity::Warning,
            });
        }
        if matches!(default.server_mode, crate::models::ServerMode::Router)
            && default.router_max_models < 2
        {
            warnings.push(ValidationWarning {
                field: "default.router_max_models".to_string(),
                message: "router_max_models should be >= 2 for Router mode".to_string(),
                severity: ValidationSeverity::Warning,
            });
        }
        if !default.spec_type.is_empty() && default.draft_tokens == 0 {
            warnings.push(ValidationWarning {
                field: "default.spec_type".to_string(),
                message: "spec_type is set but draft_tokens is 0".to_string(),
                severity: ValidationSeverity::Warning,
            });
        }
        if default.server_tls_enabled {
            if let Some(cert) = &default.server_tls_cert
                && !cert.is_empty()
                && !std::path::Path::new(cert).exists()
            {
                warnings.push(ValidationWarning {
                    field: "default.server_tls_cert".to_string(),
                    message: format!("TLS cert path does not exist: {}", cert),
                    severity: ValidationSeverity::Warning,
                });
            }
            if let Some(key) = &default.server_tls_key
                && !key.is_empty()
                && !std::path::Path::new(key).exists()
            {
                warnings.push(ValidationWarning {
                    field: "default.server_tls_key".to_string(),
                    message: format!("TLS key path does not exist: {}", key),
                    severity: ValidationSeverity::Warning,
                });
            }
        }

        warnings
    }

    /// Resolve settings for a specific model and profile.
    pub fn resolve_settings(
        &self,
        model_name: Option<&str>,
        profile_name: Option<&str>,
    ) -> crate::models::ModelSettings {
        let mut settings = crate::models::ModelSettings::from_config(self);

        // Apply model-specific override
        if let Some(name) = model_name
            && let Some(override_settings) = self.model_overrides.get(name)
        {
            override_settings.apply(&mut settings);
        }

        // Apply profile override if specified
        if let Some(p_name) = profile_name {
            if let Some(profile) = self.profiles.get(p_name) {
                profile.settings.apply(&mut settings);
            } else if let Some(profile) = builtin_profiles().iter().find(|p| p.name == p_name) {
                profile.settings.apply(&mut settings);
            }
        }

        // Resolve system_prompt from preset name (after all overrides)
        if let Some(preset) = self
            .system_prompt_presets
            .get(&settings.system_prompt_preset_name)
        {
            settings.system_prompt = preset.content.clone();
        }

        settings
    }

    /// Get a system prompt preset content by name.
    pub fn get_preset_content(&self, name: &str) -> Option<String> {
        self.system_prompt_presets
            .get(name)
            .map(|p| p.content.clone())
    }

    fn normalize_config(mut config: Config) -> Config {
        // normalize models_dirs
        for path in &mut config.models_dirs {
            let path_str = path.to_string_lossy();
            if let Some(stripped) = path_str.strip_prefix("~/") {
                let home = dirs::home_dir().unwrap_or_default();
                *path = home.join(stripped);
            } else if !path.is_absolute() {
                let home = dirs::home_dir().unwrap_or_default();
                *path = home.join(path_str.as_ref());
            }
        }

        // Merge built-in profiles into in-memory cache (do not persist to disk)
        for p in builtin_profiles() {
            if config.profiles.get(&p.name).is_none() {
                config.profiles.insert_builtin(p);
            }
        }

        // Merge built-in system prompt presets into in-memory cache (do not persist to disk)
        for p in builtin_system_prompt_presets() {
            if config.system_prompt_presets.get(&p.name).is_none() {
                config.system_prompt_presets.insert_builtin(p);
            }
        }
        config
    }

    fn load_impl(path: &PathBuf) -> Result<Self, Box<dyn std::error::Error>> {
        let content = std::fs::read_to_string(path)?;

        // Phase 1: Parse as Value to check for unknown fields
        let parsed: serde_yml::Value = serde_yml::from_str(&content)
            .map_err(|e| format!("Failed to parse config file {}: {}", path.display(), e))?;
        let mut warnings = Self::validate_unknown_fields(&parsed);

        // Phase 2: Deserialize normally (serde_yaml ignores unknown fields)
        let config: Config = serde_yml::from_str(&content)
            .map_err(|e| format!("Failed to parse config file {}: {}", path.display(), e))?;
        let config = Self::normalize_config(config);
        let config = config.auto_detect_platform();

        // Phase 3: Value validation
        warnings.extend(config.validate());

        // Log warnings
        if !warnings.is_empty() {
            eprintln!("Config validation warnings:");
            for warning in &warnings {
                eprintln!(
                    "  [{}] {}: {}",
                    match warning.severity {
                        ValidationSeverity::Warning => "WARN",
                        ValidationSeverity::Error => "ERROR",
                    },
                    warning.field,
                    warning.message
                );
            }
        }
        Ok(config)
    }

    pub fn load() -> Result<Self, Box<dyn std::error::Error>> {
        let path = Self::config_path();
        if path.exists() {
            Self::load_impl(&path)
        } else {
            let mut config = Config::default();
            config.save()?;
            Ok(config)
        }
    }

    pub fn load_from(path: PathBuf) -> Result<Self, Box<dyn std::error::Error>> {
        if path.exists() {
            Self::load_impl(&path)
        } else {
            Err(format!("Config file not found: {}", path.display()).into())
        }
    }

    /// Auto-detect the platform if not explicitly set in config.
    fn auto_detect_platform(mut self) -> Self {
        if self.default.platform.is_none() {
            self.default.platform =
                Some(
                    crate::backend::hardware::platform_name(
                        crate::backend::hardware::detect_platform(),
                    )
                    .to_string(),
                );
        }
        self
    }

    pub fn save(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        let path = Self::config_path();
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let content = serde_yml::to_string(self)?;
        std::fs::write(&path, content)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
        }
        // Persist model configs to individual YAML files
        let entries: Vec<(String, ModelOverride)> = self
            .model_overrides
            .keys()
            .iter()
            .filter_map(|k| self.model_overrides.get(k).map(|v| (k.clone(), v.clone())))
            .collect();
        for (name, cfg) in entries {
            self.model_overrides.save(&name, &cfg);
        }
        // Persist user profiles to individual YAML files (skip built-ins)
        for profile in self.profiles.user_profiles() {
            self.profiles.save(&profile);
        }
        // Persist user presets to individual YAML files (skip built-ins)
        for preset in self.system_prompt_presets.user_presets() {
            self.system_prompt_presets.save(&preset);
        }
        Ok(())
    }

    pub fn merged_profiles(&self) -> Vec<Profile> {
        self.profiles.all()
    }

    pub fn merged_presets(&self) -> Vec<SystemPromptPreset> {
        self.system_prompt_presets.all()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogLevel {
    Info,
    Warning,
    Error,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValidationSeverity {
    Warning,
    Error,
}

#[derive(Debug, Clone)]
pub struct ValidationWarning {
    pub field: String,
    pub message: String,
    pub severity: ValidationSeverity,
}

impl LogLevel {
    pub fn label(&self) -> &'static str {
        match self {
            LogLevel::Info => "INFO",
            LogLevel::Warning => "WARNING",
            LogLevel::Error => "ERROR",
        }
    }
}

#[derive(Debug, Clone)]
pub struct LogEntry {
    pub timestamp: String,
    pub level: LogLevel,
    pub message: String,
}

impl LogEntry {
    pub fn new(message: impl Into<String>, level: LogLevel) -> Self {
        let timestamp = Local::now().format("%H:%M:%S").to_string();
        let message = sanitize_log(&message.into());
        Self {
            timestamp,
            level,
            message,
        }
    }
}

/// Sanitize log messages to prevent TUI layout breakages.
/// Strips non-printable characters and control sequences, and limits length.
fn sanitize_log(input: &str) -> String {
    // Limit length to avoid layout/perf issues with massive lines
    let max_len = 2000;
    let chars: Vec<char> = input.chars().collect();
    let truncated = chars.len() > max_len;
    let chars = if truncated {
        chars[..max_len].to_vec()
    } else {
        chars
    };

    let mut output = String::with_capacity(chars.len());
    for c in chars {
        // Strip ALL control characters except newline and tab.
        // Critically: strip \r (carriage return) as it breaks TUI rendering.
        if c.is_control() && c != '\n' && c != '\t' {
            continue;
        }
        output.push(c);
    }

    // Replace tabs with spaces for consistent rendering
    let output = output.replace('\t', "    ");

    // Final trim to remove trailing junk
    let mut result = output.trim_end().to_string();
    if truncated {
        result.push_str("... (truncated)");
    }
    result
}