synaps-tui 0.11.0

Terminal UI layer — ratatui, crossterm, syntect, tachyonfx
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
use arc_swap::ArcSwap;
use ratatui::style::Color;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::Arc;
use std::sync::LazyLock;

pub(crate) mod mxc;
mod palettes;
pub(crate) mod transition;

/// Identifies a piece of high-value modal chrome for per-part style
/// resolution. Each variant maps to an optional `<modal>.border` /
/// `<modal>.title` override key in the user theme file. When no override is
/// set the resolver falls back to the shared base token, so the default look
/// is byte-identical to before per-part overrides existed.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum ModalKind {
    Settings,
    Plugins,
    Models,
    Sessions,
}

/// All colors used by the TUI, grouped so they can be overridden from a
/// user theme file. Defaults match the current built-in look.
///
/// Field names are what the theme file uses as keys. Unknown keys are
/// ignored; missing keys keep the default. Colors are written as `#rrggbb`
/// or `#rgb` hex.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Theme {
    // Markdown
    pub(crate) code_fg: Color,
    pub(crate) code_bg: Color,
    pub(crate) heading_color: Color,
    pub(crate) quote_color: Color,
    pub(crate) list_bullet_color: Color,
    pub(crate) table_border_color: Color,
    pub(crate) table_header_color: Color,
    pub(crate) table_cell_color: Color,

    // Base. `message_bg` is the conversation canvas between the header and input.
    // Color::Reset means derive a theme-relative lift from `bg`.
    pub(crate) bg: Color,
    pub(crate) message_bg: Color,
    pub(crate) border: Color,
    pub(crate) border_active: Color,
    pub(crate) muted: Color,
    pub(crate) system_msg: Color,

    // Messages
    pub(crate) user_color: Color,
    pub(crate) user_bg: Color,
    pub(crate) claude_label: Color,
    pub(crate) claude_text: Color,
    pub(crate) thinking_color: Color,
    pub(crate) tool_label: Color,
    pub(crate) tool_param: Color,
    pub(crate) tool_result_color: Color,
    pub(crate) tool_result_ok: Color,
    pub(crate) error_color: Color,
    pub(crate) warning_color: Color,

    // UI chrome
    pub(crate) header_fg: Color,
    pub(crate) status_streaming: Color,
    pub(crate) status_ready: Color,
    pub(crate) help_fg: Color,
    pub(crate) input_fg: Color,
    pub(crate) prompt_fg: Color,
    pub(crate) separator: Color,
    pub(crate) cost_color: Color,

    // Subagent panel
    pub(crate) subagent_border: Color,
    pub(crate) subagent_name: Color,
    pub(crate) subagent_status: Color,
    pub(crate) subagent_done: Color,
    pub(crate) subagent_time: Color,

    // Event bus. `Color::Reset` = derive from this palette (the default);
    // read them through `event_accent`/`event_label`/`event_body`.
    pub(crate) event_icon: Color,
    pub(crate) event_source: Color,
    pub(crate) event_text: Color,
    pub(crate) event_critical: Color,

    // Tool styling — per-tool gutter/accent colours + panel backgrounds.
    // `tool_input_bg`/`tool_output_bg` set to `Color::Reset` mean "derive from
    // this palette" (see `Theme::tool_input_background`); the default theme
    // sets them explicitly, and a theme file can override either.
    pub(crate) tool_bash: Color,
    pub(crate) tool_read: Color,
    pub(crate) tool_write: Color,
    pub(crate) tool_edit: Color,
    pub(crate) tool_grep: Color,
    pub(crate) tool_find: Color,
    pub(crate) tool_ls: Color,
    pub(crate) tool_subagent: Color,
    pub(crate) tool_ext: Color,
    pub(crate) tool_generic: Color,
    pub(crate) tool_input_bg: Color,
    pub(crate) tool_output_bg: Color,

    // --- Per-part chrome overrides (P19.1) --------------------------------
    // Optional overlays keyed off dotted TOML names (e.g. `settings.border`).
    // `None` is the default for every field, which means "resolve to the base
    // token" — so an unconfigured theme renders exactly as it did before these
    // fields existed. Only set when a user opts in per part.
    pub(crate) settings_border: Option<Color>,
    pub(crate) settings_title: Option<Color>,
    pub(crate) plugins_border: Option<Color>,
    pub(crate) plugins_title: Option<Color>,
    pub(crate) models_border: Option<Color>,
    pub(crate) models_title: Option<Color>,
    pub(crate) sessions_border: Option<Color>,
    pub(crate) sessions_title: Option<Color>,
    /// Resting tint of the sidecar header pill (idle + unarmed). `None` falls
    /// back to `muted`, the color the pill uses today.
    pub(crate) sidecar_pill: Option<Color>,

    // --- Namespaced extension tokens (P19.2) -------------------------------
    /// User-TOML overrides for extension theme tokens, keyed by the full
    /// dotted name `ext.<plugin-id>.<token>`. Parsed by `set` from any theme
    /// file line whose key starts with `ext.`. These always WIN over
    /// manifest-declared values (see [`Theme::ext_token`]). Empty by default,
    /// so themes without `ext.*` keys are unaffected.
    pub(crate) ext_overrides: std::collections::HashMap<String, Color>,
}

impl Default for Theme {
    fn default() -> Self {
        Self {
            code_fg: Color::Rgb(170, 210, 220),
            code_bg: Color::Rgb(14, 18, 24),
            heading_color: Color::Rgb(72, 202, 222),
            quote_color: Color::Rgb(85, 100, 120),
            list_bullet_color: Color::Rgb(48, 184, 204),
            table_border_color: Color::Rgb(38, 49, 67),
            table_header_color: Color::Rgb(72, 202, 222),
            table_cell_color: Color::Rgb(175, 185, 200),

            bg: Color::Rgb(19, 23, 33),
            // Recessed transcript surface; deliberately distinct from user and tool cards.
            message_bg: Color::Rgb(11, 13, 20),
            border: Color::Rgb(33, 42, 58),
            border_active: Color::Rgb(54, 190, 210),
            muted: Color::Rgb(62, 73, 90),
            system_msg: Color::Rgb(140, 160, 180),

            user_color: Color::Rgb(185, 195, 215),
            user_bg: Color::Rgb(19, 23, 33),
            claude_label: Color::Rgb(72, 202, 222),
            claude_text: Color::Rgb(192, 198, 210),
            thinking_color: Color::Rgb(45, 55, 75),
            tool_label: Color::Rgb(66, 174, 198),
            tool_param: Color::Rgb(85, 119, 151),
            tool_result_color: Color::Rgb(106, 151, 164),
            tool_result_ok: Color::Rgb(50, 175, 160),
            error_color: Color::Rgb(230, 70, 70),
            warning_color: Color::Rgb(220, 180, 60),

            header_fg: Color::Rgb(110, 125, 150),
            status_streaming: Color::Rgb(220, 175, 60),
            status_ready: Color::Rgb(50, 195, 190),
            help_fg: Color::Rgb(55, 67, 86),
            input_fg: Color::Rgb(196, 203, 216),
            prompt_fg: Color::Rgb(54, 190, 210),
            separator: Color::Rgb(30, 38, 53),
            cost_color: Color::Rgb(218, 178, 76),

            subagent_border: Color::Rgb(40, 45, 75),
            subagent_name: Color::Rgb(140, 130, 220),
            subagent_status: Color::Rgb(120, 140, 170),
            subagent_done: Color::Rgb(50, 195, 190),
            subagent_time: Color::Rgb(80, 95, 120),

            // Event cards derive from the palette (Reset sentinel, like the
            // tool_* fields): see `event_accent`/`event_label`/`event_body`.
            // A palette sets these only to override (night_city, myx).
            event_icon: Color::Reset,
            event_source: Color::Reset,
            event_text: Color::Reset,
            event_critical: Color::Reset,

            // Tool styling — accent colours default to Reset (sentinel: derive
            // from this theme's own palette via tool_accent()).  Only
            // night-city sets explicit neon values.  Backgrounds always
            // auto-derive from `bg`.
            tool_bash: Color::Reset,
            tool_read: Color::Reset,
            tool_write: Color::Reset,
            tool_edit: Color::Reset,
            tool_grep: Color::Reset,
            tool_find: Color::Reset,
            tool_ls: Color::Reset,
            tool_subagent: Color::Reset,
            tool_ext: Color::Reset,
            tool_generic: Color::Reset,
            // Tool input/output are explicit rather than generic derived tints:
            // the paired panels must remain visibly distinct through tmux.
            tool_input_bg: Color::Rgb(23, 28, 40),
            tool_output_bg: Color::Rgb(32, 40, 55),

            // Per-part overrides are absent by default => resolvers fall back
            // to base tokens => zero visual change across all 18 palettes.
            settings_border: None,
            settings_title: None,
            plugins_border: None,
            plugins_title: None,
            models_border: None,
            models_title: None,
            sessions_border: None,
            sessions_title: None,
            sidecar_pill: None,

            // No user overrides for extension tokens by default.
            ext_overrides: std::collections::HashMap::new(),
        }
    }
}

