atomcode-core 4.23.1

Open-source terminal AI coding agent
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
// crates/atomcode-core/src/coding_plan/setup.rs
//
// Orchestrator for the 4-step CodingPlan flow. Single `run` entrypoint
// shared by the CLI subcommand and the TUI slash command; both render
// the returned `SetupReport` their own way (stdout vs. body scrollback).
//
// Failure policy (matches product spec D5):
//
//   Step 1 Login  — if not logged in and OAuth fails → bail out (nothing
//                   downstream works without a token).
//   Step 2 Claim  — `duplicate=true` means "already claimed / in review"
//                   — report it as a skip, NOT an error, and continue.
//                   Transport/5xx errors → bail (server is in a bad state).
//   Step 3 Models — empty list or request failure → bail. The whole point
//                   of the flow is setting up providers; without models
//                   we have nothing to install.
//   Step 4 Status — warn-only. The plan is already set up; a failed
//                   status fetch just means we can't show the quota
//                   widget. User can retry with `/codingplan` later.
//
// Provider mutation (D2 + D4):
//
//   - All previously-created `AtomGit*` entries are wiped before inserts.
//     Since CodingPlan is the authoritative source of truth for the
//     model list, keeping stale names around would confuse `/model`.
//   - Single model → one provider named `AtomGit`.
//   - Multiple models → one provider per model, named
//     `AtomGit-{display_model_name}` with `/` → `-` (keeps config.toml
//     section names clean — `[providers.AtomGit-moonshotai-Kimi-K2]`).
//   - `default_provider` is set to the first model in the API order.

use anyhow::Result;
use std::sync::Arc;

use super::client::{is_auth_expired, Client};
use super::types::{ModelEntry, PlanType, StatusResponse};
use crate::auth;
use crate::config::provider::ProviderConfig;
use crate::config::Config;

/// Default LLM gateway base URL for CodingPlan-managed providers when
/// the `models-v2` payload doesn't carry a per-model `base_url`. Used
/// only inside [`codingplan_llm_base_url`] — call that, not this.
///
/// The new signed gateway. `coding_plan::crypto::is_atomgit_gateway`
/// **only** matches `llm-api.atomgit.com` (see the host whitelist at
/// `crypto.rs:129`), so this is the URL where codingplan request
/// signing actually engages. The previous default (the legacy
/// `api-ai.gitcode.com` host) silently routed new installs to a
/// plaintext path that bypassed signing — and surfaced in users'
/// error logs as "my requests go to a URL I never configured."
const DEFAULT_CODINGPLAN_LLM_BASE_URL: &str = "https://llm-api.atomgit.com/v1";

/// Resolve the LLM gateway base URL for CodingPlan-managed providers.
///
/// Read order:
///   1. `ATOMCODE_CODINGPLAN_LLM_BASE_URL` env var (trimmed, trailing
///      `/` stripped, empty value treated as unset). Set this when
///      pointing the client at a staging gateway.
///   2. [`DEFAULT_CODINGPLAN_LLM_BASE_URL`].
///
/// Cached once at first call via `OnceLock` — same shape as
/// [`auth::oauth::platform_base_url`] — so every provider registered
/// by `step_models_and_register` lands on the same host even if the
/// env var changes mid-flight, and the per-provider build cost is
/// one atomic read after the first call.
///
/// Returns `String` rather than `&'static str` because the cached
/// value's lifetime is tied to the `OnceLock`; callers that need an
/// owned URL (e.g. `ProviderConfig::base_url: Option<String>`) get
/// one without an extra clone.
fn codingplan_llm_base_url() -> String {
    use std::sync::OnceLock;
    static URL: OnceLock<String> = OnceLock::new();
    URL.get_or_init(|| {
        std::env::var("ATOMCODE_CODINGPLAN_LLM_BASE_URL")
            .ok()
            .map(|v| v.trim().trim_end_matches('/').to_string())
            .filter(|v| !v.is_empty())
            .unwrap_or_else(|| DEFAULT_CODINGPLAN_LLM_BASE_URL.to_string())
    })
    .clone()
}

/// Provider type for the AtomGit LLM gateway (it's OpenAI-compatible).
const PROVIDER_TYPE: &str = "openai";

/// Context window for each coding-plan provider. The models endpoint
/// doesn't currently return a per-model window, so we apply the same
/// 64k value that the legacy `/login` flow hard-coded.
const CONTEXT_WINDOW: usize = 64_000;

/// Prefix used for every coding-plan-managed provider name.
const PROVIDER_PREFIX: &str = "AtomGit";

/// Result of one orchestrator step. Distinct from `Result` because
/// "already done / idempotent skip" is a first-class outcome, not an
/// error — the report needs to tell the user "you already claimed this
/// last week" in the same place it'd tell them "just claimed".
#[derive(Debug, Clone)]
pub enum StepResult<T> {
    /// Step ran and completed with the carried payload.
    Ok(T),
    /// Step was idempotent-skipped (already logged in, already claimed).
    /// The string is a human-readable reason for display.
    Skipped(String),
    /// Step failed. The string is a human-readable error.
    Err(String),
}

impl<T> StepResult<T> {
    pub fn is_err(&self) -> bool {
        matches!(self, StepResult::Err(_))
    }
    pub fn is_ok_or_skipped(&self) -> bool {
        !self.is_err()
    }
}

/// Describes how the auto-detected vision_preprocessor_provider was
/// (or was not) updated by `step_models_and_register`. Surfaces in
/// `SetupReport::render` so the user can see what happened to that
/// config knob across the /codingplan flow.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VisionPreprocessorOutcome {
    /// Field was None and remains None (no VL/OCR in list).
    UnchangedNone,
    /// Field was a non-AtomGit user-supplied value; preserved.
    /// Carries the value for display.
    UserSupplied(String),
    /// Field was None or a stale AtomGit-* key; auto-pointed at a
    /// vision-capable provider in the freshly-installed list.
    /// Carries the new key.
    AutoSet(String),
    /// Field was an AtomGit-* key but the new list has no VL/OCR
    /// candidate, so the field was cleared to None to avoid pointing
    /// at a wiped provider key.
    Cleared,
}

impl SetupReport {
    /// Render as a multi-line plain-text block for stdout / TUI body.
    /// Shared by the CLI subcommand and the `/codingplan` slash command
    /// so the visual contract stays consistent.
    pub fn render(&self) -> String {
        use crate::i18n::{t, Msg};

        let mut out = String::new();
        out.push_str(&t(Msg::CpSetupHeader));

        // Step 1: login
        match &self.login {
            StepResult::Ok(info) => {
                let who = info.display_name.as_deref().unwrap_or(&info.username);
                let email = info.email.as_deref().unwrap_or("");
                out.push_str(&t(Msg::CpLoggedIn {
                    who,
                    username: &info.username,
                    email,
                }));
            }
            StepResult::Skipped(reason) => {
                out.push_str(&t(Msg::CpStepSkipped { reason }));
            }
            StepResult::Err(msg) => {
                out.push_str(&t(Msg::CpLoginFailed { error: msg }));
            }
        }

        // Step 2: claim. When `claim_attempts` is populated (production
        // path), emit one row per tier so refused / errored
        // intermediates are visible alongside the winner. When empty
        // (login-cascade suppression OR legacy test fixtures), fall
        // back to a single summary row from `self.claim` — preserves
        // pre-refactor test semantics without churning every fixture.
        if !self.claim_attempts.is_empty() {
            for attempt in &self.claim_attempts {
                let tier = attempt.tier.as_str();
                match &attempt.outcome {
                    TierOutcome::Claimed { .. } => {
                        out.push_str(&t(Msg::CpClaimTierSucceeded { tier }));
                    }
                    TierOutcome::AlreadyHeld { .. } => {
                        out.push_str(&t(Msg::CpClaimTierAlreadyHeld { tier }));
                    }
                    TierOutcome::Refused { message } => {
                        let reason = if message.is_empty() {
                            // Server returned success=false +
                            // duplicate=false with no message — surface
                            // a placeholder so the row isn't a
                            // confusing "claim failed — " with nothing
                            // after the em-dash.
                            "(no reason given)"
                        } else {
                            message.as_str()
                        };
                        out.push_str(&t(Msg::CpClaimTierFailed { tier, reason }));
                    }
                    TierOutcome::Errored { error } => {
                        // 5xx / transport / parse — same "claim
                        // failed" glyph as Refused; the message is
                        // the error text (truncated so a stack
                        // trace doesn't blow up the row).
                        let reason = truncate_inline(error, 150);
                        out.push_str(&t(Msg::CpClaimTierFailed {
                            tier,
                            reason: &reason,
                        }));
                    }
                }
            }
        } else {
            match &self.claim {
                StepResult::Ok(info) => {
                    let fallback = t(Msg::CpClaimSuccessFallback);
                    let message = if info.message.is_empty() {
                        fallback.as_ref()
                    } else {
                        info.message.as_str()
                    };
                    out.push_str(&t(Msg::CpClaimed {
                        message,
                        plan_type: info.plan_type.as_str(),
                    }));
                }
                StepResult::Skipped(reason) if reason == CASCADE_FROM_UPSTREAM_FAIL => {
                    // Cascade from login failure — suppressed.
                }
                StepResult::Skipped(reason) => {
                    out.push_str(&t(Msg::CpAlreadyClaimed { reason }));
                }
                StepResult::Err(msg) => {
                    out.push_str(&t(Msg::CpClaimFailed { error: msg }));
                }
            }
        }

        // Step 3: models. When the cascade marker is present (claim
        // failed upstream), skip the row entirely — printing
        // "Models step skipped — claim failed" right after the claim
        // failure line is just noise. Same for the status row below.
        match &self.models {
            StepResult::Ok(info) => {
                let count = info.provider_names.len();
                let plural_s = if count == 1 { "" } else { "s" };
                out.push_str(&t(Msg::CpAddedProviders { count, plural_s }));
                // Build a quick lookup of which display names made it
                // into the registered provider list — anything in
                // `all_models` but NOT in this set is locked behind
                // the user's plan tier.
                let registered: std::collections::HashSet<&str> =
                    info.display_names.iter().map(|s| s.as_str()).collect();
                // Locked models render FIRST so the upgrade prompt is the
                // first thing the eye lands on under "Added N providers:".
                // Visual cue is an `✗` prefix matching the existing
                // failure rows (`✗ CodingPlan Max claim failed — …`)
                // plus the explicit `(requires Pro plan or higher)` suffix —
                // both plain text, so every renderer (alt-screen /
                // retained / plain) and every terminal font carries
                // the meaning. An earlier U+0336 combining strikethrough
                // pass was dropped after a user report that fonts in
                // the wild silently skip the overlay glyph; the SGR 9
                // approach before that was eaten by the TUI's CSI
                // sanitizer (`tuix::sanitize::scrub_controls`). The
                // prefix-plus-suffix combo doesn't depend on either.
                let locked: Vec<&ModelEntry> = info
                    .all_models
                    .iter()
                    .filter(|m| !m.plan_available && !registered.contains(m.display_model_name.as_str()))
                    .collect();
                for m in &locked {
                    out.push_str(&t(Msg::CpLocked {
                        name: &m.display_model_name,
                    }));
                }
                let default_suffix_cow = t(Msg::CpDefaultSuffix);
                for (pname, model) in info.provider_names.iter().zip(info.display_names.iter()) {
                    let suffix = if pname == &info.default_provider {
                        default_suffix_cow.as_ref()
                    } else {
                        ""
                    };
                    out.push_str(&t(Msg::CpProviderRow {
                        provider: pname,
                        model,
                        default_suffix: suffix,
                    }));
                }
                // Vision-preprocessor outcome line.
                match &info.vision_preprocessor {
                    VisionPreprocessorOutcome::AutoSet(k) => {
                        out.push_str(&t(Msg::CpVisionAuto { kind: k }));
                    }
                    VisionPreprocessorOutcome::UserSupplied(k) => {
                        out.push_str(&t(Msg::CpVisionUserSupplied { kind: k }));
                    }
                    VisionPreprocessorOutcome::Cleared => {
                        out.push_str(&t(Msg::CpVisionCleared));
                    }
                    VisionPreprocessorOutcome::UnchangedNone => {
                        // No-op: nothing to say when both the previous and
                        // new state are "no preprocessor configured".
                    }
                }
            }
            StepResult::Skipped(reason) if reason == CASCADE_FROM_UPSTREAM_FAIL => {
                // Suppress — claim failure line above is the explanation.
            }
            StepResult::Skipped(reason) => {
                out.push_str(&t(Msg::CpModelsSkipped { reason }));
            }
            StepResult::Err(msg) => {
                out.push_str(&t(Msg::CpModelsFailed { error: msg }));
            }
        }

        // Step 4: status
        match &self.status {
            StepResult::Ok(s) => {
                out.push_str(&t(Msg::CpStatusHeader));
                if let Some(plan) = &s.codingplan_free {
                    if plan.expires_at.is_empty() {
                        // Backend sends null claimed_at/expires_at while a
                        // fresh claim is still propagating. Don't render an
                        // empty date with `(0d / 0d remaining)` zeros — say
                        // "pending activation" so the user knows to wait.
                        out.push_str(&t(Msg::CpPlanPending { plan: &plan.plan_name }));
                    } else {
                        out.push_str(&t(Msg::CpPlanActive {
                            plan: &plan.plan_name,
                            expires_at: &plan.expires_at,
                            remaining_days: plan.remaining_days,
                            total_days: plan.total_days,
                        }));
                    }
                }
                if let Some(u) = &s.current_usage {
                    out.push_str(&t(Msg::CpUsageLine {
                        usage: &u.display_desc(),
                        reset_at: &u.reset_at_display,
                        duration: &format_duration_secs(u.seconds_until_reset),
                    }));
                }
                if s.window_quota_exhausted {
                    if let Some(hint) = &s.window_quota_hint {
                        out.push_str(&t(Msg::CpWindowQuotaHint { hint }));
                    } else {
                        out.push_str(&t(Msg::CpWindowQuotaExhausted));
                    }
                }
            }
            StepResult::Skipped(reason) if reason == CASCADE_FROM_UPSTREAM_FAIL => {
                // Suppress — cascade from claim failure.
            }
            StepResult::Skipped(reason) => {
                out.push_str(&t(Msg::CpStatusFetchSkipped { reason }));
            }
            StepResult::Err(msg) => {
                // Truncate the error chain so a server-side parse failure
                // doesn't dump the entire response body inline. The cause
                // chain commonly includes the raw JSON via anyhow's
                // `with_context(format!("(body: {})", body))`, easily
                // 200+ chars; the diagnostic value beyond ~150 is low.
                out.push_str(&t(Msg::CpStatusFetchFailed {
                    error: &truncate_inline(msg, 150),
                }));
            }
        }

        out
    }

