opencode-provider-manager 0.1.7-beta.3

TUI/CLI binary crate for managing OpenCode provider configs
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
//! TUI application state and event loop.

use anyhow::{Context, Result};
use opencode_provider_manager::discovery::provider_api::ModelDiscovery as _;
use opencode_provider_manager::{app, config_core, discovery};

use crate::event::AppEvent;
use crate::ui;
use app::state::AppState;

/// TUI application with full state management.
pub struct App {
    /// The current mode/view.
    pub mode: AppMode,
    /// Whether the app should quit.
    pub should_quit: bool,
    /// Currently selected provider (for detail/edit views).
    pub selected_provider: Option<String>,
    /// Currently selected list index.
    pub selected_index: usize,
    /// Error message to display, if any.
    pub error_message: Option<String>,
    /// Discovered models from models.dev (cached).
    pub discovered_models: Vec<discovery::DiscoveredModel>,
    /// Whether model discovery is currently loading.
    pub models_loading: bool,
    /// Which source to use for model discovery.
    pub discovery_source: DiscoverySource,
}

/// Current UI mode.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, PartialEq)]
pub enum AppMode {
    /// Main merged config view.
    MergedView,
    /// Split pane view (global vs project).
    SplitView,
    /// Provider list.
    ProviderList,
    /// Auth status view.
    AuthStatus,
    /// Model selector for a provider.
    ModelSelector,
    /// Config detail view (JSON).
    ConfigDetail,
    /// Help overlay.
    Help,
    /// Confirm delete provider dialog.
    ConfirmDelete(String),
    /// Confirm refresh (discard unsaved changes).
    ConfirmRefresh,
    /// Add provider wizard (form with text inputs).
    AddProvider(AddProviderForm),
    /// Edit provider view (display and edit fields).
    EditProvider(EditProviderForm),
    /// Import config wizard (URL/path/snippet).
    Import(ImportForm),
    /// Oh-my-openagent configuration screen.
    OmoConfig(OmoConfigState),
}

/// Known SDK packages for provider configuration.
/// The last entry "Custom" signals manual text entry mode.
pub const KNOWN_SDKS: &[&str] = &[
    "@ai-sdk/openai",
    "@ai-sdk/openai-compatible",
    "@ai-sdk/anthropic",
    "@ai-sdk/google",
    "@ai-sdk/groq",
    "@ai-sdk/mistral",
    "@ai-sdk/amazon-bedrock",
    "@ai-sdk/azure",
    "Custom...",
];

/// Return all configured provider IDs.
pub fn all_provider_ids(state: &AppState) -> Vec<String> {
    state.provider_ids()
}

/// Build the list of providers available for copying (configured only).
/// Returns (id, display_name) pairs.
pub fn copy_source_list(state: &AppState) -> Vec<(String, String)> {
    let configured = state.provider_ids();
    let mut result: Vec<(String, String)> = Vec::new();

    // Add configured providers
    for id in &configured {
        let name = state
            .get_provider(id)
            .and_then(|p| p.name.clone())
            .unwrap_or_else(|| id.clone());
        result.push((id.clone(), name));
    }

    result
}

/// State for the SDK selection sub-field within a form.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SdkSelectState {
    /// Currently highlighted index in KNOWN_SDKS list.
    pub highlight: usize,
    /// Whether we're in custom text entry mode (last option selected + Enter pressed).
    pub custom_mode: bool,
    /// Custom text (only used when custom_mode is true).
    pub custom_text: String,
}

impl SdkSelectState {
    pub fn new() -> Self {
        Self {
            highlight: 0,
            custom_mode: false,
            custom_text: String::new(),
        }
    }

    /// Get the current SDK value (either a known one or the custom text).
    pub fn value(&self) -> String {
        if self.custom_mode {
            self.custom_text.clone()
        } else {
            KNOWN_SDKS[self.highlight].to_string()
        }
    }

    /// Initialize from an existing npm value. If it matches a known SDK, select it;
    /// otherwise go into custom mode with the existing value.
    pub fn from_value(value: &str) -> Self {
        if let Some(idx) = KNOWN_SDKS.iter().position(|&s| s == value) {
            Self {
                highlight: idx,
                custom_mode: false,
                custom_text: String::new(),
            }
        } else {
            Self {
                highlight: KNOWN_SDKS.len() - 1, // "Custom..."
                custom_mode: true,
                custom_text: value.to_string(),
            }
        }
    }
}

/// Form state for the add provider wizard.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddProviderForm {
    /// Which field is currently focused (0=id, 1=name, 2=sdk, 3=base_url).
    pub focus: usize,
    /// Provider ID field.
    pub id: String,
    /// Provider display name.
    pub name: String,
    /// SDK package selection.
    pub sdk: SdkSelectState,
    /// Base URL (for options).
    pub base_url: String,
    /// Whether the copy-from list is shown.
    pub show_copy_list: bool,
    /// Highlighted index in the copy source list.
    pub copy_highlight: usize,
}

impl AddProviderForm {
    pub fn new() -> Self {
        Self {
            focus: 0,
            id: String::new(),
            name: String::new(),
            sdk: SdkSelectState::new(),
            base_url: String::new(),
            show_copy_list: false,
            copy_highlight: 0,
        }
    }

    pub fn field_labels() -> [&'static str; 4] {
        [
            "Provider ID",
            "Display Name",
            "SDK Package (↑↓ select, Enter confirm)",
            "Base URL (optional)",
        ]
    }
}

/// Form state for editing an existing provider.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EditProviderForm {
    /// Provider ID being edited.
    pub provider_id: String,
    /// Currently focused field index.
    pub focus: usize,
    /// Editable name field.
    pub name: String,
    /// SDK package selection.
    pub sdk: SdkSelectState,
    /// Editable base URL field.
    pub base_url: String,
}

impl EditProviderForm {
    pub fn field_labels() -> [&'static str; 3] {
        [
            "Display Name",
            "SDK Package (↑↓ select, Enter confirm)",
            "Base URL",
        ]
    }
}

/// Form state for the import wizard.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImportForm {
    /// Which field is focused (0=source, 1=layer, 2=mode, 3=provider_id).
    pub focus: usize,
    /// Source URL, file path, or inline snippet.
    pub source: String,
    /// Target layer index: 0=project, 1=global, 2=custom.
    pub layer_index: usize,
    /// Merge mode: 0=merge, 1=replace.
    pub mode_index: usize,
    /// Optional provider ID hint.
    pub provider_id: String,
    /// Result message after import attempt.
    pub result_message: Option<String>,
}

impl ImportForm {
    pub fn new() -> Self {
        Self {
            focus: 0,
            source: String::new(),
            layer_index: 0,
            mode_index: 0,
            provider_id: String::new(),
            result_message: None,
        }
    }

    pub fn field_labels() -> [&'static str; 4] {
        [
            "Source (URL/path/snippet)",
            "Target Layer (↑↓)",
            "Import Mode (↑↓)",
            "Provider ID (optional)",
        ]
    }
}

/// Form state for editing an omo agent.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OmoAgentEditForm {
    /// Agent ID being edited.
    pub agent_id: String,
    /// Currently focused field index (0=model, 1=fallback, 2=disable, 3=temperature).
    pub focus: usize,
    /// Model ID field.
    pub model: String,
    /// Fallback models (comma-separated).
    pub fallback: String,
    /// Whether the agent is disabled.
    pub disable: bool,
    /// Temperature field (optional number).
    pub temperature: String,
}

/// State for the omo config screen.
#[derive(Debug, Clone, PartialEq)]
pub struct OmoConfigState {
    /// Agent config manager.
    pub manager: omo_config::AgentConfigManager,
    /// List of agents (id, definition) for the current layer.
    pub agents: Vec<(String, omo_config::AgentDefinition)>,
    /// Currently selected agent index.
    pub selected_index: usize,
    /// Whether we're in edit mode (true) or list mode (false).
    pub edit_mode: bool,
    /// Edit form state (when edit_mode is true).
    pub edit_form: Option<OmoAgentEditForm>,
    /// Which config layer is being viewed/edited.
    pub layer: omo_config::ConfigLayer,
    /// Available models from `opencode models`.
    pub available_models: Vec<String>,
    /// Whether models are currently loading.
    pub models_loading: bool,
    /// Whether the current layer has unsaved changes.
    pub dirty: bool,
}

/// Which source to use for model discovery in the model selector.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiscoverySource {
    /// Fetch from the models.dev catalog (default).
    ModelsDev,
    /// Query the provider's own API directly (e.g., /v1/models).
    ProviderApi,
}

impl DiscoverySource {
    pub fn label(&self) -> &'static str {
        match self {
            DiscoverySource::ModelsDev => "models.dev",
            DiscoverySource::ProviderApi => "Provider API",
        }
    }

    pub fn toggle(&self) -> Self {
        match self {
            DiscoverySource::ModelsDev => DiscoverySource::ProviderApi,
            DiscoverySource::ProviderApi => DiscoverySource::ModelsDev,
        }
    }
}

impl App {
    /// Create a new app instance.
    pub fn new() -> Self {
        Self {
            mode: AppMode::ProviderList,
            should_quit: false,
            selected_provider: None,
            selected_index: 0,
            error_message: None,
            discovered_models: Vec::new(),
            models_loading: false,
            discovery_source: DiscoverySource::ModelsDev,
        }
    }

    /// Handle an application event.
    pub fn on_event(&mut self, event: AppEvent) {
        match event {
            AppEvent::Quit => self.should_quit = true,
            AppEvent::SwitchMode(mode) => {
                self.mode = mode;
                self.selected_index = 0;
                self.selected_provider = None;
            }
            AppEvent::SelectProvider(id) => {
                self.selected_provider = Some(id);
            }
            AppEvent::SelectIndex(idx) => {
                self.selected_index = idx;
            }
            AppEvent::Error(msg) => {
                self.error_message = Some(msg);
            }
            AppEvent::ClearError => {
                self.error_message = None;
            }
            _ => {}
        }
    }