impl Theme {
    /// Conversation canvas. Every built-in palette specifies this independently
    /// so its transcript contrast is intentional rather than a generic RGB rule.
    pub(crate) fn message_background(&self) -> Color {
        self.message_bg
    }

    /// A builtin palette by name, for tests outside this module.
    #[cfg(test)]
    pub(crate) fn builtin_for_test(name: &str) -> Self {
        Self::builtin(name).unwrap_or_else(|| panic!("{name} is a builtin theme"))
    }

    /// Dispatcher for builtin themes
    fn builtin(name: &str) -> Option<Self> {
        match name {
            "default" => Some(Self::default()),
            "night-city" => Some(Self::night_city()),
            "neon-rain" => Some(Self::neon_rain()),
            "amber" => Some(Self::amber()),
            "phosphor" => Some(Self::phosphor()),
            "solarized-dark" => Some(Self::solarized_dark()),
            "blood" => Some(Self::blood()),
            "ocean" => Some(Self::ocean()),
            "rose-pine" => Some(Self::rose_pine()),
            "nord" => Some(Self::nord()),
            "dracula" => Some(Self::dracula()),
            "monokai" => Some(Self::monokai()),
            "myx" => Some(Self::myx()),
            "gruvbox" => Some(Self::gruvbox()),
            "catppuccin" => Some(Self::catppuccin()),
            "tokyo-night" => Some(Self::tokyo_night()),
            "sunset" => Some(Self::sunset()),
            "ice" => Some(Self::ice()),
            "forest" => Some(Self::forest()),
            "lavender" => Some(Self::lavender()),
            "paper" => Some(Self::paper()),
            _ => None,
        }
    }

    /// Load theme from a TOML-like file. Unknown keys are ignored, missing
    /// keys retain defaults. Allows loading user themes.
    fn load_from(path: &std::path::Path) -> Self {
        let mut theme = Self::default();
        if let Ok(content) = std::fs::read_to_string(path) {
            for line in content.lines() {
                let line = line.trim();
                if line.starts_with('#') || line.is_empty() {
                    continue;
                }
                if let Some((key, value)) = line.split_once('=') {
                    let key = key.trim();
                    let value = value.trim().trim_matches('"').trim_matches('\'');
                    if let Some(color) = parse_hex_color(value) {
                        theme.set(key, color);
                    }
                }
            }
        }
        theme
    }

    /// Sets a field by string name. Used by theme loading.
    fn set(&mut self, key: &str, c: Color) {
        match key {
            "code_fg" => self.code_fg = c,
            "code_bg" => self.code_bg = c,
            "heading_color" => self.heading_color = c,
            "quote_color" => self.quote_color = c,
            "list_bullet_color" => self.list_bullet_color = c,
            "table_border_color" => self.table_border_color = c,
            "table_header_color" => self.table_header_color = c,
            "table_cell_color" => self.table_cell_color = c,
            "bg" => self.bg = c,
            "message_bg" => self.message_bg = c,
            "border" => self.border = c,
            "border_active" => self.border_active = c,
            "muted" => self.muted = c,
            "system_msg" => self.system_msg = c,
            "user_color" => self.user_color = c,
            "user_bg" => self.user_bg = c,
            "claude_label" => self.claude_label = c,
            "claude_text" => self.claude_text = c,
            "thinking_color" => self.thinking_color = c,
            "tool_label" => self.tool_label = c,
            "tool_param" => self.tool_param = c,
            "tool_result_color" => self.tool_result_color = c,
            "tool_result_ok" => self.tool_result_ok = c,
            "error_color" => self.error_color = c,
            "warning_color" => self.warning_color = c,
            "header_fg" => self.header_fg = c,
            "status_streaming" => self.status_streaming = c,
            "status_ready" => self.status_ready = c,
            "help_fg" => self.help_fg = c,
            "input_fg" => self.input_fg = c,
            "prompt_fg" => self.prompt_fg = c,
            "separator" => self.separator = c,
            "cost_color" => self.cost_color = c,
            "subagent_border" => self.subagent_border = c,
            "subagent_name" => self.subagent_name = c,
            "subagent_status" => self.subagent_status = c,
            "subagent_done" => self.subagent_done = c,
            "subagent_time" => self.subagent_time = c,
            "tool_bash" => self.tool_bash = c,
            "tool_read" => self.tool_read = c,
            "tool_write" => self.tool_write = c,
            "tool_edit" => self.tool_edit = c,
            "tool_grep" => self.tool_grep = c,
            "tool_find" => self.tool_find = c,
            "tool_ls" => self.tool_ls = c,
            "tool_subagent" => self.tool_subagent = c,
            "tool_ext" => self.tool_ext = c,
            "tool_generic" => self.tool_generic = c,
            "tool_input_bg" => self.tool_input_bg = c,
            "tool_output_bg" => self.tool_output_bg = c,

            // Per-part chrome overrides (dotted keys). Present => Some(c).
            "settings.border" => self.settings_border = Some(c),
            "settings.title" => self.settings_title = Some(c),
            "plugins.border" => self.plugins_border = Some(c),
            "plugins.title" => self.plugins_title = Some(c),
            "models.border" => self.models_border = Some(c),
            "models.title" => self.models_title = Some(c),
            "sessions.border" => self.sessions_border = Some(c),
            "sessions.title" => self.sessions_title = Some(c),
            "sidecar.pill" => self.sidecar_pill = Some(c),

            // Extension token overrides (P19.2): any `ext.<id>.<token>` key
            // is stored verbatim; resolution happens in `ext_token`.
            k if k.starts_with("ext.") => {
                self.ext_overrides.insert(k.to_string(), c);
            }
            _ => {} // unknown key, ignore
        }
    }
}

/// WCAG 2 contrast ratio between two colours; non-RGB colours count as black.
pub(crate) fn wcag_contrast(a: Color, b: Color) -> f64 {
    fn lum(c: Color) -> f64 {
        let Color::Rgb(r, g, b) = c else {
            return 0.0;
        };
        let lin = |v: u8| {
            let v = f64::from(v) / 255.0;
            if v <= 0.04045 {
                v / 12.92
            } else {
                ((v + 0.055) / 1.055).powf(2.4)
            }
        };
        0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
    }
    let (la, lb) = (lum(a), lum(b));
    let (hi, lo) = if la > lb { (la, lb) } else { (lb, la) };
    (hi + 0.05) / (lo + 0.05)
}

/// Tool-card panels derived from a palette: how far each stands off the
/// transcript canvas (WCAG contrast). Matched to the default theme's
/// hand-tuned pair (argument panel 1.14, result panel 1.31), which keeps the
/// two visibly distinct through SSH → tmux.
const TOOL_INPUT_CONTRAST: f64 = 1.14;
const TOOL_OUTPUT_CONTRAST: f64 = 1.31;

impl Theme {
    /// A raised surface on the chrome (`bg`), for selected rows and popups in
    /// modals (Noodle's `backgroundElement`): `bg` lifted toward `input_fg`
    /// just until it stands `step` off the chrome (WCAG contrast).
    pub(crate) fn raised_surface(&self, step: f64) -> Color {
        let (Color::Rgb(r, g, b), Color::Rgb(tr, tg, tb)) = (self.bg, self.input_fg) else {
            return self.bg;
        };
        let mut out = self.bg;
        for i in 1..=80u8 {
            let t = f64::from(i) * 0.005;
            let mix =
                |x: u8, y: u8| (f64::from(x) + (f64::from(y) - f64::from(x)) * t).round() as u8;
            out = Color::Rgb(mix(r, tr), mix(g, tg), mix(b, tb));
            if wcag_contrast(out, self.bg) >= step {
                break;
            }
        }
        out
    }

    /// Tool-card argument panel: the explicit `tool_input_bg`, or derived
    /// from this palette when it is `Color::Reset`.
    /// Event-card accent (left bar + glyph) for a severity: the explicit
    /// `event_*` colour, or the palette's own — error for `critical`, the
    /// active accent for `high`/`medium`/unknown, system text for `low`.
    pub(crate) fn event_accent(&self, severity: &str) -> Color {
        match severity {
            "critical" => derive_reset(self.event_critical, self.error_color),
            "low" => derive_reset(self.event_source, self.system_msg),
            _ => derive_reset(self.event_icon, self.border_active),
        }
    }

