cc-switch-tui 0.2.1

All-in-One Assistant for Claude Code, Codex, Gemini, OpenCode, OpenClaw & Hermes
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
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
use std::collections::HashSet;

mod claude;
mod codex;
#[cfg(test)]
mod codex_openai_auth_tests;
mod common;
mod common_config;
mod endpoints;
mod gemini;
mod gemini_auth;
mod live;
mod models;
#[cfg(test)]
mod tests;
mod usage;

use indexmap::IndexMap;
use serde::Deserialize;
use serde_json::{json, Value};

use crate::app_config::{AppType, MultiAppConfig};
use crate::codex_config::{get_codex_auth_path, get_codex_config_path};
use crate::config::{
    delete_file, get_claude_settings_path, get_provider_config_path, read_json_file,
    write_json_file,
};
use crate::error::AppError;
use crate::provider::Provider;
use crate::store::AppState;

use gemini_auth::GeminiAuthType;
use live::LiveSnapshot;

pub use common::migrate_legacy_codex_config;
#[cfg(test)]
use common::strip_codex_common_config_from_full_text;

/// 供应商相关业务逻辑
pub struct ProviderService;

fn current_timestamp() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as i64
}

#[cfg(test)]
fn state_from_config(config: MultiAppConfig) -> AppState {
    let db = std::sync::Arc::new(crate::Database::memory().expect("create memory database"));
    db.migrate_from_json(&config)
        .expect("seed memory database from config");
    let mut config = config;
    ProviderService::migrate_common_config_upstream_semantics_if_needed(&db, &mut config)
        .expect("migrate common config semantics for test state");
    AppState {
        db: db.clone(),
        config: std::sync::RwLock::new(config),
        proxy_service: crate::ProxyService::new(db),
    }
}