    /// Render the current UI.
    pub fn render(&self, frame: &mut ratatui::Frame, state: &AppState) {
        match &self.mode {
            AppMode::MergedView => ui::render_merged_view(frame, state, self),
            AppMode::SplitView => ui::render_split_view(frame, state, self),
            AppMode::ProviderList => ui::render_provider_list(frame, state, self),
            AppMode::AuthStatus => ui::render_auth_status(frame, state, self),
            AppMode::ModelSelector => ui::render_model_selector(frame, state, self),
            AppMode::ConfigDetail => ui::render_config_detail(frame, state, self),
            AppMode::Help => ui::render_help(frame),
            AppMode::ConfirmDelete(provider_id) => {
                ui::render_provider_list(frame, state, self);
                ui::render_confirm_delete(frame, provider_id);
            }
            AppMode::ConfirmRefresh => {
                ui::render_provider_list(frame, state, self);
                ui::render_confirm_refresh(frame);
            }
            AppMode::AddProvider(form) => {
                ui::render_add_provider(frame, form, state);
            }
            AppMode::EditProvider(form) => {
                ui::render_edit_provider(frame, state, form);
            }
            AppMode::Import(form) => {
                ui::render_import(frame, form);
            }
            AppMode::OmoConfig(omo_state) => {
                ui::render_omo_config(frame, self, omo_state);
            }
        }
    }
}

/// Async action to perform after key handling.
enum AsyncAction {
    /// Fetch models from models.dev for a provider.
    FetchModels {
        provider_id: String,
        force_refresh: bool,
    },
    /// Fetch models directly from the provider's own API.
    FetchModelsFromApi {
        provider_id: String,
        base_url: String,
        api_key: Option<String>,
    },
    /// Fetch available models from `opencode models` for omo config validation.
    FetchOmoModels,
    /// No async action needed.
    None,
}