    /// Event-card `[source]` label: explicit `event_source`, or the tool-card
    /// label colour so an event reads like the cards around it.
    pub(crate) fn event_label(&self) -> Color {
        derive_reset(self.event_source, self.tool_label)
    }

    /// Event-card body text: explicit `event_text`, or the tool-result colour.
    pub(crate) fn event_body(&self) -> Color {
        derive_reset(self.event_text, self.tool_result_color)
    }

    pub(crate) fn tool_input_background(&self) -> Color {
        self.tool_panel(self.tool_input_bg, TOOL_INPUT_CONTRAST)
    }

    /// Tool-card result panel: the explicit `tool_output_bg`, or derived
    /// (one step further off the canvas than the argument panel).
    pub(crate) fn tool_output_background(&self) -> Color {
        self.tool_panel(self.tool_output_bg, TOOL_OUTPUT_CONTRAST)
    }

    /// The canvas lifted toward the palette's own assistant text colour until
    /// it reaches `target`, so panels carry the palette's hue (green on
    /// phosphor, amber on amber) instead of a foreign slate.
    fn tool_panel(&self, explicit: Color, target: f64) -> Color {
        if explicit != Color::Reset {
            return explicit;
        }
        let (Color::Rgb(r, g, b), Color::Rgb(tr, tg, tb)) =
            (self.message_background(), self.claude_text)
        else {
            return self.bg;
        };
        let canvas = Color::Rgb(r, g, b);
        let mut out = canvas;
        for step in 1..=80u8 {
            let t = f64::from(step) * 0.005;
            let mix =
                |x: u8, y: u8| (f64::from(x) + (f64::from(y) - f64::from(x)) * t).round() as u8;
            out = Color::Rgb(mix(r, tr), mix(g, tg), mix(b, tb));
            if wcag_contrast(out, canvas) >= target {
                break;
            }
        }
        out
    }

    /// Secondary text on the chrome (`bg`): `muted` lifted toward `input_fg`
    /// just until it reads at 4.5:1 (WCAG AA). Several palettes' `muted` and
    /// `help_fg` sit near 2:1 on chrome, which is the "dimmed text is low
    /// contrast" note from the Ratatui showcase review.
    pub(crate) fn chrome_dim(&self) -> Color {
        let (Color::Rgb(r, g, b), Color::Rgb(tr, tg, tb)) = (self.muted, self.input_fg) else {
            return self.muted;
        };
        for step in 0..=20u8 {
            let t = f64::from(step) / 20.0;
            let mix =
                |x: u8, y: u8| (f64::from(x) + (f64::from(y) - f64::from(x)) * t).round() as u8;
            let c = Color::Rgb(mix(r, tr), mix(g, tg), mix(b, tb));
            if wcag_contrast(c, self.bg) >= 4.5 {
                return c;
            }
        }
        self.input_fg
    }
}

/// Per-part style resolvers (P19.1).
///
/// Resolution rule: **part override if present, else the base token**. The
/// border resolver always returns a concrete `Color` (base = `border_active`)
/// so the call site is unconditional and identical to today when unset. The
/// title resolver returns `Option<Color>`: today no modal sets a title style,
/// so the call site applies `.title_style(..)` ONLY when `Some`, keeping the
/// unset path byte-identical.
impl Theme {
    /// Border color for a modal's outer block. Falls back to `border_active`.
    pub(crate) fn modal_border(&self, kind: ModalKind) -> Color {
        let part = match kind {
            ModalKind::Settings => self.settings_border,
            ModalKind::Plugins => self.plugins_border,
            ModalKind::Models => self.models_border,
            ModalKind::Sessions => self.sessions_border,
        };
        part.unwrap_or(self.border_active)
    }

    /// Optional title color for a modal's block. `None` => leave the title
    /// unstyled exactly as today (do not call `.title_style`).
    pub(crate) fn modal_title(&self, kind: ModalKind) -> Option<Color> {
        match kind {
            ModalKind::Settings => self.settings_title,
            ModalKind::Plugins => self.plugins_title,
            ModalKind::Models => self.models_title,
            ModalKind::Sessions => self.sessions_title,
        }
    }

    /// Resting tint of the sidecar header pill. Falls back to `muted`.
    pub(crate) fn sidecar_pill_color(&self) -> Color {
        self.sidecar_pill.unwrap_or(self.muted)
    }

    /// Resolve a namespaced extension theme token `ext.<ext_id>.<token>`
    /// (P19.2). Resolution order: user theme-TOML override (in
    /// `ext_overrides`) → extension manifest declaration (in the load-time
    /// registry) → `None`. Extension-rendered surfaces treat `None` as "use
    /// whatever base token you use today", so extensions that declare no
    /// tokens — and users that set no overrides — see zero change.
    pub(crate) fn ext_token(&self, ext_id: &str, token: &str) -> Option<Color> {
        let key = format!("ext.{ext_id}.{token}");
        if let Some(c) = self.ext_overrides.get(&key) {
            return Some(*c);
        }
        EXT_DECLARED_TOKENS
            .read()
            .ok()
            .and_then(|map| map.get(&key).copied())
    }
}

/// Extension-declared theme tokens, keyed `ext.<plugin-id>.<token>` (P19.2).
///
/// Lives OUTSIDE the `Theme` value on purpose: the theme in [`THEME`] is
/// rebuilt wholesale on palette switches (`set_theme`), and manifest-declared
/// tokens must survive that — they are a property of the loaded extensions,
/// not of the palette. User overrides, by contrast, live inside `Theme`
/// (parsed from the theme file) and therefore correctly reload with it.
static EXT_DECLARED_TOKENS: LazyLock<std::sync::RwLock<std::collections::HashMap<String, Color>>> =
    LazyLock::new(|| std::sync::RwLock::new(std::collections::HashMap::new()));

/// Merge one extension's manifest-declared theme tokens into the registry
/// under `ext.<ext_id>.<token>` (P19.2). Values are `#rgb`/`#rrggbb` hex;
/// unparseable entries are skipped (same forgiving posture as the theme-file
/// loader — the manifest validator upstream already rejects them at load).
/// Idempotent per (ext, token): reloading an extension re-registers cleanly.
pub(crate) fn register_ext_theme_tokens<'a>(
    ext_id: &str,
    tokens: impl IntoIterator<Item = (&'a str, &'a str)>,
) {
    if let Ok(mut map) = EXT_DECLARED_TOKENS.write() {
        for (token, value) in tokens {
            if let Some(color) = parse_hex_color(value) {
                map.insert(format!("ext.{ext_id}.{token}"), color);
            }
        }
    }
}

/// Drop all declared tokens for one extension (unload hygiene).
#[allow(dead_code)]
pub(crate) fn clear_ext_theme_tokens(ext_id: &str) {
    if let Ok(mut map) = EXT_DECLARED_TOKENS.write() {
        let prefix = format!("ext.{ext_id}.");
        map.retain(|k, _| !k.starts_with(&prefix));
    }
}

/// Parse `#rrggbb` or `#rgb` into a `Color::Rgb`. Returns `None` for anything
/// that doesn't match — malformed entries should be skipped, not crash.
fn parse_hex_color(s: &str) -> Option<Color> {
    let s = s.trim().trim_start_matches('#');
    match s.len() {
        6 => {
            let r = u8::from_str_radix(&s[0..2], 16).ok()?;
            let g = u8::from_str_radix(&s[2..4], 16).ok()?;
            let b = u8::from_str_radix(&s[4..6], 16).ok()?;
            Some(Color::Rgb(r, g, b))
        }
        3 => {
            let r = u8::from_str_radix(&s[0..1], 16).ok()?;
            let g = u8::from_str_radix(&s[1..2], 16).ok()?;
            let b = u8::from_str_radix(&s[2..3], 16).ok()?;
            Some(Color::Rgb(r * 17, g * 17, b * 17)) // 0xF -> 0xFF
        }
        _ => None,
    }
}

/// `Color::Reset` means "derive": use `derived`; anything else is explicit.
fn derive_reset(raw: Color, derived: Color) -> Color {
    if raw == Color::Reset {
        derived
    } else {
        raw
    }
}

/// Environment variable that picks the theme for one process (one TUI run),
/// ahead of `~/.synaps-cli/theme` and `theme = <name>` in config. For an app
/// that embeds the TUI (e.g. a terminal pane in a light window) and must not
/// change the user's global theme. The value is a theme name: a user theme
/// file `~/.synaps-cli/themes/<name>`, else a builtin. A value that is not a
/// plain name, or names no theme, is ignored, so the usual order applies.
pub(crate) const THEME_ENV: &str = "SYNAPS_THEME";