    /// True iff every persist-relevant step (login + claim + models)
    /// either succeeded outright or was skipped non-fatally (server
    /// reported `duplicate=true`, model list already current, etc.).
    /// Callers use this to decide whether to persist config changes
    /// to disk.
    ///
    /// `claim` MUST be in the predicate: when claim returns `Err`
    /// (e.g. backend 500 like the AtomGit `claim-v2` transaction-
    /// rollback bug), `run()` short-circuits and parks `models` as
    /// `Skipped(CASCADE_FROM_UPSTREAM_FAIL)` so the report stays
    /// focused on the actual failure. Without the claim check the
    /// gate flipped to `true` on every claim-failure path —
    /// triggering `save_and_reload` to rewrite `config.toml`
    /// unconditionally. That clobbered any manual edits the user
    /// made between TUI startup and `/codingplan`, and read as
    /// "claim failed but it still wrote models to my config".
    pub fn should_persist_config(&self) -> bool {
        self.login.is_ok_or_skipped()
            && self.claim.is_ok_or_skipped()
            && self.models.is_ok_or_skipped()
    }
}

/// Display-friendly summary of each step's outcome. Returned by `run`
/// so the caller can render however it wants (plain stdout, TUI body
/// scrollback, future JSON output for scripting).
#[derive(Debug, Clone)]
pub struct SetupReport {
    pub login: StepResult<LoginInfo>,
    pub claim: StepResult<ClaimInfo>,
    /// Per-tier cascade history. Populated by `step_claim` with one
    /// entry per tier actually attempted (in cascade order Max → Pro
    /// → Lite). Empty when the cascade never ran (e.g. login failed
    /// upstream — claim is `Skipped(CASCADE_FROM_UPSTREAM_FAIL)`) or
    /// when a legacy test fixture wants the old single-row claim
    /// summary. `render` walks this to emit one row per tier so
    /// refused / errored intermediate tiers are visible, not hidden
    /// behind a single "claim failed" summary.
    pub claim_attempts: Vec<TierAttempt>,
    pub models: StepResult<ModelsInfo>,
    pub status: StepResult<StatusResponse>,
    /// True when any API call rejected the stored bearer token
    /// (401/403). `is_logged_in()` only checks "does auth.toml exist"
    /// and `get_valid_token` only refreshes when the recorded
    /// `expires_in` says so — neither catches a server-side revocation
    /// or a refresh-token that the broker no longer accepts. Shells
    /// (TUI `/codingplan`, CLI `atomcode codingplan`) read this flag
    /// to drive an inline re-OAuth + retry instead of leaving the user
    /// staring at a "claim failed — run `atomcode login` again" line
    /// when `/login` would have fixed it in one step.
    pub auth_expired: bool,
}

#[derive(Debug, Clone)]
pub struct LoginInfo {
    pub username: String,
    pub display_name: Option<String>,
    pub email: Option<String>,
}

#[derive(Debug, Clone)]
pub struct ClaimInfo {
    pub message: String,
    /// true when server reported `duplicate=true` — surfaces in the
    /// rendered report as "(already claimed)" rather than "(just claimed)".
    pub duplicate: bool,
    /// The CodingPlan tier the cascade landed on. `Max` if the
    /// highest-tier claim succeeded, `Pro` / `Lite` for fallbacks.
    /// Threaded into `step_models_and_register` as the `?plan_type=`
    /// argument so the model list comes back with availability gated
    /// to the user's actual entitlement.
    pub plan_type: PlanType,
}

/// Per-tier outcome captured while `step_claim` walks the cascade.
/// Surfaces in `SetupReport::render` as one row per attempted tier so
/// the user can see exactly why the cascade stopped where it did — a
/// single "claim failed: Lite: 暂无开放" line hid the Max / Pro tier
/// rejections users wanted to see.
#[derive(Debug, Clone)]
pub enum TierOutcome {
    /// `success=true` on this tier — cascade winner.
    Claimed { message: String },
    /// `duplicate=true` — user already held this (or a higher) tier;
    /// cascade treats this as winner and stops.
    AlreadyHeld { message: String },
    /// `2xx success=false duplicate=false` — per-tier refusal (e.g.
    /// `额度已满` / `暂无开放`). Cascade walks past to the next tier.
    Refused { message: String },
    /// Transport / 5xx / parse failure. Cascade aborts.
    Errored { error: String },
}

#[derive(Debug, Clone)]
pub struct TierAttempt {
    pub tier: PlanType,
    pub outcome: TierOutcome,
}

#[derive(Debug, Clone)]
pub struct ModelsInfo {
    /// Model names of the **available** subset, in server order.
    /// Parallel to `provider_names` — these are the entries that
    /// actually got registered as providers.
    pub display_names: Vec<String>,
    /// Provider keys actually inserted into Config (available only).
    pub provider_names: Vec<String>,
    /// Which of `provider_names` was set as `default_provider`.
    pub default_provider: String,
    /// Outcome of vision_preprocessor_provider auto-config. Drives the
    /// "Vision preprocessor → ..." line in the rendered report.
    pub vision_preprocessor: VisionPreprocessorOutcome,
    /// Full v2 model list — including `plan_available=false` entries
    /// that we didn't register as providers. Renderer iterates this
    /// to show locked models with strikethrough so users see what
    /// upgrading the plan would unlock.
    pub all_models: Vec<ModelEntry>,
}