/// Run the main TUI event loop.
pub async fn run(
    mut terminal: ratatui::DefaultTerminal,
    mut state: AppState,
    split: bool,
) -> Result<()> {
    let mut app = App::new();
    if split {
        app.mode = AppMode::SplitView;
    }

    loop {
        if app.should_quit {
            break;
        }

        terminal.draw(|frame| app.render(frame, &state))?;

        // Handle key events via crossterm
        if crossterm::event::poll(std::time::Duration::from_millis(100))? {
            if let crossterm::event::Event::Key(key) = crossterm::event::read()? {
                // Only handle key press events (crossterm 0.28+ sends Press/Release/Repeat)
                if key.kind == crossterm::event::KeyEventKind::Press {
                    let action = handle_key_event(key, &mut app, &mut state);
                    match action {
                        AsyncAction::FetchModels {
                            provider_id,
                            force_refresh,
                        } => {
                            app.models_loading = true;
                            // Re-render to show loading state
                            terminal.draw(|frame| app.render(frame, &state))?;
                            let client = discovery::models_dev::ModelsDevClient::new();
                            match client
                                .fetch_provider_models_cached(&provider_id, force_refresh)
                                .await
                            {
                                Ok(models) => {
                                    app.discovered_models = models;
                                }
                                Err(e) => {
                                    app.error_message =
                                        Some(format!("Failed to fetch models: {e}"));
                                }
                            }
                            app.models_loading = false;
                        }
                        AsyncAction::FetchModelsFromApi {
                            provider_id,
                            base_url,
                            api_key,
                        } => {
                            app.models_loading = true;
                            terminal.draw(|frame| app.render(frame, &state))?;
                            let result = if provider_id == "ollama" {
                                discovery::provider_api::OllamaDiscovery::new(&base_url)
                                    .discover_models(None)
                                    .await
                            } else {
                                discovery::provider_api::OpenAICompatibleDiscovery::new(
                                    &provider_id,
                                    &base_url,
                                )
                                .discover_models(api_key.as_deref())
                                .await
                            };
                            match result {
                                Ok(models) => {
                                    app.discovered_models = models;
                                }
                                Err(e) => {
                                    app.error_message =
                                        Some(format!("Failed to fetch models from API: {e}"));
                                }
                            }
                            app.models_loading = false;
                        }
                        AsyncAction::FetchOmoModels => {
                            {
                                if let AppMode::OmoConfig(ref mut omo_state) = app.mode {
                                    omo_state.models_loading = true;
                                }
                            }
                            terminal.draw(|frame| app.render(frame, &state))?;
                            let models = tokio::task::spawn_blocking(fetch_omo_models_sync).await;
                            {
                                if let AppMode::OmoConfig(ref mut omo_state) = app.mode {
                                    match models {
                                        Ok(Ok(model_set)) => {
                                            let mut model_list: Vec<String> =
                                                model_set.into_iter().collect();
                                            model_list.sort();
                                            omo_state.available_models = model_list;
                                        }
                                        Ok(Err(e)) => {
                                            app.error_message =
                                                Some(format!("Failed to fetch models: {e}"));
                                        }
                                        Err(e) => {
                                            app.error_message =
                                                Some(format!("Failed to fetch models: {e}"));
                                        }
                                    }
                                    omo_state.models_loading = false;
                                }
                            }
                        }
                        AsyncAction::None => {}
                    }
                }
            }
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Omo config helpers
// ---------------------------------------------------------------------------

/// Extract all agents from an OhMyOpencodeConfig into a flat list.
fn extract_agents(
    config: &omo_config::OhMyOpencodeConfig,
) -> Vec<(String, omo_config::AgentDefinition)> {
    let mut agents = Vec::new();
    if let Some(ref agent_configs) = config.agents {
        let mut push = |id: &str, agent: &Option<omo_config::AgentDefinition>| {
            if let Some(a) = agent {
                agents.push((id.to_string(), a.clone()));
            }
        };
        push("build", &agent_configs.build);
        push("plan", &agent_configs.plan);
        push("sisyphus", &agent_configs.sisyphus);
        push("hephaestus", &agent_configs.hephaestus);
        push("prometheus", &agent_configs.prometheus);
        push("oracle", &agent_configs.oracle);
        push("librarian", &agent_configs.librarian);
        push("explore", &agent_configs.explore);
        push("multimodal-looker", &agent_configs.multimodal_looker);
        push("metis", &agent_configs.metis);
        push("momus", &agent_configs.momus);
        push("atlas", &agent_configs.atlas);
        for (id, agent) in &agent_configs.custom {
            agents.push((id.clone(), agent.clone()));
        }
    }
    agents
}

/// Initialize the omo config state for the TUI.
fn initialize_omo_config() -> Result<OmoConfigState> {
    let mut manager = omo_config::AgentConfigManager::new()?;
    manager.load_all()?;

    let layer = omo_config::ConfigLayer::Project;
    let config = manager.project_config.clone().unwrap_or_default();
    let agents = extract_agents(&config);

    Ok(OmoConfigState {
        manager,
        agents,
        selected_index: 0,
        edit_mode: false,
        edit_form: None,
        layer,
        available_models: Vec::new(),
        models_loading: false,
        dirty: false,
    })
}

/// Update an agent in the current layer's cached config from the edit form.
fn update_agent_in_state(omo_state: &mut OmoConfigState, form: &OmoAgentEditForm) -> Result<()> {
    let config = match omo_state.layer {
        omo_config::ConfigLayer::Global => omo_state.manager.global_config.as_mut(),
        omo_config::ConfigLayer::Project => omo_state.manager.project_config.as_mut(),
    }
    .ok_or_else(|| anyhow::anyhow!("No config loaded for current layer"))?;

    if config.agents.is_none() {
        config.agents = Some(omo_config::AgentsConfig::default());
    }
    let agents = config.agents.as_mut().unwrap();

    let agent = match form.agent_id.as_str() {
        "build" => agents
            .build
            .get_or_insert_with(omo_config::AgentDefinition::default),
        "plan" => agents
            .plan
            .get_or_insert_with(omo_config::AgentDefinition::default),
        "sisyphus" => agents
            .sisyphus
            .get_or_insert_with(omo_config::AgentDefinition::default),
        "hephaestus" => agents
            .hephaestus
            .get_or_insert_with(omo_config::AgentDefinition::default),
        "prometheus" => agents
            .prometheus
            .get_or_insert_with(omo_config::AgentDefinition::default),
        "oracle" => agents
            .oracle
            .get_or_insert_with(omo_config::AgentDefinition::default),
        "librarian" => agents
            .librarian
            .get_or_insert_with(omo_config::AgentDefinition::default),
        "explore" => agents
            .explore
            .get_or_insert_with(omo_config::AgentDefinition::default),
        "multimodal-looker" => agents
            .multimodal_looker
            .get_or_insert_with(omo_config::AgentDefinition::default),
        "metis" => agents
            .metis
            .get_or_insert_with(omo_config::AgentDefinition::default),
        "momus" => agents
            .momus
            .get_or_insert_with(omo_config::AgentDefinition::default),
        "atlas" => agents
            .atlas
            .get_or_insert_with(omo_config::AgentDefinition::default),
        custom => agents
            .custom
            .entry(custom.to_string())
            .or_insert_with(omo_config::AgentDefinition::default),
    };

    let model_trimmed = form.model.trim().to_string();
    agent.model = if model_trimmed.is_empty() {
        None
    } else {
        Some(model_trimmed)
    };

    let fallback_trimmed = form.fallback.trim().to_string();
    agent.fallback_models = if fallback_trimmed.is_empty() {
        None
    } else {
        let fb_ids: Vec<String> = fallback_trimmed
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect();
        if fb_ids.is_empty() {
            None
        } else {
            Some(omo_config::FallbackModels::StringList(fb_ids))
        }
    };

    agent.disable = Some(form.disable);

    let temp_trimmed = form.temperature.trim().to_string();
    agent.temperature = if temp_trimmed.is_empty() {
        None
    } else {
        Some(
            temp_trimmed
                .parse::<f64>()
                .map_err(|e| anyhow::anyhow!("Invalid temperature: {e}"))?,
        )
    };

    omo_state.dirty = true;

    // Reload agents list from updated config
    let config_ref = match omo_state.layer {
        omo_config::ConfigLayer::Global => omo_state.manager.global_config.as_ref(),
        omo_config::ConfigLayer::Project => omo_state.manager.project_config.as_ref(),
    }
    .unwrap();
    omo_state.agents = extract_agents(config_ref);

    Ok(())
}

/// Save the current omo config layer to disk.
fn save_omo_config(omo_state: &mut OmoConfigState) -> Result<()> {
    let config = match omo_state.layer {
        omo_config::ConfigLayer::Global => omo_state.manager.global_config.as_ref(),
        omo_config::ConfigLayer::Project => omo_state.manager.project_config.as_ref(),
    }
    .ok_or_else(|| anyhow::anyhow!("No config loaded for current layer"))?;

    omo_state.manager.save(omo_state.layer, config)?;
    Ok(())
}

/// Fetch available models from `opencode models` synchronously.
fn fetch_omo_models_sync() -> Result<std::collections::HashSet<String>> {
    let output = if cfg!(target_os = "windows") {
        std::process::Command::new("opencode.cmd")
            .args(["models"])
            .output()
            .or_else(|_| {
                std::process::Command::new("cmd")
                    .args(["/c", "opencode", "models"])
                    .output()
            })
            .context("Failed to run 'opencode models'")?
    } else {
        std::process::Command::new("opencode")
            .args(["models"])
            .output()
            .context("Failed to run 'opencode models'")?
    };

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(anyhow::anyhow!(
            "'opencode models' exited with code {:?}: {}",
            output.status.code(),
            stderr
        ));
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    Ok(stdout
        .lines()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect())
}

/// Handle a keyboard event. Returns an async action if needed.
fn handle_key_event(
    key: crossterm::event::KeyEvent,
    app: &mut App,
    state: &mut AppState,
) -> AsyncAction {
    use crossterm::event::KeyCode;

    // Clear error on any keypress
    let had_error = app.error_message.is_some();
    if had_error {
        app.error_message = None;
    }

    // Handle confirm refresh mode separately
    if app.mode == AppMode::ConfirmRefresh {
        match key.code {
            KeyCode::Char('y') | KeyCode::Char('Y') => {
                if let Err(e) = state.load_configs() {
                    app.error_message = Some(format!("Refresh failed: {e}"));
                }
                app.mode = AppMode::ProviderList;
            }
            KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
                app.mode = AppMode::ProviderList;
            }
            _ => {}
        }
        return AsyncAction::None;
    }

    // Handle edit provider mode separately
    if let AppMode::EditProvider(ref mut form) = app.mode {
        match key.code {
            KeyCode::Esc => {
                app.mode = AppMode::ProviderList;
            }
            KeyCode::Tab => {
                form.focus = (form.focus + 1) % EditProviderForm::field_labels().len();
            }
            KeyCode::BackTab => {
                form.focus = (form.focus + EditProviderForm::field_labels().len() - 1)
                    % EditProviderForm::field_labels().len();
            }
            KeyCode::Enter => {
                // If focused on SDK field and not yet confirmed, confirm selection
                if form.focus == 1
                    && !form.sdk.custom_mode
                    && form.sdk.highlight == KNOWN_SDKS.len() - 1
                {
                    // "Custom..." selected — enter custom text mode
                    form.sdk.custom_mode = true;
                } else if form.focus == 1 && !form.sdk.custom_mode {
                    // Known SDK confirmed — no action needed, value is set
                } else {
                    // Save edited fields back to state
                    let pid = form.provider_id.clone();
                    let name_val = form.name.trim().to_string();
                    let npm_val = form.sdk.value();
                    let base_url_val = form.base_url.trim().to_string();

                    let edit_result = (|| -> Result<(), app::error::AppError> {
                        if !name_val.is_empty() {
                            state.edit_provider_field(
                                &pid,
                                "name",
                                serde_json::Value::String(name_val),
                                state.edit_layer,
                            )?;
                        }
                        if !npm_val.is_empty() {
                            state.edit_provider_field(
                                &pid,
                                "npm",
                                serde_json::Value::String(npm_val),
                                state.edit_layer,
                            )?;
                        }
                        if !base_url_val.is_empty() {
                            state.edit_provider_field(
                                &pid,
                                "baseURL",
                                serde_json::Value::String(base_url_val),
                                state.edit_layer,
                            )?;
                        }
                        Ok(())
                    })();

                    match edit_result {
                        Ok(()) => app.mode = AppMode::ProviderList,
                        Err(e) => app.error_message = Some(format!("Edit failed: {e}")),
                    }
                }
            }
            KeyCode::Up | KeyCode::Char('k') => {
                if form.focus == 1 && !form.sdk.custom_mode && form.sdk.highlight > 0 {
                    form.sdk.highlight -= 1;
                } else if form.focus == 0 {
                    // nothing
                }
            }
            KeyCode::Down | KeyCode::Char('j')
                if form.focus == 1
                    && !form.sdk.custom_mode
                    && form.sdk.highlight < KNOWN_SDKS.len() - 1 =>
            {
                form.sdk.highlight += 1;
            }
            KeyCode::Backspace => match form.focus {
                0 => {
                    form.name.pop();
                }
                1 if form.sdk.custom_mode => {
                    form.sdk.custom_text.pop();
                }
                2 => {
                    form.base_url.pop();
                }
                _ => {}
            },
            KeyCode::Char(c) => match form.focus {
                0 => form.name.push(c),
                1 if form.sdk.custom_mode => form.sdk.custom_text.push(c),
                2 => form.base_url.push(c),
                _ => {}
            },
            _ => {}
        }
        return AsyncAction::None;
    }

    // Handle import mode separately
    if let AppMode::Import(ref mut form) = app.mode {
        match key.code {
            KeyCode::Esc => {
                app.mode = AppMode::ProviderList;
            }
            KeyCode::Tab => {
                form.focus = (form.focus + 1) % ImportForm::field_labels().len();
            }
            KeyCode::BackTab => {
                form.focus = (form.focus + ImportForm::field_labels().len() - 1)
                    % ImportForm::field_labels().len();
            }
            KeyCode::Up => match form.focus {
                1 if form.layer_index > 0 => {
                    form.layer_index -= 1;
                }
                2 if form.mode_index > 0 => {
                    form.mode_index -= 1;
                }
                _ => {}
            },
            KeyCode::Down => match form.focus {
                1 if form.layer_index < 2 => {
                    form.layer_index += 1;
                }
                2 if form.mode_index < 1 => {
                    form.mode_index += 1;
                }
                _ => {}
            },
            KeyCode::Backspace => match form.focus {
                0 => {
                    form.source.pop();
                }
                3 => {
                    form.provider_id.pop();
                }
                _ => {}
            },
            KeyCode::Char(c) => match form.focus {
                0 => form.source.push(c),
                3 => form.provider_id.push(c),
                _ => {}
            },
            KeyCode::Enter => {
                let source = form.source.trim().to_string();
                if source.is_empty() {
                    form.result_message = Some("Source cannot be empty".to_string());
                } else {
                    let layer = match form.layer_index {
                        0 => config_core::ConfigLayer::Project,
                        1 => config_core::ConfigLayer::Global,
                        2 => config_core::ConfigLayer::Custom,
                        _ => config_core::ConfigLayer::Project,
                    };
                    let mode = if form.mode_index == 0 {
                        app::import::ImportMergeMode::Merge
                    } else {
                        app::import::ImportMergeMode::Replace
                    };
                    let provider_hint = if form.provider_id.trim().is_empty() {
                        None
                    } else {
                        Some(form.provider_id.trim().to_string())
                    };
                    match app::import::import_source(
                        state,
                        &source,
                        provider_hint.as_deref(),
                        layer,
                        mode,
                    ) {
                        Ok(summary) => {
                            form.result_message = Some(format!(
                                "OK: {} provider(s), {} model(s): {}",
                                summary.provider_count,
                                summary.model_count,
                                if summary.provider_ids.is_empty() {
                                    "(none)".to_string()
                                } else {
                                    summary.provider_ids.join(", ")
                                }
                            ));
                        }
                        Err(e) => {
                            form.result_message = Some(format!("Import failed: {e:#}"));
                        }
                    }
                }
            }
            _ => {}
        }
        return AsyncAction::None;
    }

    // Handle confirm delete mode separately
    if let AppMode::ConfirmDelete(ref provider_id) = app.mode {
        match key.code {
            KeyCode::Char('y') | KeyCode::Char('Y') => {
                let id = provider_id.clone();
                if let Err(e) = state.remove_provider(&id, state.edit_layer) {
                    app.error_message = Some(format!("Failed to remove provider: {e}"));
                }
                app.mode = AppMode::ProviderList;
                app.selected_provider = None;
            }
            KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
                app.mode = AppMode::ProviderList;
            }
            _ => {}
        }
        return AsyncAction::None;
    }

    // Handle add provider form mode separately
    if let AppMode::AddProvider(ref mut form) = app.mode {
        // Handle copy-from list mode first
        if form.show_copy_list {
            match key.code {
                KeyCode::Esc => {
                    app.mode = AppMode::ProviderList;
                }
                KeyCode::Char('c') => {
                    // Toggle copy-from list
                    if !form.show_copy_list && !copy_source_list(state).is_empty() {
                        form.show_copy_list = true;
                        form.copy_highlight = 0;
                    } else {
                        form.show_copy_list = false;
                    }
                }
                KeyCode::Up | KeyCode::Char('k') if form.copy_highlight > 0 => {
                    form.copy_highlight -= 1;
                }
                KeyCode::Down | KeyCode::Char('j') => {
                    let sources = copy_source_list(state);
                    if form.copy_highlight + 1 < sources.len() {
                        form.copy_highlight += 1;
                    }
                }
                KeyCode::Enter => {
                    let sources = copy_source_list(state);
                    if let Some((id, _name)) = sources.get(form.copy_highlight) {
                        // Get provider config from configured providers
                        if let Some(provider) = state.get_provider(id).cloned() {
                            form.name = provider.name.unwrap_or_default();
                            let npm_val = provider.npm.unwrap_or_default();
                            form.sdk = SdkSelectState::from_value(&npm_val);
                            form.base_url = provider
                                .options
                                .as_ref()
                                .and_then(|o| o.get("baseURL"))
                                .and_then(|v| v.as_str())
                                .unwrap_or_default()
                                .to_string();
                            // Auto-fill ID if empty
                            if form.id.is_empty() {
                                form.id = format!("{id}-copy");
                            }
                        }
                    }
                    form.show_copy_list = false;
                }
                _ => {}
            }
            return AsyncAction::None;
        }

        match key.code {
            KeyCode::Esc => {
                app.mode = AppMode::ProviderList;
            }
            KeyCode::Char('c')
                if key
                    .modifiers
                    .contains(crossterm::event::KeyModifiers::CONTROL) =>
            {
                // Toggle copy-from list (Ctrl+C to avoid conflict with text input)
                if !form.show_copy_list && !copy_source_list(state).is_empty() {
                    form.show_copy_list = true;
                    form.copy_highlight = 0;
                } else {
                    form.show_copy_list = false;
                }
            }
            KeyCode::Tab => {
                form.focus = (form.focus + 1) % AddProviderForm::field_labels().len();
            }
            KeyCode::BackTab => {
                form.focus = (form.focus + AddProviderForm::field_labels().len() - 1)
                    % AddProviderForm::field_labels().len();
            }
            KeyCode::Up | KeyCode::Char('k')
                if form.focus == 2 && !form.sdk.custom_mode && form.sdk.highlight > 0 =>
            {
                form.sdk.highlight -= 1;
            }
            KeyCode::Down | KeyCode::Char('j')
                if form.focus == 2
                    && !form.sdk.custom_mode
                    && form.sdk.highlight < KNOWN_SDKS.len() - 1 =>
            {
                form.sdk.highlight += 1;
            }
            KeyCode::Enter => {
                // If focused on SDK field and "Custom..." is highlighted, enter custom mode
                if form.focus == 2
                    && !form.sdk.custom_mode
                    && form.sdk.highlight == KNOWN_SDKS.len() - 1
                {
                    form.sdk.custom_mode = true;
                    return AsyncAction::None;
                }

                // Submit form
                let id = form.id.trim().to_string();
                let name_val = form.name.trim().to_string();
                let npm_val = form.sdk.value();
                let base_url_val = form.base_url.trim().to_string();

                if id.is_empty() {
                    app.error_message = Some("Provider ID cannot be empty".to_string());
                    return AsyncAction::None;
                }

                // Build ProviderConfig
                let mut options = std::collections::HashMap::new();
                if !base_url_val.is_empty() {
                    options.insert(
                        "baseURL".to_string(),
                        serde_json::Value::String(base_url_val),
                    );
                }

                let provider_config = config_core::ProviderConfig {
                    name: if name_val.is_empty() {
                        None
                    } else {
                        Some(name_val)
                    },
                    npm: if npm_val.is_empty() || npm_val == "Custom..." {
                        None
                    } else {
                        Some(npm_val)
                    },
                    options: if options.is_empty() {
                        None
                    } else {
                        Some(options)
                    },
                    models: None,
                    disabled: None,
                    extra: Default::default(),
                };

                if let Err(e) = state.add_provider(id, provider_config, state.edit_layer) {
                    app.error_message = Some(format!("Failed to add provider: {e}"));
                }
                app.mode = AppMode::ProviderList;
            }
            KeyCode::Backspace => match form.focus {
                0 => {
                    form.id.pop();
                }
                1 => {
                    form.name.pop();
                }
                2 if form.sdk.custom_mode => {
                    form.sdk.custom_text.pop();
                }
                3 => {
                    form.base_url.pop();
                }
                _ => {}
            },
            KeyCode::Char(c) => match form.focus {
                0 => form.id.push(c),
                1 => form.name.push(c),
                2 if form.sdk.custom_mode => form.sdk.custom_text.push(c),
                3 => form.base_url.push(c),
                _ => {}
            },
            _ => {}
        }
        return AsyncAction::None;
    }

    // Handle omo config mode separately
    if let AppMode::OmoConfig(ref mut omo_state) = app.mode {
        if omo_state.edit_mode {
            if let Some(ref mut form) = omo_state.edit_form {
                match key.code {
                    KeyCode::Esc => {
                        omo_state.edit_mode = false;
                        omo_state.edit_form = None;
                    }
                    KeyCode::Tab => {
                        form.focus = (form.focus + 1) % 4;
                    }
                    KeyCode::BackTab => {
                        form.focus = (form.focus + 3) % 4;
                    }
                    KeyCode::Enter => {
                        let form_data = omo_state.edit_form.take().unwrap();
                        if let Err(e) = update_agent_in_state(omo_state, &form_data) {
                            app.error_message = Some(format!("Failed to save agent: {e}"));
                            omo_state.edit_form = Some(form_data);
                        } else {
                            omo_state.edit_mode = false;
                        }
                    }
                    KeyCode::Backspace => match form.focus {
                        0 => {
                            form.model.pop();
                        }
                        1 => {
                            form.fallback.pop();
                        }
                        3 => {
                            form.temperature.pop();
                        }
                        _ => {}
                    },
                    KeyCode::Char(c) => match form.focus {
                        0 => form.model.push(c),
                        1 => form.fallback.push(c),
                        3 => form.temperature.push(c),
                        2 if c == ' ' => {
                            form.disable = !form.disable;
                        }
                        _ => {}
                    },
                    _ => {}
                }
            }
        } else {
            match key.code {
                KeyCode::Esc => {
                    app.mode = AppMode::ProviderList;
                }
                KeyCode::Char('o') => {
                    // Toggle layer
                    omo_state.layer = match omo_state.layer {
                        omo_config::ConfigLayer::Global => omo_config::ConfigLayer::Project,
                        omo_config::ConfigLayer::Project => omo_config::ConfigLayer::Global,
                    };
                    let config = match omo_state.layer {
                        omo_config::ConfigLayer::Global => {
                            omo_state.manager.global_config.clone().unwrap_or_default()
                        }
                        omo_config::ConfigLayer::Project => {
                            omo_state.manager.project_config.clone().unwrap_or_default()
                        }
                    };
                    omo_state.agents = extract_agents(&config);
                    omo_state.selected_index = 0;
                }
                KeyCode::Char('s') => {
                    if let Err(e) = save_omo_config(omo_state) {
                        app.error_message = Some(format!("Save failed: {e}"));
                    } else {
                        omo_state.dirty = false;
                        app.error_message = Some("Agent config saved".to_string());
                    }
                }
                KeyCode::Up | KeyCode::Char('k') if omo_state.selected_index > 0 => {
                    omo_state.selected_index -= 1;
                }
                KeyCode::Down | KeyCode::Char('j')
                    if omo_state.selected_index + 1 < omo_state.agents.len() =>
                {
                    omo_state.selected_index += 1;
                }
                KeyCode::Enter => {
                    if let Some((agent_id, agent)) = omo_state.agents.get(omo_state.selected_index)
                    {
                        let fallback_str = match &agent.fallback_models {
                            Some(omo_config::FallbackModels::Single(s)) => s.clone(),
                            Some(omo_config::FallbackModels::StringList(list)) => list.join(", "),
                            Some(omo_config::FallbackModels::DetailedList(list)) => list
                                .iter()
                                .map(|spec| spec.model.clone())
                                .collect::<Vec<_>>()
                                .join(", "),
                            Some(omo_config::FallbackModels::MixedList(list)) => list
                                .iter()
                                .map(|entry| match entry {
                                    omo_config::FallbackModelEntry::String(s) => s.clone(),
                                    omo_config::FallbackModelEntry::Detailed(spec) => {
                                        spec.model.clone()
                                    }
                                })
                                .collect::<Vec<_>>()
                                .join(", "),
                            None => String::new(),
                        };
                        omo_state.edit_form = Some(OmoAgentEditForm {
                            agent_id: agent_id.clone(),
                            focus: 0,
                            model: agent.model.clone().unwrap_or_default(),
                            fallback: fallback_str,
                            disable: agent.disable.unwrap_or(false),
                            temperature: agent
                                .temperature
                                .map(|t| t.to_string())
                                .unwrap_or_default(),
                        });
                        omo_state.edit_mode = true;
                    }
                }
                _ => {}
            }
        }
        return AsyncAction::None;
    }

    // Global keybindings
    let mut async_action = AsyncAction::None;
    match key.code {
        KeyCode::Char('q') | KeyCode::Esc => {
            if app.mode == AppMode::Help {
                app.on_event(AppEvent::SwitchMode(AppMode::ProviderList));
            } else {
                app.on_event(AppEvent::Quit);
            }
        }
        KeyCode::Char('?') => {
            if app.mode == AppMode::Help {
                app.on_event(AppEvent::SwitchMode(AppMode::ProviderList));
            } else {
                app.on_event(AppEvent::SwitchMode(AppMode::Help));
            }
        }
        KeyCode::Char('1') => app.on_event(AppEvent::SwitchMode(AppMode::MergedView)),
        KeyCode::Char('2') => app.on_event(AppEvent::SwitchMode(AppMode::SplitView)),
        KeyCode::Char('p') => app.on_event(AppEvent::SwitchMode(AppMode::ProviderList)),
        KeyCode::Char('a') => app.on_event(AppEvent::SwitchMode(AppMode::AuthStatus)),
        KeyCode::Char('m') => {
            // Switch to model selector and fetch models for selected provider
            app.mode = AppMode::ModelSelector;
            app.selected_index = 0;
            app.discovered_models.clear();
            // Determine which provider to fetch models for
            let provider_ids = state.provider_ids();
            if let Some(provider_id) = provider_ids.get(app.selected_index) {
                app.selected_provider = Some(provider_id.clone());
                async_action = AsyncAction::FetchModels {
                    provider_id: provider_id.clone(),
                    force_refresh: false,
                };
            }
        }
        KeyCode::Char('o') => {
            // Enter omo config screen
            match initialize_omo_config() {
                Ok(omo_state) => {
                    app.mode = AppMode::OmoConfig(omo_state);
                    async_action = AsyncAction::FetchOmoModels;
                }
                Err(e) => {
                    app.error_message = Some(format!("Failed to load agent config: {e}"));
                }
            }
        }
        KeyCode::Char('c') => app.on_event(AppEvent::SwitchMode(AppMode::ConfigDetail)),
        KeyCode::Char('s') => {
            // Save current config
            if let Err(e) = state.save(state.edit_layer) {
                app.error_message = Some(format!("Save failed: {e}"));
            }
        }
        KeyCode::Char('r') => {
            if app.mode == AppMode::ModelSelector {
                // In model selector, `r` re-fetches the model list for the
                // currently selected provider using the current source.
                if let Some(provider_id) = app.selected_provider.clone() {
                    app.discovered_models.clear();
                    async_action = match app.discovery_source {
                        DiscoverySource::ModelsDev => AsyncAction::FetchModels {
                            provider_id: provider_id.clone(),
                            force_refresh: true,
                        },
                        DiscoverySource::ProviderApi => {
                            let base_url = state
                                .get_provider(&provider_id)
                                .and_then(|p| p.options.as_ref())
                                .and_then(|o| o.get("baseURL"))
                                .and_then(|v| v.as_str())
                                .unwrap_or("http://localhost:11434")
                                .to_string();
                            let api_key = state
                                .get_provider(&provider_id)
                                .and_then(|p| p.options.as_ref())
                                .and_then(|o| o.get("apiKey"))
                                .and_then(|v| v.as_str())
                                .map(str::to_string);
                            AsyncAction::FetchModelsFromApi {
                                provider_id: provider_id.clone(),
                                base_url,
                                api_key,
                            }
                        }
                    };
                }
            } else if state.dirty {
                // Refresh configs from disk — check for unsaved changes first
                app.mode = AppMode::ConfirmRefresh;
            } else if let Err(e) = state.load_configs() {
                app.error_message = Some(format!("Refresh failed: {e}"));
            }
        }
        KeyCode::Char('d') => {
            // Delete selected provider (with confirmation)
            if app.mode == AppMode::ProviderList
                && let Some(provider_id) = state.provider_ids().get(app.selected_index)
            {
                app.mode = AppMode::ConfirmDelete(provider_id.clone());
            }
        }
        KeyCode::Char('g') if app.mode == AppMode::ProviderList => {
            // Copy the selected provider from current edit_layer to global config,
            // then switch edit_layer to Global so pressing 's' saves the right file.
            let provider_ids = state.provider_ids();
            if let Some(provider_id) = provider_ids.get(app.selected_index) {
                match state.copy_provider_to_global(provider_id) {
                    Ok(()) => {
                        state.edit_layer = config_core::ConfigLayer::Global;
                        app.error_message = Some(format!(
                            "Provider '{provider_id}' copied to global — layer switched to Global, press s to save"
                        ));
                    }
                    Err(e) => {
                        app.error_message = Some(format!("Copy to global failed: {e}"));
                    }
                }
            }
        }
        KeyCode::Char('t') if app.mode == AppMode::ModelSelector => {
            // Toggle discovery source and re-fetch models.
            app.discovery_source = app.discovery_source.toggle();
            app.discovered_models.clear();
            if let Some(ref provider_id) = app.selected_provider.clone() {
                async_action = match app.discovery_source {
                    DiscoverySource::ModelsDev => AsyncAction::FetchModels {
                        provider_id: provider_id.clone(),
                        force_refresh: false,
                    },
                    DiscoverySource::ProviderApi => {
                        let base_url = state
                            .get_provider(provider_id)
                            .and_then(|p| p.options.as_ref())
                            .and_then(|o| o.get("baseURL"))
                            .and_then(|v| v.as_str())
                            .unwrap_or("http://localhost:11434")
                            .to_string();
                        let api_key = state
                            .get_provider(provider_id)
                            .and_then(|p| p.options.as_ref())
                            .and_then(|o| o.get("apiKey"))
                            .and_then(|v| v.as_str())
                            .map(str::to_string);
                        AsyncAction::FetchModelsFromApi {
                            provider_id: provider_id.clone(),
                            base_url,
                            api_key,
                        }
                    }
                };
            }
        }
        KeyCode::Char('n') if app.mode == AppMode::ProviderList => {
            // Add new provider
            app.mode = AppMode::AddProvider(AddProviderForm::new());
        }
        KeyCode::Char('i') if app.mode == AppMode::ProviderList => {
            // Import config
            app.mode = AppMode::Import(ImportForm::new());
        }
        KeyCode::Up | KeyCode::Char('k') if app.selected_index > 0 => {
            app.on_event(AppEvent::SelectIndex(app.selected_index - 1));
        }
        KeyCode::Down | KeyCode::Char('j') => {
            // Clamp to actual list length when in ProviderList mode
            let max = if app.mode == AppMode::ProviderList {
                all_provider_ids(state).len().saturating_sub(1)
            } else {
                usize::MAX
            };
            if app.selected_index < max {
                app.on_event(AppEvent::SelectIndex(app.selected_index + 1));
            }
        }
        KeyCode::Enter => {
            // In provider list, open edit view for the selected provider
            if app.mode == AppMode::ProviderList {
                let all_ids = all_provider_ids(state);
                if let Some(provider_id) = all_ids.get(app.selected_index) {
                    let provider = state.get_provider(provider_id);
                    let npm_val = provider.and_then(|p| p.npm.clone()).unwrap_or_default();
                    let form = EditProviderForm {
                        provider_id: provider_id.clone(),
                        focus: 0,
                        name: provider.and_then(|p| p.name.clone()).unwrap_or_default(),
                        sdk: SdkSelectState::from_value(&npm_val),
                        base_url: provider
                            .and_then(|p| p.options.as_ref())
                            .and_then(|opts| opts.get("baseURL"))
                            .and_then(|v| v.as_str())
                            .unwrap_or_default()
                            .to_string(),
                    };
                    app.mode = AppMode::EditProvider(form);
                }
            }
            // In model selector, add selected model to provider
            if app.mode == AppMode::ModelSelector {
                if let Some(ref provider_id) = app.selected_provider {
                    if let Some(model) = app.discovered_models.get(app.selected_index) {
                        let model_config = config_core::ModelConfig {
                            name: if model.name.is_empty() || model.name == model.id {
                                None
                            } else {
                                Some(model.name.clone())
                            },
                            limit: match (model.context_length, model.max_output_tokens) {
                                (None, None) => None,
                                (ctx, out) => Some(config_core::ModelLimit {
                                    context: ctx,
                                    output: out,
                                }),
                            },
                            ..Default::default()
                        };
                        if let Err(e) = state.add_model(
                            provider_id,
                            model.id.clone(),
                            model_config,
                            state.edit_layer,
                        ) {
                            app.error_message = Some(format!("Failed to add model: {e}"));
                        }
                    }
                }
            }
        }
        _ => {}
    }
    async_action
}

#[cfg(test)]
mod tests {
    use super::*;
    use app::state::AppState;
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    /// Helper to create a key event.
    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    /// Helper to create an App with a test config loaded.
    /// Returns (App, AppState). provider_ids() order is not guaranteed
    /// (HashMap), so tests must use provider_ids() to find indices.
    fn test_app_with_providers() -> (App, AppState) {
        let mut state = AppState::new().unwrap();
        // Add providers directly to the merged config for testing
        let mut providers = std::collections::HashMap::new();
        providers.insert(
            "openai".to_string(),
            config_core::ProviderConfig {
                name: Some("OpenAI".to_string()),
                npm: Some("openai".to_string()),
                options: None,
                models: Some({
                    let mut m = std::collections::HashMap::new();
                    m.insert("gpt-4o".to_string(), config_core::ModelConfig::default());
                    m
                }),
                disabled: None,
                extra: Default::default(),
            },
        );
        providers.insert(
            "anthropic".to_string(),
            config_core::ProviderConfig {
                name: Some("Anthropic".to_string()),
                npm: Some("@anthropic-ai/sdk".to_string()),
                options: Some({
                    let mut o = std::collections::HashMap::new();
                    o.insert(
                        "baseURL".to_string(),
                        serde_json::Value::String("https://api.anthropic.com".to_string()),
                    );
                    o
                }),
                models: None,
                disabled: None,
                extra: Default::default(),
            },
        );
        state.merged_config.provider = Some(providers);
        let app = App::new();
        (app, state)
    }

    /// Helper to find the index of a provider by ID.
    fn provider_index(state: &AppState, target_id: &str) -> usize {
        state
            .provider_ids()
            .iter()
            .position(|id| id == target_id)
            .unwrap_or(0)
    }

    // --- App creation ---

    #[test]
    fn test_app_new_defaults() {
        let app = App::new();
        assert_eq!(app.mode, AppMode::ProviderList);
        assert!(!app.should_quit);
        assert!(app.selected_provider.is_none());
        assert_eq!(app.selected_index, 0);
        assert!(app.error_message.is_none());
        assert!(app.discovered_models.is_empty());
        assert!(!app.models_loading);
    }

    // --- Mode switching ---

    #[test]
    fn test_switch_to_merged_view() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Char('1')), &mut app, &mut state);
        assert_eq!(app.mode, AppMode::MergedView);
    }

    #[test]
    fn test_switch_to_split_view() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Char('2')), &mut app, &mut state);
        assert_eq!(app.mode, AppMode::SplitView);
    }

    #[test]
    fn test_switch_to_auth_status() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Char('a')), &mut app, &mut state);
        assert_eq!(app.mode, AppMode::AuthStatus);
    }

    #[test]
    fn test_switch_to_config_detail() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Char('c')), &mut app, &mut state);
        assert_eq!(app.mode, AppMode::ConfigDetail);
    }

    #[test]
    fn test_help_toggle() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Char('?')), &mut app, &mut state);
        assert_eq!(app.mode, AppMode::Help);
        // Press ? again to go back
        handle_key_event(key(KeyCode::Char('?')), &mut app, &mut state);
        assert_eq!(app.mode, AppMode::ProviderList);
    }

    #[test]
    fn test_quit_from_provider_list() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Char('q')), &mut app, &mut state);
        assert!(app.should_quit);
    }

    #[test]
    fn test_esc_from_provider_list_quits() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Esc), &mut app, &mut state);
        assert!(app.should_quit);
    }

    #[test]
    fn test_esc_from_help_goes_back() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Char('?')), &mut app, &mut state);
        assert_eq!(app.mode, AppMode::Help);
        handle_key_event(key(KeyCode::Esc), &mut app, &mut state);
        assert_eq!(app.mode, AppMode::ProviderList);
        assert!(!app.should_quit);
    }

    // --- Navigation ---

    #[test]
    fn test_navigate_down() {
        let (mut app, mut state) = test_app_with_providers();
        assert_eq!(app.selected_index, 0);
        handle_key_event(key(KeyCode::Down), &mut app, &mut state);
        assert_eq!(app.selected_index, 1);
    }

    #[test]
    fn test_navigate_up() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Down), &mut app, &mut state);
        assert_eq!(app.selected_index, 1);
        handle_key_event(key(KeyCode::Up), &mut app, &mut state);
        assert_eq!(app.selected_index, 0);
    }

    #[test]
    fn test_navigate_j_k() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Char('j')), &mut app, &mut state);
        assert_eq!(app.selected_index, 1);
        handle_key_event(key(KeyCode::Char('k')), &mut app, &mut state);
        assert_eq!(app.selected_index, 0);
    }

    #[test]
    fn test_navigate_up_at_zero_does_nothing() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Up), &mut app, &mut state);
        assert_eq!(app.selected_index, 0);
    }

    // --- Error clearing ---

    #[test]
    fn test_error_cleared_on_next_key() {
        let (mut app, mut state) = test_app_with_providers();
        app.error_message = Some("test error".to_string());
        handle_key_event(key(KeyCode::Down), &mut app, &mut state);
        assert!(app.error_message.is_none());
    }

    // --- AddProvider form ---

    #[test]
    fn test_add_provider_opens() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Char('n')), &mut app, &mut state);
        assert!(matches!(app.mode, AppMode::AddProvider(_)));
    }

    #[test]
    fn test_add_provider_type_fields() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Char('n')), &mut app, &mut state);
        // Type provider ID
        for c in "test-provider".chars() {
            handle_key_event(key(KeyCode::Char(c)), &mut app, &mut state);
        }
        if let AppMode::AddProvider(ref form) = app.mode {
            assert_eq!(form.id, "test-provider");
            assert_eq!(form.focus, 0);
        }

        // Tab to name field
        handle_key_event(key(KeyCode::Tab), &mut app, &mut state);
        if let AppMode::AddProvider(ref form) = app.mode {
            assert_eq!(form.focus, 1);
        }
        for c in "Test Provider".chars() {
            handle_key_event(key(KeyCode::Char(c)), &mut app, &mut state);
        }
        if let AppMode::AddProvider(ref form) = app.mode {
            assert_eq!(form.name, "Test Provider");
        }

        // Tab to sdk field (now a selection list)
        handle_key_event(key(KeyCode::Tab), &mut app, &mut state);
        if let AppMode::AddProvider(ref form) = app.mode {
            assert_eq!(form.focus, 2);
        }
        // Navigate down to "Custom..." (last entry, index 7)
        for _ in 0..KNOWN_SDKS.len() - 1 {
            handle_key_event(key(KeyCode::Down), &mut app, &mut state);
        }
        // Press Enter to enter custom text mode
        handle_key_event(key(KeyCode::Enter), &mut app, &mut state);
        if let AppMode::AddProvider(ref form) = app.mode {
            assert!(form.sdk.custom_mode);
        }
        // Type custom SDK name
        for c in "@test/sdk".chars() {
            handle_key_event(key(KeyCode::Char(c)), &mut app, &mut state);
        }
        if let AppMode::AddProvider(ref form) = app.mode {
            assert_eq!(form.sdk.custom_text, "@test/sdk");
        }

        // Tab to base_url field
        handle_key_event(key(KeyCode::Tab), &mut app, &mut state);
        if let AppMode::AddProvider(ref form) = app.mode {
            assert_eq!(form.focus, 3);
        }
        for c in "https://api.test.com".chars() {
            handle_key_event(key(KeyCode::Char(c)), &mut app, &mut state);
        }
        if let AppMode::AddProvider(ref form) = app.mode {
            assert_eq!(form.base_url, "https://api.test.com");
        }
    }

    #[test]
    fn test_add_provider_tab_cycles() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Char('n')), &mut app, &mut state);
        // Tab 4 times should cycle back to 0
        for _ in 0..4 {
            handle_key_event(key(KeyCode::Tab), &mut app, &mut state);
        }
        if let AppMode::AddProvider(ref form) = app.mode {
            assert_eq!(form.focus, 0);
        }
    }

    #[test]
    fn test_add_provider_backspace() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Char('n')), &mut app, &mut state);
        handle_key_event(key(KeyCode::Char('a')), &mut app, &mut state);
        handle_key_event(key(KeyCode::Char('b')), &mut app, &mut state);
        handle_key_event(key(KeyCode::Backspace), &mut app, &mut state);
        if let AppMode::AddProvider(ref form) = app.mode {
            assert_eq!(form.id, "a");
        }
    }

    #[test]
    fn test_add_provider_empty_id_shows_error() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Char('n')), &mut app, &mut state);
        handle_key_event(key(KeyCode::Enter), &mut app, &mut state);
        assert!(app.error_message.is_some());
        assert!(app.error_message.unwrap().contains("cannot be empty"));
    }

    #[test]
    fn test_add_provider_esc_cancels() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Char('n')), &mut app, &mut state);
        handle_key_event(key(KeyCode::Esc), &mut app, &mut state);
        assert_eq!(app.mode, AppMode::ProviderList);
    }

    #[test]
    fn test_add_provider_submit_creates_provider() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Char('n')), &mut app, &mut state);

        // Type provider ID
        for c in "groq".chars() {
            handle_key_event(key(KeyCode::Char(c)), &mut app, &mut state);
        }
        // Tab to name
        handle_key_event(key(KeyCode::Tab), &mut app, &mut state);
        for c in "Groq".chars() {
            handle_key_event(key(KeyCode::Char(c)), &mut app, &mut state);
        }
        // Tab to npm
        handle_key_event(key(KeyCode::Tab), &mut app, &mut state);
        // Skip npm (empty)
        // Tab to base_url
        handle_key_event(key(KeyCode::Tab), &mut app, &mut state);
        // Skip base_url (empty)

        // Submit
        handle_key_event(key(KeyCode::Enter), &mut app, &mut state);

        assert_eq!(app.mode, AppMode::ProviderList);
        assert!(state.dirty);
        let ids = state.provider_ids();
        assert!(ids.contains(&"groq".to_string()));
        let provider = state.get_provider("groq").unwrap();
        assert_eq!(provider.name.as_deref(), Some("Groq"));
    }

    // --- EditProvider ---

    #[test]
    fn test_enter_opens_edit_provider() {
        let (mut app, mut state) = test_app_with_providers();
        let idx = provider_index(&state, "openai");
        app.selected_index = idx;
        handle_key_event(key(KeyCode::Enter), &mut app, &mut state);
        assert!(matches!(app.mode, AppMode::EditProvider(_)));
        if let AppMode::EditProvider(ref form) = app.mode {
            assert_eq!(form.provider_id, "openai");
            assert_eq!(form.name, "OpenAI");
            // "openai" is not in KNOWN_SDKS anymore, so custom mode
            assert!(form.sdk.custom_mode);
            assert_eq!(form.sdk.custom_text, "openai");
            assert_eq!(form.base_url, "");
        }
    }

    #[test]
    fn test_edit_provider_esc_cancels() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Enter), &mut app, &mut state);
        handle_key_event(key(KeyCode::Esc), &mut app, &mut state);
        assert_eq!(app.mode, AppMode::ProviderList);
    }

    #[test]
    fn test_edit_provider_edit_name() {
        let (mut app, mut state) = test_app_with_providers();
        // Copy merged into project_config so edit_provider_field has a target
        state.project_config = Some(state.merged_config.clone());
        let idx = provider_index(&state, "openai");
        app.selected_index = idx;
        handle_key_event(key(KeyCode::Enter), &mut app, &mut state);
        // Clear existing name and type new
        if let AppMode::EditProvider(ref form) = app.mode {
            assert_eq!(form.name, "OpenAI");
        }
        // Backspace to clear
        for _ in 0.."OpenAI".len() {
            handle_key_event(key(KeyCode::Backspace), &mut app, &mut state);
        }
        for c in "NewOpenAI".chars() {
            handle_key_event(key(KeyCode::Char(c)), &mut app, &mut state);
        }
        if let AppMode::EditProvider(ref form) = app.mode {
            assert_eq!(form.name, "NewOpenAI");
        }

        // Save
        handle_key_event(key(KeyCode::Enter), &mut app, &mut state);
        assert_eq!(app.mode, AppMode::ProviderList);
        let provider = state.get_provider("openai").unwrap();
        assert_eq!(provider.name.as_deref(), Some("NewOpenAI"));
    }

    #[test]
    fn test_edit_provider_tab_cycles() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Enter), &mut app, &mut state);
        for _ in 0..EditProviderForm::field_labels().len() {
            handle_key_event(key(KeyCode::Tab), &mut app, &mut state);
        }
        if let AppMode::EditProvider(ref form) = app.mode {
            assert_eq!(form.focus, 0);
        }
    }

    // --- EditProvider with baseURL ---

    #[test]
    fn test_edit_provider_shows_base_url() {
        let (mut app, mut state) = test_app_with_providers();
        // Select anthropic
        let idx = provider_index(&state, "anthropic");
        app.selected_index = idx;
        handle_key_event(key(KeyCode::Enter), &mut app, &mut state);
        if let AppMode::EditProvider(ref form) = app.mode {
            assert_eq!(form.provider_id, "anthropic");
            assert_eq!(form.base_url, "https://api.anthropic.com");
        }
    }

    // --- ConfirmDelete ---

    #[test]
    fn test_delete_opens_confirm() {
        let (mut app, mut state) = test_app_with_providers();
        let idx = provider_index(&state, "openai");
        app.selected_index = idx;
        handle_key_event(key(KeyCode::Char('d')), &mut app, &mut state);
        assert!(matches!(app.mode, AppMode::ConfirmDelete(_)));
        if let AppMode::ConfirmDelete(ref id) = app.mode {
            assert_eq!(id, "openai");
        }
    }

    #[test]
    fn test_delete_confirm_yes_removes() {
        let (mut app, mut state) = test_app_with_providers();
        let idx = provider_index(&state, "openai");
        app.selected_index = idx;
        handle_key_event(key(KeyCode::Char('d')), &mut app, &mut state);
        handle_key_event(key(KeyCode::Char('y')), &mut app, &mut state);
        assert_eq!(app.mode, AppMode::ProviderList);
        let ids = state.provider_ids();
        assert!(!ids.contains(&"openai".to_string()));
        assert!(state.dirty);
    }

    #[test]
    fn test_delete_confirm_n_cancels() {
        let (mut app, mut state) = test_app_with_providers();
        let original_count = state.provider_ids().len();
        handle_key_event(key(KeyCode::Char('d')), &mut app, &mut state);
        handle_key_event(key(KeyCode::Char('n')), &mut app, &mut state);
        assert_eq!(app.mode, AppMode::ProviderList);
        assert_eq!(state.provider_ids().len(), original_count);
    }

    #[test]
    fn test_delete_confirm_esc_cancels() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Char('d')), &mut app, &mut state);
        handle_key_event(key(KeyCode::Esc), &mut app, &mut state);
        assert_eq!(app.mode, AppMode::ProviderList);
    }

    // --- ConfirmRefresh ---

    #[test]
    fn test_refresh_when_dirty_shows_confirm() {
        let (mut app, mut state) = test_app_with_providers();
        state.dirty = true;
        handle_key_event(key(KeyCode::Char('r')), &mut app, &mut state);
        assert_eq!(app.mode, AppMode::ConfirmRefresh);
    }

    #[test]
    fn test_refresh_confirm_yes_reloads() {
        let (mut app, mut state) = test_app_with_providers();
        state.dirty = true;
        handle_key_event(key(KeyCode::Char('r')), &mut app, &mut state);
        handle_key_event(key(KeyCode::Char('y')), &mut app, &mut state);
        assert_eq!(app.mode, AppMode::ProviderList);
        assert!(!state.dirty);
    }

    #[test]
    fn test_refresh_confirm_n_cancels() {
        let (mut app, mut state) = test_app_with_providers();
        state.dirty = true;
        handle_key_event(key(KeyCode::Char('r')), &mut app, &mut state);
        handle_key_event(key(KeyCode::Char('n')), &mut app, &mut state);
        assert_eq!(app.mode, AppMode::ProviderList);
        assert!(state.dirty); // Still dirty
    }

    #[test]
    fn test_refresh_when_not_dirty_reloads_directly() {
        let (mut app, mut state) = test_app_with_providers();
        assert!(!state.dirty);
        handle_key_event(key(KeyCode::Char('r')), &mut app, &mut state);
        assert_eq!(app.mode, AppMode::ProviderList);
    }

    // --- ModelSelector ---

    #[test]
    fn test_m_key_triggers_model_fetch() {
        let (mut app, mut state) = test_app_with_providers();
        app.selected_index = 0;
        let action = handle_key_event(key(KeyCode::Char('m')), &mut app, &mut state);
        assert_eq!(app.mode, AppMode::ModelSelector);
        assert!(app.selected_provider.is_some());
        assert!(matches!(
            action,
            AsyncAction::FetchModels {
                force_refresh: false,
                ..
            }
        ));
    }

    #[test]
    fn test_r_in_model_selector_refetches() {
        let (mut app, mut state) = test_app_with_providers();
        // Enter model selector first
        let _ = handle_key_event(key(KeyCode::Char('m')), &mut app, &mut state);
        app.discovered_models = vec![discovery::DiscoveredModel {
            id: "gpt-5".to_string(),
            name: "GPT-5".to_string(),
            provider_id: "openai".to_string(),
            context_length: Some(128000),
            max_output_tokens: Some(16384),
            input_cost_per_million: Some(10.0),
            output_cost_per_million: Some(30.0),
        }];
        // Press r to refresh
        let action = handle_key_event(key(KeyCode::Char('r')), &mut app, &mut state);
        assert!(app.discovered_models.is_empty());
        assert!(matches!(
            action,
            AsyncAction::FetchModels {
                force_refresh: true,
                ..
            }
        ));
    }

    // --- Save ---

    #[test]
    fn test_save_marks_dirty() {
        let (mut app, mut state) = test_app_with_providers();
        state.dirty = true;
        // Save to a layer that has no path will fail, but the attempt is made
        let _ = handle_key_event(key(KeyCode::Char('s')), &mut app, &mut state);
        // Error expected since no real config file exists
        // Just verify it doesn't crash
    }

    // --- AddProvider with npm and baseURL ---

    #[test]
    fn test_add_provider_with_all_fields() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Char('n')), &mut app, &mut state);

        // Type ID
        for c in "mistral".chars() {
            handle_key_event(key(KeyCode::Char(c)), &mut app, &mut state);
        }
        // Tab → name
        handle_key_event(key(KeyCode::Tab), &mut app, &mut state);
        for c in "Mistral AI".chars() {
            handle_key_event(key(KeyCode::Char(c)), &mut app, &mut state);
        }
        // Tab → sdk (selection list — navigate to @ai-sdk/mistral at index 5)
        handle_key_event(key(KeyCode::Tab), &mut app, &mut state);
        for _ in 0..5 {
            handle_key_event(key(KeyCode::Down), &mut app, &mut state);
        }
        if let AppMode::AddProvider(ref form) = app.mode {
            assert_eq!(form.sdk.highlight, 5); // @ai-sdk/mistral
        }
        // Tab → base_url
        handle_key_event(key(KeyCode::Tab), &mut app, &mut state);
        for c in "https://api.mistral.ai".chars() {
            handle_key_event(key(KeyCode::Char(c)), &mut app, &mut state);
        }

        // Submit
        handle_key_event(key(KeyCode::Enter), &mut app, &mut state);

        assert_eq!(app.mode, AppMode::ProviderList);
        let provider = state.get_provider("mistral").unwrap();
        assert_eq!(provider.name.as_deref(), Some("Mistral AI"));
        assert_eq!(provider.npm.as_deref(), Some("@ai-sdk/mistral"));
        let base_url = provider
            .options
            .as_ref()
            .and_then(|o| o.get("baseURL"))
            .and_then(|v| v.as_str());
        assert_eq!(base_url, Some("https://api.mistral.ai"));
    }

    // --- BackTab in forms ---

    #[test]
    fn test_add_provider_shift_tab_goes_back() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Char('n')), &mut app, &mut state);
        // Tab to field 1
        handle_key_event(key(KeyCode::Tab), &mut app, &mut state);
        if let AppMode::AddProvider(ref form) = app.mode {
            assert_eq!(form.focus, 1);
        }
        // BackTab to field 0
        handle_key_event(key(KeyCode::BackTab), &mut app, &mut state);
        if let AppMode::AddProvider(ref form) = app.mode {
            assert_eq!(form.focus, 0);
        }
    }

    // --- Provider list ---

    #[test]
    fn test_all_provider_ids_returns_configured() {
        let (_app, state) = test_app_with_providers();
        let all = all_provider_ids(&state);
        // Should only have configured providers (openai + anthropic)
        assert_eq!(all.len(), state.provider_ids().len());
        // All configured providers should be present
        for id in state.provider_ids() {
            assert!(all.contains(&id));
        }
    }

    #[test]
    fn test_copy_source_list() {
        let (_app, state) = test_app_with_providers();
        let sources = copy_source_list(&state);
        // Should have exactly the configured providers
        assert_eq!(sources.len(), state.provider_ids().len());
        // Configured providers should be there
        for id in state.provider_ids() {
            assert!(sources.iter().any(|(sid, _)| *sid == id));
        }
    }

    #[test]
    fn test_add_provider_copy_mode() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Char('n')), &mut app, &mut state);
        // Press Ctrl+C to enter copy mode
        handle_key_event(
            KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL),
            &mut app,
            &mut state,
        );
        if let AppMode::AddProvider(ref form) = app.mode {
            assert!(form.show_copy_list);
        }
        // Press Esc to cancel copy
        handle_key_event(key(KeyCode::Esc), &mut app, &mut state);
        if let AppMode::AddProvider(ref form) = app.mode {
            assert!(!form.show_copy_list);
        }
    }

    #[test]
    fn test_add_provider_copy_selects() {
        let (mut app, mut state) = test_app_with_providers();
        handle_key_event(key(KeyCode::Char('n')), &mut app, &mut state);
        // Enter copy mode with Ctrl+C
        handle_key_event(
            KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL),
            &mut app,
            &mut state,
        );
        // Press Enter to select first provider in copy list
        handle_key_event(key(KeyCode::Enter), &mut app, &mut state);
        if let AppMode::AddProvider(ref form) = app.mode {
            assert!(!form.show_copy_list);
            // Should have pre-filled fields (auto ID since empty)
            assert!(!form.id.is_empty() || !form.name.is_empty());
        }
    }

    // --- Import ---

    #[test]
    fn test_i_opens_import() {
        let (mut app, mut state) = test_app_with_providers();
        app.mode = AppMode::ProviderList;
        handle_key_event(key(KeyCode::Char('i')), &mut app, &mut state);
        assert!(matches!(app.mode, AppMode::Import(_)));
    }

    #[test]
    fn test_import_esc_cancels() {
        let (mut app, mut state) = test_app_with_providers();
        app.mode = AppMode::Import(ImportForm::new());
        handle_key_event(key(KeyCode::Esc), &mut app, &mut state);
        assert_eq!(app.mode, AppMode::ProviderList);
    }

    #[test]
    fn test_import_tab_cycles() {
        let (mut app, mut state) = test_app_with_providers();
        app.mode = AppMode::Import(ImportForm::new());
        handle_key_event(key(KeyCode::Tab), &mut app, &mut state);
        if let AppMode::Import(ref form) = app.mode {
            assert_eq!(form.focus, 1);
        }
    }

    #[test]
    fn test_import_shift_tab_goes_back() {
        let (mut app, mut state) = test_app_with_providers();
        app.mode = AppMode::Import(ImportForm::new());
        handle_key_event(key(KeyCode::Tab), &mut app, &mut state);
        handle_key_event(key(KeyCode::BackTab), &mut app, &mut state);
        if let AppMode::Import(ref form) = app.mode {
            assert_eq!(form.focus, 0);
        }
    }

    #[test]
    fn test_import_type_source() {
        let (mut app, mut state) = test_app_with_providers();
        app.mode = AppMode::Import(ImportForm::new());
        for c in "https://example.com/config.json".chars() {
            handle_key_event(key(KeyCode::Char(c)), &mut app, &mut state);
        }
        if let AppMode::Import(ref form) = app.mode {
            assert_eq!(form.source, "https://example.com/config.json");
        }
    }

    #[test]
    fn test_import_empty_source_shows_error() {
        let (mut app, mut state) = test_app_with_providers();
        app.mode = AppMode::Import(ImportForm::new());
        handle_key_event(key(KeyCode::Enter), &mut app, &mut state);
        if let AppMode::Import(ref form) = app.mode {
            assert!(form.result_message.is_some());
            assert!(form.result_message.as_ref().unwrap().contains("empty"));
        }
    }

    #[test]
    fn test_import_layer_toggle() {
        let (mut app, mut state) = test_app_with_providers();
        let mut form = ImportForm::new();
        form.focus = 1; // layer field
        app.mode = AppMode::Import(form);
        handle_key_event(key(KeyCode::Down), &mut app, &mut state);
        if let AppMode::Import(ref form) = app.mode {
            assert_eq!(form.layer_index, 1); // global
        }
    }

    #[test]
    fn test_import_mode_toggle() {
        let (mut app, mut state) = test_app_with_providers();
        let mut form = ImportForm::new();
        form.focus = 2; // mode field
        app.mode = AppMode::Import(form);
        handle_key_event(key(KeyCode::Down), &mut app, &mut state);
        if let AppMode::Import(ref form) = app.mode {
            assert_eq!(form.mode_index, 1); // replace
        }
    }

    #[test]
    fn test_import_backspace() {
        let (mut app, mut state) = test_app_with_providers();
        let mut form = ImportForm::new();
        form.source = "test".to_string();
        app.mode = AppMode::Import(form);
        handle_key_event(key(KeyCode::Backspace), &mut app, &mut state);
        if let AppMode::Import(ref form) = app.mode {
            assert_eq!(form.source, "tes");
        }
    }

    // --- Copy to Global ---

    fn test_app_with_project_provider() -> (App, AppState) {
        let mut state = AppState::new().unwrap();
        state.edit_layer = config_core::ConfigLayer::Project;

        let mut project_models = std::collections::HashMap::new();
        project_models.insert("gpt-4o".to_string(), config_core::ModelConfig::default());
        let project_provider = config_core::ProviderConfig {
            npm: Some("@ai-sdk/openai".to_string()),
            name: Some("OpenAI".to_string()),
            models: Some(project_models),
            ..Default::default()
        };
        state.project_config = Some(config_core::OpenCodeConfig::default());
        state
            .project_config
            .as_mut()
            .unwrap()
            .provider
            .get_or_insert_with(std::collections::HashMap::new)
            .insert("openai".to_string(), project_provider);
        state.recompute_merged();
        let app = App::new();
        (app, state)
    }

    #[test]
    fn test_g_copies_provider_to_global() {
        let (mut app, mut state) = test_app_with_project_provider();
        let idx = provider_index(&state, "openai");
        app.selected_index = idx;

        handle_key_event(key(KeyCode::Char('g')), &mut app, &mut state);

        // Success message shown
        assert!(app.error_message.is_some());
        let msg = app.error_message.as_ref().unwrap();
        assert!(msg.contains("openai"), "message should mention provider id");

        // Global config should now contain the provider
        let global = state.global_config.as_ref().unwrap();
        assert!(global.provider.as_ref().unwrap().contains_key("openai"));
        assert!(state.dirty);
        // edit_layer should have switched to Global so 's' saves the right file
        assert_eq!(state.edit_layer, config_core::ConfigLayer::Global);
    }

    #[test]
    fn test_g_noop_in_other_modes() {
        let (mut app, mut state) = test_app_with_project_provider();
        app.mode = AppMode::MergedView;

        handle_key_event(key(KeyCode::Char('g')), &mut app, &mut state);

        // Should not have created a global config or mutated dirty
        assert!(state.global_config.is_none() || !state.dirty);
    }

    // --- ModelSelector: DiscoverySource toggle ---

    #[test]
    fn test_discovery_source_default_is_models_dev() {
        let app = App::new();
        assert_eq!(app.discovery_source, DiscoverySource::ModelsDev);
    }

    #[test]
    fn test_t_toggles_discovery_source() {
        let (mut app, mut state) = test_app_with_providers();
        // Enter model selector
        let _ = handle_key_event(key(KeyCode::Char('m')), &mut app, &mut state);
        assert_eq!(app.mode, AppMode::ModelSelector);
        assert_eq!(app.discovery_source, DiscoverySource::ModelsDev);

        // Toggle to ProviderApi
        handle_key_event(key(KeyCode::Char('t')), &mut app, &mut state);
        assert_eq!(app.discovery_source, DiscoverySource::ProviderApi);

        // Toggle back to ModelsDev
        handle_key_event(key(KeyCode::Char('t')), &mut app, &mut state);
        assert_eq!(app.discovery_source, DiscoverySource::ModelsDev);
    }

    #[test]
    fn test_t_only_works_in_model_selector() {
        let (mut app, mut state) = test_app_with_providers();
        assert_eq!(app.mode, AppMode::ProviderList);

        handle_key_event(key(KeyCode::Char('t')), &mut app, &mut state);

        // Source should not change outside ModelSelector
        assert_eq!(app.discovery_source, DiscoverySource::ModelsDev);
    }

    // --- ModelSelector: ModelConfig pre-fill ---

    #[test]
    fn test_enter_in_model_selector_prefills_model_config() {
        let (mut app, mut state) = test_app_with_project_provider();
        app.mode = AppMode::ModelSelector;
        app.selected_provider = Some("openai".to_string());
        app.selected_index = 0;

        // Simulate a discovered model with metadata
        app.discovered_models = vec![discovery::DiscoveredModel {
            id: "gpt-4o".to_string(),
            name: "GPT-4o".to_string(),
            provider_id: "openai".to_string(),
            context_length: Some(128_000),
            max_output_tokens: Some(16_384),
            input_cost_per_million: Some(5.0),
            output_cost_per_million: Some(15.0),
        }];

        handle_key_event(key(KeyCode::Enter), &mut app, &mut state);

        // The model should now be in the merged config with pre-filled data
        let provider = state.get_provider("openai").unwrap();
        let models = provider.models.as_ref().unwrap();
        let model = models.get("gpt-4o").unwrap();

        // Name should be set since it differs from the ID
        assert_eq!(model.name.as_deref(), Some("GPT-4o"));
        // Limit should be pre-filled from discovery data
        let limit = model.limit.as_ref().unwrap();
        assert_eq!(limit.context, Some(128_000));
        assert_eq!(limit.output, Some(16_384));
    }

    #[test]
    fn test_enter_in_model_selector_name_not_set_when_same_as_id() {
        let (mut app, mut state) = test_app_with_project_provider();
        app.mode = AppMode::ModelSelector;
        app.selected_provider = Some("openai".to_string());
        app.selected_index = 0;

        // Model where name == id (common for provider API discovery)
        app.discovered_models = vec![discovery::DiscoveredModel {
            id: "gpt-4o".to_string(),
            name: "gpt-4o".to_string(), // same as id
            provider_id: "openai".to_string(),
            context_length: None,
            max_output_tokens: None,
            input_cost_per_million: None,
            output_cost_per_million: None,
        }];

        handle_key_event(key(KeyCode::Enter), &mut app, &mut state);

        let provider = state.get_provider("openai").unwrap();
        let models = provider.models.as_ref().unwrap();
        let model = models.get("gpt-4o").unwrap();

        // Name should NOT be set since it equals the id
        assert_eq!(model.name, None);
        // No limit when context_length and max_output_tokens are None
        assert_eq!(model.limit, None);
    }
}