/// A theme name from `SYNAPS_THEME`, if it is a plain name: 1 to 64 ASCII
/// letters, digits, `-`, `_` or `.`, not starting with `.`. Anything else
/// (a path, `..`, empty, non-UTF-8) is not a name and is ignored, so the
/// value can never reach outside `themes/`.
fn theme_env_name(value: Option<&std::ffi::OsStr>) -> Option<&str> {
    let name = value?.to_str()?.trim();
    let plain = !name.is_empty()
        && name.len() <= 64
        && !name.starts_with('.')
        && name
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'));
    plain.then_some(name)
}

/// The theme `SYNAPS_THEME` names, resolved by `resolve` (a user theme file,
/// else a builtin: [`load_theme_by_name`]); `None` when it is unset, not a
/// plain name, or names no theme.
fn theme_from_env(
    value: Option<&std::ffi::OsStr>,
    resolve: impl FnOnce(&str) -> Option<Theme>,
) -> Option<Theme> {
    theme_env_name(value).and_then(resolve)
}

/// The theme name `SYNAPS_THEME` sets for this process, if it names a theme.
/// Boot uses it instead of the config's `theme` (e.g. whether the live-MXC
/// subscriber starts for "myx").
pub(crate) fn env_theme_name() -> Option<String> {
    let value = std::env::var_os(THEME_ENV);
    let name = theme_env_name(value.as_deref())?;
    load_theme_by_name(name).map(|_| name.to_string())
}

/// Global theme, loaded in this order:
/// 0. `SYNAPS_THEME=<name>` in the environment (see [`THEME_ENV`]), if it
///    names a theme — for this process only
/// 1. `~/.synaps-cli/theme` file (if exists) — overrides everything else
/// 2. `theme = <name>` in config:
///    a. Check `~/.synaps-cli/themes/<name>` file first (user-editable)
///    b. Fall back to compiled-in builtin
/// 3. Falls back to default
pub(crate) fn load_theme_from_config() -> Theme {
    if let Some(theme) = theme_from_env(std::env::var_os(THEME_ENV).as_deref(), load_theme_by_name)
    {
        return theme;
    }

    // First check for a theme file (highest priority after the environment)
    let path = synaps_cli::config::resolve_read_path("theme");
    if path.exists() {
        return Theme::load_from(&path);
    }

    // Then check config for a named built-in theme
    if let Ok(content) = std::fs::read_to_string(synaps_cli::config::resolve_read_path("config")) {
        for line in content.lines() {
            let line = line.trim();
            if line.starts_with('#') || line.is_empty() {
                continue;
            }
            if let Some((key, val)) = line.split_once('=') {
                if key.trim() == "theme" {
                    let name = val.trim();
                    let theme_file = synaps_cli::config::base_dir().join("themes").join(name);
                    if theme_file.exists() {
                        return Theme::load_from(&theme_file);
                    }
                    if let Some(theme) = Theme::builtin(name) {
                        return theme;
                    }
                }
            }
        }
    }

    // No theme configured: use the default palette.
    Theme::default()
}

pub(crate) fn load_theme_by_name(name: &str) -> Option<Theme> {
    let theme_file = synaps_cli::config::base_dir().join("themes").join(name);
    if theme_file.exists() {
        return Some(Theme::load_from(&theme_file));
    }
    Theme::builtin(name)
}

/// The `theme = <name>` value from config, if any. Used at boot to decide
/// whether the live-MXC subscriber should start alongside the "myx" theme.
/// (A `~/.synaps-cli/theme` override file wins over this for *colors*, same
/// as `load_theme_from_config` — this only reports the configured name.)
///
/// Routed through the real config loader (shady F6): a second hand-rolled
/// parser drifted on lines like `theme = "myx" # comment`, silently keeping
/// the boot subscriber off while the color loader still resolved myx.
pub(crate) fn configured_theme_name() -> Option<String> {
    synaps_cli::config::load_config().theme
}

/// Whether the root TUI paints an opaque canvas. `false` preserves the exact
/// legacy 0.7.0 layout behavior outside individual widgets.
pub(crate) static BACKGROUND_OPAQUE: LazyLock<AtomicBool> =
    LazyLock::new(|| AtomicBool::new(synaps_cli::config::load_config().tui_background_opaque));

pub(crate) fn background_is_opaque() -> bool {
    BACKGROUND_OPAQUE.load(Ordering::Relaxed)
}

pub(crate) fn set_background_opaque(opaque: bool) {
    BACKGROUND_OPAQUE.store(opaque, Ordering::Relaxed);
}

/// 8-bit RGB triple, as the terminal reports its default background.
pub(crate) type Rgb8 = (u8, u8, u8);

/// The terminal's default background (OSC 11, settled once at boot by
/// `run_setup` from the DA1-fenced burst). Packed `0x01RRGGBB`; `0` means
/// unknown (no reply / timeout / not a tty) ⇒ painting is unchanged.
///
/// Why it matters: terminals with background opacity (kitty
/// `background_opacity`) apply it to every cell whose bg EQUALS the default
/// bg, not only unpainted cells — so a theme colour that happens to match the
/// user's terminal colour renders see-through even in opaque mode.
static TERMINAL_DEFAULT_BG: AtomicU32 = AtomicU32::new(0);

fn pack_rgb8(bg: Option<Rgb8>) -> u32 {
    bg.map_or(0, |(r, g, b)| {
        0x0100_0000 | (u32::from(r) << 16) | (u32::from(g) << 8) | u32::from(b)
    })
}

fn unpack_rgb8(v: u32) -> Option<Rgb8> {
    (v & 0x0100_0000 != 0).then_some(((v >> 16) as u8, (v >> 8) as u8, v as u8))
}

/// Record the detected terminal default bg (`None` = unknown).
pub(crate) fn set_terminal_default_bg(bg: Option<Rgb8>) {
    TERMINAL_DEFAULT_BG.store(pack_rgb8(bg), Ordering::Relaxed);
}

#[cfg(any(test, feature = "testing"))]
thread_local! {
    /// Test seam: the terminal bg frames rendered on this thread see
    /// (`TestHarness::set_terminal_bg`). Outer `None` = no override (use the
    /// process global); `Some(None)` = forced unknown. Headless tests render
    /// on their own thread, so this never leaks between parallel tests.
    static TERMINAL_BG_OVERRIDE: std::cell::Cell<Option<Option<Rgb8>>> =
        const { std::cell::Cell::new(None) };
}

/// Override (or with `None`, clear the override of) this thread's terminal bg.
#[cfg(any(test, feature = "testing"))]
pub(crate) fn set_terminal_default_bg_for_thread(bg: Option<Option<Rgb8>>) {
    TERMINAL_BG_OVERRIDE.with(|o| o.set(bg));
}

/// The detected terminal default bg, or `None` if unknown.
pub(crate) fn terminal_default_bg() -> Option<Rgb8> {
    #[cfg(any(test, feature = "testing"))]
    if let Some(bg) = TERMINAL_BG_OVERRIDE.with(std::cell::Cell::get) {
        return bg;
    }
    unpack_rgb8(TERMINAL_DEFAULT_BG.load(Ordering::Relaxed))
}

/// `c`, moved one imperceptible step (±1 on blue, staying in range) if it is
/// exactly the terminal's default bg `term`; otherwise `c` unchanged. Pure.
/// Only `Color::Rgb` can be compared: named/indexed colours resolve through
/// the terminal's palette, which we don't query.
pub(crate) fn steer_off_terminal_bg(c: Color, term: Option<Rgb8>) -> Color {
    match (c, term) {
        (Color::Rgb(r, g, b), Some(t)) if (r, g, b) == t => {
            Color::Rgb(r, g, if b < u8::MAX { b + 1 } else { b - 1 })
        }
        _ => c,
    }
}

/// Steer every cell bg in `buf` off `term` (fg untouched). Pure; a cheap
/// compare per cell, no-op when `term` is `None`.
pub(crate) fn steer_buffer_off_terminal_bg(buf: &mut ratatui::buffer::Buffer, term: Option<Rgb8>) {
    if term.is_none() {
        return;
    }
    for cell in &mut buf.content {
        cell.bg = steer_off_terminal_bg(cell.bg, term);
    }
}

/// The terminal bg the opaque guard steers off: `Some` only in opaque mode
/// with a detected terminal bg. Invisible mode is `None` — there the
/// see-through is the point.
pub(crate) fn opaque_guard_target() -> Option<Rgb8> {
    if background_is_opaque() {
        terminal_default_bg()
    } else {
        None
    }
}