#[derive(Clone)]
struct PostCommitAction {
    app_type: AppType,
    provider: Provider,
    backup: LiveSnapshot,
    write_live_snapshot: bool,
    sync_mcp: bool,
    sync_codex_catalog: bool,
    stale_codex_catalog_keys: Vec<String>,
    refresh_snapshot: bool,
    apply_hermes_switch_defaults: bool,
    common_config_snippet: Option<String>,
    takeover_active: bool,
    /// When true, user-facing preference keys (approval_mode, disable_response_storage,
    /// etc.) in the current live config are preserved when writing the Codex live config.
    /// Set to false for common-snippet-only operations where old snippet values should
    /// not bleed through.
    preserve_live_preferences: bool,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CodexImportReport {
    pub created: usize,
    pub merged_by_key: usize,
    pub merged_by_name: usize,
    pub needs_auth: usize,
    pub conflicts: usize,
    pub used_default_fallback: bool,
}

impl CodexImportReport {
    pub fn imported_any(&self) -> bool {
        self.created > 0
            || self.merged_by_key > 0
            || self.merged_by_name > 0
            || self.used_default_fallback
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct CodexCurrentProviderMismatch {
    pub(crate) stored_provider_id: String,
    pub(crate) stored_provider_name: String,
    pub(crate) live_provider_id: String,
    pub(crate) live_provider_name: String,
    pub(crate) live_model_provider_key: String,
}

impl ProviderService {
    fn is_codex_official_provider(provider: &Provider) -> bool {
        provider
            .meta
            .as_ref()
            .and_then(|meta| meta.codex_official)
            .unwrap_or(false)
            || provider
                .category
                .as_deref()
                .is_some_and(|value| value.eq_ignore_ascii_case("official"))
    }

    fn codex_config_has_base_url(config_text: &str) -> bool {
        let Ok(table) = toml::from_str::<toml::Table>(config_text.trim()) else {
            return false;
        };

        if table
            .get("base_url")
            .and_then(|value| value.as_str())
            .is_some_and(|value| !value.trim().is_empty())
        {
            return true;
        }

        let Some(provider_key) = table.get("model_provider").and_then(|value| value.as_str())
        else {
            return false;
        };

        table
            .get("model_providers")
            .and_then(|value| value.as_table())
            .and_then(|providers| providers.get(provider_key))
            .and_then(|value| value.as_table())
            .and_then(|provider| provider.get("base_url"))
            .and_then(|value| value.as_str())
            .is_some_and(|value| !value.trim().is_empty())
    }

    pub fn sync_openclaw_to_live(state: &AppState) -> Result<(), AppError> {
        let (providers, snippet) = {
            let guard = state.config.read().map_err(AppError::from)?;
            let Some(manager) = guard.get_manager(&AppType::OpenClaw) else {
                return Ok(());
            };

            (
                manager
                    .providers
                    .values()
                    .filter(|provider| Self::provider_live_config_managed(provider) != Some(false))
                    .cloned()
                    .collect::<Vec<_>>(),
                guard
                    .common_config_snippets
                    .get(&AppType::OpenClaw)
                    .cloned(),
            )
        };

        for provider in &providers {
            Self::write_live_snapshot(
                &AppType::OpenClaw,
                provider,
                snippet.as_deref(),
                true,
                true,
            )?;
        }

        Ok(())
    }

    pub(crate) fn valid_openclaw_live_provider_ids() -> Result<Option<HashSet<String>>, AppError> {
        if !crate::openclaw_config::get_openclaw_config_path().exists() {
            return Ok(None);
        }

        let mut valid_provider_ids = HashSet::new();
        for (provider_id, live_provider) in crate::openclaw_config::get_providers()? {
            if provider_id.trim().is_empty() {
                continue;
            }

            let Ok(config) = Self::parse_openclaw_provider_settings(&live_provider) else {
                continue;
            };

            if Self::validate_openclaw_provider_models(&provider_id, &config).is_err() {
                continue;
            }

            if config.models.iter().any(|model| model.id.trim().is_empty()) {
                continue;
            }

            valid_provider_ids.insert(provider_id);
        }

        Ok(Some(valid_provider_ids))
    }

    fn provider_live_config_managed(provider: &Provider) -> Option<bool> {
        provider
            .meta
            .as_ref()
            .and_then(|meta| meta.live_config_managed)
    }

    fn set_provider_live_config_managed(provider: &mut Provider, managed: bool) {
        provider
            .meta
            .get_or_insert_with(Default::default)
            .live_config_managed = Some(managed);
    }

    fn additive_provider_exists_in_live_config(
        app_type: &AppType,
        provider_id: &str,
        live_config_managed: Option<bool>,
    ) -> Result<bool, AppError> {
        let read_presence = || match app_type {
            AppType::OpenCode => crate::opencode_config::get_providers()
                .map(|providers| providers.contains_key(provider_id)),
            AppType::OpenClaw => Self::valid_openclaw_live_provider_ids()
                .map(|ids| ids.is_some_and(|ids| ids.contains(provider_id))),
            AppType::Hermes => crate::hermes_config::get_providers()
                .map(|providers| providers.contains_key(provider_id)),
            _ => Ok(false),
        };

        if live_config_managed == Some(false) {
            Ok(read_presence().unwrap_or(false))
        } else {
            read_presence()
        }
    }

    fn run_transaction<R, F>(state: &AppState, f: F) -> Result<R, AppError>
    where
        F: FnOnce(&mut MultiAppConfig) -> Result<(R, Option<PostCommitAction>), AppError>,
    {
        let mut guard = state.config.write().map_err(AppError::from)?;
        let original = guard.clone();
        let (result, action) = match f(&mut guard) {
            Ok(value) => value,
            Err(err) => {
                *guard = original;
                return Err(err);
            }
        };
        drop(guard);

        if let Err(save_err) = state.save() {
            if let Err(rollback_err) = Self::restore_config_only(state, original.clone()) {
                return Err(AppError::localized(
                    "config.save.rollback_failed",
                    format!("保存配置失败: {save_err};回滚失败: {rollback_err}"),
                    format!("Failed to save config: {save_err}; rollback failed: {rollback_err}"),
                ));
            }
            return Err(save_err);
        }

        if let Some(action) = action {
            if let Err(err) = Self::apply_post_commit(state, &action) {
                if let Err(rollback_err) =
                    Self::rollback_after_failure(state, original.clone(), action.backup.clone())
                {
                    return Err(AppError::localized(
                        "post_commit.rollback_failed",
                        format!("后置操作失败: {err};回滚失败: {rollback_err}"),
                        format!("Post-commit step failed: {err}; rollback failed: {rollback_err}"),
                    ));
                }
                return Err(err);
            }
        }

        Ok(result)
    }

    fn run_transaction_preserving_current_providers<R, F>(
        state: &AppState,
        preserved_current_apps: &[AppType],
        f: F,
    ) -> Result<R, AppError>
    where
        F: FnOnce(&mut MultiAppConfig) -> Result<(R, Option<PostCommitAction>), AppError>,
    {
        let mut guard = state.config.write().map_err(AppError::from)?;
        let original = guard.clone();
        let (result, action) = match f(&mut guard) {
            Ok(value) => value,
            Err(err) => {
                *guard = original;
                return Err(err);
            }
        };
        drop(guard);

        if let Err(save_err) = state.save_preserving_current_providers(preserved_current_apps) {
            if let Err(rollback_err) = Self::restore_config_only_preserving_current_providers(
                state,
                original.clone(),
                preserved_current_apps,
            ) {
                return Err(AppError::localized(
                    "config.save.rollback_failed",
                    format!("保存配置失败: {save_err};回滚失败: {rollback_err}"),
                    format!("Failed to save config: {save_err}; rollback failed: {rollback_err}"),
                ));
            }
            return Err(save_err);
        }

        if let Some(action) = action {
            if let Err(err) = Self::apply_post_commit(state, &action) {
                if let Err(rollback_err) = Self::rollback_after_failure_preserving_current_providers(
                    state,
                    original.clone(),
                    preserved_current_apps,
                    action.backup.clone(),
                ) {
                    return Err(AppError::localized(
                        "post_commit.rollback_failed",
                        format!("后置操作失败: {err};回滚失败: {rollback_err}"),
                        format!("Post-commit step failed: {err}; rollback failed: {rollback_err}"),
                    ));
                }
                return Err(err);
            }
        }

        Ok(result)
    }

    fn restore_config_only(state: &AppState, snapshot: MultiAppConfig) -> Result<(), AppError> {
        {
            let mut guard = state.config.write().map_err(AppError::from)?;
            *guard = snapshot;
        }
        state.save()
    }

    fn restore_config_only_preserving_current_providers(
        state: &AppState,
        snapshot: MultiAppConfig,
        preserved_current_apps: &[AppType],
    ) -> Result<(), AppError> {
        {
            let mut guard = state.config.write().map_err(AppError::from)?;
            *guard = snapshot;
        }
        state.save_preserving_current_providers(preserved_current_apps)
    }

    fn rollback_after_failure(
        state: &AppState,
        snapshot: MultiAppConfig,
        backup: LiveSnapshot,
    ) -> Result<(), AppError> {
        Self::restore_config_only(state, snapshot)?;
        backup.restore()
    }

    fn rollback_after_failure_preserving_current_providers(
        state: &AppState,
        snapshot: MultiAppConfig,
        preserved_current_apps: &[AppType],
        backup: LiveSnapshot,
    ) -> Result<(), AppError> {
        Self::restore_config_only_preserving_current_providers(
            state,
            snapshot,
            preserved_current_apps,
        )?;
        backup.restore()
    }

    fn apply_post_commit(state: &AppState, action: &PostCommitAction) -> Result<(), AppError> {
        if action.takeover_active {
            futures::executor::block_on(
                state
                    .proxy_service
                    .update_live_backup_from_provider(action.app_type.as_str(), &action.provider),
            )
            .map_err(AppError::Message)?;
        } else if action.write_live_snapshot {
            let apply_common_config = action
                .provider
                .meta
                .as_ref()
                .and_then(|meta| meta.apply_common_config)
                .unwrap_or(true);
            Self::write_live_snapshot(
                &action.app_type,
                &action.provider,
                action.common_config_snippet.as_deref(),
                apply_common_config,
                action.preserve_live_preferences,
            )?;
            if action.apply_hermes_switch_defaults {
                crate::hermes_config::apply_switch_defaults(
                    &action.provider.id,
                    &action.provider.settings_config,
                )
                .map(|_| ())?;
            }
        }
        if action.sync_mcp {
            // Provider/config side effects must not erase Codex live drift;
            // Codex MCP changes are handled by explicit resolve/sync actions.
            use crate::services::mcp::McpService;
            McpService::sync_all_enabled_except(state, &[AppType::Codex])?;
        }
        if !action.takeover_active
            && action.refresh_snapshot
            && crate::sync_policy::should_sync_live(&action.app_type)
        {
            Self::refresh_provider_snapshot(state, &action.app_type, &action.provider.id)?;
        }
        if !action.takeover_active
            && action.sync_codex_catalog
            && crate::sync_policy::should_sync_live(&AppType::Codex)
        {
            Self::sync_codex_provider_catalog_to_live(state, &action.stale_codex_catalog_keys)?;
        }

        // D6: Align upstream live flows - also sync skills (best effort, should not block provider ops).
        if let Err(e) = crate::services::skill::SkillService::sync_all_enabled_best_effort() {
            log::warn!("同步 Skills 失败: {e}");
        }
        Ok(())
    }

    fn refresh_provider_snapshot(
        state: &AppState,
        app_type: &AppType,
        provider_id: &str,
    ) -> Result<(), AppError> {
        match app_type {
            AppType::Claude => {
                let settings_path = get_claude_settings_path();
                if !settings_path.exists() {
                    return Err(AppError::localized(
                        "claude.live.missing",
                        "Claude 设置文件不存在,无法刷新快照",
                        "Claude settings file missing; cannot refresh snapshot",
                    ));
                }
                let mut live_after = read_json_file::<Value>(&settings_path)?;
                let _ = Self::normalize_claude_models_in_value(&mut live_after);

                let (provider, common_snippet) = {
                    let guard = state.config.read().map_err(AppError::from)?;
                    (
                        guard
                            .get_manager(app_type)
                            .and_then(|manager| manager.providers.get(provider_id))
                            .cloned()
                            .ok_or_else(|| {
                                AppError::localized(
                                    "provider.not_found",
                                    format!("供应商不存在: {provider_id}"),
                                    format!("Provider not found: {provider_id}"),
                                )
                            })?,
                        guard.common_config_snippets.claude.clone(),
                    )
                };
                live_after = common_config::strip_common_config_from_live_settings(
                    app_type,
                    &provider,
                    live_after,
                    common_snippet.as_deref(),
                );
                {
                    let mut guard = state.config.write().map_err(AppError::from)?;
                    if let Some(manager) = guard.get_manager_mut(app_type) {
                        if let Some(target) = manager.providers.get_mut(provider_id) {
                            target.settings_config = live_after;
                        }
                    }
                }
                state.save()?;
            }
            AppType::Codex => {
                let auth_path = get_codex_auth_path();
                let cfg_text = crate::codex_config::read_and_validate_codex_config_text()?;
                let common_snippet_extracted =
                    Self::extract_codex_common_config_from_config_toml(&cfg_text)?;
                let cfg_text_for_storage =
                    Self::strip_codex_runtime_local_keys_from_snapshot_config(&cfg_text)?;

                let (provider, common_snippet_for_strip) = {
                    let guard = state.config.read().map_err(AppError::from)?;
                    (
                        guard
                            .get_manager(app_type)
                            .and_then(|manager| manager.providers.get(provider_id))
                            .cloned()
                            .ok_or_else(|| {
                                AppError::localized(
                                    "provider.not_found",
                                    format!("供应商不存在: {provider_id}"),
                                    format!("Provider not found: {provider_id}"),
                                )
                            })?,
                        guard.common_config_snippets.codex.clone(),
                    )
                };

                // Read auth from disk; if absent, fall back to the DB snapshot's auth
                // so that WebDAV-synced credentials are not overwritten with empty data.
                let auth = if auth_path.exists() {
                    Some(read_json_file::<Value>(&auth_path)?)
                } else {
                    provider.settings_config.get("auth").cloned()
                };

                let effective_common_snippet = if common_snippet_for_strip
                    .as_deref()
                    .unwrap_or_default()
                    .trim()
                    .is_empty()
                    && !common_snippet_extracted.trim().is_empty()
                {
                    Some(common_snippet_extracted.clone())
                } else {
                    common_snippet_for_strip.clone()
                };

                let raw_settings = crate::codex_config::codex_settings_snapshot_from_toml(
                    auth,
                    &cfg_text_for_storage,
                )?;
                let mut settings_to_store = Self::normalize_settings_config_for_storage(
                    app_type,
                    &provider,
                    raw_settings,
                    effective_common_snippet.as_deref(),
                )?;
                Self::restore_codex_model_provider_for_storage_best_effort(
                    &provider,
                    &mut settings_to_store,
                );

                {
                    let mut guard = state.config.write().map_err(AppError::from)?;
                    if !common_snippet_extracted.trim().is_empty()
                        && guard
                            .common_config_snippets
                            .codex
                            .as_deref()
                            .unwrap_or_default()
                            .trim()
                            .is_empty()
                    {
                        guard.common_config_snippets.codex = Some(common_snippet_extracted.clone());
                        Self::normalize_existing_provider_snapshots_for_storage_best_effort(
                            &mut guard,
                            app_type,
                            Some(common_snippet_extracted.as_str()),
                        );
                    }
                    if let Some(manager) = guard.get_manager_mut(app_type) {
                        if let Some(target) = manager.providers.get_mut(provider_id) {
                            target.settings_config = settings_to_store.clone();
                        }
                    }
                }
                state.save()?;
            }
            AppType::Gemini => {
                use crate::gemini_config::{
                    env_to_json, get_gemini_env_path, get_gemini_settings_path, read_gemini_env,
                };

                let env_path = get_gemini_env_path();
                if !env_path.exists() {
                    return Err(AppError::localized(
                        "gemini.live.missing",
                        "Gemini .env 文件不存在,无法刷新快照",
                        "Gemini .env file missing; cannot refresh snapshot",
                    ));
                }
                let env_map = read_gemini_env()?;
                let mut live_after = env_to_json(&env_map);

                let settings_path = get_gemini_settings_path();
                let config_value = if settings_path.exists() {
                    read_json_file(&settings_path)?
                } else {
                    json!({})
                };

                if let Some(obj) = live_after.as_object_mut() {
                    obj.insert("config".to_string(), config_value);
                }

                let (provider, common_snippet) = {
                    let guard = state.config.read().map_err(AppError::from)?;
                    (
                        guard
                            .get_manager(app_type)
                            .and_then(|manager| manager.providers.get(provider_id))
                            .cloned()
                            .ok_or_else(|| {
                                AppError::localized(
                                    "provider.not_found",
                                    format!("供应商不存在: {provider_id}"),
                                    format!("Provider not found: {provider_id}"),
                                )
                            })?,
                        guard.common_config_snippets.gemini.clone(),
                    )
                };
                let live_after = Self::normalize_settings_config_for_storage(
                    app_type,
                    &provider,
                    live_after,
                    common_snippet.as_deref(),
                )?;

                {
                    let mut guard = state.config.write().map_err(AppError::from)?;
                    if let Some(manager) = guard.get_manager_mut(app_type) {
                        if let Some(target) = manager.providers.get_mut(provider_id) {
                            target.settings_config = live_after;
                        }
                    }
                }
                state.save()?;
            }
            AppType::OpenCode => {
                let providers = crate::opencode_config::get_providers()?;
                let live_after = providers.get(provider_id).cloned().ok_or_else(|| {
                    AppError::localized(
                        "opencode.live.missing_provider",
                        format!("OpenCode live 配置中缺少供应商: {provider_id}"),
                        format!("OpenCode live config missing provider: {provider_id}"),
                    )
                })?;

                {
                    let mut guard = state.config.write().map_err(AppError::from)?;
                    if let Some(manager) = guard.get_manager_mut(app_type) {
                        if let Some(target) = manager.providers.get_mut(provider_id) {
                            target.settings_config = live_after;
                        }
                    }
                }
                state.save()?;
            }
            AppType::OpenClaw => {
                let providers = crate::openclaw_config::get_providers()?;
                let live_after = providers.get(provider_id).cloned().ok_or_else(|| {
                    AppError::localized(
                        "openclaw.live.missing_provider",
                        format!("OpenClaw live 配置中缺少供应商: {provider_id}"),
                        format!("OpenClaw live config missing provider: {provider_id}"),
                    )
                })?;

                {
                    let mut guard = state.config.write().map_err(AppError::from)?;
                    if let Some(manager) = guard.get_manager_mut(app_type) {
                        if let Some(target) = manager.providers.get_mut(provider_id) {
                            target.settings_config = live_after;
                        }
                    }
                }
                state.save()?;
            }
            AppType::Hermes => {
                let providers = crate::hermes_config::get_providers()?;
                let live_after = providers.get(provider_id).cloned().unwrap_or_else(|| {
                    log::warn!(
                        "Hermes live config missing provider '{provider_id}', using empty config"
                    );
                    serde_json::Value::Object(serde_json::Map::new())
                });

                {
                    let mut guard = state.config.write().map_err(AppError::from)?;
                    if let Some(manager) = guard.get_manager_mut(app_type) {
                        if let Some(target) = manager.providers.get_mut(provider_id) {
                            target.settings_config = live_after;
                        }
                    }
                }
                state.save()?;
            }
        }
        Ok(())
    }

    fn capture_live_snapshot(app_type: &AppType) -> Result<LiveSnapshot, AppError> {
        live::capture_live_snapshot(app_type)
    }

    fn validate_common_config_snippet(
        app_type: &AppType,
        snippet: Option<&str>,
    ) -> Result<(), AppError> {
        common_config::validate_common_config_snippet(app_type, snippet)
    }

    fn should_skip_common_config_migration_error(app_type: &AppType, err: &AppError) -> bool {
        match (app_type, err) {
            (AppType::Claude, AppError::Localized { key, .. }) => {
                key.starts_with("common_config.claude.")
            }
            (AppType::Codex, AppError::Config(message)) => {
                message.starts_with("Common config TOML parse error:")
            }
            (AppType::Gemini, AppError::Localized { key, .. }) => {
                key.starts_with("common_config.gemini.")
            }
            _ => false,
        }
    }

    fn migrate_old_common_config_snippet_best_effort(
        config: &mut MultiAppConfig,
        app_type: &AppType,
        strict_current_provider_id: Option<&str>,
        old_snippet: Option<&str>,
    ) -> Result<(), AppError> {
        let Some(old_snippet) = old_snippet.map(str::trim) else {
            return Ok(());
        };
        if old_snippet.is_empty() {
            return Ok(());
        }

        let result = match app_type {
            AppType::Claude => Self::migrate_claude_common_config_snippet(config, old_snippet),
            AppType::Codex => Self::migrate_codex_common_config_snippet(
                config,
                strict_current_provider_id,
                old_snippet,
            ),
            AppType::Gemini => Self::migrate_gemini_common_config_snippet(
                config,
                strict_current_provider_id,
                old_snippet,
            ),
            AppType::OpenCode | AppType::OpenClaw => Ok(()),
            AppType::Hermes => Ok(()),
        };

        match result {
            Ok(()) => Ok(()),
            Err(err) if Self::should_skip_common_config_migration_error(app_type, &err) => {
                log::warn!(
                    "skip migrating {app_type} provider snapshots from invalid stored common config snippet: {err}"
                );
                Ok(())
            }
            Err(err) => Err(err),
        }
    }

    #[doc(hidden)]
    pub fn migrate_common_config_upstream_semantics_if_needed(
        db: &crate::database::Database,
        config: &mut MultiAppConfig,
    ) -> Result<(), AppError> {
        common_config::migrate_common_config_upstream_semantics_if_needed(db, config)
    }

    fn build_common_config_post_commit_action(
        config: &MultiAppConfig,
        app_type: &AppType,
        current_provider_id: Option<&str>,
        takeover_active: bool,
    ) -> Result<Option<PostCommitAction>, AppError> {
        if app_type.is_additive_mode() {
            return Ok(None);
        }

        let Some(current_provider_id) = current_provider_id else {
            return Ok(None);
        };

        Self::build_post_commit_action_for_current_provider(
            config,
            app_type,
            &current_provider_id,
            takeover_active,
            false,
        )
    }

    fn build_post_commit_action_for_current_provider(
        config: &MultiAppConfig,
        app_type: &AppType,
        current_provider_id: &str,
        takeover_active: bool,
        preserve_live_preferences: bool,
    ) -> Result<Option<PostCommitAction>, AppError> {
        let provider = config
            .get_manager(app_type)
            .and_then(|manager| manager.providers.get(current_provider_id).cloned());

        let Some(provider) = provider else {
            return Ok(None);
        };

        Ok(Some(PostCommitAction {
            app_type: app_type.clone(),
            provider,
            backup: Self::capture_live_snapshot(app_type)?,
            write_live_snapshot: true,
            sync_mcp: false,
            sync_codex_catalog: matches!(app_type, AppType::Codex),
            stale_codex_catalog_keys: Vec::new(),
            refresh_snapshot: false,
            apply_hermes_switch_defaults: false,
            common_config_snippet: config.common_config_snippets.get(app_type).cloned(),
            takeover_active,
            preserve_live_preferences,
        }))
    }

    fn resolve_live_apply_common_config(
        app_type: &AppType,
        provider: &Provider,
        common_config_snippet: Option<&str>,
        requested_apply_common_config: bool,
    ) -> bool {
        if !requested_apply_common_config {
            return false;
        }

        common_config::provider_uses_common_config(app_type, provider, common_config_snippet)
    }

    fn normalize_provider_for_storage(
        app_type: &AppType,
        provider: &mut Provider,
        common_config_snippet: Option<&str>,
    ) -> Result<(), AppError> {
        common_config::normalize_provider_common_config_for_storage(
            app_type,
            provider,
            common_config_snippet,
        )?;

        if matches!(app_type, AppType::Codex) {
            crate::codex_config::normalize_codex_settings_config_for_storage(
                &mut provider.settings_config,
            )?;
        }

        Ok(())
    }

    fn migrate_provider_for_storage(
        app_type: &AppType,
        provider: &mut Provider,
        common_config_snippet: Option<&str>,
    ) -> Result<(), AppError> {
        common_config::migrate_provider_subset_usage_for_storage(
            app_type,
            provider,
            common_config_snippet,
        )?;

        if matches!(app_type, AppType::Codex) {
            crate::codex_config::normalize_codex_settings_config_for_storage(
                &mut provider.settings_config,
            )?;
        }

        Ok(())
    }

    pub(crate) fn normalize_settings_config_for_storage(
        app_type: &AppType,
        provider: &Provider,
        settings_config: Value,
        common_config_snippet: Option<&str>,
    ) -> Result<Value, AppError> {
        let mut snapshot_provider = provider.clone();
        snapshot_provider.settings_config = settings_config;
        Self::normalize_provider_for_storage(
            app_type,
            &mut snapshot_provider,
            common_config_snippet,
        )?;
        Ok(snapshot_provider.settings_config)
    }

    fn restore_codex_model_provider_for_storage_best_effort(
        provider: &Provider,
        settings_config: &mut Value,
    ) {
        if let Err(err) =
            crate::codex_config::restore_codex_settings_config_model_provider_for_backfill(
                settings_config,
                &provider.settings_config,
            )
        {
            log::warn!(
                "Failed to restore Codex provider id while storing snapshot for '{}': {err}",
                provider.id
            );
        }
    }

    pub(crate) fn remove_common_config_from_settings_for_preview(
        app_type: &AppType,
        settings_config: &Value,
        common_config_snippet: &str,
    ) -> Result<Value, AppError> {
        common_config::remove_common_config_from_settings(
            app_type,
            settings_config,
            common_config_snippet,
        )
    }

    fn normalize_existing_provider_snapshots_for_storage(
        config: &mut MultiAppConfig,
        app_type: &AppType,
        common_config_snippet: Option<&str>,
    ) -> Result<(), AppError> {
        let Some(manager) = config.get_manager_mut(app_type) else {
            return Ok(());
        };

        for provider in manager.providers.values_mut() {
            Self::migrate_provider_for_storage(app_type, provider, common_config_snippet)?;
        }

        Ok(())
    }

    fn normalize_existing_provider_snapshots_for_storage_best_effort(
        config: &mut MultiAppConfig,
        app_type: &AppType,
        common_config_snippet: Option<&str>,
    ) {
        let Some(manager) = config.get_manager_mut(app_type) else {
            return;
        };

        for (provider_id, provider) in manager.providers.iter_mut() {
            if let Err(err) =
                Self::migrate_provider_for_storage(app_type, provider, common_config_snippet)
            {
                log::warn!(
                    "skip normalizing {app_type} provider snapshot '{provider_id}' while applying auto-extracted common config: {err}"
                );
            }
        }
    }

    fn normalize_existing_provider_snapshots_for_storage_strict_current_best_effort_others(
        config: &mut MultiAppConfig,
        app_type: &AppType,
        strict_current_provider_id: Option<&str>,
        common_config_snippet: Option<&str>,
    ) -> Result<(), AppError> {
        let Some(current_provider_id) = strict_current_provider_id.and_then(|provider_id| {
            config.get_manager(app_type).and_then(|manager| {
                manager
                    .providers
                    .contains_key(provider_id)
                    .then(|| provider_id.to_string())
            })
        }) else {
            return Self::normalize_existing_provider_snapshots_for_storage(
                config,
                app_type,
                common_config_snippet,
            );
        };

        let Some(manager) = config.get_manager_mut(app_type) else {
            return Ok(());
        };

        if let Some(current_provider) = manager.providers.get_mut(&current_provider_id) {
            Self::migrate_provider_for_storage(app_type, current_provider, common_config_snippet)?;
        }

        for (provider_id, provider) in manager.providers.iter_mut() {
            if provider_id == &current_provider_id {
                continue;
            }

            if let Err(err) =
                Self::migrate_provider_for_storage(app_type, provider, common_config_snippet)
            {
                log::warn!(
                    "skip normalizing {app_type} non-current provider snapshot '{provider_id}' while updating common config snippet: {err}"
                );
            }
        }

        Ok(())
    }

    fn hydrate_missing_provider_snapshots_from_db(
        config: &mut MultiAppConfig,
        app_type: &AppType,
        db_providers: &IndexMap<String, Provider>,
    ) -> Result<(), AppError> {
        let manager = config
            .get_manager_mut(app_type)
            .ok_or_else(|| Self::app_not_found(app_type))?;

        for (provider_id, provider) in db_providers {
            manager
                .providers
                .entry(provider_id.clone())
                .or_insert_with(|| provider.clone());
        }

        Ok(())
    }

    pub fn set_common_config_snippet(
        state: &AppState,
        app_type: AppType,
        snippet: Option<String>,
    ) -> Result<(), AppError> {
        let normalized_snippet = snippet.and_then(|value| {
            let trimmed = value.trim();
            if trimmed.is_empty() {
                None
            } else {
                Some(trimmed.to_string())
            }
        });
        Self::validate_common_config_snippet(&app_type, normalized_snippet.as_deref())?;

        let app_type_clone = app_type.clone();
        let (effective_current_provider, db_providers) = if app_type.is_additive_mode() {
            (None, None)
        } else {
            (
                crate::settings::get_effective_current_provider(&state.db, &app_type)?,
                Some(state.db.get_all_providers(app_type.as_str())?),
            )
        };
        let takeover_active = if app_type.is_additive_mode() {
            false
        } else {
            let is_running = state
                .proxy_service
                .is_running_blocking()
                .map_err(AppError::Message)?;
            if !is_running {
                false
            } else {
                state
                    .proxy_service
                    .is_app_takeover_active_blocking(&app_type)
                    .map_err(AppError::Message)?
            }
        };

        Self::run_transaction_preserving_current_providers(
            state,
            std::slice::from_ref(&app_type),
            move |config| {
                config.ensure_app(&app_type_clone);

                if let Some(db_providers) = db_providers.as_ref() {
                    Self::hydrate_missing_provider_snapshots_from_db(
                        config,
                        &app_type_clone,
                        db_providers,
                    )?;
                }

                let old_snippet = config
                    .common_config_snippets
                    .get(&app_type_clone)
                    .cloned()
                    .filter(|value| !value.trim().is_empty());

                Self::migrate_old_common_config_snippet_best_effort(
                    config,
                    &app_type_clone,
                    effective_current_provider.as_deref(),
                    old_snippet.as_deref(),
                )?;

                config
                    .common_config_snippets
                    .set(&app_type_clone, normalized_snippet.clone());

                if matches!(
                    app_type_clone,
                    AppType::Claude | AppType::Codex | AppType::Gemini
                ) {
                    Self::normalize_existing_provider_snapshots_for_storage_strict_current_best_effort_others(
                    config,
                    &app_type_clone,
                    effective_current_provider.as_deref(),
                    normalized_snippet.as_deref(),
                )?;
                }

                let action = Self::build_common_config_post_commit_action(
                    config,
                    &app_type_clone,
                    effective_current_provider.as_deref(),
                    takeover_active,
                )?;
                Ok(((), action))
            },
        )
    }

    pub fn clear_common_config_snippet(
        state: &AppState,
        app_type: AppType,
    ) -> Result<(), AppError> {
        Self::set_common_config_snippet(state, app_type, None)
    }

    /// 列出指定应用下的所有供应商
    pub fn list(
        state: &AppState,
        app_type: AppType,
    ) -> Result<IndexMap<String, Provider>, AppError> {
        let config = state.config.read().map_err(AppError::from)?;
        let manager = config
            .get_manager(&app_type)
            .ok_or_else(|| Self::app_not_found(&app_type))?;
        Ok(manager.get_all_providers().clone())
    }

    pub(crate) fn sync_openclaw_providers_from_live(state: &AppState) -> Result<(), AppError> {
        live::sync_openclaw_providers_from_live(state)?;
        Ok(())
    }

    /// 获取当前供应商 ID
    pub fn current(state: &AppState, app_type: AppType) -> Result<String, AppError> {
        if app_type == AppType::Hermes {
            return Ok(crate::hermes_config::get_model_config()?
                .and_then(|model| model.provider)
                .map(|provider| provider.trim().to_string())
                .filter(|provider| !provider.is_empty())
                .unwrap_or_default());
        }
        if app_type.is_additive_mode() {
            return Ok(String::new());
        }
        crate::settings::get_effective_current_provider(&state.db, &app_type)
            .map(|opt| opt.unwrap_or_default())
    }

    /// 新增供应商
    pub fn add(state: &AppState, app_type: AppType, provider: Provider) -> Result<bool, AppError> {
        let mut provider = provider;
        // 归一化 Claude 模型键
        Self::normalize_provider_if_claude(&app_type, &mut provider);
        Self::validate_provider_settings(&app_type, &provider)?;

        let app_type_clone = app_type.clone();
        let provider_clone = provider.clone();
        let stored_current_provider = if app_type.is_additive_mode() {
            None
        } else {
            state.db.get_current_provider(app_type.as_str())?
        };

        Self::run_transaction(state, move |config| {
            let common_config_snippet = config.common_config_snippets.get(&app_type_clone).cloned();
            let mut provider_to_store = provider_clone.clone();
            Self::normalize_provider_for_storage(
                &app_type_clone,
                &mut provider_to_store,
                common_config_snippet.as_deref(),
            )?;

            if matches!(app_type_clone, AppType::OpenClaw)
                && provider_to_store.created_at.is_none()
                && live::is_auto_mirrored_openclaw_snapshot(&provider_to_store)
            {
                provider_to_store.created_at = Some(current_timestamp());
            }
            if app_type_clone.is_additive_mode() {
                Self::set_provider_live_config_managed(&mut provider_to_store, true);
            }

            config.ensure_app(&app_type_clone);
            let manager = config
                .get_manager_mut(&app_type_clone)
                .ok_or_else(|| Self::app_not_found(&app_type_clone))?;

            if !app_type_clone.is_additive_mode() {
                manager.current = stored_current_provider.clone().unwrap_or_default();
            }

            let was_empty = manager.providers.is_empty();
            manager
                .providers
                .insert(provider_to_store.id.clone(), provider_to_store.clone());

            if !app_type_clone.is_additive_mode()
                && stored_current_provider.is_none()
                && (was_empty || manager.current.is_empty())
            {
                manager.current = provider_to_store.id.clone();
            }

            let is_current =
                app_type_clone.is_additive_mode() || manager.current == provider_to_store.id;
            let action = if is_current {
                let backup = Self::capture_live_snapshot(&app_type_clone)?;
                Some(PostCommitAction {
                    app_type: app_type_clone.clone(),
                    provider: provider_to_store.clone(),
                    backup,
                    write_live_snapshot: true,
                    // Codex write uses merge which preserves [mcp_servers] as-is,
                    // so no MCP re-sync is needed (would lose comment-only lines).
                    sync_mcp: false,
                    sync_codex_catalog: matches!(&app_type_clone, AppType::Codex),
                    stale_codex_catalog_keys: Vec::new(),
                    refresh_snapshot: false,
                    apply_hermes_switch_defaults: false,
                    common_config_snippet,
                    takeover_active: false,
                    preserve_live_preferences: true,
                })
            } else if matches!(&app_type_clone, AppType::Codex) {
                Some(PostCommitAction {
                    app_type: app_type_clone.clone(),
                    provider: provider_to_store.clone(),
                    backup: Self::capture_live_snapshot(&app_type_clone)?,
                    write_live_snapshot: false,
                    sync_mcp: false,
                    sync_codex_catalog: true,
                    stale_codex_catalog_keys: Vec::new(),
                    refresh_snapshot: false,
                    apply_hermes_switch_defaults: false,
                    common_config_snippet,
                    takeover_active: false,
                    preserve_live_preferences: true,
                })
            } else {
                None
            };

            Ok((true, action))
        })
    }

    /// 更新供应商
    pub fn update(
        state: &AppState,
        app_type: AppType,
        provider: Provider,
    ) -> Result<bool, AppError> {
        let mut provider = provider;
        // 归一化 Claude 模型键
        Self::normalize_provider_if_claude(&app_type, &mut provider);
        Self::validate_provider_settings(&app_type, &provider)?;
        let provider_id = provider.id.clone();
        let app_type_clone = app_type.clone();
        let provider_clone = provider.clone();
        let (effective_current_provider, stored_current_provider) = if app_type.is_additive_mode() {
            (None, None)
        } else {
            (
                crate::settings::get_effective_current_provider(&state.db, &app_type)?,
                state.db.get_current_provider(app_type.as_str())?,
            )
        };

        Self::run_transaction(state, move |config| {
            let common_config_snippet = config.common_config_snippets.get(&app_type_clone).cloned();
            let manager = config
                .get_manager_mut(&app_type_clone)
                .ok_or_else(|| Self::app_not_found(&app_type_clone))?;

            if !manager.providers.contains_key(&provider_id) {
                return Err(AppError::localized(
                    "provider.not_found",
                    format!("供应商不存在: {provider_id}"),
                    format!("Provider not found: {provider_id}"),
                ));
            }

            if !app_type_clone.is_additive_mode() {
                manager.current = stored_current_provider.clone().unwrap_or_default();
            }

            let existing_live_config_managed = manager
                .providers
                .get(&provider_id)
                .and_then(Self::provider_live_config_managed);
            let previous_codex_catalog_key = manager
                .providers
                .get(&provider_id)
                .and_then(Self::provider_codex_model_provider_key);
            let mut merged = if let Some(existing) = manager.providers.get(&provider_id) {
                let mut updated = provider_clone.clone();
                match (existing.meta.as_ref(), updated.meta.take()) {
                    // 前端未提供 meta,表示不修改,沿用旧值
                    (Some(old_meta), None) => {
                        updated.meta = Some(old_meta.clone());
                    }
                    (None, None) => {
                        updated.meta = None;
                    }
                    // 前端提供的 meta 视为权威,直接覆盖(其中 custom_endpoints 允许是空,表示删除所有自定义端点)
                    (_old, Some(new_meta)) => {
                        updated.meta = Some(new_meta);
                    }
                }
                if matches!(app_type_clone, AppType::OpenClaw)
                    && updated.created_at.is_none()
                    && live::is_auto_mirrored_openclaw_snapshot(&updated)
                {
                    updated.created_at = Some(current_timestamp());
                }
                updated
            } else {
                provider_clone.clone()
            };

            Self::normalize_provider_for_storage(
                &app_type_clone,
                &mut merged,
                common_config_snippet.as_deref(),
            )?;

            let should_write_live = if app_type_clone.is_additive_mode() {
                if matches!(app_type_clone, AppType::Hermes) {
                    // Hermes does not support "remove from live config" — every
                    // provider is always backed by the YAML file.  Always write
                    // so that edits (e.g. API key changes) are persisted to
                    // config.yaml, even when live_config_managed metadata is
                    // stale or absent.
                    Self::set_provider_live_config_managed(&mut merged, true);
                    true
                } else {
                    let live_config_managed = Self::additive_provider_exists_in_live_config(
                        &app_type_clone,
                        &provider_id,
                        Self::provider_live_config_managed(&merged)
                            .or(existing_live_config_managed),
                    )?;
                    Self::set_provider_live_config_managed(&mut merged, live_config_managed);
                    live_config_managed
                }
            } else {
                effective_current_provider.as_deref() == Some(provider_id.as_str())
            };

            manager
                .providers
                .insert(provider_id.clone(), merged.clone());

            let action = if should_write_live {
                let backup = Self::capture_live_snapshot(&app_type_clone)?;
                Some(PostCommitAction {
                    app_type: app_type_clone.clone(),
                    provider: merged,
                    backup,
                    write_live_snapshot: true,
                    // Codex write uses merge which preserves [mcp_servers] as-is,
                    // so no MCP re-sync is needed (would lose comment-only lines).
                    sync_mcp: false,
                    sync_codex_catalog: matches!(&app_type_clone, AppType::Codex),
                    stale_codex_catalog_keys: Vec::new(),
                    refresh_snapshot: false,
                    apply_hermes_switch_defaults: false,
                    common_config_snippet,
                    takeover_active: false,
                    preserve_live_preferences: true,
                })
            } else if matches!(&app_type_clone, AppType::Codex) {
                let backup = Self::capture_live_snapshot(&app_type_clone)?;
                let current_codex_catalog_key = Self::provider_codex_model_provider_key(&merged);
                let stale_codex_catalog_keys = previous_codex_catalog_key
                    .filter(|old_key| {
                        current_codex_catalog_key.as_deref() != Some(old_key.as_str())
                    })
                    .into_iter()
                    .collect();
                Some(PostCommitAction {
                    app_type: app_type_clone.clone(),
                    provider: merged,
                    backup,
                    write_live_snapshot: false,
                    sync_mcp: false,
                    sync_codex_catalog: true,
                    stale_codex_catalog_keys,
                    refresh_snapshot: false,
                    apply_hermes_switch_defaults: false,
                    common_config_snippet,
                    takeover_active: false,
                    preserve_live_preferences: true,
                })
            } else {
                None
            };

            Ok((true, action))
        })
    }

    /// 导入当前 live 配置为默认供应商。
    ///
    /// 返回 `Ok(true)` 表示实际导入,`Ok(false)` 表示该 app 已有非官方 seed provider 而跳过。
    pub fn import_default_config(state: &AppState, app_type: AppType) -> Result<bool, AppError> {
        if app_type.is_additive_mode() {
            return Ok(false);
        }

        if state.db.has_non_official_seed_provider(app_type.as_str())? {
            return Ok(false);
        }

        let settings_config = match app_type {
            AppType::Codex => {
                let auth_path = get_codex_auth_path();
                if !auth_path.exists() {
                    return Err(AppError::localized(
                        "codex.live.missing",
                        "Codex 配置文件不存在",
                        "Codex configuration file is missing",
                    ));
                }
                let auth: Value = read_json_file(&auth_path)?;
                let config_str = crate::codex_config::read_and_validate_codex_config_text()?;
                crate::codex_config::codex_settings_snapshot_from_toml(Some(auth), &config_str)?
            }
            AppType::Claude => {
                let settings_path = get_claude_settings_path();
                if !settings_path.exists() {
                    return Err(AppError::localized(
                        "claude.live.missing",
                        "Claude Code 配置文件不存在",
                        "Claude settings file is missing",
                    ));
                }
                let mut v = read_json_file::<Value>(&settings_path)?;
                let _ = Self::normalize_claude_models_in_value(&mut v);
                v
            }
            AppType::Gemini => {
                use crate::gemini_config::{
                    env_to_json, get_gemini_env_path, get_gemini_settings_path, read_gemini_env,
                };

                // 读取 .env 文件(环境变量)
                let env_path = get_gemini_env_path();
                if !env_path.exists() {
                    return Err(AppError::localized(
                        "gemini.live.missing",
                        "Gemini 配置文件不存在",
                        "Gemini configuration file is missing",
                    ));
                }

                let env_map = read_gemini_env()?;
                let env_json = env_to_json(&env_map);
                let env_obj = env_json.get("env").cloned().unwrap_or_else(|| json!({}));

                // 读取 settings.json 文件(MCP 配置等)
                let settings_path = get_gemini_settings_path();
                let config_obj = if settings_path.exists() {
                    read_json_file(&settings_path)?
                } else {
                    json!({})
                };

                // 返回完整结构:{ "env": {...}, "config": {...} }
                json!({
                    "env": env_obj,
                    "config": config_obj
                })
            }
            AppType::OpenCode => unreachable!("additive mode apps are handled earlier"),
            AppType::OpenClaw => unreachable!("additive mode apps are handled earlier"),
            AppType::Hermes => unreachable!("additive mode apps are handled earlier"),
        };

        let mut provider = Provider::with_id(
            "default".to_string(),
            "default".to_string(),
            settings_config,
            None,
        );
        provider.category = Some("custom".to_string());
        let common_config_snippet = {
            let guard = state.config.read().map_err(AppError::from)?;
            guard.common_config_snippets.get(&app_type).cloned()
        };
        Self::normalize_provider_for_storage(
            &app_type,
            &mut provider,
            common_config_snippet.as_deref(),
        )?;

        state.db.save_provider(app_type.as_str(), &provider)?;
        state
            .db
            .set_current_provider(app_type.as_str(), &provider.id)?;
        {
            let mut guard = state.config.write().map_err(AppError::from)?;
            guard.ensure_app(&app_type);
            let manager = guard
                .get_manager_mut(&app_type)
                .ok_or_else(|| AppError::Config("manager missing after ensure_app".into()))?;
            manager.current = provider.id.clone();
            manager.providers.insert(provider.id.clone(), provider);
        }
        Ok(true)
    }

    /// 读取当前 live 配置
    pub fn read_live_settings(app_type: AppType) -> Result<Value, AppError> {
        match app_type {
            AppType::Codex => {
                let auth_path = get_codex_auth_path();
                let config_path = get_codex_config_path();
                if !config_path.exists() {
                    return Err(AppError::localized(
                        "codex.live.missing",
                        "Codex 配置文件不存在",
                        "Codex configuration is missing",
                    ));
                }

                let mut live_settings = serde_json::Map::new();
                if auth_path.exists() {
                    live_settings.insert("auth".to_string(), read_json_file(&auth_path)?);
                }
                if config_path.exists() {
                    let cfg_text = crate::codex_config::read_and_validate_codex_config_text()?;
                    live_settings.insert("config".to_string(), Value::String(cfg_text));
                }

                Ok(Value::Object(live_settings))
            }
            AppType::Claude => {
                let path = get_claude_settings_path();
                if !path.exists() {
                    return Err(AppError::localized(
                        "claude.live.missing",
                        "Claude Code 配置文件不存在",
                        "Claude settings file is missing",
                    ));
                }
                read_json_file(&path)
            }
            AppType::Gemini => {
                use crate::gemini_config::{
                    env_to_json, get_gemini_env_path, get_gemini_settings_path, read_gemini_env,
                };

                // 读取 .env 文件(环境变量)
                let env_path = get_gemini_env_path();
                if !env_path.exists() {
                    return Err(AppError::localized(
                        "gemini.env.missing",
                        "Gemini .env 文件不存在",
                        "Gemini .env file not found",
                    ));
                }

                let env_map = read_gemini_env()?;
                let env_json = env_to_json(&env_map);
                let env_obj = env_json.get("env").cloned().unwrap_or_else(|| json!({}));

                // 读取 settings.json 文件(MCP 配置等)
                let settings_path = get_gemini_settings_path();
                let config_obj = if settings_path.exists() {
                    read_json_file(&settings_path)?
                } else {
                    json!({})
                };

                // 返回完整结构:{ "env": {...}, "config": {...} }
                Ok(json!({
                    "env": env_obj,
                    "config": config_obj
                }))
            }
            AppType::OpenCode => {
                let config_path = crate::opencode_config::get_opencode_config_path();
                if !config_path.exists() {
                    return Err(AppError::localized(
                        "opencode.config.missing",
                        "OpenCode 配置文件不存在",
                        "OpenCode configuration file not found",
                    ));
                }
                crate::opencode_config::read_opencode_config()
            }
            AppType::OpenClaw => {
                let config_path = crate::openclaw_config::get_openclaw_config_path();
                if !config_path.exists() {
                    return Err(AppError::localized(
                        "openclaw.config.missing",
                        "OpenClaw 配置文件不存在",
                        "OpenClaw configuration file not found",
                    ));
                }
                crate::openclaw_config::read_openclaw_config()
            }
            AppType::Hermes => {
                let yaml = crate::hermes_config::read_hermes_config()?;
                crate::hermes_config::yaml_to_json(&yaml)
            }
        }
    }

    /// 更新供应商排序
    pub fn update_sort_order(
        state: &AppState,
        app_type: AppType,
        updates: Vec<ProviderSortUpdate>,
    ) -> Result<bool, AppError> {
        {
            let mut cfg = state.config.write().map_err(AppError::from)?;
            let manager = cfg
                .get_manager_mut(&app_type)
                .ok_or_else(|| Self::app_not_found(&app_type))?;

            for update in updates {
                if let Some(provider) = manager.providers.get_mut(&update.id) {
                    provider.sort_index = Some(update.sort_index);
                }
            }
        }

        state.save()?;
        Ok(true)
    }

    pub fn remove_from_live_config(
        state: &AppState,
        app_type: AppType,
        provider_id: &str,
    ) -> Result<(), AppError> {
        if !app_type.is_additive_mode() {
            return Err(AppError::localized(
                "provider.remove_from_live_config.unsupported",
                "只有累加模式应用支持从 live 配置中移除供应商",
                "Only additive-mode apps support removing a provider from live config",
            ));
        }

        let original = {
            let config = state.config.read().map_err(AppError::from)?;
            let manager = config
                .get_manager(&app_type)
                .ok_or_else(|| Self::app_not_found(&app_type))?;
            if !manager.providers.contains_key(provider_id) {
                return Err(AppError::localized(
                    "provider.not_found",
                    format!("供应商不存在: {provider_id}"),
                    format!("Provider not found: {provider_id}"),
                ));
            }
            config.clone()
        };

        let backup = Self::capture_live_snapshot(&app_type)?;
        match &app_type {
            AppType::OpenCode => {
                if crate::opencode_config::get_opencode_dir().exists() {
                    crate::opencode_config::remove_provider(provider_id)?;
                }
            }
            AppType::OpenClaw => {
                if crate::openclaw_config::get_openclaw_dir().exists() {
                    crate::openclaw_config::remove_provider(provider_id)?;
                }
            }
            _ => unreachable!("non-additive apps should not enter remove-from-live branch"),
        }

        {
            let mut config = state.config.write().map_err(AppError::from)?;
            let manager = config
                .get_manager_mut(&app_type)
                .ok_or_else(|| Self::app_not_found(&app_type))?;
            let provider = manager.providers.get_mut(provider_id).ok_or_else(|| {
                AppError::localized(
                    "provider.not_found",
                    format!("供应商不存在: {provider_id}"),
                    format!("Provider not found: {provider_id}"),
                )
            })?;
            Self::set_provider_live_config_managed(provider, false);
        }

        if let Err(save_err) = state.save() {
            let config_restore = Self::restore_config_only(state, original);
            let live_restore = backup.restore();
            if let Err(rollback_err) = config_restore {
                return Err(AppError::localized(
                    "config.save.rollback_failed",
                    format!("保存配置失败: {save_err};回滚失败: {rollback_err}"),
                    format!("Failed to save config: {save_err}; rollback failed: {rollback_err}"),
                ));
            }
            if let Err(rollback_err) = live_restore {
                return Err(AppError::localized(
                    "post_commit.rollback_failed",
                    format!("保存配置失败: {save_err};live 回滚失败: {rollback_err}"),
                    format!(
                        "Failed to save config: {save_err}; live rollback failed: {rollback_err}"
                    ),
                ));
            }
            return Err(save_err);
        }

        Ok(())
    }

    /// 将所有应用的当前供应商配置同步到 live 文件。
    ///
    /// 用于 WebDAV 下载、备份恢复等场景:数据库已更新,但 live 配置文件
    /// (`~/.codex/config.toml`、Claude `settings.json` 等)尚未同步。
    /// 对齐上游 `sync_current_to_live` 行为。
    pub fn sync_current_to_live(state: &AppState) -> Result<(), AppError> {
        use crate::services::mcp::McpService;

        // 在读锁下收集所有需要的数据,避免持锁写文件
        let snapshots: Vec<(AppType, Provider, Option<String>)> = {
            let guard = state.config.read().map_err(AppError::from)?;
            let mut result = Vec::new();
            for app_type in AppType::all() {
                if app_type.is_additive_mode() {
                    if let Some(manager) = guard.get_manager(&app_type) {
                        let snippet = guard.common_config_snippets.get(&app_type).cloned();
                        for provider in manager.providers.values() {
                            if Self::provider_live_config_managed(provider) == Some(false) {
                                continue;
                            }
                            result.push((app_type.clone(), provider.clone(), snippet.clone()));
                        }
                    }
                    continue;
                }

                let current_id =
                    match crate::settings::get_effective_current_provider(&state.db, &app_type)? {
                        Some(id) => id,
                        None => continue,
                    };
                let providers = state.db.get_all_providers(app_type.as_str())?;
                match providers.get(&current_id) {
                    Some(provider) => {
                        let snippet = state.db.get_config_snippet(app_type.as_str())?;
                        result.push((app_type.clone(), provider.clone(), snippet));
                    }
                    None => {
                        log::warn!(
                            "sync_current_to_live: {app_type} 当前供应商 {} 不存在于数据库,跳过",
                            current_id
                        );
                    }
                }
            }
            result
        };

        let openclaw_live_provider_ids = match Self::valid_openclaw_live_provider_ids() {
            Ok(provider_ids) => provider_ids,
            Err(err) => {
                log::warn!(
                    "sync_current_to_live: 读取 OpenClaw live providers 失败,跳过 OpenClaw 同步: {err}"
                );
                None
            }
        };

        for (app_type, provider, snippet) in &snapshots {
            if matches!(app_type, AppType::OpenClaw)
                && !openclaw_live_provider_ids
                    .as_ref()
                    .is_some_and(|provider_ids| provider_ids.contains(&provider.id))
            {
                continue;
            }

            if let Err(e) =
                Self::write_live_snapshot(app_type, provider, snippet.as_deref(), true, true)
            {
                log::warn!("sync_current_to_live: 写入 {app_type} live 配置失败: {e}");
            }
        }

        if snapshots
            .iter()
            .any(|(app_type, _, _)| matches!(app_type, AppType::Codex))
        {
            if let Err(e) = Self::sync_codex_provider_catalog_to_live(state, &[]) {
                log::warn!("sync_current_to_live: Codex provider catalog 同步失败: {e}");
            }
        }

        if let Err(e) =
            crate::services::prompt::PromptService::sync_all_active_to_live_best_effort(state)
        {
            log::warn!("sync_current_to_live: Prompt 同步失败: {e}");
        }

        if let Err(e) = McpService::sync_all_enabled_except(state, &[AppType::Codex]) {
            log::warn!("sync_current_to_live: 非 Codex MCP 同步失败: {e}");
        }

        if let Err(e) = crate::services::skill::SkillService::sync_all_enabled_best_effort() {
            log::warn!("sync_current_to_live: Skills 同步失败: {e}");
        }

        Ok(())
    }

    /// 切换指定应用的供应商
    pub fn switch(state: &AppState, app_type: AppType, provider_id: &str) -> Result<(), AppError> {
        if !app_type.is_additive_mode() {
            let providers = state.db.get_all_providers(app_type.as_str())?;
            providers.get(provider_id).ok_or_else(|| {
                AppError::localized(
                    "provider.not_found",
                    format!("供应商不存在: {provider_id}"),
                    format!("Provider not found: {provider_id}"),
                )
            })?;

            let is_app_taken_over =
                futures::executor::block_on(state.db.get_live_backup(app_type.as_str()))
                    .ok()
                    .flatten()
                    .is_some();
            let is_proxy_running = state
                .proxy_service
                .is_running_blocking()
                .map_err(AppError::Message)?;
            let live_taken_over = state
                .proxy_service
                .detect_takeover_in_live_config_for_app(&app_type);
            let should_hot_switch = (is_app_taken_over || live_taken_over) && is_proxy_running;

            if should_hot_switch {
                futures::executor::block_on(
                    state
                        .proxy_service
                        .hot_switch_provider(app_type.as_str(), provider_id),
                )
                .map_err(|e| AppError::Message(format!("热切换失败: {e}")))?;

                let mut guard = state.config.write().map_err(AppError::from)?;
                if let Some(manager) = guard.get_manager_mut(&app_type) {
                    manager.current = provider_id.to_string();
                }
                return Ok(());
            }
        }

        let app_type_clone = app_type.clone();
        let provider_id_owned = provider_id.to_string();
        let effective_current_provider = if app_type.is_additive_mode() {
            None
        } else if matches!(app_type, AppType::Codex) {
            Self::codex_live_current_provider_id(state)?.or(
                crate::settings::get_effective_current_provider(&state.db, &app_type)?,
            )
        } else {
            crate::settings::get_effective_current_provider(&state.db, &app_type)?
        };

        Self::run_transaction(state, move |config| {
            if app_type_clone.is_additive_mode() {
                let provider = {
                    let provider = config
                        .get_manager_mut(&app_type_clone)
                        .ok_or_else(|| Self::app_not_found(&app_type_clone))?
                        .providers
                        .get_mut(&provider_id_owned)
                        .ok_or_else(|| {
                            AppError::localized(
                                "provider.not_found",
                                format!("供应商不存在: {provider_id_owned}"),
                                format!("Provider not found: {provider_id_owned}"),
                            )
                        })?;
                    Self::set_provider_live_config_managed(provider, true);
                    provider.clone()
                };

                let action = PostCommitAction {
                    app_type: app_type_clone.clone(),
                    provider,
                    backup: Self::capture_live_snapshot(&app_type_clone)?,
                    write_live_snapshot: true,
                    sync_mcp: matches!(app_type_clone, AppType::OpenCode),
                    sync_codex_catalog: false,
                    stale_codex_catalog_keys: Vec::new(),
                    refresh_snapshot: false,
                    apply_hermes_switch_defaults: matches!(app_type_clone, AppType::Hermes),
                    common_config_snippet: config
                        .common_config_snippets
                        .get(&app_type_clone)
                        .cloned(),
                    takeover_active: false,
                    preserve_live_preferences: true,
                };

                return Ok(((), Some(action)));
            }

            let backup = Self::capture_live_snapshot(&app_type_clone)?;
            let provider = match app_type_clone {
                AppType::Codex => Self::prepare_switch_codex(
                    config,
                    &provider_id_owned,
                    effective_current_provider.as_deref(),
                )?,
                AppType::Claude => Self::prepare_switch_claude(
                    config,
                    &provider_id_owned,
                    effective_current_provider.as_deref(),
                )?,
                AppType::Gemini => Self::prepare_switch_gemini(
                    config,
                    &provider_id_owned,
                    effective_current_provider.as_deref(),
                )?,
                AppType::OpenCode => unreachable!("additive mode handled above"),
                AppType::OpenClaw => unreachable!("additive mode handled above"),
                AppType::Hermes => unreachable!("additive mode handled above"),
            };

            let action = PostCommitAction {
                app_type: app_type_clone.clone(),
                provider,
                backup,
                write_live_snapshot: true,
                // Codex writes provider config through a TOML merge that preserves
                // [mcp_servers]. A global MCP resync here would overwrite live
                // edits with cc-switch's stored MCP snapshot.
                sync_mcp: !matches!(app_type_clone, AppType::Codex),
                sync_codex_catalog: matches!(app_type_clone, AppType::Codex),
                stale_codex_catalog_keys: Vec::new(),
                refresh_snapshot: true,
                apply_hermes_switch_defaults: false,
                common_config_snippet: config.common_config_snippets.get(&app_type_clone).cloned(),
                takeover_active: false,
                preserve_live_preferences: true,
            };

            Ok(((), Some(action)))
        })?;

        if !app_type.is_additive_mode() {
            crate::settings::set_current_provider(&app_type, Some(provider_id))?;
        }

        Ok(())
    }

    fn write_live_snapshot(
        app_type: &AppType,
        provider: &Provider,
        common_config_snippet: Option<&str>,
        apply_common_config: bool,
        preserve_live_preferences: bool,
    ) -> Result<(), AppError> {
        let apply_common_config = Self::resolve_live_apply_common_config(
            app_type,
            provider,
            common_config_snippet,
            apply_common_config,
        );

        match app_type {
            AppType::Codex => Self::write_codex_live(
                provider,
                common_config_snippet,
                apply_common_config,
                preserve_live_preferences,
            ),
            AppType::Claude => {
                Self::write_claude_live(provider, common_config_snippet, apply_common_config)
            }
            AppType::Gemini => Self::write_gemini_live(
                provider,
                if apply_common_config {
                    common_config_snippet
                } else {
                    None
                },
            ),
            AppType::OpenCode => {
                let config_to_write = if let Some(obj) = provider.settings_config.as_object() {
                    if obj.contains_key("$schema") || obj.contains_key("provider") {
                        obj.get("provider")
                            .and_then(|providers| providers.get(&provider.id))
                            .cloned()
                            .unwrap_or_else(|| provider.settings_config.clone())
                    } else {
                        provider.settings_config.clone()
                    }
                } else {
                    provider.settings_config.clone()
                };

                match serde_json::from_value::<crate::provider::OpenCodeProviderConfig>(
                    config_to_write.clone(),
                ) {
                    Ok(config) => crate::opencode_config::set_typed_provider(&provider.id, &config),
                    Err(_) => {
                        // 尝试从原始 JSON 中提取 apiKey 同步到 auth.json
                        let api_key = config_to_write
                            .get("options")
                            .and_then(|o| o.get("apiKey"))
                            .and_then(|v| v.as_str());
                        if let Some(key) = api_key {
                            crate::opencode_config::sync_provider_auth(&provider.id, key)?;
                        }
                        crate::opencode_config::set_provider(&provider.id, config_to_write)
                    }
                }
            }
            AppType::OpenClaw => {
                let settings_config = provider.settings_config.clone();
                let looks_like_provider = settings_config.get("baseUrl").is_some()
                    || settings_config.get("api").is_some()
                    || settings_config.get("models").is_some();
                if !looks_like_provider {
                    return Ok(());
                }

                let config = Self::parse_openclaw_provider_settings(&settings_config)?;
                Self::validate_openclaw_provider_models(&provider.id, &config)?;
                let write_result =
                    crate::openclaw_config::set_typed_provider(&provider.id, &config).map(|_| ());

                write_result.map_err(Self::normalize_openclaw_live_write_error)
            }
            AppType::Hermes => {
                crate::hermes_config::set_provider(&provider.id, provider.settings_config.clone())
                    .map(|_| ())
            }
        }
    }

    fn parse_openclaw_provider_settings(
        settings_config: &Value,
    ) -> Result<crate::provider::OpenClawProviderConfig, AppError> {
        let settings_obj = settings_config.as_object().ok_or_else(|| {
            AppError::localized(
                "provider.openclaw.settings.not_object",
                "OpenClaw 配置必须是 JSON 对象",
                "OpenClaw configuration must be a JSON object",
            )
        })?;

        let legacy_aliases = Self::collect_openclaw_legacy_aliases(settings_obj);
        if !legacy_aliases.is_empty() {
            let aliases = legacy_aliases.join(", ");
            return Err(AppError::localized(
                "provider.openclaw.settings.invalid",
                format!(
                    "OpenClaw 配置使用了不支持的旧字段: {aliases}。请改用规范 OpenClaw 字段。"
                ),
                format!(
                    "OpenClaw config uses unsupported legacy alias keys: {aliases}. Use canonical OpenClaw keys instead."
                ),
            ));
        }

        serde_json::from_value(settings_config.clone()).map_err(|err| {
            AppError::localized(
                "provider.openclaw.settings.invalid",
                format!("OpenClaw 配置格式无效: {err}"),
                format!("OpenClaw provider schema is invalid: {err}"),
            )
        })
    }

    fn validate_openclaw_provider_models(
        provider_id: &str,
        config: &crate::provider::OpenClawProviderConfig,
    ) -> Result<(), AppError> {
        if config.models.is_empty() {
            return Err(AppError::localized(
                "provider.openclaw.models.missing",
                format!("OpenClaw 供应商 {provider_id} 至少需要一个模型"),
                format!("OpenClaw provider {provider_id} must define at least one model"),
            ));
        }

        Ok(())
    }

    fn collect_openclaw_legacy_aliases(
        settings_obj: &serde_json::Map<String, Value>,
    ) -> Vec<String> {
        let mut aliases = Vec::new();

        for alias in ["api_key", "base_url", "options", "npm"] {
            if settings_obj.contains_key(alias) {
                aliases.push(alias.to_string());
            }
        }

        if let Some(models) = settings_obj.get("models").and_then(Value::as_array) {
            for (index, model) in models.iter().enumerate() {
                if let Some(model_obj) = model.as_object() {
                    if model_obj.contains_key("context_window") {
                        aliases.push(format!("models[{index}].context_window"));
                    }
                }
            }
        }

        aliases
    }

    fn normalize_openclaw_live_write_error(err: AppError) -> AppError {
        match err {
            AppError::Config(message)
                if message.starts_with("Failed to parse OpenClaw config as JSON5:") =>
            {
                AppError::Config(message.replacen(
                    "Failed to parse OpenClaw config as JSON5",
                    "Failed to parse OpenClaw config as round-trip JSON5 document",
                    1,
                ))
            }
            other => other,
        }
    }

    pub(crate) fn build_effective_live_snapshot(
        app_type: &AppType,
        provider: &Provider,
        common_config_snippet: Option<&str>,
        apply_common_config: bool,
    ) -> Result<Value, AppError> {
        let apply_common_config = Self::resolve_live_apply_common_config(
            app_type,
            provider,
            common_config_snippet,
            apply_common_config,
        );

        match app_type {
            AppType::Claude => {
                let mut effective = common_config::build_effective_settings_with_common_config(
                    app_type,
                    provider,
                    common_config_snippet,
                    apply_common_config,
                )?;
                let _ = Self::normalize_claude_models_in_value(&mut effective);
                Ok(effective)
            }
            AppType::Codex => {
                let effective = common_config::build_effective_settings_with_common_config(
                    app_type,
                    provider,
                    common_config_snippet,
                    apply_common_config,
                )?;
                let settings = effective
                    .as_object()
                    .ok_or_else(|| AppError::Config("Codex 配置必须是 JSON 对象".into()))?;
                let auth = settings.get("auth").cloned();
                let cfg_text = crate::codex_config::codex_config_text_from_settings(&effective)?;

                if !cfg_text.trim().is_empty() {
                    crate::codex_config::validate_config_toml(&cfg_text)?;
                }

                let mut backup = serde_json::Map::new();
                if let Some(auth) = auth {
                    backup.insert("auth".to_string(), auth);
                }
                backup.insert("config".to_string(), Value::String(cfg_text));
                Ok(Value::Object(backup))
            }
            AppType::Gemini => {
                let content_to_write = common_config::build_effective_settings_with_common_config(
                    app_type,
                    provider,
                    common_config_snippet,
                    apply_common_config,
                )?;

                let env_obj = content_to_write
                    .get("env")
                    .cloned()
                    .unwrap_or_else(|| json!({}));
                let settings_path = crate::gemini_config::get_gemini_settings_path();
                let config_value = if let Some(config_value) = content_to_write.get("config") {
                    if config_value.is_null() {
                        if settings_path.exists() {
                            read_json_file(&settings_path)?
                        } else {
                            json!({})
                        }
                    } else if let Some(provider_config) = config_value.as_object() {
                        if provider_config.is_empty() {
                            if settings_path.exists() {
                                read_json_file(&settings_path)?
                            } else {
                                json!({})
                            }
                        } else {
                            let mut merged = if settings_path.exists() {
                                read_json_file(&settings_path)?
                            } else {
                                json!({})
                            };

                            if !merged.is_object() {
                                merged = json!({});
                            }

                            let merged_map = merged.as_object_mut().ok_or_else(|| {
                                AppError::localized(
                                    "gemini.validation.invalid_settings",
                                    "Gemini 现有 settings.json 格式错误: 必须是对象",
                                    "Gemini existing settings.json invalid: must be a JSON object",
                                )
                            })?;
                            for (key, value) in provider_config {
                                merged_map.insert(key.clone(), value.clone());
                            }
                            merged
                        }
                    } else {
                        return Err(AppError::localized(
                            "gemini.validation.invalid_config",
                            "Gemini 配置格式错误: config 必须是对象或 null",
                            "Gemini config invalid: config must be an object or null",
                        ));
                    }
                } else if settings_path.exists() {
                    read_json_file(&settings_path)?
                } else {
                    json!({})
                };

                Ok(json!({
                    "env": env_obj,
                    "config": config_value,
                }))
            }
            AppType::OpenCode => Err(AppError::Config(
                "OpenCode does not support proxy takeover backups".into(),
            )),
            AppType::OpenClaw => Err(AppError::Config(
                "OpenClaw does not support proxy takeover backups".into(),
            )),
            AppType::Hermes => Err(AppError::Config(
                "Hermes does not support proxy takeover backups".into(),
            )),
        }
    }

    fn validate_provider_settings(app_type: &AppType, provider: &Provider) -> Result<(), AppError> {
        match app_type {
            AppType::Claude => {
                if !provider.settings_config.is_object() {
                    return Err(AppError::localized(
                        "provider.claude.settings.not_object",
                        "Claude 配置必须是 JSON 对象",
                        "Claude configuration must be a JSON object",
                    ));
                }
            }
            AppType::Codex => {
                let settings = provider.settings_config.as_object().ok_or_else(|| {
                    AppError::localized(
                        "provider.codex.settings.not_object",
                        "Codex 配置必须是 JSON 对象",
                        "Codex configuration must be a JSON object",
                    )
                })?;

                let auth = settings.get("auth").ok_or_else(|| {
                    AppError::localized(
                        "provider.codex.auth.missing",
                        format!("供应商 {} 缺少 auth 配置", provider.id),
                        format!("Provider {} is missing auth configuration", provider.id),
                    )
                })?;
                if !auth.is_object() {
                    return Err(AppError::localized(
                        "provider.codex.auth.not_object",
                        format!("供应商 {} 的 auth 配置必须是 JSON 对象", provider.id),
                        format!(
                            "Provider {} auth configuration must be a JSON object",
                            provider.id
                        ),
                    ));
                }

                if let Some(config_value) = settings.get("config") {
                    if !(config_value.is_string() || config_value.is_null()) {
                        return Err(AppError::localized(
                            "provider.codex.config.invalid_type",
                            "Codex config 字段必须是字符串",
                            "Codex config field must be a string",
                        ));
                    }
                    if let Some(cfg_text) = config_value.as_str() {
                        crate::codex_config::validate_config_toml(cfg_text)?;
                    }
                }
                if let Some(codex_value) = settings.get("codex") {
                    if !(codex_value.is_object() || codex_value.is_null()) {
                        return Err(AppError::localized(
                            "provider.codex.config.invalid_type",
                            "Codex codex 字段必须是对象",
                            "Codex codex field must be an object",
                        ));
                    }
                    let cfg_text =
                        crate::codex_config::codex_structured_config_to_toml(codex_value)?;
                    crate::codex_config::validate_config_toml(&cfg_text)?;
                }

                if !Self::is_codex_official_provider(provider) {
                    let config_text = crate::codex_config::codex_config_text_from_settings(
                        &provider.settings_config,
                    )?;
                    if !Self::codex_config_has_base_url(&config_text) {
                        return Err(AppError::localized(
                            "provider.codex.base_url.missing",
                            format!("供应商 {} 缺少有效的 Codex Base URL", provider.id),
                            format!("Provider {} is missing a valid Codex base_url", provider.id),
                        ));
                    }
                }
            }
            AppType::Gemini => {
                use crate::gemini_config::validate_gemini_settings;
                validate_gemini_settings(&provider.settings_config)?
            }
            AppType::OpenCode => {
                if !provider.settings_config.is_object() {
                    return Err(AppError::localized(
                        "provider.opencode.settings.not_object",
                        "OpenCode 配置必须是 JSON 对象",
                        "OpenCode configuration must be a JSON object",
                    ));
                }
            }
            AppType::OpenClaw => {
                let config = Self::parse_openclaw_provider_settings(&provider.settings_config)?;
                Self::validate_openclaw_provider_models(&provider.id, &config)?;
            }
            AppType::Hermes => {
                // Hermes uses flexible YAML config; basic check that settings is an object
                if !provider.settings_config.is_object() {
                    return Err(AppError::localized(
                        "provider.hermes.settings.not_object",
                        "Hermes 供应商配置必须是 JSON 对象",
                        "Hermes provider configuration must be a JSON object",
                    ));
                }
            }
        }

        // 🔧 验证并清理 UsageScript 配置(所有应用类型通用)
        if let Some(meta) = &provider.meta {
            if let Some(usage_script) = &meta.usage_script {
                Self::validate_usage_script(usage_script)?;
            }
        }

        Ok(())
    }

    pub(crate) fn build_live_backup_snapshot(
        app_type: &AppType,
        provider: &Provider,
        common_config_snippet: Option<&str>,
        apply_common_config: bool,
    ) -> Result<Value, AppError> {
        Self::build_effective_live_snapshot(
            app_type,
            provider,
            common_config_snippet,
            apply_common_config,
        )
    }

    pub(crate) fn build_effective_live_snapshot_from_state(
        state: &AppState,
        app_type: AppType,
        provider: &Provider,
    ) -> Result<Value, AppError> {
        let common_config_snippet = {
            let config = state.config.read().map_err(AppError::from)?;
            config.common_config_snippets.get(&app_type).cloned()
        };

        Self::build_effective_live_snapshot(
            &app_type,
            provider,
            common_config_snippet.as_deref(),
            true,
        )
    }

    pub(crate) fn get_provider(
        state: &AppState,
        app_type: AppType,
        provider_id: &str,
    ) -> Result<Provider, AppError> {
        let config = state.config.read().map_err(AppError::from)?;
        let manager = config
            .get_manager(&app_type)
            .ok_or_else(|| Self::app_not_found(&app_type))?;

        manager.providers.get(provider_id).cloned().ok_or_else(|| {
            AppError::localized(
                "provider.not_found",
                format!("供应商不存在: {provider_id}"),
                format!("Provider not found: {provider_id}"),
            )
        })
    }

    fn app_not_found(app_type: &AppType) -> AppError {
        AppError::localized(
            "provider.app_not_found",
            format!("应用类型不存在: {app_type:?}"),
            format!("App type not found: {app_type:?}"),
        )
    }

    pub fn delete(state: &AppState, app_type: AppType, provider_id: &str) -> Result<(), AppError> {
        let (local_current_provider, stored_current_provider) = if app_type.is_additive_mode() {
            (None, None)
        } else {
            (
                crate::settings::get_current_provider(&app_type),
                state.db.get_current_provider(app_type.as_str())?,
            )
        };
        let provider_snapshot = {
            let config = state.config.read().map_err(AppError::from)?;
            let manager = config
                .get_manager(&app_type)
                .ok_or_else(|| Self::app_not_found(&app_type))?;

            if !app_type.is_additive_mode()
                && (local_current_provider.as_deref() == Some(provider_id)
                    || stored_current_provider.as_deref() == Some(provider_id))
            {
                return Err(AppError::localized(
                    "provider.delete.current",
                    "不能删除当前正在使用的供应商",
                    "Cannot delete the provider currently in use",
                ));
            }

            manager.providers.get(provider_id).cloned().ok_or_else(|| {
                AppError::localized(
                    "provider.not_found",
                    format!("供应商不存在: {provider_id}"),
                    format!("Provider not found: {provider_id}"),
                )
            })?
        };
        let stale_codex_catalog_keys = if matches!(app_type, AppType::Codex) {
            Self::provider_codex_model_provider_key(&provider_snapshot)
                .into_iter()
                .collect::<Vec<_>>()
        } else {
            Vec::new()
        };

        if app_type.is_additive_mode() {
            match app_type {
                AppType::OpenCode => {
                    if crate::opencode_config::get_opencode_dir().exists() {
                        crate::opencode_config::remove_provider(provider_id)?;
                    }
                }
                AppType::OpenClaw => {
                    if crate::openclaw_config::get_openclaw_dir().exists() {
                        crate::openclaw_config::remove_provider(provider_id)?;
                    }
                }
                AppType::Hermes => {
                    if crate::hermes_config::get_hermes_dir().exists() {
                        crate::hermes_config::remove_provider(provider_id)?;
                    }
                }
                _ => unreachable!("non-additive apps should not enter additive delete branch"),
            }

            {
                let mut config = state.config.write().map_err(AppError::from)?;
                let manager = config
                    .get_manager_mut(&app_type)
                    .ok_or_else(|| Self::app_not_found(&app_type))?;
                manager.providers.shift_remove(provider_id);
            }

            return state.save();
        }

        match app_type {
            AppType::Codex => {
                crate::codex_config::delete_codex_provider_config(
                    provider_id,
                    &provider_snapshot.name,
                )?;
            }
            AppType::Claude => {
                // 兼容旧版本:历史上会在 Claude 目录内为每个供应商生成 settings-*.json 副本
                // 这里继续清理这些遗留文件,避免堆积过期配置。
                let by_name = get_provider_config_path(provider_id, Some(&provider_snapshot.name));
                let by_id = get_provider_config_path(provider_id, None);
                delete_file(&by_name)?;
                delete_file(&by_id)?;
            }
            AppType::Gemini => {
                // Gemini 使用单一的 .env 文件,不需要删除单独的供应商配置文件
            }
            AppType::OpenCode => {
                let _ = provider_snapshot;
            }
            AppType::OpenClaw => {
                let _ = provider_snapshot;
            }
            AppType::Hermes => {
                let _ = provider_snapshot;
            }
        }

        {
            let mut config = state.config.write().map_err(AppError::from)?;
            let manager = config
                .get_manager_mut(&app_type)
                .ok_or_else(|| Self::app_not_found(&app_type))?;

            if !app_type.is_additive_mode()
                && (local_current_provider.as_deref() == Some(provider_id)
                    || stored_current_provider.as_deref() == Some(provider_id))
            {
                return Err(AppError::localized(
                    "provider.delete.current",
                    "不能删除当前正在使用的供应商",
                    "Cannot delete the provider currently in use",
                ));
            }

            if !app_type.is_additive_mode() && manager.current == provider_id {
                manager.current = stored_current_provider.clone().unwrap_or_default();
            }

            manager.providers.shift_remove(provider_id);
        }

        state.save()?;
        if matches!(app_type, AppType::Codex) {
            Self::sync_codex_provider_catalog_to_live(state, &stale_codex_catalog_keys)?;
        }
        Ok(())
    }

    pub fn import_openclaw_providers_from_live(state: &AppState) -> Result<usize, AppError> {
        live::import_openclaw_providers_from_live(state)
    }

    pub fn import_opencode_providers_from_live(state: &AppState) -> Result<usize, AppError> {
        live::import_opencode_providers_from_live(state)
    }

    pub fn import_hermes_providers_from_live(state: &AppState) -> Result<usize, AppError> {
        live::import_hermes_providers_from_live(state)
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct ProviderSortUpdate {
    pub id: String,
    #[serde(rename = "sortIndex")]
    pub sort_index: usize,
}