/// Entry point. Mutates `config` in place (providers + default_provider);
/// the caller is responsible for persisting it to disk after a successful
/// run. This keeps the core free of I/O concerns — tests can call `run`
/// against a `Config::default()` without touching the filesystem.
///
/// Emits exactly one `TakeCodingplan { Success | Fail }` event at each exit path.
pub fn run(
    config: &mut Config,
    tel: Option<&Arc<atomcode_telemetry::Telemetry>>,
) -> Result<SetupReport> {
    // Step 1: login
    let login = step_login(tel);
    if login.is_err() {
        // No point continuing — every downstream call needs a token.
        if let Some(t) = tel {
            t.track(atomcode_telemetry::Event::TakeCodingplan {
                type_: atomcode_telemetry::CodingplanResult::Fail,
                error_kind: Some(atomcode_telemetry::CodingplanErrorKind::AuthError),
                error_data: Some(serde_json::json!({
                    "step": "login",
                    "message": "Not logged in",
                }).to_string()),
            });
        }
        // Use the cascade sentinel so format() suppresses the three
        // "Foo failed — skipped: login failed" rows that used to spam
        // the report. The login-failure line above is the only thing
        // worth showing; the rest is implied.
        return Ok(SetupReport {
            login,
            claim: StepResult::Skipped(CASCADE_FROM_UPSTREAM_FAIL.into()),
            claim_attempts: Vec::new(),
            models: StepResult::Skipped(CASCADE_FROM_UPSTREAM_FAIL.into()),
            status: StepResult::Skipped(CASCADE_FROM_UPSTREAM_FAIL.into()),
            auth_expired: false,
        });
    }

    // Step 2: claim — cascade Max → Pro → Lite, first success wins.
    let (claim, claim_attempts, claim_auth_expired) = step_claim();
    if claim.is_err() {
        // Claim failed at every tier — adding providers / fetching
        // status both make no sense without an active plan. Bail
        // with cascade markers for models/status; `claim_attempts`
        // still carries every tier's outcome so the renderer shows
        // the per-tier rows that explain WHY the cascade gave up.
        return Ok(SetupReport {
            login,
            claim,
            claim_attempts,
            models: StepResult::Skipped(CASCADE_FROM_UPSTREAM_FAIL.into()),
            status: StepResult::Skipped(CASCADE_FROM_UPSTREAM_FAIL.into()),
            auth_expired: claim_auth_expired,
        });
    }

    // Decide the plan_type to send to /models-v2. Three sources:
    //   * Fresh `Ok` claim: use the tier the cascade landed on.
    //   * `Skipped` (server returned `duplicate=true` at one of the
    //     tiers): step_claim picked the tier it stopped at; we don't
    //     have the structured value here, so fall back to Max — the
    //     server will gate availability the same way regardless. Pro
    //     and Lite users will see Pro/Max-tier models marked
    //     `plan_available=false` and rendered with strikethrough,
    //     which matches the spec ("show locked models too").
    //   * (Err is unreachable here — handled above.)
    let plan_type_for_models = match &claim {
        StepResult::Ok(info) => info.plan_type,
        _ => PlanType::Max,
    };

    // Step 3: models — critical. Without models there's nothing to set up.
    let (models, models_auth_expired) = step_models_and_register(config, plan_type_for_models);
    if models.is_err() {
        if let Some(t) = tel {
            t.track(atomcode_telemetry::Event::TakeCodingplan {
                type_: atomcode_telemetry::CodingplanResult::Fail,
                error_kind: Some(atomcode_telemetry::CodingplanErrorKind::NetworkError),
                error_data: Some(serde_json::json!({
                    "step": "models",
                    "message": "Failed to fetch model list",
                }).to_string()),
            });
        }
        // Same cascade pattern: the models-failure line above is the
        // explanation; "Status fetch failed — skipped: models step
        // failed" adds nothing.
        return Ok(SetupReport {
            login,
            claim,
            claim_attempts,
            models,
            status: StepResult::Skipped(CASCADE_FROM_UPSTREAM_FAIL.into()),
            auth_expired: models_auth_expired,
        });
    }

    // Step 4: status — warn-only. A 401 here is rare (claim+models
    // both passed) but still worth surfacing so a retry has a chance
    // to capture the warm token.
    let (status, status_auth_expired) = step_status();

    // All critical steps (login + models) succeeded. Emit success event.
    if let Some(t) = tel {
        t.track(atomcode_telemetry::Event::TakeCodingplan {
            type_: atomcode_telemetry::CodingplanResult::Success,
            error_kind: None,
            error_data: Some(serde_json::json!({
                "step": null,
            }).to_string()),
        });
    }

    Ok(SetupReport {
        login,
        claim,
        claim_attempts,
        models,
        status,
        auth_expired: status_auth_expired,
    })
}

/// Sentinel reason used when downstream steps are skipped because an
/// earlier required step failed (login / claim / models). `format()`
/// recognises this exact string and renders nothing — the upstream
/// failure line above already explains why nothing came after it.
const CASCADE_FROM_UPSTREAM_FAIL: &str = "__cascade_upstream_fail__";

fn step_login(tel: Option<&Arc<atomcode_telemetry::Telemetry>>) -> StepResult<LoginInfo> {
    if auth::is_logged_in() {
        // Already authed — surface the stored identity so the report
        // shows *who* we're running as, not a bare "skipped". When
        // display-name and username differ (the common case), show
        // both so the user can tell them apart: `TheoCui(saulcy)`.
        if let Some(info) = auth::get_stored_auth() {
            let display = match info.user.name.as_deref() {
                Some(name) if !name.is_empty() && name != info.user.username => {
                    format!("{}({})", name, info.user.username)
                }
                _ => info.user.username.clone(),
            };
            return StepResult::Skipped(format!("already logged in as {}", display));
        }
        // Weird: is_logged_in said yes but stored auth is None. Treat
        // as "login succeeded, details unavailable" rather than failing.
        return StepResult::Skipped("already logged in".into());
    }
    // Not logged in — run OAuth. This prints to stdout + opens a browser.
    // Callers in TUI context must have already suspended raw mode before
    // calling `run`.
    match auth::login(tel).and_then(|a| auth::save_auth(&a).map(|_| a)) {
        Ok(auth_info) => StepResult::Ok(LoginInfo {
            username: auth_info.user.username.clone(),
            display_name: auth_info.user.name.clone(),
            email: auth_info.user.email.clone(),
        }),
        Err(e) => StepResult::Err(format!("login failed: {:#}", e)),
    }
}

/// Walk `PlanType::CASCADE_ORDER` (Max → Pro → Lite), POSTing
/// `claim-v2` for each tier, and stop at the first that lands the
/// user with an entitlement. Two outcomes count as "stop":
///
///   * `success=true`              — fresh claim of this tier.
///   * `duplicate=true`            — user already holds this tier (or
///                                   higher). Treat as success and use
///                                   this tier as the working tier;
///                                   trying lower tiers wouldn't help.
///
/// `success=false && duplicate=false` for a 2xx response is a per-tier
/// "you can't have this" signal (e.g. quota exhausted at the Max tier
/// but Pro/Lite slots still open). Try the next tier with the message
/// preserved as the "last error" we'll show if everything below also
/// fails.
///
/// Transport / 5xx errors abort the whole cascade — those mean the
/// server is in a bad state, not "this tier is unavailable", so
/// retrying lower tiers would just stack identical failures.
/// Walk the cascade and capture every tier's outcome.
///
/// Returns `(overall, attempts, auth_expired)`:
/// * `overall` — the legacy single-summary view of what happened
///   (`Ok` / `Skipped` / `Err`). Drives `should_persist_config` and
///   the downstream `step_models_and_register` plan-type selection.
/// * `attempts` — every tier actually attempted, in cascade order.
///   Renderer walks this to emit one row per tier (refused /
///   errored / claimed) so users can see the full picture instead
///   of just the winner.
/// * `auth_expired` — true iff the failure was a 401/403 from
///   `claim-v2` (or a `from_stored_auth` refresh failure). Bubbled
///   up to `SetupReport.auth_expired` so the shell knows to
///   re-OAuth and retry instead of just printing the failure.
fn step_claim() -> (StepResult<ClaimInfo>, Vec<TierAttempt>, bool) {
    let client = match Client::from_stored_auth() {
        Ok(c) => c,
        Err(e) => {
            let auth_expired = is_auth_expired(&e);
            return (
                StepResult::Err(format!("build client: {:#}", e)),
                Vec::new(),
                auth_expired,
            );
        }
    };
    let mut attempts: Vec<TierAttempt> = Vec::with_capacity(PlanType::CASCADE_ORDER.len());
    let mut last_msg = String::new();
    for &tier in PlanType::CASCADE_ORDER {
        match client.claim_v2(tier) {
            Ok(resp) => {
                if resp.duplicate {
                    attempts.push(TierAttempt {
                        tier,
                        outcome: TierOutcome::AlreadyHeld {
                            message: resp.message.clone(),
                        },
                    });
                    let skipped = StepResult::Skipped(if resp.message.is_empty() {
                        format!(
                            "already claimed (or under review) — using {}",
                            tier.as_str()
                        )
                    } else {
                        format!("{} ({})", resp.message, tier.as_str())
                    });
                    return (skipped, attempts, false);
                }
                if resp.success {
                    attempts.push(TierAttempt {
                        tier,
                        outcome: TierOutcome::Claimed {
                            message: resp.message.clone(),
                        },
                    });
                    let ok = StepResult::Ok(ClaimInfo {
                        message: if resp.message.is_empty() {
                            format!("claimed {}", tier.as_str())
                        } else {
                            resp.message
                        },
                        duplicate: false,
                        plan_type: tier,
                    });
                    return (ok, attempts, false);
                }
                // 2xx + success=false + duplicate=false: per-tier
                // refusal (quota / not eligible / 暂无开放).
                attempts.push(TierAttempt {
                    tier,
                    outcome: TierOutcome::Refused {
                        message: resp.message.clone(),
                    },
                });
                last_msg = if resp.message.is_empty() {
                    format!("{} claim refused", tier.as_str())
                } else {
                    format!("{}: {}", tier.as_str(), resp.message)
                };
            }
            Err(e) => {
                // Transport / 5xx / parse failure — bail. These don't
                // get more useful when retried at a lower tier. Capture
                // the auth-expired bit BEFORE flattening `e` to a string
                // so the shell layer can retry with a fresh OAuth.
                let auth_expired = is_auth_expired(&e);
                let err_text = format!("{:#}", e);
                attempts.push(TierAttempt {
                    tier,
                    outcome: TierOutcome::Errored {
                        error: err_text.clone(),
                    },
                });
                return (
                    StepResult::Err(format!("claim {} request: {}", tier.as_str(), err_text)),
                    attempts,
                    auth_expired,
                );
            }
        }
    }
    let overall = StepResult::Err(if last_msg.is_empty() {
        "claim failed at every tier (Max/Pro/Lite)".into()
    } else {
        format!("claim failed at every tier — {}", last_msg)
    });
    (overall, attempts, false)
}

fn step_models_and_register(
    config: &mut Config,
    plan_type: PlanType,
) -> (StepResult<ModelsInfo>, bool) {
    let client = match Client::from_stored_auth() {
        Ok(c) => c,
        Err(e) => {
            let auth_expired = is_auth_expired(&e);
            return (
                StepResult::Err(format!("build client: {:#}", e)),
                auth_expired,
            );
        }
    };
    let all_models = match client.list_models_v2(plan_type) {
        Ok(v) => v,
        Err(e) => {
            let auth_expired = is_auth_expired(&e);
            return (
                StepResult::Err(format!("list models-v2: {:#}", e)),
                auth_expired,
            );
        }
    };
    if all_models.is_empty() {
        return (
            StepResult::Err(
                "server returned an empty model list — cannot set up any provider".into(),
            ),
            false,
        );
    }

    // Available subset — only these become providers. Locked ones
    // (`plan_available=false`) survive in `all_models` for the
    // strikethrough-display path; registering them as providers would
    // give the user something they can `/model` into that 403s on the
    // first request.
    let available: Vec<&ModelEntry> = all_models.iter().filter(|m| m.plan_available).collect();
    if available.is_empty() {
        return (
            StepResult::Err(format!(
                "no models available on plan {} — server returned {} locked entries",
                plan_type.as_str(),
                all_models.len()
            )),
            false,
        );
    }

    // Wipe any stale AtomGit* entries so we don't accumulate old names.
    let stale: Vec<String> = config
        .providers
        .keys()
        .filter(|k| is_codingplan_provider_name(k))
        .cloned()
        .collect();
    for k in stale {
        config.providers.remove(&k);
    }

    let names: Vec<String> = available
        .iter()
        .map(|m| m.display_model_name.clone())
        .collect();
    let provider_names = provider_names_for(&names);
    let default_provider = provider_names
        .first()
        .cloned()
        .unwrap_or_else(|| PROVIDER_PREFIX.to_string());

    for (pname, m) in provider_names.iter().zip(available.iter()) {
        let pc = build_codingplan_provider(m);
        config.providers.insert(pname.clone(), pc);
    }
    config.default_provider = default_provider.clone();

    // Auto-detect a vision_preprocessor candidate from the freshly
    // installed list. Precedence:
    //   - User-supplied non-AtomGit value: leave alone.
    //   - None / AtomGit-* (i.e. previous /codingplan run): replace
    //     with first VL/OCR model's provider key from the new list,
    //     or clear to None when the new list has no VL candidate.
    let vl_idx = names
        .iter()
        .position(|n| crate::provider::model_name_suggests_vision(n));
    let new_vl_key = vl_idx.map(|i| provider_names[i].clone());

    let vision_preprocessor = {
        let current = config.vision_preprocessor_provider.clone();
        let user_supplied_non_atomgit = current
            .as_deref()
            .map(|k| !k.is_empty() && !is_codingplan_provider_name(k))
            .unwrap_or(false);

        if user_supplied_non_atomgit {
            VisionPreprocessorOutcome::UserSupplied(current.unwrap())
        } else {
            match new_vl_key {
                Some(k) => {
                    config.vision_preprocessor_provider = Some(k.clone());
                    VisionPreprocessorOutcome::AutoSet(k)
                }
                None => {
                    if current.is_some() {
                        config.vision_preprocessor_provider = None;
                        VisionPreprocessorOutcome::Cleared
                    } else {
                        VisionPreprocessorOutcome::UnchangedNone
                    }
                }
            }
        }
    };

    (
        StepResult::Ok(ModelsInfo {
            display_names: names,
            provider_names,
            default_provider,
            vision_preprocessor,
            all_models,
        }),
        false,
    )
}