/// Final per-frame pass (end of `render_frame_into`): in opaque mode, no
/// cell may carry the terminal's exact default bg.
pub(crate) fn guard_opaque_frame(buf: &mut ratatui::buffer::Buffer) {
    steer_buffer_off_terminal_bg(buf, opaque_guard_target());
}

pub(crate) static THEME: LazyLock<ArcSwap<Theme>> =
    LazyLock::new(|| ArcSwap::from_pointee(load_theme_from_config()));

/// Replace the process-global theme. Tests: every test in this crate shares
/// this global and runs in parallel with render tests that read it, so a test
/// may only store the theme that is already applied (see
/// `theme::transition::tests::applied`) — never a different one.
pub(crate) fn set_theme(theme: Theme) {
    THEME.store(Arc::new(theme));
}
#[cfg(test)]
mod theme_tests {
    use super::*;

    /// `SYNAPS_THEME=<name>` picks a theme (trimmed); unset, empty or an
    /// unknown name gives `None`, so `load_theme_from_config` falls through
    /// to the theme file and config as before. Resolved through an injected
    /// resolver: the process environment and the user's themes folder are
    /// shared by every test, so nothing here sets or reads them.
    #[test]
    fn synaps_theme_names_the_theme_for_this_process() {
        use std::ffi::OsStr;
        let builtin = |n: &str| Theme::builtin(n);
        assert_eq!(
            theme_from_env(Some(OsStr::new("paper")), builtin),
            Theme::builtin("paper")
        );
        assert_eq!(
            theme_from_env(Some(OsStr::new("  nord\n")), builtin),
            Theme::builtin("nord"),
            "trimmed"
        );
        assert_eq!(theme_from_env(None, builtin), None, "unset");
        assert_eq!(theme_from_env(Some(OsStr::new("")), builtin), None, "empty");
        assert_eq!(
            theme_from_env(Some(OsStr::new("  ")), builtin),
            None,
            "blank"
        );
        assert_eq!(
            theme_from_env(Some(OsStr::new("no-such-theme")), builtin),
            None,
            "unknown: fall through"
        );
    }

    /// The value is joined under `themes/`, so it must be a plain name:
    /// anything path-like is ignored before any file is looked up.
    #[test]
    fn synaps_theme_is_a_name_never_a_path() {
        use std::ffi::OsStr;
        let long = "a".repeat(65);
        for v in [
            "..",
            "../theme",
            ".hidden",
            "a/b",
            "/etc/passwd",
            "a\\b",
            "x y",
            "pa\0per",
            "nörd",
            long.as_str(),
        ] {
            let mut asked = false;
            let got = theme_from_env(Some(OsStr::new(v)), |_| {
                asked = true;
                Some(Theme::default())
            });
            assert!(got.is_none() && !asked, "{v:?} must not be looked up");
        }
        #[cfg(unix)]
        {
            use std::os::unix::ffi::OsStrExt;
            assert_eq!(theme_env_name(Some(OsStr::from_bytes(b"pa\xffper"))), None);
        }
        for ok in ["paper", "solarized-dark", "my_theme.v2", &long[..64]] {
            assert_eq!(theme_env_name(Some(OsStr::new(ok))), Some(ok));
        }
    }

    #[test]
    fn default_tool_panels_are_explicit() {
        // The default theme is hand-tuned: argument and result panels must
        // remain visibly distinct through the SSH → tmux rendering path.
        let t = Theme::default();
        assert_eq!(t.tool_bash, Color::Reset);
        assert_eq!(t.tool_read, Color::Reset);
        assert_eq!(t.tool_generic, Color::Reset);
        assert_eq!(t.tool_input_bg, Color::Rgb(23, 28, 40));
        assert_eq!(t.tool_output_bg, Color::Rgb(32, 40, 55));
    }

    #[test]
    fn tool_styling_is_themeable() {
        let mut t = Theme::default();
        // A theme file can override each via its key name.
        t.set("tool_bash", Color::Rgb(1, 2, 3));
        t.set("tool_read", Color::Rgb(4, 5, 6));
        t.set("tool_input_bg", Color::Rgb(7, 8, 9));
        t.set("tool_output_bg", Color::Rgb(10, 11, 12));
        assert_eq!(t.tool_bash, Color::Rgb(1, 2, 3));
        assert_eq!(t.tool_read, Color::Rgb(4, 5, 6));
        assert_eq!(t.tool_input_bg, Color::Rgb(7, 8, 9));
        assert_eq!(t.tool_output_bg, Color::Rgb(10, 11, 12));
    }

    #[test]
    fn night_city_has_neon_tool_colors() {
        // night-city is the ONLY theme with explicit neon tool accents.
        let t = Theme::builtin("night-city").expect("night-city exists");
        assert_eq!(t.tool_bash, Color::Rgb(108, 240, 122));
        assert_eq!(t.tool_read, Color::Rgb(34, 211, 238));
        assert_eq!(t.tool_write, Color::Rgb(255, 46, 136));
        assert_eq!(t.tool_ext, Color::Rgb(252, 214, 70));
    }

    #[test]
    fn builtin_palettes_use_reset_tool_colors() {
        // Other palettes should NOT inherit neon — they get Reset via Default —
        // and their tool panels derive from the palette, not the default's
        // slate.
        let t = Theme::builtin("dracula").expect("dracula exists");
        assert_eq!(t.tool_bash, Color::Reset);
        assert_eq!(t.tool_input_bg, Color::Reset);
        assert_eq!(t.tool_output_bg, Color::Reset);
    }

    /// Every builtin's tool panels: the default keeps its hand-tuned pair;
    /// every other palette derives a pair in its own hue that stands off the
    /// canvas like the default's does, with the result panel a clear step
    /// beyond the argument panel.
    #[test]
    fn tool_panels_follow_each_palette() {
        let d = Theme::default();
        assert_eq!(d.tool_input_background(), Color::Rgb(23, 28, 40));
        assert_eq!(d.tool_output_background(), Color::Rgb(32, 40, 55));
        for name in [
            "night-city",
            "neon-rain",
            "amber",
            "phosphor",
            "solarized-dark",
            "blood",
            "ocean",
            "rose-pine",
            "nord",
            "dracula",
            "monokai",
            "gruvbox",
            "catppuccin",
            "tokyo-night",
            "sunset",
            "ice",
            "forest",
            "lavender",
            "paper",
        ] {
            let t = Theme::builtin(name).unwrap();
            let canvas = t.message_background();
            let (i, o) = (t.tool_input_background(), t.tool_output_background());
            assert_ne!(i, Color::Rgb(23, 28, 40), "{name}: not the default slate");
            let (ci, co) = (wcag_contrast(i, canvas), wcag_contrast(o, canvas));
            assert!((1.12..1.30).contains(&ci), "{name}: input step {ci:.3}");
            assert!(
                co >= 1.28 && co - ci >= 0.1,
                "{name}: output {co:.3} vs input {ci:.3}"
            );
        }
        // myx is untouched: its panels are Myx's own surfaces, verbatim.
        let m = Theme::builtin("myx").unwrap();
        assert_eq!(
            m.tool_input_background(),
            Color::Rgb(0x1e, 0x20, 0x30),
            "myx panel"
        );
        assert_eq!(
            m.tool_output_background(),
            Color::Rgb(0x22, 0x24, 0x36),
            "myx element"
        );
        // The case that was reported: phosphor's panels are green, not slate.
        let p = Theme::builtin("phosphor").unwrap();
        for c in [p.tool_input_background(), p.tool_output_background()] {
            let Color::Rgb(r, g, b) = c else {
                unreachable!()
            };
            assert!(g > r && g > b, "phosphor panel {c:?} should be green");
        }
    }

    // ---- Per-part chrome overrides (P19.1) --------------------------------

    #[test]
    fn per_part_overrides_absent_by_default() {
        // The whole point: no part keys => every Option is None => resolvers
        // fall back to base tokens => frames are byte-identical to today.
        let t = Theme::default();
        assert_eq!(t.settings_border, None);
        assert_eq!(t.settings_title, None);
        assert_eq!(t.plugins_border, None);
        assert_eq!(t.plugins_title, None);
        assert_eq!(t.models_border, None);
        assert_eq!(t.models_title, None);
        assert_eq!(t.sidecar_pill, None);
    }

    #[test]
    fn modal_border_falls_back_to_base_token_when_unset() {
        // Regression guard: absent part key => resolver returns border_active,
        // identical to the value every modal used before P19.1.
        let t = Theme::default();
        assert_eq!(t.modal_border(ModalKind::Settings), t.border_active);
        assert_eq!(t.modal_border(ModalKind::Plugins), t.border_active);
        assert_eq!(t.modal_border(ModalKind::Models), t.border_active);
    }

    #[test]
    fn modal_title_is_none_when_unset() {
        // None => call sites skip `.title_style` => title unstyled as today.
        let t = Theme::default();
        assert_eq!(t.modal_title(ModalKind::Settings), None);
        assert_eq!(t.modal_title(ModalKind::Plugins), None);
        assert_eq!(t.modal_title(ModalKind::Models), None);
    }

    #[test]
    fn sidecar_pill_falls_back_to_muted_when_unset() {
        let t = Theme::default();
        assert_eq!(t.sidecar_pill_color(), t.muted);
    }

    #[test]
    fn fallback_holds_across_all_18_palettes() {
        // Every built-in palette, with no part overrides, must resolve each
        // part to its base token — the "zero regression across 18 palettes"
        // guarantee, asserted directly against the resolvers.
        // The 20 named palettes plus the built-in `default` (21 total).
        const NAMES: [&str; 21] = [
            "default",
            "night-city",
            "neon-rain",
            "amber",
            "phosphor",
            "solarized-dark",
            "blood",
            "ocean",
            "rose-pine",
            "nord",
            "dracula",
            "monokai",
            "myx",
            "gruvbox",
            "catppuccin",
            "tokyo-night",
            "sunset",
            "ice",
            "forest",
            "lavender",
            "paper",
        ];
        for name in NAMES {
            let t = Theme::builtin(name).unwrap_or_else(|| panic!("{name} exists"));
            for kind in [
                ModalKind::Settings,
                ModalKind::Plugins,
                ModalKind::Models,
                ModalKind::Sessions,
            ] {
                assert_eq!(
                    t.modal_border(kind),
                    t.border_active,
                    "{name}: {kind:?} border must fall back to border_active"
                );
                assert_eq!(
                    t.modal_title(kind),
                    None,
                    "{name}: {kind:?} title must be None"
                );
            }
            assert_eq!(
                t.sidecar_pill_color(),
                t.muted,
                "{name}: pill falls back to muted"
            );
        }
    }

    #[test]
    fn settings_border_distinct_from_plugins_border() {
        // Acceptance (a): a user TOML setting settings.border != plugins.border
        // makes the resolver return *different* colors — so the two modals
        // render distinctly. Parsed through the real `set`/dotted-key path.
        let mut t = Theme::default();
        t.set("settings.border", Color::Rgb(0xAA, 0x00, 0x00));
        t.set("plugins.border", Color::Rgb(0x00, 0x00, 0xBB));
        let sb = t.modal_border(ModalKind::Settings);
        let pb = t.modal_border(ModalKind::Plugins);
        assert_eq!(sb, Color::Rgb(0xAA, 0x00, 0x00));
        assert_eq!(pb, Color::Rgb(0x00, 0x00, 0xBB));
        assert_ne!(sb, pb, "settings border must differ from plugins border");
        // Models was NOT overridden => still falls back to base token.
        assert_eq!(t.modal_border(ModalKind::Models), t.border_active);
    }

    #[test]
    fn per_part_keys_parse_from_theme_file_lines() {
        // Exercise the same dotted-key path the TOML loader uses.
        let mut t = Theme::default();
        t.set("settings.title", Color::Rgb(1, 2, 3));
        t.set("plugins.title", Color::Rgb(4, 5, 6));
        t.set("models.border", Color::Rgb(7, 8, 9));
        t.set("sidecar.pill", Color::Rgb(10, 11, 12));
        assert_eq!(
            t.modal_title(ModalKind::Settings),
            Some(Color::Rgb(1, 2, 3))
        );
        assert_eq!(t.modal_title(ModalKind::Plugins), Some(Color::Rgb(4, 5, 6)));
        assert_eq!(t.modal_border(ModalKind::Models), Color::Rgb(7, 8, 9));
        assert_eq!(t.sidecar_pill_color(), Color::Rgb(10, 11, 12));
        // Unknown dotted keys are still ignored, not panics.
        t.set("bogus.key", Color::Rgb(0, 0, 0));
    }

    // ---- Namespaced extension tokens (P19.2) -------------------------------
    // NOTE: the declared-token registry is a process-wide static; every test
    // below uses a unique ext id so tests stay independent under parallel run.

    #[test]
    fn ext_token_is_none_when_nothing_declared() {
        // Baseline: no manifest declaration, no user override => None.
        // This is the "existing extensions unaffected" guarantee.
        let t = Theme::default();
        assert_eq!(t.ext_token("p192-none-ext", "accent"), None);
    }

    #[test]
    fn manifest_declared_token_resolves() {
        // Acceptance: an extension ships a token; it resolves via ext_token.
        register_ext_theme_tokens("p192-decl-ext", [("accent", "#22d3ee")]);
        let t = Theme::default();
        assert_eq!(
            t.ext_token("p192-decl-ext", "accent"),
            Some(Color::Rgb(0x22, 0xd3, 0xee))
        );
        // A token the extension did NOT declare stays None.
        assert_eq!(t.ext_token("p192-decl-ext", "other"), None);
    }

    #[test]
    fn user_toml_override_wins_over_manifest() {
        // Acceptance: user theme TOML `ext.<id>.<token>` beats the manifest.
        register_ext_theme_tokens("p192-override-ext", [("accent", "#111111")]);
        let mut t = Theme::default();
        // Same dotted-key path the theme-file loader uses.
        t.set("ext.p192-override-ext.accent", Color::Rgb(0xAA, 0xBB, 0xCC));
        assert_eq!(
            t.ext_token("p192-override-ext", "accent"),
            Some(Color::Rgb(0xAA, 0xBB, 0xCC)),
            "user override must win over the manifest-declared value"
        );
    }

    #[test]
    fn user_override_resolves_even_without_declaration() {
        // A user may theme a token the extension never declared — still works.
        let mut t = Theme::default();
        t.set("ext.p192-useronly-ext.badge", Color::Rgb(1, 2, 3));
        assert_eq!(
            t.ext_token("p192-useronly-ext", "badge"),
            Some(Color::Rgb(1, 2, 3))
        );
    }

    #[test]
    fn declared_tokens_survive_palette_switch() {
        // The registry lives outside Theme, so switching palettes (a fresh
        // Theme value) must not lose manifest-declared tokens.
        register_ext_theme_tokens("p192-switch-ext", [("accent", "#fa0")]);
        let fresh = Theme::builtin("dracula").expect("dracula exists");
        assert_eq!(
            fresh.ext_token("p192-switch-ext", "accent"),
            Some(Color::Rgb(0xff, 0xaa, 0x00)), // #fa0 short-form expansion
        );
    }

    #[test]
    fn malformed_declared_values_are_skipped() {
        // register_ext_theme_tokens is forgiving: bad hex never lands.
        register_ext_theme_tokens("p192-badhex-ext", [("accent", "not-a-color")]);
        let t = Theme::default();
        assert_eq!(t.ext_token("p192-badhex-ext", "accent"), None);
    }

    #[test]
    fn clear_ext_theme_tokens_removes_only_that_extension() {
        register_ext_theme_tokens("p192-clear-a", [("accent", "#111111")]);
        register_ext_theme_tokens("p192-clear-b", [("accent", "#222222")]);
        clear_ext_theme_tokens("p192-clear-a");
        let t = Theme::default();
        assert_eq!(t.ext_token("p192-clear-a", "accent"), None);
        assert_eq!(
            t.ext_token("p192-clear-b", "accent"),
            Some(Color::Rgb(0x22, 0x22, 0x22))
        );
    }