fn step_status() -> (StepResult<StatusResponse>, bool) {
    let client = match Client::from_stored_auth() {
        Ok(c) => c,
        Err(e) => {
            let auth_expired = is_auth_expired(&e);
            return (
                StepResult::Err(format!("build client: {:#}", e)),
                auth_expired,
            );
        }
    };
    match client.status_v2() {
        Ok(s) => (StepResult::Ok(s), false),
        Err(e) => {
            let auth_expired = is_auth_expired(&e);
            (
                StepResult::Err(format!("status-v2: {:#}", e)),
                auth_expired,
            )
        }
    }
}

/// Truncate a single-line message to at most `max` chars, appending `…`
/// when shortened. Char-boundary safe (won't split a UTF-8 codepoint).
/// Used when rendering error messages whose source includes a server
/// response body — useful diagnostic prefix, useless multi-KB tail.
fn truncate_inline(msg: &str, max: usize) -> String {
    if msg.chars().count() <= max {
        return msg.to_string();
    }
    let mut out: String = msg.chars().take(max).collect();
    out.push('');
    out
}

/// Format a duration in seconds as a short human-readable label —
/// `90s`, `5m`, `2h 30m`, `3d 4h`. Replaces the previous "{N}s" which
/// was unreadable for anything past a minute (e.g. "in 86340s" instead
/// of "in 23h 59m").
fn format_duration_secs(secs: i64) -> String {
    if secs < 0 {
        return "".into();
    }
    let s = secs as u64;
    if s < 60 {
        return format!("{}s", s);
    }
    let (m, sr) = (s / 60, s % 60);
    if m < 60 {
        return if sr == 0 { format!("{}m", m) } else { format!("{}m {}s", m, sr) };
    }
    let (h, mr) = (m / 60, m % 60);
    if h < 24 {
        return if mr == 0 { format!("{}h", h) } else { format!("{}h {}m", h, mr) };
    }
    let (d, hr) = (h / 24, h % 24);
    if hr == 0 { format!("{}d", d) } else { format!("{}d {}h", d, hr) }
}

/// Decide the config-key name for each model. Single model → bare
/// `AtomGit` (keeps the name tidy for the common case); 2+ models →
/// `AtomGit-{name with / replaced by -}`.
fn provider_names_for(model_names: &[String]) -> Vec<String> {
    if model_names.len() == 1 {
        vec![PROVIDER_PREFIX.to_string()]
    } else {
        model_names
            .iter()
            .map(|m| format!("{}-{}", PROVIDER_PREFIX, sanitize_model_for_name(m)))
            .collect()
    }
}

/// Turn `moonshotai/Kimi-K2-Instruct` → `moonshotai-Kimi-K2-Instruct`.
/// Only swaps `/`; other punctuation stays verbatim (model names in the
/// wild use `.` and digits freely, and TOML keys handle those fine).
fn sanitize_model_for_name(model: &str) -> String {
    model.replace('/', "-")
}

/// Match `AtomGit` OR `AtomGit-<anything>` — the set of config keys
/// owned by the coding-plan flow. Used to wipe stale entries before
/// re-populating from the fresh model list.
fn is_codingplan_provider_name(name: &str) -> bool {
    name == PROVIDER_PREFIX || name.starts_with(&format!("{}-", PROVIDER_PREFIX))
}