    #[test]
    fn hello_ext_demo_token_resolves_and_user_override_wins() {
        // The P19.2 acceptance vehicle: hello-ext (examples/extensions/
        // hello-ext) declares `accent = #22d3ee` in its manifest. Simulate
        // exactly what the extension-loader arm does at load, then apply a
        // user TOML override and confirm it wins.
        register_ext_theme_tokens("hello-ext", [("accent", "#22d3ee")]);
        let mut t = Theme::default();
        assert_eq!(
            t.ext_token("hello-ext", "accent"),
            Some(Color::Rgb(0x22, 0xd3, 0xee)),
            "hello-ext's manifest token must resolve"
        );
        t.set("ext.hello-ext.accent", Color::Rgb(0xff, 0x00, 0xff));
        assert_eq!(
            t.ext_token("hello-ext", "accent"),
            Some(Color::Rgb(0xff, 0x00, 0xff)),
            "user TOML `ext.hello-ext.accent` must override the manifest"
        );
    }
}

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

    const BUILTINS: &[&str] = &[
        "default",
        "night-city",
        "neon-rain",
        "amber",
        "phosphor",
        "solarized-dark",
        "blood",
        "ocean",
        "rose-pine",
        "nord",
        "dracula",
        "monokai",
        "myx",
        "gruvbox",
        "catppuccin",
        "tokyo-night",
        "sunset",
        "ice",
        "forest",
        "lavender",
        "paper",
    ];

    fn rgb(c: Color) -> (u8, u8, u8) {
        match c {
            Color::Rgb(r, g, b) => (r, g, b),
            other => panic!("expected an explicit Rgb value, got {other:?}"),
        }
    }

    /// WCAG relative luminance.
    fn luminance((r, g, b): (u8, u8, u8)) -> f64 {
        fn lin(v: u8) -> f64 {
            let v = f64::from(v) / 255.0;
            if v <= 0.04045 {
                v / 12.92
            } else {
                ((v + 0.055) / 1.055).powf(2.4)
            }
        }
        0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
    }

    fn contrast(a: (u8, u8, u8), b: (u8, u8, u8)) -> f64 {
        let (la, lb) = (luminance(a), luminance(b));
        let (hi, lo) = if la > lb { (la, lb) } else { (lb, la) };
        (hi + 0.05) / (lo + 0.05)
    }

    /// Themes whose base is too near black to hold a distinct canvas.
    ///
    /// Measured, not guessed: on these palettes `bg` sits within a few RGB
    /// units of black, so even a *pure black* canvas fails to reach 1.05
    /// contrast, and raising it instead collides with `code_bg` (which renders
    /// on top of the canvas). There is no third elevation level available
    /// between two colours that are already touching.
    ///
    /// These deliberately render flush with the header and input chrome. The
    /// message area still draws its own border, which carries the separation.
    const FLUSH: &[&str] = &[
        "amber",
        "blood",
        "dracula",
        "forest",
        "ice",
        "lavender",
        "neon-rain",
        "night-city",
        "ocean",
        "phosphor",
        "rose-pine",
        "sunset",
    ];

    /// Flush themes must match chrome EXACTLY. A near-miss reads as a
    /// rendering bug rather than a deliberate choice.
    #[test]
    fn flush_themes_match_chrome_exactly() {
        for name in FLUSH {
            let t = Theme::builtin(name).unwrap_or_else(|| panic!("{name} is a builtin"));
            assert_eq!(
                rgb(t.message_background()),
                rgb(t.bg),
                "{name} is a flush theme: canvas must equal chrome exactly"
            );
        }
    }

    /// User turns paint `user_bg` over the canvas. If the two match, user
    /// messages have no surface at all (ocean shipped like this).
    #[test]
    fn user_turns_stand_off_the_canvas() {
        for name in BUILTINS {
            let t = Theme::builtin_for_test(name);
            assert_ne!(
                t.user_bg,
                t.message_background(),
                "{name}: user_bg must differ from the canvas"
            );
        }
    }

    /// Every non-flush theme must clear the perceptibility floor.
    #[test]
    fn elevated_themes_separate_canvas_from_chrome() {
        for name in BUILTINS.iter().filter(|n| !FLUSH.contains(n)) {
            let t = Theme::builtin(name).unwrap_or_else(|| panic!("{name} is a builtin"));
            let c = contrast(rgb(t.bg), rgb(t.message_background()));
            assert!(
                (1.05..=1.30).contains(&c),
                "{name}: canvas/chrome contrast {c:.3} outside 1.05-1.30"
            );
        }
    }

    /// Recessing preserves hue and saturation; lightening did not. An earlier
    /// attempt raised CIELAB L* with a/b held fixed and `blood` kept 23% of its
    /// saturation, rendering a grey canvas under a deep-red theme.
    #[test]
    fn elevated_themes_keep_their_colour() {
        fn saturation((r, g, b): (u8, u8, u8)) -> f64 {
            let (hi, lo) = (r.max(g).max(b), r.min(g).min(b));
            if hi == 0 {
                0.0
            } else {
                f64::from(hi - lo) / f64::from(hi)
            }
        }
        // "myx" is exempt: its bg and canvas are BOTH verbatim Myx-designed
        // surfaces (library panel + background), not a derived recess — this
        // guard exists for derivation drift, and Myx's own hierarchy sits at
        // 84% saturation retention by design.
        for name in BUILTINS
            .iter()
            .filter(|n| !FLUSH.contains(n) && **n != "myx")
        {
            let t = Theme::builtin(name).unwrap_or_else(|| panic!("{name} is a builtin"));
            let (bg, canvas) = (rgb(t.bg), rgb(t.message_background()));
            let base = saturation(bg);
            if base < 0.05 {
                continue; // achromatic (gruvbox)
            }
            let kept = saturation(canvas) / base;
            assert!(
                kept >= 0.85,
                "{name}: canvas kept only {:.0}% of theme saturation (bg={bg:?} canvas={canvas:?})",
                kept * 100.0
            );
        }
    }

    /// `code_bg` and `user_bg` render ON TOP of the canvas, so the canvas must
    /// never be brighter than `code_bg` or code blocks invert.
    ///
    /// `solarized-dark` is exempt: its `code_bg` (0,36,43) is already darker
    /// than its `bg` (0,43,54), so code blocks recess by that palette's own
    /// design. Its canvas is raised toward its separator instead.
    ///
    /// `paper` is exempt: it is the light palette, and its code blocks are
    /// dark islands on purpose (syntax highlighting is always a dark syntect
    /// theme), so they sit far below its canvas. `paper_is_light_with_dark_code_islands`
    /// pins that instead.
    #[test]
    fn canvas_never_outranks_code_blocks() {
        for name in BUILTINS.iter().filter(|n| !FLUSH.contains(n)) {
            if *name == "solarized-dark" || *name == "paper" {
                continue;
            }
            let t = Theme::builtin(name).unwrap_or_else(|| panic!("{name} is a builtin"));
            assert!(
                luminance(rgb(t.message_background())) < luminance(rgb(t.code_bg)),
                "{name}: canvas must sit below code_bg in elevation"
            );
        }
    }

    /// `paper`, the light palette: a light canvas and chrome, dark code
    /// islands, body text at 11:1 or more on the canvas, and every accent
    /// that is drawn as text at 4.5:1 (WCAG AA) or more on the chrome and the
    /// canvas. Every surface it paints is explicit, never a `Reset` derived
    /// from a dark-canvas rule.
    #[test]
    fn paper_is_light_with_dark_code_islands() {
        let t = Theme::builtin_for_test("paper");
        let (bg, canvas) = (rgb(t.bg), rgb(t.message_background()));
        assert!(
            luminance(bg) > 0.5 && luminance(canvas) > luminance(bg),
            "light, canvas brightest"
        );
        assert!(
            luminance(rgb(t.code_bg)) < 0.05,
            "code blocks stay dark islands"
        );
        assert!(
            contrast(rgb(t.code_fg), rgb(t.code_bg)) >= 7.0,
            "inline code reads on its island"
        );
        for (what, c) in [
            ("claude_text", t.claude_text),
            ("user_color", t.user_color),
            ("input_fg", t.input_fg),
            ("table_cell_color", t.table_cell_color),
        ] {
            let got = contrast(rgb(c), canvas);
            assert!(got >= 11.0, "paper: {what} {got:.2} on the canvas");
        }
        for (what, c) in [
            ("border_active", t.border_active),
            ("prompt_fg", t.prompt_fg),
            ("claude_label", t.claude_label),
            ("heading_color", t.heading_color),
            ("list_bullet_color", t.list_bullet_color),
            ("table_header_color", t.table_header_color),
            ("system_msg", t.system_msg),
            ("header_fg", t.header_fg),
            ("tool_label", t.tool_label),
            ("tool_param", t.tool_param),
            ("tool_result_color", t.tool_result_color),
            ("tool_result_ok", t.tool_result_ok),
            ("error_color", t.error_color),
            ("warning_color", t.warning_color),
            ("status_streaming", t.status_streaming),
            ("status_ready", t.status_ready),
            ("cost_color", t.cost_color),
            ("subagent_name", t.subagent_name),
            ("subagent_status", t.subagent_status),
            ("subagent_done", t.subagent_done),
        ] {
            for (on, ground) in [("chrome", bg), ("canvas", canvas)] {
                let got = contrast(rgb(c), ground);
                assert!(got >= 4.5, "paper: {what} {got:.2} on the {on}");
            }
        }
        for (what, c) in [
            ("bg", t.bg),
            ("message_bg", t.message_bg),
            ("user_bg", t.user_bg),
            ("border", t.border),
            ("separator", t.separator),
            ("code_bg", t.code_bg),
        ] {
            assert_ne!(c, Color::Reset, "paper: {what} is explicit");
        }
    }

    /// Event cards (subagent completions, inbox events) take each palette's
    /// own colours. Every builtin used to share one orange/blue/grey set.
    #[test]
    fn event_cards_take_the_palette_colours() {
        const EXPLICIT: &[&str] = &["night-city", "myx"];
        for name in BUILTINS.iter().filter(|n| !EXPLICIT.contains(n)) {
            let t = Theme::builtin_for_test(name);
            assert_eq!(t.event_accent("high"), t.border_active, "{name} high");
            assert_eq!(t.event_accent("medium"), t.border_active, "{name} medium");
            assert_eq!(t.event_accent("whatever"), t.border_active, "{name} unknown");
            assert_eq!(t.event_accent("critical"), t.error_color, "{name} critical");
            assert_eq!(t.event_accent("low"), t.system_msg, "{name} low");
            assert_eq!(t.event_label(), t.tool_label, "{name} label");
            assert_eq!(t.event_body(), t.tool_result_color, "{name} body");
            for c in [t.event_accent("high"), t.event_accent("critical"), t.event_label(), t.event_body()] {
                rgb(c); // resolves to a real colour, never the Reset sentinel
            }
        }
    }

    #[test]
    fn explicit_event_colours_still_win() {
        for name in ["night-city", "myx"] {
            let t = Theme::builtin_for_test(name);
            assert_ne!(t.event_icon, Color::Reset, "{name} sets its own");
            assert_eq!(t.event_accent("high"), t.event_icon, "{name}");
            assert_eq!(t.event_accent("critical"), t.event_critical, "{name}");
            assert_eq!(t.event_label(), t.event_source, "{name}");
            assert_eq!(t.event_body(), t.event_text, "{name}");
        }
    }
}

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

    #[test]
    fn chrome_dim_reads_at_aa_on_every_builtin_and_stays_below_text() {
        for name in [
            "default",
            "night-city",
            "neon-rain",
            "amber",
            "phosphor",
            "solarized-dark",
            "blood",
            "ocean",
            "rose-pine",
            "nord",
            "dracula",
            "monokai",
            "myx",
            "gruvbox",
            "catppuccin",
            "tokyo-night",
            "sunset",
            "ice",
            "forest",
            "lavender",
            "paper",
        ] {
            let t = Theme::builtin_for_test(name);
            let dim = t.chrome_dim();
            let c = wcag_contrast(dim, t.bg);
            assert!(c >= 4.5, "{name}: chrome_dim {c:.2}");
            assert!(
                c <= wcag_contrast(t.input_fg, t.bg) + 1e-9,
                "{name}: dim text must not outshine the input text"
            );
        }
    }
}