/// Build a ProviderConfig from a model-list entry. The server's
/// per-model fields take precedence; missing fields fall back to the
/// historical fallbacks ([`codingplan_llm_base_url`] / `PROVIDER_TYPE`
/// / `CONTEXT_WINDOW`) so older `models-v2` payloads without the new
/// columns continue to work without code changes.
///
/// `api_key` stays `None` regardless — `create_provider()` loads the
/// OAuth token at runtime via `auth.toml` so we never persist it into
/// the user's `config.toml`.
fn build_codingplan_provider(entry: &ModelEntry) -> ProviderConfig {
    ProviderConfig {
        provider_type: entry
            .provider_type
            .clone()
            .filter(|s| !s.is_empty())
            .unwrap_or_else(|| PROVIDER_TYPE.to_string()),
        api_key: None,
        model: entry.display_model_name.clone(),
        base_url: Some(
            entry
                .base_url
                .clone()
                .filter(|s| !s.is_empty())
                .unwrap_or_else(codingplan_llm_base_url),
        ),
        system_prompt: None,
        user_agent: None,
        // `context_window: 0` from a misconfigured row would degrade
        // every request to a zero-token window; treat that as
        // "missing" and fall back rather than ship a broken provider.
        context_window: entry
            .context_window
            .filter(|n| *n > 0)
            .unwrap_or(CONTEXT_WINDOW),
        max_tokens: None,
        thinking_type: None,
        thinking_keep: None,
        reasoning_history: None,
        thinking_enabled: None,
        thinking_budget: None,
        skip_tls_verify: false,
        ephemeral: false,
    }
}

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

    /// Build a `ModelEntry` for tests that only care about the
    /// model name and want every other field to take its fallback
    /// (`base_url` → [`codingplan_llm_base_url`], `provider_type` →
    /// `PROVIDER_TYPE`, `context_window` → `CONTEXT_WINDOW`,
    /// `plan_available: true`).
    /// Lets the bulk of the test suite stay short while the
    /// per-field-override behaviour gets its own dedicated tests
    /// further down.
    fn entry(display_model_name: &str) -> super::super::types::ModelEntry {
        super::super::types::ModelEntry {
            display_model_name: display_model_name.to_string(),
            plan_available: true,
            ..Default::default()
        }
    }

    fn blank_config() -> Config {
        Config {
            default_provider: String::new(),
            default_workdir: None,
            providers: HashMap::new(),
            datalog: Default::default(),
            auto_update: true,
            notifications: Default::default(),
            telemetry: Default::default(),
            lsp: Default::default(),
            auto_commit: false,
            subagent: Default::default(),
            vision_preprocessor_provider: None,
            language: None,
            ui: Default::default(),
            plugin: Default::default(),
        }
    }

    #[test]
    fn single_model_uses_bare_prefix() {
        let names = vec!["moonshotai/Kimi-K2-Instruct".into()];
        let p = provider_names_for(&names);
        assert_eq!(p, vec!["AtomGit".to_string()]);
    }

    #[test]
    fn multiple_models_expand_to_prefix_suffixes() {
        let names = vec![
            "moonshotai/Kimi-K2-Instruct".into(),
            "anthropic/claude-3.5-sonnet".into(),
            "openai/gpt-5".into(),
        ];
        let p = provider_names_for(&names);
        assert_eq!(
            p,
            vec![
                "AtomGit-moonshotai-Kimi-K2-Instruct".to_string(),
                "AtomGit-anthropic-claude-3.5-sonnet".to_string(),
                "AtomGit-openai-gpt-5".to_string(),
            ]
        );
    }

    #[test]
    fn sanitize_replaces_slash_only() {
        // `/` becomes `-`; `.` and digits stay (valid in TOML keys).
        assert_eq!(
            sanitize_model_for_name("anthropic/claude-3.5-sonnet"),
            "anthropic-claude-3.5-sonnet"
        );
    }

    #[test]
    fn is_codingplan_name_matches_prefix_and_exact() {
        assert!(is_codingplan_provider_name("AtomGit"));
        assert!(is_codingplan_provider_name("AtomGit-foo"));
        assert!(is_codingplan_provider_name("AtomGit-moonshotai-Kimi-K2"));
        assert!(!is_codingplan_provider_name("AtomGitPlus"));
        assert!(!is_codingplan_provider_name("atomgit")); // case-sensitive
        assert!(!is_codingplan_provider_name("claude"));
    }

    #[test]
    fn step_models_wipes_stale_atomgit_entries() {
        // Simulate a user who previously ran `/login` (old MiniMax entry)
        // and a manual `/provider` session (custom Anthropic entry). After
        // coding-plan setup, only fresh AtomGit* entries should remain;
        // the manual Anthropic one stays.
        let mut config = blank_config();
        config.providers.insert(
            "AtomGit".to_string(),
            build_codingplan_provider(&entry("stale-MiniMax")),
        );
        config.providers.insert(
            "AtomGit-legacy".to_string(),
            build_codingplan_provider(&entry("another-stale")),
        );
        config.providers.insert(
            "claude".to_string(),
            build_codingplan_provider(&entry("anthropic/claude-3.5")),
        );

        // Manually drive the "install" side without network — mirror
        // what step_models_and_register does after a successful API call.
        let names = vec!["meta-llama/Llama-3-70B".to_string()];
        let stale: Vec<String> = config
            .providers
            .keys()
            .filter(|k| is_codingplan_provider_name(k))
            .cloned()
            .collect();
        for k in stale {
            config.providers.remove(&k);
        }
        let provider_names = provider_names_for(&names);
        for (pname, m) in provider_names.iter().zip(names.iter()) {
            config
                .providers
                .insert(pname.clone(), build_codingplan_provider(&entry(m)));
        }
        config.default_provider = provider_names[0].clone();

        assert_eq!(config.providers.len(), 2, "claude + one fresh AtomGit");
        assert!(
            config.providers.contains_key("claude"),
            "unrelated entry kept"
        );
        assert!(
            config.providers.contains_key("AtomGit"),
            "fresh AtomGit added"
        );
        assert!(
            !config.providers.contains_key("AtomGit-legacy"),
            "stale removed"
        );
        let fresh = &config.providers["AtomGit"];
        assert_eq!(fresh.model, "meta-llama/Llama-3-70B");
        assert_eq!(
            fresh.base_url.as_deref(),
            Some(codingplan_llm_base_url().as_str())
        );
        assert_eq!(fresh.provider_type, PROVIDER_TYPE);
        assert_eq!(config.default_provider, "AtomGit");
    }

    #[test]
    fn codingplan_llm_base_url_defaults_to_new_signed_gateway() {
        // Lock in the default. If `ATOMCODE_CODINGPLAN_LLM_BASE_URL` is
        // set in the test environment (CI / staging override / dev box
        // with a stray export), honour it — otherwise the default must
        // be the modern `llm-api.atomgit.com` host. Anything else (most
        // notably the legacy `api-ai.gitcode.com`) silently disables
        // codingplan request signing because `is_atomgit_gateway` in
        // `coding_plan::crypto` only whitelists the new host.
        //
        // OnceLock caches across test threads, so this test reflects
        // whatever the env was at the FIRST call site in the process.
        // That's deliberate — it ensures every test in this module
        // agrees on the URL, mirroring production behaviour where the
        // value is fixed for the lifetime of one `atomcode` run.
        let actual = codingplan_llm_base_url();
        let env_override = std::env::var("ATOMCODE_CODINGPLAN_LLM_BASE_URL")
            .ok()
            .map(|v| v.trim().trim_end_matches('/').to_string())
            .filter(|v| !v.is_empty());
        if let Some(want) = env_override {
            assert_eq!(actual, want, "env override must win when set");
        } else {
            assert_eq!(
                actual, "https://llm-api.atomgit.com/v1",
                "default must point at the new signed gateway (NOT legacy api-ai.gitcode.com); \
                 otherwise codingplan signing never engages"
            );
        }
    }

    #[test]
    fn build_provider_uses_canonical_defaults() {
        // All optional server fields missing → fall back to the
        // historical constants. Pins the back-compat path for
        // older `models-v2` builds that don't yet emit `base_url`,
        // `type`, or `context_window`.
        let p = build_codingplan_provider(&entry("foo/bar"));
        assert_eq!(p.provider_type, "openai");
        assert_eq!(
            p.base_url.as_deref(),
            Some(codingplan_llm_base_url().as_str())
        );
        assert_eq!(p.context_window, 64_000);
        assert!(
            p.api_key.is_none(),
            "token loaded at runtime from auth.toml"
        );
        assert!(!p.ephemeral);
    }

    #[test]
    fn build_provider_uses_server_overrides_when_present() {
        // Per-model server fields take precedence over the
        // hard-coded fallbacks. Mirrors the new wire shape:
        // `base_url`, `type`, `context_window` all populated.
        let e = super::super::types::ModelEntry {
            id: 2052994857682014210,
            is_infinity: 2,
            is_atomcode_exclusive: 1,
            display_model_name: "GLM-5.1".into(),
            base_url: Some("https://custom.example.com/v1".into()),
            provider_type: Some("claude".into()),
            context_window: Some(128_000),
            plan_available: true,
        };
        let p = build_codingplan_provider(&e);
        assert_eq!(p.model, "GLM-5.1");
        assert_eq!(p.provider_type, "claude");
        assert_eq!(p.base_url.as_deref(), Some("https://custom.example.com/v1"));
        assert_eq!(p.context_window, 128_000);
    }

    #[test]
    fn build_provider_treats_empty_or_zero_overrides_as_missing() {
        // Defensive: a malformed server row (empty string base_url /
        // type, zero context window) shouldn't ship a provider that
        // refuses every request. Fall back to constants instead.
        let e = super::super::types::ModelEntry {
            display_model_name: "weird".into(),
            base_url: Some(String::new()),
            provider_type: Some(String::new()),
            context_window: Some(0),
            plan_available: true,
            ..Default::default()
        };
        let p = build_codingplan_provider(&e);
        assert_eq!(p.provider_type, "openai");
        assert_eq!(
            p.base_url.as_deref(),
            Some(codingplan_llm_base_url().as_str())
        );
        assert_eq!(p.context_window, 64_000);
    }

    #[test]
    fn model_entry_deserialises_new_wire_shape() {
        // The exact JSON payload from the spec —
        // every new field must parse without error.
        let raw = r#"[{
            "id": 2052994857682014210,
            "is_infinity": 2,
            "is_atomcode_exclusive": 1,
            "display_model_name": "GLM-5.1",
            "base_url": "https://api-ai.gitcode.com/v1",
            "type": "openai",
            "context_window": 64000,
            "plan_available": true
        }]"#;
        let list: Vec<super::super::types::ModelEntry> =
            serde_json::from_str(raw).expect("payload deserialises");
        assert_eq!(list.len(), 1);
        let m = &list[0];
        assert_eq!(m.id, 2052994857682014210);
        assert_eq!(m.is_infinity, 2);
        assert_eq!(m.is_atomcode_exclusive, 1);
        assert_eq!(m.display_model_name, "GLM-5.1");
        assert_eq!(m.base_url.as_deref(), Some("https://api-ai.gitcode.com/v1"));
        assert_eq!(m.provider_type.as_deref(), Some("openai"));
        assert_eq!(m.context_window, Some(64_000));
        assert!(m.plan_available);
    }

    #[test]
    fn model_entry_deserialises_legacy_wire_shape() {
        // Older server build with only the v2-minimum fields. New
        // fields default to `None` / `0` so older payloads keep
        // working — the orchestrator falls back to the constants.
        let raw = r#"[{
            "id": 1,
            "is_atomcode_exclusive": 0,
            "display_model_name": "legacy/model",
            "plan_available": true
        }]"#;
        let list: Vec<super::super::types::ModelEntry> =
            serde_json::from_str(raw).expect("legacy payload deserialises");
        let m = &list[0];
        assert_eq!(m.display_model_name, "legacy/model");
        assert!(m.base_url.is_none());
        assert!(m.provider_type.is_none());
        assert!(m.context_window.is_none());
        assert_eq!(m.is_infinity, 0);
    }

    /// Render exercise: every step Ok. Verifies the three-line output
    /// structure the user sees on a fresh happy-path run.
    #[test]
    fn render_happy_path_has_all_checkmarks() {
        let report = SetupReport {
            login: StepResult::Ok(LoginInfo {
                username: "theo".into(),
                display_name: Some("Theo".into()),
                email: Some("theo@example.com".into()),
            }),
            claim: StepResult::Ok(ClaimInfo {
                message: "领取成功".into(),
                duplicate: false,
                plan_type: PlanType::Max,
            }),
            claim_attempts: Vec::new(),
            models: StepResult::Ok(ModelsInfo {
                display_names: vec!["moonshotai/Kimi-K2-Instruct".into()],
                provider_names: vec!["AtomGit".into()],
                default_provider: "AtomGit".into(),
                vision_preprocessor: VisionPreprocessorOutcome::UnchangedNone,
                all_models: vec![],
            }),
            status: StepResult::Ok(crate::coding_plan::types::StatusResponse {
                codingplan_free: Some(crate::coding_plan::types::PlanInfo {
                    plan_name: "CodingPlan Free".into(),
                    status: 1,
                    claimed_at: "2026-04-22".into(),
                    expires_at: "2026-05-22".into(),
                    remaining_days: 29,
                    total_days: 30,
                    apply_id: 1,
                }),
                current_usage: Some(crate::coding_plan::types::UsageInfo {
                    placeholder: false,
                    window_token_limit: 50000,
                    window_tokens_used: 0,
                    usage_percent: 0.0,
                    window_hours: 1,
                    reset_at: "2026-04-23T12:13:14".into(),
                    reset_at_display: "12:13".into(),
                    seconds_until_reset: 693,
                    reset_label: String::new(),
                    usage_status_desc: String::new(),
                }),
                audit_status: 1,
                expires_at: Some("2026-05-22".into()),
                window_quota_exhausted: false,
                window_quota_hint: None,
            }),
            auth_expired: false,
        };
        let out = report.render();
        assert!(out.contains("✓ Logged in as Theo"));
        assert!(out.contains("theo@example.com"));
        assert!(out.contains("CodingPlan claimed"));
        assert!(out.contains("Kimi-K2-Instruct"));
        assert!(out.contains("AtomGit"));
        assert!(out.contains("(default)"));
        assert!(out.contains("CodingPlan Free"));
        assert!(out.contains("12:13"));
        assert!(report.should_persist_config());
    }

    /// Render exercise: claim returned duplicate=true. Must render as
    /// a skipped checkmark, NOT a failure — user already had the plan.
    #[test]
    fn render_claim_duplicate_renders_as_success() {
        let report = SetupReport {
            login: StepResult::Skipped("already logged in as theo".into()),
            claim: StepResult::Skipped("already claimed / in review".into()),
            claim_attempts: Vec::new(),
            models: StepResult::Ok(ModelsInfo {
                display_names: vec!["a/b".into()],
                provider_names: vec!["AtomGit".into()],
                default_provider: "AtomGit".into(),
                vision_preprocessor: VisionPreprocessorOutcome::UnchangedNone,
                all_models: vec![],
            }),
            status: StepResult::Err("request timeout".into()),
            auth_expired: false,
        };
        let out = report.render();
        assert!(out.contains("✓ already logged in"));
        assert!(out.contains("already claimed"));
        assert!(!out.contains("✗ CodingPlan claim"), "duplicate ≠ failure");
        // Status failed but it's warn-only: ⚠ prefix, NOT ✗.
        assert!(out.contains("⚠ Status fetch failed"));
        assert!(!out.contains("✗ Status"));
        // Login skipped + models ok ⇒ config should still be persisted.
        assert!(report.should_persist_config());
    }

    /// Regression: when a fresh claim hasn't activated yet the backend
    /// returns `claimed_at: null, expires_at: null, total_days: 0,
    /// remaining_days: 0`. Pre-fix the render line came out as
    /// `Plan: CodingPlan Free  ·  expires  (0d / 0d remaining)` — empty
    /// gap in the middle + bogus zeros, looked like a parser bug. Now
    /// the empty-expiry case shows a meaningful "pending activation"
    /// state instead.
    #[test]
    fn render_status_pending_activation_omits_zero_expiry() {
        let report = SetupReport {
            login: StepResult::Skipped("already logged in".into()),
            claim: StepResult::Ok(ClaimInfo {
                message: "claimed".into(),
                duplicate: false,
                plan_type: PlanType::Max,
            }),
            claim_attempts: Vec::new(),
            models: StepResult::Ok(ModelsInfo {
                display_names: vec!["a/b".into()],
                provider_names: vec!["AtomGit".into()],
                default_provider: "AtomGit".into(),
                vision_preprocessor: VisionPreprocessorOutcome::UnchangedNone,
                all_models: vec![],
            }),
            status: StepResult::Ok(crate::coding_plan::types::StatusResponse {
                codingplan_free: Some(crate::coding_plan::types::PlanInfo {
                    plan_name: "CodingPlan Free".into(),
                    status: 0,
                    claimed_at: String::new(),
                    expires_at: String::new(),
                    remaining_days: 0,
                    total_days: 0,
                    apply_id: 0,
                }),
                current_usage: None,
                audit_status: 0,
                expires_at: None,
                window_quota_exhausted: false,
                window_quota_hint: None,
            }),
            auth_expired: false,
        };
        let out = report.render();
        assert!(out.contains("Plan: CodingPlan Free"), "plan name still shown: {}", out);
        assert!(
            out.contains("pending activation"),
            "must surface pending state to user: {}",
            out
        );
        assert!(
            !out.contains("(0d / 0d"),
            "bogus zero countdown must not render: {}",
            out
        );
        assert!(
            !out.contains("expires  ("),
            "empty expires-date with double space must not render: {}",
            out
        );
    }

    /// Render exercise: login failed. Downstream steps are pre-marked
    /// with the cascade sentinel; format() suppresses them so only the
    /// login-failure line appears. Config must NOT be persisted.
    #[test]
    fn render_login_failed_blocks_persist_and_suppresses_cascade() {
        let report = SetupReport {
            login: StepResult::Err("browser handshake timed out".into()),
            claim: StepResult::Skipped(CASCADE_FROM_UPSTREAM_FAIL.into()),
            claim_attempts: Vec::new(),
            models: StepResult::Skipped(CASCADE_FROM_UPSTREAM_FAIL.into()),
            status: StepResult::Skipped(CASCADE_FROM_UPSTREAM_FAIL.into()),
            auth_expired: false,
        };
        let out = report.render();
        assert!(out.contains("✗ Login failed"));
        // Cascade rows must NOT appear.
        assert!(!out.contains("CodingPlan claim"), "no cascade claim row on login fail");
        assert!(!out.contains("Models step"), "no cascade models row on login fail");
        assert!(!out.contains("Status fetch"), "no cascade status row on login fail");
        // Login Err ⇒ should_persist_config = false (login.is_ok_or_skipped() is false).
        assert!(
            !report.should_persist_config(),
            "don't write config on login failure"
        );
    }

    /// Regression: claim returned Err (e.g. AtomGit `claim-v2` 500
    /// with the Spring `UnexpectedRollbackException` payload). `run()`
    /// short-circuits and stamps the cascade sentinel into `models` /
    /// `status`. Before this fix, `should_persist_config` only
    /// checked `login` and `models` — both `is_ok_or_skipped()` =
    /// `true` here — so the gate flipped open and `save_and_reload`
    /// rewrote `config.toml`. Surfaced to the user as "claim failed
    /// but models still got written to my config". Now the predicate
    /// also requires `claim.is_ok_or_skipped()` so any real claim
    /// failure blocks the persist.
    #[test]
    fn claim_err_blocks_persist() {
        let report = SetupReport {
            login: StepResult::Skipped("already logged in".into()),
            claim: StepResult::Err(
                "claim Pro request: claim-v2 returned 500 Internal Server Error \
                 — Transaction rolled back because it has been marked as rollback-only"
                    .into(),
            ),
            claim_attempts: Vec::new(),
            models: StepResult::Skipped(CASCADE_FROM_UPSTREAM_FAIL.into()),
            status: StepResult::Skipped(CASCADE_FROM_UPSTREAM_FAIL.into()),
            auth_expired: false,
        };
        assert!(
            !report.should_persist_config(),
            "claim Err must block save_and_reload — config rewrite was overwriting \
             manual edits between TUI startup and /codingplan",
        );
        // Sanity-check: the duplicate-claim Skipped path (server says
        // "already claimed") must STILL persist so two-runs-in-a-row
        // /codingplan keeps working as a model-list sync.
        let dup = SetupReport {
            login: StepResult::Skipped("already logged in".into()),
            claim: StepResult::Skipped("already claimed / using Max".into()),
            claim_attempts: Vec::new(),
            models: StepResult::Ok(ModelsInfo {
                display_names: vec!["a/b".into()],
                provider_names: vec!["AtomGit".into()],
                default_provider: "AtomGit".into(),
                vision_preprocessor: VisionPreprocessorOutcome::UnchangedNone,
                all_models: vec![],
            }),
            status: StepResult::Err("status fetch timeout".into()),
            auth_expired: false,
        };
        assert!(
            dup.should_persist_config(),
            "duplicate-claim Skipped must still allow persist (it's the model-sync path)",
        );
    }

    /// `auth_expired = true` MUST NOT flip `should_persist_config()`
    /// open on its own — the gate already requires every critical step
    /// to be `is_ok_or_skipped`, and that's where the actual safety
    /// lives. `auth_expired` is a side-channel for the shell to decide
    /// "retry with fresh OAuth"; it's orthogonal to "is this report
    /// good enough to write to disk". Regression guard: a future
    /// refactor that ANDs `auth_expired` into the predicate would
    /// double-gate (claim Err + auth_expired both block) but a future
    /// refactor that ORs it the wrong way would open the persist gate
    /// on an auth-expired-but-otherwise-skipped report. Lock the
    /// orthogonality in.
    #[test]
    fn auth_expired_alone_does_not_change_persist_gate() {
        // All-Skipped report (login skipped, no claim attempted, etc.)
        // with auth_expired=true. Persist gate is driven by the step
        // outcomes — Skipped counts as "ok or skipped" — so this should
        // still allow persist.
        let allow = SetupReport {
            login: StepResult::Skipped("already logged in".into()),
            claim: StepResult::Skipped("already claimed".into()),
            claim_attempts: Vec::new(),
            models: StepResult::Ok(ModelsInfo {
                display_names: vec!["a/b".into()],
                provider_names: vec!["AtomGit".into()],
                default_provider: "AtomGit".into(),
                vision_preprocessor: VisionPreprocessorOutcome::UnchangedNone,
                all_models: vec![],
            }),
            status: StepResult::Skipped("ok".into()),
            auth_expired: true,
        };
        assert!(
            allow.should_persist_config(),
            "auth_expired must not gate persist when every critical step \
             is ok/skipped — it's a side-channel for retry, not safety",
        );

        // Claim Err report. Persist gate already false, auth_expired
        // doesn't matter.
        let block = SetupReport {
            login: StepResult::Skipped("already logged in".into()),
            claim: StepResult::Err("auth failed".into()),
            claim_attempts: Vec::new(),
            models: StepResult::Skipped(CASCADE_FROM_UPSTREAM_FAIL.into()),
            status: StepResult::Skipped(CASCADE_FROM_UPSTREAM_FAIL.into()),
            auth_expired: true,
        };
        assert!(
            !block.should_persist_config(),
            "claim Err already blocks persist — auth_expired doesn't \
             relax it",
        );
    }

    /// Per-tier cascade rendering: Max refused (额度已满) → Pro
    /// refused (额度已满) → Lite claimed. Users should see ALL three
    /// rows so they understand the cascade walked Max → Pro → Lite,
    /// not just the winner.
    #[test]
    fn render_per_tier_cascade_shows_every_attempt() {
        let report = SetupReport {
            login: StepResult::Skipped("already logged in as Code_dh".into()),
            claim: StepResult::Ok(ClaimInfo {
                message: "claimed".into(),
                duplicate: false,
                plan_type: PlanType::Lite,
            }),
            claim_attempts: vec![
                TierAttempt {
                    tier: PlanType::Max,
                    outcome: TierOutcome::Refused {
                        message: "额度已满".into(),
                    },
                },
                TierAttempt {
                    tier: PlanType::Pro,
                    outcome: TierOutcome::Refused {
                        message: "额度已满".into(),
                    },
                },
                TierAttempt {
                    tier: PlanType::Lite,
                    outcome: TierOutcome::Claimed {
                        message: "领取成功".into(),
                    },
                },
            ],
            models: StepResult::Skipped("models step not exercised here".into()),
            status: StepResult::Skipped("status not exercised here".into()),
            auth_expired: false,
        };
        let out = report.render();
        // Max + Pro must surface as 领取失败 with the actual server
        // message so users can tell the cascade walked past them
        // (and why) instead of a single "claim failed: Lite: 额度已满".
        assert!(
            out.contains("CodingPlan Max 领取失败 — 额度已满")
                || out.contains("CodingPlan Max claim failed — 额度已满"),
            "Max refusal row missing: {}",
            out
        );
        assert!(
            out.contains("CodingPlan Pro 领取失败 — 额度已满")
                || out.contains("CodingPlan Pro claim failed — 额度已满"),
            "Pro refusal row missing: {}",
            out
        );
        // Lite must surface as 领取成功 (the winner).
        assert!(
            out.contains("CodingPlan Lite 领取成功")
                || out.contains("CodingPlan Lite claimed"),
            "Lite success row missing: {}",
            out
        );
        // The legacy single-line summary must NOT appear when
        // claim_attempts is populated — would be a duplicate "claimed
        // Lite" row.
        assert!(
            !out.contains("CodingPlan claimed"),
            "legacy claim-summary row must be suppressed when per-tier rows present: {}",
            out
        );
    }

    /// Per-tier cascade where every tier refused — winning tier is
    /// `None`, overall claim is `Err`. Each refused tier still gets
    /// its own row.
    #[test]
    fn render_per_tier_cascade_all_refused() {
        let report = SetupReport {
            login: StepResult::Skipped("already logged in".into()),
            claim: StepResult::Err(
                "claim failed at every tier — Lite: 暂无开放".into(),
            ),
            claim_attempts: vec![
                TierAttempt {
                    tier: PlanType::Max,
                    outcome: TierOutcome::Refused {
                        message: "暂无开放".into(),
                    },
                },
                TierAttempt {
                    tier: PlanType::Pro,
                    outcome: TierOutcome::Refused {
                        message: "暂无开放".into(),
                    },
                },
                TierAttempt {
                    tier: PlanType::Lite,
                    outcome: TierOutcome::Refused {
                        message: "暂无开放".into(),
                    },
                },
            ],
            models: StepResult::Skipped(CASCADE_FROM_UPSTREAM_FAIL.into()),
            status: StepResult::Skipped(CASCADE_FROM_UPSTREAM_FAIL.into()),
            auth_expired: false,
        };
        let out = report.render();
        // All three tier rows present with the 暂无开放 message.
        for tier in &["Max", "Pro", "Lite"] {
            let zh = format!("CodingPlan {} 领取失败 — 暂无开放", tier);
            let en = format!("CodingPlan {} claim failed — 暂无开放", tier);
            assert!(
                out.contains(&zh) || out.contains(&en),
                "{} refusal row missing: {}",
                tier,
                out
            );
        }
        // Overall claim is Err but with claim_attempts populated, the
        // legacy "✗ CodingPlan claim failed — ..." summary line is
        // suppressed (per-tier rows already explain the failure).
        assert!(
            !out.contains("claim failed at every tier"),
            "legacy err-summary row must not appear: {}",
            out
        );
        // Models row also suppressed (cascade sentinel).
        assert!(
            !out.contains("Models step"),
            "cascade-from-claim-fail must hide models row: {}",
            out
        );
    }

    /// Per-tier cascade where Max errored (5xx). `Errored` and
    /// `Refused` both render as `领取失败` with the message — same
    /// visual to the user, same cause from their POV. Make sure the
    /// error text gets truncated so a long stack trace doesn't blow
    /// up the row.
    #[test]
    fn render_per_tier_cascade_with_errored_tier_truncates_long_message() {
        let long_err = "x".repeat(500);
        let report = SetupReport {
            login: StepResult::Skipped("already logged in".into()),
            claim: StepResult::Err(format!("claim Max request: {}", long_err)),
            claim_attempts: vec![TierAttempt {
                tier: PlanType::Max,
                outcome: TierOutcome::Errored {
                    error: long_err.clone(),
                },
            }],
            models: StepResult::Skipped(CASCADE_FROM_UPSTREAM_FAIL.into()),
            status: StepResult::Skipped(CASCADE_FROM_UPSTREAM_FAIL.into()),
            auth_expired: false,
        };
        let out = report.render();
        // The Max row is present with 领取失败.
        assert!(
            out.contains("CodingPlan Max 领取失败 —")
                || out.contains("CodingPlan Max claim failed —"),
            "Max errored row missing: {}",
            out
        );
        // The full 500-char error must NOT appear verbatim — truncated.
        assert!(
            !out.contains(&long_err),
            "long error must be truncated, not pasted whole: {}",
            out
        );
    }

    /// Render exercise: multi-model report. Verifies each provider
    /// name gets its own bullet + `(default)` marks only the first.
    #[test]
    fn render_multi_model_lists_all_providers_with_default_mark() {
        let report = SetupReport {
            login: StepResult::Skipped("already logged in as theo".into()),
            claim: StepResult::Ok(ClaimInfo {
                message: String::new(),
                duplicate: false,
                plan_type: PlanType::Max,
            }),
            claim_attempts: Vec::new(),
            models: StepResult::Ok(ModelsInfo {
                display_names: vec![
                    "moonshotai/Kimi-K2-Instruct".into(),
                    "anthropic/claude-3.5-sonnet".into(),
                    "openai/gpt-5".into(),
                ],
                provider_names: vec![
                    "AtomGit-moonshotai-Kimi-K2-Instruct".into(),
                    "AtomGit-anthropic-claude-3.5-sonnet".into(),
                    "AtomGit-openai-gpt-5".into(),
                ],
                default_provider: "AtomGit-moonshotai-Kimi-K2-Instruct".into(),
                vision_preprocessor: VisionPreprocessorOutcome::UnchangedNone,
                all_models: vec![],
            }),
            status: StepResult::Err("status endpoint 500".into()),
            auth_expired: false,
        };
        let out = report.render();
        assert!(out.contains("Added 3 providers"));
        assert!(out.contains(
            "AtomGit-moonshotai-Kimi-K2-Instruct  →  moonshotai/Kimi-K2-Instruct  (default)"
        ));
        assert!(
            out.contains("AtomGit-anthropic-claude-3.5-sonnet  →  anthropic/claude-3.5-sonnet\n")
        );
        assert!(
            !out.contains("anthropic/claude-3.5-sonnet  (default)"),
            "only first is default"
        );
    }

    /// Render exercise: claim failed. The cascade markers on models +
    /// status must render as nothing — the claim-failed line is the
    /// explanation, repeating it twice more is noise.
    #[test]
    fn render_claim_failed_suppresses_cascade_rows() {
        let report = SetupReport {
            login: StepResult::Skipped("already logged in as theo".into()),
            claim: StepResult::Err("今日codingplan申请额度已满,请明天再试".into()),
            claim_attempts: Vec::new(),
            models: StepResult::Skipped(CASCADE_FROM_UPSTREAM_FAIL.into()),
            status: StepResult::Skipped(CASCADE_FROM_UPSTREAM_FAIL.into()),
            auth_expired: false,
        };
        let out = report.render();
        assert!(out.contains("✗ CodingPlan claim failed"));
        assert!(out.contains("今日codingplan申请额度已满"));
        // The cascade rows must NOT appear.
        assert!(!out.contains("Models step skipped"), "no cascade row for models");
        assert!(!out.contains("Status fetch skipped"), "no cascade row for status");
        assert!(!out.contains("Added "), "must not say 'Added N providers' on claim fail");
        // The huge JSON body that used to leak through here must NOT appear.
        assert!(!out.contains("invalid type: null"));
        assert!(!out.contains("plan_name"));
    }

    /// Non-cascade Skipped reasons still render — only the sentinel
    /// (`__cascade_upstream_fail__`) is suppressed.
    #[test]
    fn render_skipped_with_non_cascade_reason_still_shows() {
        let report = SetupReport {
            login: StepResult::Skipped("already logged in as theo".into()),
            claim: StepResult::Skipped("already claimed".into()),
            claim_attempts: Vec::new(),
            models: StepResult::Skipped("models cached locally".into()),
            status: StepResult::Skipped("server returned 503; using cached".into()),
            auth_expired: false,
        };
        let out = report.render();
        assert!(out.contains("Models step skipped — models cached locally"));
        assert!(out.contains("Status fetch skipped — server returned 503"));
    }

    /// Render exercise: status fetch failed with a multi-KB body chain.
    /// Output must be truncated to keep the report readable.
    #[test]
    fn render_status_error_truncates_long_message() {
        let huge = format!(
            "status: parse status response (body: {}): invalid type",
            "x".repeat(1000),
        );
        let report = SetupReport {
            login: StepResult::Skipped("already logged in".into()),
            claim: StepResult::Ok(ClaimInfo {
                message: "ok".into(),
                duplicate: false,
                plan_type: PlanType::Max,
            }),
            claim_attempts: Vec::new(),
            models: StepResult::Ok(ModelsInfo {
                display_names: vec!["a/b".into()],
                provider_names: vec!["AtomGit".into()],
                default_provider: "AtomGit".into(),
                vision_preprocessor: VisionPreprocessorOutcome::UnchangedNone,
                all_models: vec![],
            }),
            status: StepResult::Err(huge),
            auth_expired: false,
        };
        let out = report.render();
        // Find the status line and check its length is bounded.
        let line = out.lines().find(|l| l.contains("Status fetch failed")).unwrap();
        // 150 chars + ellipsis + prefix + leading spaces ⇒ comfortably under 250.
        assert!(line.chars().count() < 250, "line still ~{} chars long", line.chars().count());
        assert!(line.contains(''), "truncation marker present");
    }

    #[test]
    fn format_duration_secs_human_readable() {
        assert_eq!(format_duration_secs(0), "0s");
        assert_eq!(format_duration_secs(45), "45s");
        assert_eq!(format_duration_secs(60), "1m");
        assert_eq!(format_duration_secs(90), "1m 30s");
        assert_eq!(format_duration_secs(3600), "1h");
        assert_eq!(format_duration_secs(3660), "1h 1m");
        assert_eq!(format_duration_secs(86400), "1d");
        assert_eq!(format_duration_secs(90060), "1d 1h");
        assert_eq!(format_duration_secs(-1), "");
    }

    #[test]
    fn truncate_inline_passes_short_strings_through() {
        assert_eq!(truncate_inline("short", 10), "short");
        assert_eq!(truncate_inline("exactly_ten", 11), "exactly_ten");
    }

    #[test]
    fn truncate_inline_appends_ellipsis_when_long() {
        let r = truncate_inline("abcdefghijklmnop", 5);
        assert_eq!(r, "abcde…");
    }

    #[test]
    fn truncate_inline_handles_unicode_safely() {
        // 5 CJK chars = 5 chars (regardless of byte count). No char-boundary panic.
        let r = truncate_inline("一二三四五六七八", 5);
        assert_eq!(r, "一二三四五…");
    }

    // ── Vision-preprocessor auto-config tests ────────────────────────────

    fn vl_model_entry(model: &str) -> super::super::types::ModelEntry {
        super::super::types::ModelEntry {
            id: 1,
            display_model_name: model.to_string(),
            // Tests in this section drive `run_register` directly with
            // a curated `Vec<ModelEntry>` — they're testing the
            // post-availability-filter logic, so every entry counts as
            // "available". The split-by-`plan_available` happens
            // upstream in the real `step_models_and_register`.
            plan_available: true,
            // The new wire-shape optional fields default to None/0 —
            // these tests only care about the model name and the
            // availability flag, so let them fall back to the
            // constants via `Default`.
            ..Default::default()
        }
    }

    /// Helper that mirrors `step_models_and_register`'s wipe-and-insert
    /// + auto-detect body, sans network call. Tests the precedence logic
    /// in isolation.
    fn run_register(
        config: &mut Config,
        models: Vec<super::super::types::ModelEntry>,
    ) -> ModelsInfo {
        let stale: Vec<String> = config
            .providers
            .keys()
            .filter(|k| is_codingplan_provider_name(k))
            .cloned()
            .collect();
        for k in stale {
            config.providers.remove(&k);
        }
        let names: Vec<String> = models.iter().map(|m| m.display_model_name.clone()).collect();
        let provider_names = provider_names_for(&names);
        let default_provider = provider_names
            .first()
            .cloned()
            .unwrap_or_else(|| PROVIDER_PREFIX.to_string());
        for (pname, m) in provider_names.iter().zip(models.iter()) {
            config
                .providers
                .insert(pname.clone(), build_codingplan_provider(m));
        }
        config.default_provider = default_provider.clone();

        let vl_idx = names
            .iter()
            .position(|n| crate::provider::model_name_suggests_vision(n));
        let new_vl_key = vl_idx.map(|i| provider_names[i].clone());
        let vision_preprocessor = {
            let current = config.vision_preprocessor_provider.clone();
            let user_supplied_non_atomgit = current
                .as_deref()
                .map(|k| !k.is_empty() && !is_codingplan_provider_name(k))
                .unwrap_or(false);
            if user_supplied_non_atomgit {
                VisionPreprocessorOutcome::UserSupplied(current.unwrap())
            } else {
                match new_vl_key {
                    Some(k) => {
                        config.vision_preprocessor_provider = Some(k.clone());
                        VisionPreprocessorOutcome::AutoSet(k)
                    }
                    None => {
                        if current.is_some() {
                            config.vision_preprocessor_provider = None;
                            VisionPreprocessorOutcome::Cleared
                        } else {
                            VisionPreprocessorOutcome::UnchangedNone
                        }
                    }
                }
            }
        };

        ModelsInfo {
            display_names: names,
            provider_names,
            default_provider,
            vision_preprocessor,
            // Test helper doesn't exercise the locked-model rendering
            // path; mirror the input slice into all_models so the
            // shape stays consistent if any future assertion peeks.
            all_models: models,
        }
    }

    #[test]
    fn vision_preprocessor_auto_set_when_none_and_list_has_vl() {
        let mut config = blank_config();
        let models = vec![
            vl_model_entry("moonshotai/Kimi-K2-Instruct"),
            vl_model_entry("Qwen/Qwen3-VL-32B-Instruct"),
            vl_model_entry("deepseek/deepseek-v4-flash"),
        ];
        let info = run_register(&mut config, models);
        let expected = "AtomGit-Qwen-Qwen3-VL-32B-Instruct".to_string();
        assert_eq!(
            info.vision_preprocessor,
            VisionPreprocessorOutcome::AutoSet(expected.clone())
        );
        assert_eq!(config.vision_preprocessor_provider, Some(expected));
    }

    #[test]
    fn vision_preprocessor_unchanged_none_when_list_has_no_vl() {
        let mut config = blank_config();
        let models = vec![vl_model_entry("moonshotai/Kimi-K2-Instruct")];
        let info = run_register(&mut config, models);
        assert_eq!(info.vision_preprocessor, VisionPreprocessorOutcome::UnchangedNone);
        assert_eq!(config.vision_preprocessor_provider, None);
    }

    #[test]
    fn vision_preprocessor_overwrites_stale_atomgit_value() {
        let mut config = blank_config();
        config.vision_preprocessor_provider = Some("AtomGit-Qwen-Qwen2-VL-72B".into());
        let models = vec![
            vl_model_entry("Kimi-K2-Instruct"),
            vl_model_entry("Qwen/Qwen3-VL-32B-Instruct"),
        ];
        let info = run_register(&mut config, models);
        let expected = "AtomGit-Qwen-Qwen3-VL-32B-Instruct".to_string();
        assert_eq!(
            info.vision_preprocessor,
            VisionPreprocessorOutcome::AutoSet(expected.clone())
        );
        assert_eq!(config.vision_preprocessor_provider, Some(expected));
    }

    #[test]
    fn vision_preprocessor_cleared_when_stale_atomgit_and_list_has_no_vl() {
        let mut config = blank_config();
        config.vision_preprocessor_provider = Some("AtomGit-Qwen-Qwen2-VL-72B".into());
        let models = vec![vl_model_entry("moonshotai/Kimi-K2-Instruct")];
        let info = run_register(&mut config, models);
        assert_eq!(info.vision_preprocessor, VisionPreprocessorOutcome::Cleared);
        assert_eq!(config.vision_preprocessor_provider, None);
    }

    #[test]
    fn vision_preprocessor_preserves_user_set_non_atomgit() {
        let mut config = blank_config();
        config.vision_preprocessor_provider = Some("Qwen3-VL-32B-Instruct".into());
        let models = vec![
            vl_model_entry("Kimi-K2-Instruct"),
            vl_model_entry("Qwen/Qwen3-VL-32B-Instruct"),
        ];
        let info = run_register(&mut config, models);
        assert_eq!(
            info.vision_preprocessor,
            VisionPreprocessorOutcome::UserSupplied("Qwen3-VL-32B-Instruct".into())
        );
        assert_eq!(
            config.vision_preprocessor_provider.as_deref(),
            Some("Qwen3-VL-32B-Instruct")
        );
    }

    #[test]
    fn vision_preprocessor_recognises_pure_ocr_model_name() {
        let mut config = blank_config();
        let models = vec![
            vl_model_entry("Kimi-K2-Instruct"),
            vl_model_entry("PaddleOCR-2.0"),
        ];
        let info = run_register(&mut config, models);
        let expected = "AtomGit-PaddleOCR-2.0".to_string();
        assert_eq!(
            info.vision_preprocessor,
            VisionPreprocessorOutcome::AutoSet(expected.clone())
        );
        assert_eq!(config.vision_preprocessor_provider, Some(expected));
    }

    #[test]
    fn render_includes_vision_preprocessor_auto_set_line() {
        let report = SetupReport {
            login: StepResult::Skipped("already logged in".into()),
            claim: StepResult::Ok(ClaimInfo { message: String::new(), duplicate: false, plan_type: PlanType::Max }),
            claim_attempts: Vec::new(),
            models: StepResult::Ok(ModelsInfo {
                display_names: vec![
                    "Kimi-K2-Instruct".into(),
                    "Qwen/Qwen3-VL-32B-Instruct".into(),
                ],
                provider_names: vec![
                    "AtomGit-Kimi-K2-Instruct".into(),
                    "AtomGit-Qwen-Qwen3-VL-32B-Instruct".into(),
                ],
                default_provider: "AtomGit-Kimi-K2-Instruct".into(),
                vision_preprocessor: VisionPreprocessorOutcome::AutoSet(
                    "AtomGit-Qwen-Qwen3-VL-32B-Instruct".into(),
                ),
                all_models: vec![],
            }),
            status: StepResult::Skipped("status check skipped for this test".into()),
            auth_expired: false,
        };
        let out = report.render();
        assert!(
            out.contains("Vision preprocessor → AtomGit-Qwen-Qwen3-VL-32B-Instruct"),
            "render must include the auto-detected line: {out}",
        );
        assert!(out.contains("(auto-detected)"));
    }

    #[test]
    fn render_includes_vision_preprocessor_cleared_line_when_stale_dropped() {
        let report = SetupReport {
            login: StepResult::Skipped("already logged in".into()),
            claim: StepResult::Ok(ClaimInfo { message: String::new(), duplicate: false, plan_type: PlanType::Max }),
            claim_attempts: Vec::new(),
            models: StepResult::Ok(ModelsInfo {
                display_names: vec!["Kimi-K2-Instruct".into()],
                provider_names: vec!["AtomGit-Kimi-K2-Instruct".into()],
                default_provider: "AtomGit-Kimi-K2-Instruct".into(),
                vision_preprocessor: VisionPreprocessorOutcome::Cleared,
                all_models: vec![],
            }),
            status: StepResult::Skipped("test skip".into()),
            auth_expired: false,
        };
        let out = report.render();
        assert!(out.contains("Vision preprocessor cleared"));
    }

    #[test]
    fn render_includes_vision_preprocessor_user_supplied_line() {
        let report = SetupReport {
            login: StepResult::Skipped("already logged in".into()),
            claim: StepResult::Ok(ClaimInfo { message: String::new(), duplicate: false, plan_type: PlanType::Max }),
            claim_attempts: Vec::new(),
            models: StepResult::Ok(ModelsInfo {
                display_names: vec![
                    "Kimi-K2-Instruct".into(),
                    "Qwen/Qwen3-VL-32B-Instruct".into(),
                ],
                provider_names: vec![
                    "AtomGit-Kimi-K2-Instruct".into(),
                    "AtomGit-Qwen-Qwen3-VL-32B-Instruct".into(),
                ],
                default_provider: "AtomGit-Kimi-K2-Instruct".into(),
                vision_preprocessor: VisionPreprocessorOutcome::UserSupplied(
                    "Qwen3-VL-32B-Instruct".into(),
                ),
                all_models: vec![],
            }),
            status: StepResult::Skipped("test skip".into()),
            auth_expired: false,
        };
        let out = report.render();
        assert!(out.contains("Vision preprocessor → Qwen3-VL-32B-Instruct"));
        assert!(out.contains("(user setting kept)"));
    }

    #[test]
    fn render_omits_vision_preprocessor_line_when_unchanged_none() {
        let report = SetupReport {
            login: StepResult::Skipped("already logged in".into()),
            claim: StepResult::Ok(ClaimInfo { message: String::new(), duplicate: false, plan_type: PlanType::Max }),
            claim_attempts: Vec::new(),
            models: StepResult::Ok(ModelsInfo {
                display_names: vec!["Kimi-K2-Instruct".into()],
                provider_names: vec!["AtomGit-Kimi-K2-Instruct".into()],
                default_provider: "AtomGit-Kimi-K2-Instruct".into(),
                vision_preprocessor: VisionPreprocessorOutcome::UnchangedNone,
                all_models: vec![],
            }),
            status: StepResult::Skipped("test skip".into()),
            auth_expired: false,
        };
        let out = report.render();
        assert!(!out.contains("Vision preprocessor"));
    }

    /// Locked models (plan_available=false on a higher tier) must
    /// surface in the rendered report with a distinctive `✗` prefix
    /// + the explicit "(requires Pro plan or higher)" suffix, the whole row
    /// wrapped in SGR 31 (terminal-theme red), and appended to the
    /// same `Added N provider(s)` bullet list as the available models
    /// so users see the full slate at a glance. Pins the v2 spec's
    /// "若不可用的模型也展示出来" requirement.
    ///
    /// Three layered signals — colour, prefix glyph, suffix text —
    /// because each can fail independently:
    ///   * SGR 31 only fires when the renderer's sanitizer keeps SGR
    ///     (alt_screen, plain) — retained's strict strip pathway
    ///     drops the colour but the glyph + text still carry the
    ///     meaning.
    ///   * The `✗` glyph relies on font support (every common
    ///     terminal font has it; this is the strongest of the three).
    ///   * The "(requires Pro plan or higher)" suffix is plain ASCII / CJK
    ///     and survives even font-fallback-tofu rendering.
    ///
    /// Earlier attempts at strikethrough (SGR 9 then U+0336
    /// combining mark) were both dropped — SGR 9 was eaten by the
    /// universal CSI sanitizer, and U+0336 was silently skipped by
    /// some fonts in the wild — so this test also pins that those
    /// markers do NOT regress back into the template.
    #[test]
    fn render_shows_locked_models_with_prefix_marker() {
        let avail = super::super::types::ModelEntry {
            id: 1,
            display_model_name: "lite/foo".into(),
            plan_available: true,
            ..Default::default()
        };
        let locked = super::super::types::ModelEntry {
            id: 2,
            display_model_name: "max/super-secret".into(),
            plan_available: false,
            ..Default::default()
        };
        let report = SetupReport {
            login: StepResult::Skipped("already logged in".into()),
            claim: StepResult::Ok(ClaimInfo {
                message: "claimed".into(),
                duplicate: false,
                plan_type: PlanType::Lite,
            }),
            claim_attempts: Vec::new(),
            models: StepResult::Ok(ModelsInfo {
                display_names: vec!["lite/foo".into()],
                provider_names: vec!["AtomGit".into()],
                default_provider: "AtomGit".into(),
                vision_preprocessor: VisionPreprocessorOutcome::UnchangedNone,
                all_models: vec![avail, locked],
            }),
            status: StepResult::Skipped("test skip".into()),
            auth_expired: false,
        };
        let out = report.render();
        // Plan tier appears next to claim line.
        assert!(out.contains("(CodingPlan Lite)"), "claim row must show tier:\n{out}");
        // Available model: standard provider line.
        assert!(out.contains("AtomGit") && out.contains("lite/foo"));
        // Locked model: `✗` prefix immediately before the name, plus
        // the explicit `(requires Pro plan or higher)` suffix, all wrapped
        // in SGR 31 (red fg) → SGR 39 (default fg) so the terminal
        // renders the whole row in the theme's red.
        assert!(
            out.contains("\x1b[31m✗ max/super-secret"),
            "locked model must open with SGR 31 + ✗ prefix:\n{out}"
        );
        assert!(out.contains("(requires Pro plan or higher)\x1b[39m"));
        // Strikethrough is intentionally NOT used (SGR 9 was eaten by
        // the renderer's CSI sanitizer; U+0336 was font-dependent and
        // silently dropped on some setups). Lock those decisions in.
        assert!(
            !out.contains("\x1b[9m"),
            "locked-model line must not emit SGR 9 strikethrough:\n{out}"
        );
        assert!(
            !out.contains('\u{0336}'),
            "locked-model line must not emit U+0336 combining strikethrough:\n{out}"
        );
        // Locked model appears INSIDE the providers bullet list — its
        // line must come after the "Added N provider(s):" header and
        // before the next top-level section (Vision preprocessor /
        // CodingPlan status). The strikethrough + suffix already mark
        // it as unavailable; no separate "locked model" header.
        assert!(
            !out.contains("locked model"),
            "no separate locked-model section expected:\n{out}"
        );
        let added_idx = out.find("Added 1 provider").expect("Added header");
        let locked_idx = out.find("max/super-secret").expect("locked model line");
        let avail_idx = out.find("lite/foo").expect("available model line");
        assert!(
            locked_idx > added_idx,
            "locked model must render after the Added header:\n{out}"
        );
        assert!(
            locked_idx < avail_idx,
            "locked model must render BEFORE available providers (top-of-list upgrade prompt):\n{out}"
        );
    }

}