impl Theme {
    /// Surface of the Confirm / secret-prompt lightbox.
    pub(crate) fn prompt_surface(&self) -> Color {
        self.raised_surface(1.32)
    }

    /// Confirm dialog button colours: `(idle label, focused label, focused
    /// fill)`. Idle labels use the input text colour (≥ 4.5:1 on the prompt
    /// surface on every built-in theme; `help_fg` was 1.0–2.5:1, which made
    /// unfocused buttons near invisible). Focused = theme bg on the warning
    /// fill.
    pub(crate) fn confirm_button_colors(&self) -> (Color, Color, Color) {
        (self.input_fg, self.bg, self.warning_color)
    }
}

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

    #[test]
    fn confirm_button_labels_read_at_aa_on_every_builtin() {
        for name in [
            "default",
            "night-city",
            "neon-rain",
            "amber",
            "phosphor",
            "solarized-dark",
            "blood",
            "ocean",
            "rose-pine",
            "nord",
            "dracula",
            "monokai",
            "myx",
            "gruvbox",
            "catppuccin",
            "tokyo-night",
            "sunset",
            "ice",
            "forest",
            "lavender",
            "paper",
        ] {
            let t = Theme::builtin_for_test(name);
            let surface = t.prompt_surface();
            let (idle, focus_fg, focus_bg) = t.confirm_button_colors();
            let c = wcag_contrast(idle, surface);
            assert!(c >= 4.5, "{name}: idle button label {c:.2}:1");
            let c = wcag_contrast(focus_fg, focus_bg);
            assert!(c >= 4.5, "{name}: focused button label {c:.2}:1");
        }
    }
}

#[cfg(test)]
mod terminal_bg_guard_tests {
    //! Opaque mode must never paint a bg that EQUALS the terminal's default
    //! background (kitty `background_opacity` makes such cells see-through).
    //! Pure functions only: no global theme / opacity is touched.
    use super::*;
    use ratatui::buffer::Buffer;
    use ratatui::layout::Rect;

    const OCEAN_BG: Rgb8 = (3, 8, 16);

    /// Every bg-like colour the ocean theme can paint, base and derived.
    fn ocean_bg_palette() -> Vec<Color> {
        let t = Theme::builtin("ocean").unwrap();
        assert_eq!(t.bg, Color::Rgb(3, 8, 16), "fixture: ocean bg");
        vec![
            t.bg,
            t.message_bg,
            t.message_background(),
            t.user_bg,
            t.code_bg,
            t.tool_input_background(),
            t.tool_output_background(),
            t.raised_surface(1.1),
            t.prompt_surface(),
            t.border,
            Color::Rgb(3, 8, 16), // e.g. a slab/fx mix landing exactly on it
        ]
    }

    fn painted(colors: &[Color]) -> Buffer {
        let mut buf = Buffer::empty(Rect::new(0, 0, colors.len() as u16, 2));
        for (x, c) in colors.iter().enumerate() {
            buf[(x as u16, 0)].set_bg(*c).set_fg(Color::Rgb(3, 8, 16));
            buf[(x as u16, 1)].set_bg(*c);
        }
        buf
    }

    #[test]
    fn steered_colour_is_one_step_off_and_in_range() {
        let t = Some(OCEAN_BG);
        assert_eq!(
            steer_off_terminal_bg(Color::Rgb(3, 8, 16), t),
            Color::Rgb(3, 8, 17)
        );
        assert_eq!(
            steer_off_terminal_bg(Color::Rgb(9, 9, 255), Some((9, 9, 255))),
            Color::Rgb(9, 9, 254),
            "stays in range at the top of the channel"
        );
        // Anything else is untouched.
        assert_eq!(
            steer_off_terminal_bg(Color::Rgb(3, 8, 17), t),
            Color::Rgb(3, 8, 17)
        );
        assert_eq!(steer_off_terminal_bg(Color::Reset, t), Color::Reset);
        assert_eq!(steer_off_terminal_bg(Color::Black, t), Color::Black);
    }

    #[test]
    fn ocean_frame_never_paints_the_terminal_bg_when_detected() {
        let colors = ocean_bg_palette();
        let mut buf = painted(&colors);
        assert!(
            buf.content.iter().any(|c| c.bg == Color::Rgb(3, 8, 16)),
            "fixture must contain the exact terminal bg"
        );
        steer_buffer_off_terminal_bg(&mut buf, Some(OCEAN_BG));
        for (i, cell) in buf.content.iter().enumerate() {
            assert_ne!(cell.bg, Color::Rgb(3, 8, 16), "cell {i} still see-through");
        }
        // Only bg moves; fg and every non-matching bg are untouched.
        let before = painted(&colors);
        for (a, b) in before.content.iter().zip(buf.content.iter()) {
            assert_eq!(a.fg, b.fg, "fg must never change");
            if a.bg != Color::Rgb(3, 8, 16) {
                assert_eq!(a.bg, b.bg);
            }
        }
    }

    #[test]
    fn unknown_terminal_bg_changes_nothing() {
        let colors = ocean_bg_palette();
        let mut buf = painted(&colors);
        steer_buffer_off_terminal_bg(&mut buf, None);
        assert_eq!(buf, painted(&colors));
        for c in colors {
            assert_eq!(steer_off_terminal_bg(c, None), c);
        }
    }

    #[test]
    fn terminal_bg_global_round_trips_and_unknown_is_none() {
        // The packed atomic encoding, exercised through the thread-local
        // seam so the real process global is never written by tests.
        set_terminal_default_bg_for_thread(Some(Some(OCEAN_BG)));
        assert_eq!(terminal_default_bg(), Some(OCEAN_BG));
        set_terminal_default_bg_for_thread(Some(None));
        assert_eq!(terminal_default_bg(), None);
        set_terminal_default_bg_for_thread(None);
        // Black must not collide with the "unknown" encoding.
        assert_eq!(unpack_rgb8(pack_rgb8(Some((0, 0, 0)))), Some((0, 0, 0)));
        assert_eq!(
            unpack_rgb8(pack_rgb8(Some((255, 255, 255)))),
            Some((255, 255, 255))
        );
        assert_eq!(unpack_rgb8(pack_rgb8(None)), None);
    }
}