oino-core 1.0.0

Coding-agent runtime for Oino: AgentSession, extension runner, compaction, retry
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
//! The entry registry (§6): one per scope, owned by the session (or the host
//! catalog for host-scope entries).
//!
//! Every retained producer call of §6.3 becomes an [`UiEntry`]; mutations are
//! queued as [`RegistryOp`]s and flushed as one [`UiPatch`] with a monotonic
//! `rev` (§9.2). Entries are owned by an extension id and are disposed with it
//! (§6.6). Reserved ids are gated to their owner and component (§8).

use std::collections::{HashMap, HashSet};
use std::sync::{Arc, OnceLock, RwLock};

use indexmap::IndexMap;
use oino_ai::{JsonObject, JsonValue};
use oino_ui::extras::icon::Icon;
use oino_ui::node::Node;
use oino_ui::patch::{NodeOp, apply, diff};
use oino_ui::slot::{
    DismissReason, EntryMetaPatch, EntrySize, KeyBinding, RegistryOp, ReservedComponent, Scope,
    Slot, UiEntry, UiMeta, UiPatch, UiSnapshot, UiView,
};
use oino_ui::style::Color;
use oino_ui::text::Line;

/// A dialog request in registry form (`UiSnapshot.dialogs`, `op:"dialog"`).
pub type DialogRequest = oino_ui::slot::UiRequest;

/// One reserved first-party panel the embedding host registers (§8): the SDK ships an empty
/// table — every reserved id, its owner and its component key are embedder registration
/// ([`register_reserved`]), so a bare `oino` knows no first-party panels.
#[derive(Clone, Debug, PartialEq)]
pub struct ReservedPanelSpec {
    /// Entry id (`"<extensionId>/<name>"`, or `host/<name>` for host-created ids).
    pub id: String,
    /// Opaque component key the frontend renders (wire value, e.g. `"board"`).
    pub component: ReservedComponent,
    /// The extension id that owns (and gates) it; `host` for host-created ids.
    pub owner: String,
    /// Default slot.
    pub slot: Slot,
    /// Slots the owner may request instead (the default is always allowed).
    pub allowed: Vec<Slot>,
    /// Default title.
    pub title: String,
    /// Default `order` (§6.4) per slot; a slot without an entry defaults to 0.
    pub orders: Vec<(Slot, i32)>,
}

impl ReservedPanelSpec {
    /// A spec with no alternate slots and one default order for every slot.
    #[must_use]
    pub fn new(
        id: impl Into<String>,
        owner: impl Into<String>,
        component: impl Into<String>,
        slot: Slot,
        title: impl Into<String>,
        order: i32,
    ) -> Self {
        let slot_key = slot;
        Self {
            id: id.into(),
            component: ReservedComponent::new(component),
            owner: owner.into(),
            slot,
            allowed: Vec::new(),
            title: title.into(),
            orders: vec![(slot_key, order)],
        }
    }

    /// The default `order` of this panel in `slot` (§6.4).
    #[must_use]
    pub fn order_for(&self, slot: Slot) -> i32 {
        self.orders
            .iter()
            .find(|(key, _)| *key == slot)
            .map_or(0, |(_, order)| *order)
    }
}

fn reserved_registry() -> &'static RwLock<Vec<Arc<ReservedPanelSpec>>> {
    static RESERVED: OnceLock<RwLock<Vec<Arc<ReservedPanelSpec>>>> = OnceLock::new();
    RESERVED.get_or_init(|| RwLock::new(Vec::new()))
}

/// Registers a reserved panel for every registry of the process (§8): the embedding host
/// does this once at startup, before sessions open. Re-registering an id replaces its spec;
/// the manifest-side owner table (extension-api) is kept in sync. Idempotent and cheap —
/// embedders may call it from every entry point.
///
/// The panel is gated to `owner`, rendered as `component`, placed in `slot` (alternates in
/// `allowed`) and titled `title`.
pub fn register_reserved(spec: ReservedPanelSpec) {
    let spec = Arc::new(spec);
    let mut table = reserved_registry()
        .write()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    match table.iter_mut().find(|entry| entry.id == spec.id) {
        Some(slot) => *slot = Arc::clone(&spec),
        None => table.push(Arc::clone(&spec)),
    }
    drop(table);
    oino_extension_api::manifest::register_reserved_owner(&spec.id, &spec.owner);
}

/// Drops every registered reserved panel (tests and embedder restarts).
pub fn clear_reserved_panels() {
    reserved_registry()
        .write()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .clear();
    oino_extension_api::manifest::clear_reserved_owners();
}

/// Every registered reserved panel, in registration order (§8).
#[must_use]
pub fn reserved_panels() -> Vec<Arc<ReservedPanelSpec>> {
    reserved_registry()
        .read()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .clone()
}

/// The registered reserved panel with this id, if any (§8).
#[must_use]
pub fn reserved(id: &str) -> Option<Arc<ReservedPanelSpec>> {
    reserved_registry()
        .read()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .iter()
        .find(|entry| entry.id == id)
        .cloned()
}

/// The default `order` of a registered reserved panel in `slot` (§6.4); 0 for anything else.
#[must_use]
pub fn default_order(id: &str, slot: Slot) -> i32 {
    reserved(id).map_or(0, |spec| spec.order_for(slot))
}

/// Built-in Settings order of §6.4 (`core` first, host/app next).
#[must_use]
pub fn settings_order(extension_id: &str) -> i32 {
    match extension_id {
        "oino" | "core" => 1000,
        "host" | "app" => 900,
        _ => 0,
    }
}

/// Third-party `order` is clamped to this range (§6.4).
const ORDER_RANGE: std::ops::RangeInclusive<i32> = -100..=100;

/// Entries per extension (§4.8).
const MAX_ENTRIES: usize = 64;
/// `sidePane` entries per extension (§4.8).
const MAX_SIDE_PANES: usize = 8;
/// `bottomPane` entries per extension (§4.8).
const MAX_BOTTOM_PANES: usize = 8;

/// Why a registry mutation was rejected.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum RegistryError {
    /// An extension tried to write an id outside its own namespace.
    #[error("entry id `{id}` is not owned by `{extension}`")]
    ForeignId {
        /// The requested id.
        id: String,
        /// The requesting extension.
        extension: String,
    },
    /// A reserved id was claimed by another extension.
    #[error("reserved id `{id}` is owned by `{owner}`")]
    ReservedOwned {
        /// The reserved id.
        id: String,
        /// Its owner.
        owner: String,
    },
    /// A non-reserved id was opened as a reserved component.
    #[error("`{0}` is not a reserved id")]
    NotReserved(String),
    /// The extension is at its entry limit.
    #[error("entry limit reached for `{0}`")]
    Limit(String),
    /// The entry does not exist.
    #[error("unknown entry `{0}`")]
    NotFound(String),
    /// The node tree or patch failed validation (§4.8).
    #[error("invalid tree: {0}")]
    Invalid(String),
}

/// Where flushed patches go (the session's event hub).
pub trait RegistrySink: Send + Sync {
    /// Publishes one coalesced patch in order.
    fn publish(&self, patch: UiPatch);
}

/// One producer call's effect on the registry.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ProduceOutcome {
    /// Not a registry producer (a one-shot effect, §2 L0).
    Effect,
    /// An entry was created (`created`) or replaced.
    Entry {
        /// Entry id.
        id: String,
        /// Whether the entry is new.
        created: bool,
    },
    /// An entry was deleted.
    Deleted(String),
}

/// Result of [`UiRegistry::put`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PutOutcome {
    /// Entry id.
    pub id: String,
    /// Whether the entry is new.
    pub created: bool,
}

/// An entry to add or replace (§6.1).
#[derive(Clone, Debug, PartialEq)]
pub struct EntryRequest {
    /// Entry id (`"<extensionId>/<name>"`, or a reserved id).
    pub id: String,
    /// Owning extension.
    pub extension_id: String,
    /// Where it renders (`openPanel` placement).
    pub slot: Slot,
    /// Sort weight (§6.4).
    pub order: Option<i32>,
    /// Tab title.
    pub title: Option<String>,
    /// Tab icon.
    pub icon: Option<Icon>,
    /// Tab badge.
    pub badge: Option<Line>,
    /// Tab tone.
    pub tone: Option<Color>,
    /// What it renders.
    pub view: UiView,
    /// Key bindings.
    pub keys: Vec<KeyBinding>,
    /// Activate on open.
    pub focus: Option<bool>,
    /// Esc closes.
    pub close_on_escape: Option<bool>,
    /// Overlay width.
    pub size: Option<EntrySize>,
    /// Fallback tree of a reserved entry (§8 rule 3).
    pub fallback: Option<Node>,
    /// Reserved-component parameters.
    pub params: Option<JsonValue>,
}

/// A partial update of an existing entry (`updatePanel`, §9.1).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct EntryUpdate {
    /// Entry id.
    pub id: String,
    /// Whole new tree (core diffs it).
    pub spec: Option<Node>,
    /// Explicit node ops.
    pub patch: Option<Vec<NodeOp>>,
    /// New title.
    pub title: Option<String>,
    /// New icon.
    pub icon: Option<Icon>,
    /// New badge.
    pub badge: Option<Line>,
    /// New sort weight.
    pub order: Option<i32>,
    /// New key bindings.
    pub keys: Option<Vec<KeyBinding>>,
    /// New fallback tree (reserved entries, §8 rule 3).
    pub fallback: Option<Node>,
}

/// The entry's aggregate visibility changed in the attached frontends (§6.5).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct VisibilityChange {
    /// Entry id.
    pub entry_id: String,
    /// Visible in at least one frontend now.
    pub visible: bool,
}

/// The per-scope entry registry (§6).
pub struct UiRegistry {
    scope: Scope,
    session_id: Option<String>,
    rev: u64,
    seq: u64,
    panels: u64,
    entries: IndexMap<String, UiEntry>,
    meta: UiMeta,
    dialogs: Vec<DialogRequest>,
    settings: HashMap<String, String>,
    visible: HashMap<String, HashSet<String>>,
    pending: Vec<RegistryOp>,
    sink: Option<Arc<dyn RegistrySink>>,
}

impl std::fmt::Debug for UiRegistry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("UiRegistry")
            .field("scope", &self.scope)
            .field("rev", &self.rev)
            .field("entries", &self.entries.len())
            .finish_non_exhaustive()
    }
}

impl UiRegistry {
    /// An empty session-scope registry.
    #[must_use]
    pub fn new(scope: Scope, session_id: Option<String>) -> Self {
        Self {
            scope,
            session_id,
            rev: 0,
            seq: 0,
            panels: 0,
            entries: IndexMap::new(),
            meta: UiMeta::default(),
            dialogs: Vec::new(),
            settings: HashMap::new(),
            visible: HashMap::new(),
            pending: Vec::new(),
            sink: None,
        }
    }

    /// The emitted patch revision (a frontend at another revision resyncs, §9.2).
    #[must_use]
    pub const fn rev(&self) -> u64 {
        self.rev
    }

    /// Registry scope.
    #[must_use]
    pub const fn scope(&self) -> Scope {
        self.scope
    }

    /// Where flushed patches go.
    pub fn set_sink(&mut self, sink: Arc<dyn RegistrySink>) {
        self.sink = Some(sink);
    }

    /// Entry ids in registration order.
    #[must_use]
    pub fn ids(&self) -> Vec<String> {
        self.entries.keys().cloned().collect()
    }

    /// One entry by id.
    #[must_use]
    pub fn get(&self, id: &str) -> Option<&UiEntry> {
        self.entries.get(id)
    }

    /// Entries of one slot in registry order (`order` desc, then `seq` asc, §6.4).
    #[must_use]
    pub fn slot_entries(&self, slot: Slot) -> Vec<&UiEntry> {
        let mut entries: Vec<&UiEntry> = self
            .entries
            .values()
            .filter(|entry| entry.slot == slot)
            .collect();
        entries.sort_by(|a, b| b.order.cmp(&a.order).then(a.seq.cmp(&b.seq)));
        entries
    }

    /// The top entry of a stack slot (`overlay`, `editorReplace`): the most
    /// recently opened or focused entry (§6.4).
    #[must_use]
    pub fn stack_top(&self, slot: Slot) -> Option<&UiEntry> {
        self.entries
            .values()
            .filter(|entry| entry.slot == slot)
            .max_by_key(|entry| {
                let opened = if entry.focus == Some(true) {
                    u64::MAX
                } else {
                    entry.seq
                };
                (opened, entry.seq)
            })
    }

    /// Whether a frontend at `rev` must request a resync (§9.2).
    #[must_use]
    pub const fn needs_resync(&self, rev: u64) -> bool {
        rev != self.rev
    }

    /// A full snapshot; drops queued state ops (the snapshot supersedes them) but keeps
    /// one-shot `effect` ops, which are never part of a snapshot (§9.2).
    pub fn snapshot(&mut self) -> UiSnapshot {
        self.pending
            .retain(|op| matches!(op, RegistryOp::Effect { .. }));
        UiSnapshot {
            scope: self.scope,
            session_id: self.session_id.clone(),
            rev: self.rev,
            entries: self.entries.values().cloned().collect(),
            dialogs: self.dialogs.clone(),
            meta: self.meta.clone(),
        }
    }

    /// Takes the queued ops as one patch (`rev` = previous + 1, §9.2).
    pub fn take_patch(&mut self) -> Option<UiPatch> {
        if self.pending.is_empty() {
            return None;
        }
        self.rev += 1;
        Some(UiPatch {
            scope: self.scope,
            session_id: self.session_id.clone(),
            rev: self.rev,
            ops: std::mem::take(&mut self.pending),
        })
    }

    /// Emits the queued ops through the sink, if any.
    pub fn flush(&mut self) {
        if let Some(patch) = self.take_patch()
            && let Some(sink) = &self.sink
        {
            sink.publish(patch);
        }
    }

    /// Whether ops are waiting for a flush.
    #[must_use]
    pub fn has_pending(&self) -> bool {
        !self.pending.is_empty()
    }

    /// Queues an op, coalescing consecutive ops for the same entry (§4.7): a later
    /// whole-entry `put` replaces the earlier one, consecutive `tree` ops compose.
    fn push_op(&mut self, op: RegistryOp) {
        match (&op, self.pending.last_mut()) {
            (
                RegistryOp::Put { entry },
                Some(RegistryOp::Put {
                    entry: pending_entry,
                }),
            ) if pending_entry.id == entry.id => *pending_entry = entry.clone(),
            (
                RegistryOp::Tree { id, rev, ops },
                Some(RegistryOp::Tree {
                    id: pending_id,
                    rev: pending_rev,
                    ops: pending_ops,
                }),
            ) if pending_id == id => {
                *pending_rev = *rev;
                pending_ops.extend(ops.iter().cloned());
            }
            _ => self.pending.push(op),
        }
    }
}

/// Why a producer call could not change the registry is reported as
/// [`RegistryError`]; the caller turns it into `host-error{code:"invalid"}` and
/// an `extension_error` diagnostic (§9.1).
impl UiRegistry {
    /// Adds or replaces an entry (`openPanel`, `setWidget`, …).
    ///
    /// # Errors
    ///
    /// Foreign id, reserved-ownership, limit or validation failures.
    pub fn put(&mut self, request: EntryRequest) -> Result<PutOutcome, RegistryError> {
        let id = request.id.clone();
        let extension = request.extension_id.clone();
        check_id(&id)?;
        Self::check_ownership(&extension, &id)?;
        let (slot, view, order) = Self::gate(&request)?;
        let existing = self.entries.get(&id);
        if existing.is_none() {
            self.check_limits(&id, &extension, slot)?;
        }
        let seq = if let Some(entry) = existing {
            entry.seq
        } else {
            self.seq += 1;
            self.seq
        };
        let rev = existing.map_or(1, |entry| entry.rev + 1);
        let title = request
            .title
            .clone()
            .or_else(|| existing.and_then(|entry| entry.title.clone()))
            .or_else(|| reserved(&id).map(|reserved| reserved.title.clone()));
        let entry = UiEntry {
            id: id.clone(),
            extension_id: extension,
            scope: self.scope,
            slot,
            order,
            seq,
            title,
            icon: request.icon,
            badge: request.badge,
            tone: request.tone,
            view,
            keys: request.keys,
            focus: request.focus,
            close_on_escape: request.close_on_escape,
            size: request.size,
            rev,
        };
        let created = existing.is_none();
        match existing {
            Some(old) if only_tree_changed(old, &entry) => {
                if let (UiView::Tree { root: old }, UiView::Tree { root: new }) =
                    (&old.view, &entry.view)
                {
                    let ops = diff(old, new);
                    self.push_op(RegistryOp::Tree {
                        id: entry.id.clone(),
                        rev,
                        ops,
                    });
                }
            }
            _ => self.push_op(RegistryOp::Put {
                entry: entry.clone(),
            }),
        }
        let id = entry.id.clone();
        self.entries.insert(id.clone(), entry);
        Ok(PutOutcome { id, created })
    }

    /// Applies a partial update (`updatePanel`, §9.1).
    ///
    /// # Errors
    ///
    /// [`RegistryError::NotFound`] for an unknown id, plus the [`put`](Self::put)
    /// failures.
    pub fn update(&mut self, update: EntryUpdate) -> Result<(), RegistryError> {
        let Some(old) = self.entries.get(&update.id).cloned() else {
            return Err(RegistryError::NotFound(update.id.clone()));
        };
        Self::check_ownership(&old.extension_id, &update.id)?;
        let mut next = old.clone();
        let mut meta_changed = false;
        if let Some(title) = update.title {
            next.title = Some(title);
            meta_changed = true;
        }
        if let Some(icon) = update.icon {
            next.icon = Some(icon);
            meta_changed = true;
        }
        if let Some(badge) = update.badge {
            next.badge = Some(badge);
            meta_changed = true;
        }
        if let Some(keys) = update.keys {
            next.keys = keys;
            meta_changed = true;
        }
        if let Some(order) = update.order
            && reserved(&update.id).is_none()
        {
            next.order = order.clamp(*ORDER_RANGE.start(), *ORDER_RANGE.end());
            meta_changed = true;
        }
        if let UiView::Reserved { fallback, .. } = &mut next.view
            && let Some(tree) = update.fallback
        {
            *fallback = Some(Box::new(tree));
            meta_changed = true;
        }
        let mut explicit: Option<Vec<NodeOp>> = None;
        if let Some(ops) = update.patch {
            oino_ui::limits::validate_patch(&ops)
                .map_err(|diagnostics| RegistryError::Invalid(diagnostics_text(&diagnostics)))?;
            let UiView::Tree { root } = &next.view else {
                return Err(RegistryError::Invalid(format!(
                    "{} is not a tree entry",
                    update.id
                )));
            };
            let applied =
                apply(root, &ops).map_err(|error| RegistryError::Invalid(error.to_string()))?;
            next.view = UiView::Tree { root: applied };
            explicit = Some(ops);
        }
        if let Some(tree) = update.spec {
            oino_ui::limits::validate(&tree)
                .map_err(|diagnostics| RegistryError::Invalid(diagnostics_text(&diagnostics)))?;
            next.view = UiView::Tree { root: tree };
            explicit = None;
        }
        let view_changed = next.view != old.view;
        if !view_changed && !meta_changed {
            return Ok(());
        }
        next.rev += 1;
        let rev = next.rev;
        let id = next.id.clone();
        let tree_ops = match (&old.view, &next.view) {
            (UiView::Tree { root: old_root }, UiView::Tree { root: new_root }) => {
                Some(explicit.unwrap_or_else(|| diff(old_root, new_root)))
            }
            _ => None,
        };
        match (view_changed, tree_ops) {
            (true, Some(ops)) => {
                self.push_op(RegistryOp::Tree {
                    id: id.clone(),
                    rev,
                    ops,
                });
                if meta_changed {
                    self.pending.push(RegistryOp::Meta {
                        id: id.clone(),
                        set: meta_patch(&old, &next),
                    });
                }
            }
            (true, None) => self.push_op(RegistryOp::Put {
                entry: next.clone(),
            }),
            (false, _) => self.pending.push(RegistryOp::Meta {
                id: id.clone(),
                set: meta_patch(&old, &next),
            }),
        }
        self.entries.insert(id, next);
        Ok(())
    }

    /// Deletes an entry owned by `extension` (`closePanel`, clearing producer, `$close`).
    ///
    /// # Errors
    ///
    /// Foreign id or [`RegistryError::NotFound`].
    pub fn remove(&mut self, extension: &str, id: &str) -> Result<(), RegistryError> {
        Self::check_ownership(extension, id)?;
        if !self.entries.contains_key(id) {
            return Err(RegistryError::NotFound(id.to_owned()));
        }
        self.delete(id);
        Ok(())
    }

    /// Deletes every entry of one extension instance (dispose, §6.6).
    pub fn remove_owner(&mut self, extension: &str) -> Vec<String> {
        let ids: Vec<String> = self
            .entries
            .values()
            .filter(|entry| entry.extension_id == extension)
            .map(|entry| entry.id.clone())
            .collect();
        for id in &ids {
            self.delete(id);
        }
        ids
    }

    /// Deletes every entry (session close / reload, §6.6).
    pub fn clear(&mut self) -> Vec<String> {
        let ids = self.ids();
        for id in &ids {
            self.delete(id);
        }
        ids
    }

    fn delete(&mut self, id: &str) {
        if let Some(entry) = self.entries.shift_remove(id) {
            self.settings.retain(|_, entry_id| entry_id != id);
            for set in self.visible.values_mut() {
                set.remove(id);
            }
            self.pending.push(RegistryOp::Del {
                id: entry.id.clone(),
            });
        }
    }

    /// Creates the turn-footer entry of a renderer registration (§6.7).
    ///
    /// # Errors
    ///
    /// Ownership/limit failures (the entry id is derived, not supplied).
    pub fn register_turn_footer(
        &mut self,
        extension: &str,
        key: &str,
    ) -> Result<String, RegistryError> {
        let id = format!("{extension}/turnFooter:{key}");
        self.put(EntryRequest {
            id: id.clone(),
            extension_id: extension.to_owned(),
            slot: Slot::TurnFooter,
            order: Some(0),
            title: None,
            icon: None,
            badge: None,
            tone: None,
            view: UiView::Renderer {
                key: key.to_owned(),
            },
            keys: Vec::new(),
            focus: None,
            close_on_escape: None,
            size: None,
            fallback: None,
            params: None,
        })?;
        Ok(id)
    }

    /// Invalidates turn-footer caches (`invalidateTurnFooter`, §6.7).
    ///
    /// # Errors
    ///
    /// [`RegistryError::NotFound`] when the owner has no such renderer.
    pub fn invalidate_turn_footer(
        &mut self,
        extension: &str,
        key: &str,
        turns: Option<Vec<String>>,
    ) -> Result<String, RegistryError> {
        let id = format!("{extension}/turnFooter:{key}");
        let Some(entry) = self.entries.get_mut(&id) else {
            return Err(RegistryError::NotFound(id));
        };
        entry.rev += 1;
        self.pending.push(RegistryOp::Invalidate {
            id: id.clone(),
            turns,
        });
        Ok(id)
    }

    /// Registers a Settings namespace entry (§6.3, §7). Collisions are rejected.
    ///
    /// # Errors
    ///
    /// A namespace may only be registered once per scope; plus the [`put`](Self::put)
    /// failures.
    pub fn register_settings(
        &mut self,
        namespace: oino_ui::settings::SettingsNamespace,
    ) -> Result<String, RegistryError> {
        if let Some(existing) = self.settings.get(&namespace.namespace) {
            return Err(RegistryError::Invalid(format!(
                "settings namespace `{}` is already registered by `{existing}`",
                namespace.namespace
            )));
        }
        let extension = namespace.extension_id.clone();
        let order = namespace
            .order
            .unwrap_or_else(|| settings_order(&extension));
        let namespace_key = namespace.namespace.clone();
        let id = format!("{extension}/settings:{}", namespace.namespace);
        let title = namespace.title.clone();
        self.put(EntryRequest {
            id: id.clone(),
            extension_id: extension,
            slot: Slot::Settings,
            order: Some(order),
            title: Some(title),
            icon: namespace.icon,
            badge: None,
            tone: None,
            view: UiView::Settings { namespace },
            keys: Vec::new(),
            focus: None,
            close_on_escape: None,
            size: None,
            fallback: None,
            params: None,
        })?;
        self.settings.insert(namespace_key, id.clone());
        Ok(id)
    }

    /// Sets the registry meta (`setTitle`, `setWorkingMessage`, `setShortcuts`).
    pub fn set_meta(&mut self, set: oino_ui::slot::UiMetaPatch) {
        if let Some(title) = &set.title {
            self.meta.title = Some(title.clone());
        }
        if let Some(message) = &set.working_message {
            self.meta.working_message = Some(message.clone());
        }
        if let Some(visible) = set.working_visible {
            self.meta.working_visible = Some(visible);
        }
        if let Some(shortcuts) = &set.shortcuts {
            self.meta.shortcuts.clone_from(shortcuts);
        }
        self.pending.push(RegistryOp::SessionMeta { set });
    }

    /// Records a dialog (also sent as a legacy record to plain clients, §9.2).
    pub fn dialog_opened(&mut self, request: DialogRequest) {
        if !self.dialogs.iter().any(|dialog| dialog.id == request.id) {
            self.dialogs.push(request.clone());
        }
        self.pending.push(RegistryOp::Dialog { request });
    }

    /// Records a dialog dismissal (§9.2).
    pub fn dialog_dismissed(&mut self, id: &str, reason: DismissReason) {
        self.dialogs.retain(|dialog| dialog.id != id);
        self.pending.push(RegistryOp::Dismiss {
            id: id.to_owned(),
            reason,
        });
    }

    /// Records a one-shot effect (§9.2 `effect`; never in snapshots).
    pub fn effect(&mut self, request: DialogRequest) {
        self.pending.push(RegistryOp::Effect { request });
    }

    /// Aggregates a frontend's visibility report (§6.5); `Some` when the
    /// aggregate changed (core then sends `$show`/`$hide`).
    pub fn set_visible(
        &mut self,
        frontend: &str,
        entry_id: &str,
        visible: bool,
    ) -> Option<VisibilityChange> {
        if !self.entries.contains_key(entry_id) {
            return None;
        }
        let was = self.is_visible(entry_id);
        if visible {
            self.visible
                .entry(frontend.to_owned())
                .or_default()
                .insert(entry_id.to_owned());
        } else if let Some(set) = self.visible.get_mut(frontend) {
            set.remove(entry_id);
        }
        let now = self.is_visible(entry_id);
        (was != now).then(|| VisibilityChange {
            entry_id: entry_id.to_owned(),
            visible: now,
        })
    }

    /// Whether any attached frontend reported the entry visible.
    #[must_use]
    pub fn is_visible(&self, entry_id: &str) -> bool {
        self.visible.values().any(|set| set.contains(entry_id))
    }

    /// Deletes an entry by id (user `$close`, §6.6); no ownership check.
    pub fn close(&mut self, id: &str) {
        self.delete(id);
    }

    fn check_ownership(extension: &str, id: &str) -> Result<(), RegistryError> {
        if reserved(id).is_some() {
            return Ok(());
        }
        let owned = id
            .strip_prefix(extension)
            .is_some_and(|rest| rest.starts_with('/'))
            || (extension == "host" && id.starts_with("host/"));
        if owned {
            Ok(())
        } else {
            Err(RegistryError::ForeignId {
                id: id.to_owned(),
                extension: extension.to_owned(),
            })
        }
    }

    fn gate(request: &EntryRequest) -> Result<(Slot, UiView, i32), RegistryError> {
        let fallback = request.fallback.clone().or_else(|| match &request.view {
            UiView::Reserved { fallback, .. } => fallback.as_deref().cloned(),
            _ => None,
        });
        let params = request.params.clone().or_else(|| match &request.view {
            UiView::Reserved { params, .. } => params.clone(),
            _ => None,
        });
        if let Some(entry) = reserved(&request.id) {
            if entry.owner != request.extension_id {
                return Err(RegistryError::ReservedOwned {
                    id: request.id.clone(),
                    owner: entry.owner.clone(),
                });
            }
            let slot = if request.slot == entry.slot || entry.allowed.contains(&request.slot) {
                request.slot
            } else {
                entry.slot
            };
            let order = request
                .order
                .unwrap_or_else(|| default_order(&entry.id, slot));
            return Ok((
                slot,
                UiView::Reserved {
                    component: entry.component.clone(),
                    fallback: fallback.map(Box::new),
                    params,
                },
                order,
            ));
        }
        if matches!(request.view, UiView::Reserved { .. }) {
            return Err(RegistryError::NotReserved(request.id.clone()));
        }
        if let UiView::Tree { root } = &request.view {
            oino_ui::limits::validate(root)
                .map_err(|diagnostics| RegistryError::Invalid(diagnostics_text(&diagnostics)))?;
        }
        // Third-party order is clamped (§6.4); the host owns the built-in Settings
        // constants of core/app namespaces.
        let built_in_settings = request.slot == Slot::Settings
            && matches!(
                request.extension_id.as_str(),
                "oino" | "core" | "host" | "app"
            );
        let order = match request.order {
            Some(order) if built_in_settings => order,
            Some(order) => order.clamp(*ORDER_RANGE.start(), *ORDER_RANGE.end()),
            None => 0,
        };
        Ok((request.slot, request.view.clone(), order))
    }

    fn check_limits(&self, id: &str, extension: &str, slot: Slot) -> Result<(), RegistryError> {
        let owned = self
            .entries
            .values()
            .filter(|entry| entry.extension_id == extension);
        let (mut total, mut side, mut bottom, mut full) = (0_usize, 0_usize, 0_usize, 0_usize);
        for entry in owned {
            total += 1;
            match entry.slot {
                Slot::SidePane => side += 1,
                Slot::BottomPane => bottom += 1,
                Slot::Fullscreen => full += 1,
                _ => {}
            }
        }
        let over = match slot {
            Slot::SidePane => side >= MAX_SIDE_PANES,
            Slot::BottomPane => bottom >= MAX_BOTTOM_PANES,
            Slot::Fullscreen => full >= 1,
            _ => total >= MAX_ENTRIES,
        };
        if over && reserved(id).is_none() {
            return Err(RegistryError::Limit(extension.to_owned()));
        }
        Ok(())
    }
}

/// `true` when only the tree differs (then a `Tree` op is enough).
fn only_tree_changed(old: &UiEntry, new: &UiEntry) -> bool {
    matches!(
        (&old.view, &new.view),
        (UiView::Tree { .. }, UiView::Tree { .. })
    ) && old.title == new.title
        && old.icon == new.icon
        && old.badge == new.badge
        && old.tone == new.tone
        && old.order == new.order
        && old.slot == new.slot
        && old.keys == new.keys
        && old.focus == new.focus
        && old.close_on_escape == new.close_on_escape
        && old.size == new.size
        && old.extension_id == new.extension_id
}

/// The `meta` op for changed entry meta (§9.2).
fn meta_patch(old: &UiEntry, new: &UiEntry) -> EntryMetaPatch {
    EntryMetaPatch {
        title: if old.title == new.title {
            None
        } else {
            new.title.clone()
        },
        icon: if old.icon == new.icon { None } else { new.icon },
        badge: if old.badge == new.badge {
            None
        } else {
            new.badge.clone()
        },
        order: (old.order != new.order).then_some(new.order),
        keys: (old.keys != new.keys).then(|| new.keys.clone()),
        tone: if old.tone == new.tone {
            None
        } else {
            new.tone.clone()
        },
        focus: if old.focus == new.focus {
            None
        } else {
            new.focus
        },
    }
}

/// Renders validation diagnostics as one `extension_error` line (§4.8).
#[must_use]
pub fn diagnostics_text(diagnostics: &[oino_ui::limits::Diagnostic]) -> String {
    diagnostics
        .iter()
        .map(|diagnostic| {
            if diagnostic.path.is_empty() {
                diagnostic.message.clone()
            } else {
                format!("{}: {}", diagnostic.path.join("."), diagnostic.message)
            }
        })
        .collect::<Vec<_>>()
        .join("; ")
}

/// Entry ids are `"<extensionId>/<name>"` (1–160 chars) or a reserved id.
fn check_id(id: &str) -> Result<(), RegistryError> {
    if id.is_empty() || id.len() > 160 || !id.contains('/') {
        return Err(RegistryError::Invalid(format!("invalid entry id `{id}`")));
    }
    Ok(())
}

/// Whether `method` is a registry producer (§6.3) rather than a one-shot effect.
#[must_use]
pub fn is_producer(method: &str) -> bool {
    matches!(
        method,
        "setStatus"
            | "setWidget"
            | "setFrame"
            | "setHeader"
            | "setFooter"
            | "openPanel"
            | "updatePanel"
            | "closePanel"
            | "invalidateTurnFooter"
    )
}

/// Whether `method` changes registry **meta** instead of creating an entry (§6.3).
#[must_use]
pub fn is_meta_method(method: &str) -> bool {
    matches!(method, "setTitle" | "setWorkingMessage" | "setShortcuts")
}

fn string(params: &JsonObject, key: &str) -> Option<String> {
    params
        .get(key)
        .and_then(JsonValue::as_str)
        .filter(|value| !value.is_empty())
        .map(str::to_owned)
}

fn line(params: &JsonObject, key: &str) -> Option<Line> {
    let value = params.get(key)?;
    if value.is_null() {
        return None;
    }
    Some(
        serde_json::from_value(value.clone())
            .unwrap_or_else(|_| Line::from(value.as_str().map_or_else(String::new, str::to_owned))),
    )
}

fn color(params: &JsonObject, key: &str) -> Option<Color> {
    serde_json::from_value(params.get(key)?.clone()).ok()
}

fn order(params: &JsonObject) -> Option<i32> {
    params
        .get("priority")
        .or_else(|| params.get("order"))
        .and_then(JsonValue::as_i64)
        .and_then(|value| i32::try_from(value).ok())
}

fn widget_placement(params: &JsonObject) -> Slot {
    match params.get("widgetPlacement").and_then(JsonValue::as_str) {
        Some("belowEditor") => Slot::WidgetBelow,
        _ => Slot::Widget,
    }
}

fn widget_view(params: &JsonObject) -> Result<Option<UiView>, RegistryError> {
    if let Some(spec) = params.get("widgetSpec").filter(|value| !value.is_null()) {
        let root: Node = serde_json::from_value(spec.clone())
            .map_err(|error| RegistryError::Invalid(format!("widgetSpec: {error}")))?;
        oino_ui::limits::validate(&root)
            .map_err(|diagnostics| RegistryError::Invalid(diagnostics_text(&diagnostics)))?;
        return Ok(Some(UiView::Tree { root }));
    }
    match params.get("widgetLines") {
        Some(JsonValue::Array(lines)) => Ok(Some(UiView::Lines {
            lines: lines
                .iter()
                .map(|line| line.as_str().unwrap_or_default().to_owned())
                .collect(),
        })),
        Some(JsonValue::Null) | None => Ok(None),
        Some(_) => Err(RegistryError::Invalid(
            "widgetLines must be an array of strings".to_owned(),
        )),
    }
}
// APPEND

/// Producer calls of §6.3: one retained producer call becomes one registry
/// mutation. Everything else is a one-shot [`ProduceOutcome::Effect`] (or an
/// unknown method the bridge ignores, §3.1).
impl UiRegistry {
    /// Applies one `ui.fire` producer call of `extension`.
    ///
    /// # Errors
    ///
    /// Invalid payloads, foreign ids and limit/validation failures (§9.1).
    pub fn produce(
        &mut self,
        extension: &str,
        method: &str,
        params: &JsonObject,
    ) -> Result<ProduceOutcome, RegistryError> {
        match method {
            "setStatus" => self.produce_status(extension, params),
            "setWidget" => self.produce_widget(extension, params),
            "setFrame" => self.produce_frame(extension, params),
            "setHeader" | "setFooter" => self.produce_header_footer(extension, method, params),
            "setTitle" => {
                let title = string(params, "title");
                self.set_meta(oino_ui::slot::UiMetaPatch {
                    title,
                    ..oino_ui::slot::UiMetaPatch::default()
                });
                Ok(ProduceOutcome::Effect)
            }
            "setWorkingMessage" => {
                let set = oino_ui::slot::UiMetaPatch {
                    working_message: string(params, "message"),
                    working_visible: params.get("visible").and_then(JsonValue::as_bool),
                    ..oino_ui::slot::UiMetaPatch::default()
                };
                self.set_meta(set);
                Ok(ProduceOutcome::Effect)
            }
            "setShortcuts" => {
                let shortcuts = params
                    .get("shortcuts")
                    .and_then(JsonValue::as_array)
                    .map(|items| {
                        items
                            .iter()
                            .filter_map(|item| {
                                let keys = item.get("keys")?.as_array()?;
                                Some(KeyBinding {
                                    key: keys.first()?.as_str()?.to_owned(),
                                    action: item
                                        .get("id")
                                        .and_then(JsonValue::as_str)
                                        .map(str::to_owned),
                                    label: item
                                        .get("description")
                                        .and_then(JsonValue::as_str)
                                        .unwrap_or_default()
                                        .to_owned(),
                                })
                            })
                            .collect()
                    })
                    .unwrap_or_default();
                self.set_meta(oino_ui::slot::UiMetaPatch {
                    shortcuts: Some(shortcuts),
                    ..oino_ui::slot::UiMetaPatch::default()
                });
                Ok(ProduceOutcome::Effect)
            }
            "openPanel" => self.produce_open(extension, params),
            "updatePanel" => self.produce_update(extension, params),
            "closePanel" => {
                let id = string(params, "panelId")
                    .ok_or_else(|| RegistryError::Invalid("closePanel without panelId".into()))?;
                self.remove(extension, &id)?;
                Ok(ProduceOutcome::Deleted(id))
            }
            "invalidateTurnFooter" => {
                let key = string(params, "key").ok_or_else(|| {
                    RegistryError::Invalid("invalidateTurnFooter without key".into())
                })?;
                let turns = params
                    .get("turnEntryIds")
                    .and_then(JsonValue::as_array)
                    .map(|ids| {
                        ids.iter()
                            .filter_map(|id| id.as_str().map(str::to_owned))
                            .collect()
                    });
                self.invalidate_turn_footer(extension, &key, turns)?;
                Ok(ProduceOutcome::Effect)
            }
            _ => Ok(ProduceOutcome::Effect),
        }
    }

    fn produce_status(
        &mut self,
        extension: &str,
        params: &JsonObject,
    ) -> Result<ProduceOutcome, RegistryError> {
        let key = string(params, "statusKey")
            .ok_or_else(|| RegistryError::Invalid("setStatus without statusKey".into()))?;
        let id = format!("{extension}/status:{key}");
        let Some(text) = line(params, "statusText").or_else(|| line(params, "spans")) else {
            if self.entries.contains_key(&id) {
                self.remove(extension, &id)?;
            }
            return Ok(ProduceOutcome::Deleted(id));
        };
        let out = self.put(EntryRequest {
            id,
            extension_id: extension.to_owned(),
            slot: Slot::Status,
            order: order(params),
            title: None,
            icon: params.get("icon").and_then(icon_value),
            badge: None,
            tone: color(params, "tone"),
            view: UiView::Status { text },
            keys: Vec::new(),
            focus: None,
            close_on_escape: None,
            size: None,
            fallback: None,
            params: None,
        })?;
        Ok(ProduceOutcome::Entry {
            id: out.id,
            created: out.created,
        })
    }

    fn produce_widget(
        &mut self,
        extension: &str,
        params: &JsonObject,
    ) -> Result<ProduceOutcome, RegistryError> {
        let key = string(params, "widgetKey")
            .ok_or_else(|| RegistryError::Invalid("setWidget without widgetKey".into()))?;
        let id = format!("{extension}/widget:{key}");
        let Some(view) = widget_view(params)? else {
            if self.entries.contains_key(&id) {
                self.remove(extension, &id)?;
            }
            return Ok(ProduceOutcome::Deleted(id));
        };
        let out = self.put(EntryRequest {
            id,
            extension_id: extension.to_owned(),
            slot: widget_placement(params),
            order: order(params),
            title: None,
            icon: None,
            badge: None,
            tone: None,
            view,
            keys: Vec::new(),
            focus: None,
            close_on_escape: None,
            size: None,
            fallback: None,
            params: None,
        })?;
        Ok(ProduceOutcome::Entry {
            id: out.id,
            created: out.created,
        })
    }

    fn produce_frame(
        &mut self,
        extension: &str,
        params: &JsonObject,
    ) -> Result<ProduceOutcome, RegistryError> {
        let key = string(params, "frameKey")
            .ok_or_else(|| RegistryError::Invalid("setFrame without frameKey".into()))?;
        let prefix = format!("{extension}/frame:{key}:");
        let stale: Vec<String> = self
            .entries
            .keys()
            .filter(|id| id.starts_with(&prefix))
            .cloned()
            .collect();
        let segments = |field: &str| {
            params
                .get(field)
                .and_then(JsonValue::as_array)
                .cloned()
                .unwrap_or_default()
        };
        let segments: Vec<JsonValue> = segments("top")
            .into_iter()
            .chain(segments("bottom"))
            .collect();
        for id in stale {
            self.delete(&id);
        }
        let mut last = None;
        for (index, segment) in segments.iter().enumerate() {
            let Some(object) = segment.as_object() else {
                return Err(RegistryError::Invalid(
                    "setFrame segments must be objects".into(),
                ));
            };
            let Some(text) = line(object, "text") else {
                continue;
            };
            let id = format!("{prefix}{index}");
            let out = self.put(EntryRequest {
                id: id.clone(),
                extension_id: extension.to_owned(),
                slot: Slot::Status,
                order: order(object),
                title: None,
                icon: object.get("icon").and_then(icon_value),
                badge: None,
                tone: color(object, "tone"),
                view: UiView::Status { text },
                keys: Vec::new(),
                focus: None,
                close_on_escape: None,
                size: None,
                fallback: None,
                params: None,
            })?;
            last = Some(out.id);
        }
        Ok(match last {
            Some(id) => ProduceOutcome::Entry { id, created: false },
            None => ProduceOutcome::Deleted(format!("{extension}/frame:{key}")),
        })
    }

    fn produce_header_footer(
        &mut self,
        extension: &str,
        method: &str,
        params: &JsonObject,
    ) -> Result<ProduceOutcome, RegistryError> {
        let key = string(params, "key")
            .ok_or_else(|| RegistryError::Invalid(format!("{method} without key")))?;
        let slot = if method == "setHeader" {
            Slot::Header
        } else {
            Slot::Footer
        };
        let id = format!("{extension}/{method}:{key}");
        if let Some(spec) = params.get("spec").filter(|value| !value.is_null()) {
            let root: Node = serde_json::from_value(spec.clone())
                .map_err(|error| RegistryError::Invalid(format!("{method} spec: {error}")))?;
            let out = self.put(EntryRequest {
                id,
                extension_id: extension.to_owned(),
                slot,
                order: order(params),
                title: None,
                icon: None,
                badge: None,
                tone: None,
                view: UiView::Tree { root },
                keys: Vec::new(),
                focus: None,
                close_on_escape: None,
                size: None,
                fallback: None,
                params: None,
            })?;
            return Ok(ProduceOutcome::Entry {
                id: out.id,
                created: out.created,
            });
        }
        if self.entries.contains_key(&id) {
            self.remove(extension, &id)?;
        }
        Ok(ProduceOutcome::Deleted(id))
    }

    fn produce_open(
        &mut self,
        extension: &str,
        params: &JsonObject,
    ) -> Result<ProduceOutcome, RegistryError> {
        let id = if let Some(id) = string(params, "panelId") {
            id
        } else {
            self.panels += 1;
            format!("{extension}/panel-{}", self.panels)
        };
        let request = panel_request(extension, &id, params)?;
        let out = self.put(request)?;
        Ok(ProduceOutcome::Entry {
            id: out.id,
            created: out.created,
        })
    }

    fn produce_update(
        &mut self,
        extension: &str,
        params: &JsonObject,
    ) -> Result<ProduceOutcome, RegistryError> {
        let id = string(params, "panelId")
            .ok_or_else(|| RegistryError::Invalid("updatePanel without panelId".into()))?;
        // The caller must own the entry; `update` trusts the stored owner.
        Self::check_ownership(extension, &id)?;
        let spec = params
            .get("spec")
            .filter(|value| !value.is_null())
            .map(|value| {
                serde_json::from_value::<Node>(value.clone())
                    .map_err(|error| RegistryError::Invalid(format!("updatePanel spec: {error}")))
            })
            .transpose()?;
        let patch = params
            .get("patch")
            .filter(|value| !value.is_null())
            .map(|value| {
                serde_json::from_value::<Vec<NodeOp>>(value.clone())
                    .map_err(|error| RegistryError::Invalid(format!("updatePanel patch: {error}")))
            })
            .transpose()?;
        let fallback = params
            .get("fallback")
            .filter(|value| !value.is_null())
            .map(|value| {
                serde_json::from_value::<Node>(value.clone()).map_err(|error| {
                    RegistryError::Invalid(format!("updatePanel fallback: {error}"))
                })
            })
            .transpose()?;
        let keys = params
            .get("keys")
            .and_then(|value| serde_json::from_value::<Vec<KeyBinding>>(value.clone()).ok());
        self.update(EntryUpdate {
            id: id.clone(),
            spec,
            patch,
            title: string(params, "title"),
            icon: params.get("icon").and_then(icon_value),
            badge: params
                .get("badge")
                .and_then(|value| serde_json::from_value(value.clone()).ok()),
            order: order(params),
            keys,
            fallback,
        })?;
        Ok(ProduceOutcome::Entry { id, created: false })
    }
}

fn icon_value(value: &JsonValue) -> Option<Icon> {
    serde_json::from_value(value.clone()).ok()
}

fn panel_request(
    extension: &str,
    id: &str,
    params: &JsonObject,
) -> Result<EntryRequest, RegistryError> {
    let slot = match params.get("placement") {
        Some(value) if !value.is_null() => serde_json::from_value::<Slot>(value.clone())
            .map_err(|error| RegistryError::Invalid(format!("openPanel placement: {error}")))?,
        _ => Slot::Overlay,
    };
    let spec = params
        .get("spec")
        .filter(|value| !value.is_null())
        .map(|value| {
            serde_json::from_value::<Node>(value.clone())
                .map_err(|error| RegistryError::Invalid(format!("openPanel spec: {error}")))
        })
        .transpose()?;
    let keys = params
        .get("keys")
        .and_then(|value| serde_json::from_value::<Vec<KeyBinding>>(value.clone()).ok())
        .unwrap_or_default();
    let view = match spec {
        Some(root) => UiView::Tree { root },
        None => UiView::Lines { lines: Vec::new() },
    };
    Ok(EntryRequest {
        id: id.to_owned(),
        extension_id: extension.to_owned(),
        slot,
        order: order(params),
        title: string(params, "title"),
        icon: params.get("icon").and_then(icon_value),
        badge: params
            .get("badge")
            .and_then(|value| serde_json::from_value(value.clone()).ok()),
        tone: None,
        view,
        keys,
        focus: params.get("focus").and_then(JsonValue::as_bool),
        close_on_escape: params.get("closeOnEscape").and_then(JsonValue::as_bool),
        size: params
            .get("size")
            .and_then(|value| serde_json::from_value(value.clone()).ok()),
        fallback: None,
        params: params.get("params").cloned(),
    })
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::unwrap_used,
        clippy::expect_used,
        clippy::panic,
        reason = "tests assert by unwrapping"
    )]
    use super::*;
    use oino_ui::widgets::paragraph::Paragraph;

    fn tree(text: &str) -> Node {
        Paragraph::new(text).into()
    }

    fn request(extension: &str, id: &str, slot: Slot, root: Node) -> EntryRequest {
        EntryRequest {
            id: id.to_owned(),
            extension_id: extension.to_owned(),
            slot,
            order: None,
            title: None,
            icon: None,
            badge: None,
            tone: None,
            view: UiView::Tree { root },
            keys: Vec::new(),
            focus: None,
            close_on_escape: None,
            size: None,
            fallback: None,
            params: None,
        }
    }

    fn registry() -> UiRegistry {
        UiRegistry::new(Scope::Session, Some("s1".to_owned()))
    }

    fn params(value: JsonValue) -> JsonObject {
        serde_json::from_value(value).unwrap()
    }

    #[test]
    fn entries_render_in_order_then_seq() {
        let mut registry = registry();
        registry
            .put(request("a", "a/one", Slot::SidePane, tree("1")))
            .unwrap();
        registry
            .put(request("a", "a/two", Slot::SidePane, tree("2")))
            .unwrap();
        let mut later = request("b", "b/three", Slot::SidePane, tree("3"));
        later.order = Some(5);
        registry.put(later).unwrap();
        let ids: Vec<&str> = registry
            .slot_entries(Slot::SidePane)
            .iter()
            .map(|entry| entry.id.as_str())
            .collect();
        // order desc first (b/three), then registration order (a/one, a/two).
        assert_eq!(ids, ["b/three", "a/one", "a/two"]);
    }

    #[test]
    fn stack_slots_show_the_most_recent_entry() {
        let mut registry = registry();
        registry
            .put(request("a", "a/first", Slot::Overlay, tree("1")))
            .unwrap();
        registry
            .put(request("a", "a/second", Slot::Overlay, tree("2")))
            .unwrap();
        assert_eq!(
            registry.stack_top(Slot::Overlay).map(|e| e.id.as_str()),
            Some("a/second")
        );
        let mut focused = request("a", "a/first", Slot::Overlay, tree("1"));
        focused.focus = Some(true);
        registry.put(focused).unwrap();
        assert_eq!(
            registry.stack_top(Slot::Overlay).map(|e| e.id.as_str()),
            Some("a/first")
        );
    }

    #[test]
    fn dispose_removes_only_the_owners_entries() {
        let mut registry = registry();
        registry
            .put(request("a", "a/p", Slot::SidePane, tree("1")))
            .unwrap();
        registry
            .put(request("b", "b/p", Slot::SidePane, tree("2")))
            .unwrap();
        registry
            .put(request("b", "b/w", Slot::Widget, tree("3")))
            .unwrap();
        registry.take_patch();
        let removed = registry.remove_owner("b");
        assert_eq!(removed, ["b/p", "b/w"]);
        assert_eq!(registry.ids(), ["a/p"]);
        let patch = registry.take_patch().unwrap();
        assert_eq!(patch.rev, 2, "the first batch was the three puts");
        assert_eq!(patch.ops.len(), 2);
        assert!(
            patch
                .ops
                .iter()
                .all(|op| matches!(op, RegistryOp::Del { .. }))
        );

        // A user `$close` deletes exactly one entry.
        registry.close("a/p");
        assert_eq!(registry.ids().len(), 0);

        // Session close clears the rest.
        registry
            .put(request("a", "a/p", Slot::SidePane, tree("1")))
            .unwrap();
        assert_eq!(registry.clear(), ["a/p"]);
        assert_eq!(registry.ids().len(), 0);
    }

    #[test]
    fn foreign_ids_are_rejected() {
        let mut registry = registry();
        let error = registry
            .put(request("a", "b/panel", Slot::SidePane, tree("1")))
            .unwrap_err();
        assert_eq!(
            error,
            RegistryError::ForeignId {
                id: "b/panel".to_owned(),
                extension: "a".to_owned()
            }
        );
        assert_eq!(registry.ids().len(), 0);
    }

    #[test]
    fn reserved_ids_are_gated_to_their_owner() {
        register_reserved(ReservedPanelSpec {
            allowed: vec![Slot::Fullscreen, Slot::SidePane],
            orders: vec![(Slot::Fullscreen, 1000), (Slot::SidePane, 960)],
            ..ReservedPanelSpec::new(
                "acme.board/board",
                "acme.board",
                "board",
                Slot::Fullscreen,
                "Board",
                1000,
            )
        });
        register_reserved(ReservedPanelSpec::new(
            "acme.cron/jobs",
            "acme.cron",
            "cron",
            Slot::Fullscreen,
            "Cron",
            990,
        ));
        let mut registry = registry();
        let error = registry
            .put(request(
                "evil",
                "acme.board/board",
                Slot::Fullscreen,
                tree("1"),
            ))
            .unwrap_err();
        assert_eq!(
            error,
            RegistryError::ReservedOwned {
                id: "acme.board/board".to_owned(),
                owner: "acme.board".to_owned()
            }
        );
        // A reserved component outside the table is not allowed either.
        let mut fake = request("evil", "evil/board", Slot::Overlay, tree("1"));
        fake.view = UiView::Reserved {
            component: ReservedComponent::new("board"),
            fallback: None,
            params: None,
        };
        assert_eq!(
            registry.put(fake).unwrap_err(),
            RegistryError::NotReserved("evil/board".to_owned())
        );
        // The owner gets the component entry; its spec is ignored (§8).
        let out = registry
            .put(request(
                "acme.board",
                "acme.board/board",
                Slot::Fullscreen,
                tree("ignored"),
            ))
            .unwrap();
        assert!(out.created);
        let entry = registry.get("acme.board/board").unwrap();
        assert_eq!(
            entry.view,
            UiView::Reserved {
                component: ReservedComponent::new("board"),
                fallback: None,
                params: None,
            }
        );
        assert_eq!(entry.order, 1000);
        assert_eq!(entry.title.as_deref(), Some("Board"));
        // `sidePane` is allowed for the board; other slots fall back to the default.
        registry
            .put(request(
                "acme.board",
                "acme.board/board",
                Slot::SidePane,
                tree("ignored"),
            ))
            .unwrap();
        assert_eq!(
            registry.get("acme.board/board").unwrap().slot,
            Slot::SidePane
        );
        assert_eq!(registry.get("acme.board/board").unwrap().order, 960);
        registry
            .put(request(
                "acme.cron",
                "acme.cron/jobs",
                Slot::SidePane,
                tree("ignored"),
            ))
            .unwrap();
        assert_eq!(
            registry.get("acme.cron/jobs").unwrap().slot,
            Slot::Fullscreen
        );
    }

    #[test]
    fn reserved_fallbacks_are_set_by_update_panel() {
        register_reserved(ReservedPanelSpec::new(
            "acme.kanban/board",
            "acme.kanban",
            "board",
            Slot::Fullscreen,
            "Board",
            1000,
        ));
        let mut registry = registry();
        registry
            .put(request(
                "acme.kanban",
                "acme.kanban/board",
                Slot::Fullscreen,
                tree("ignored"),
            ))
            .unwrap();
        registry
            .update(EntryUpdate {
                id: "acme.kanban/board".to_owned(),
                fallback: Some(tree("tasks")),
                ..EntryUpdate::default()
            })
            .unwrap();
        let entry = registry.get("acme.kanban/board").unwrap();
        let UiView::Reserved { fallback, .. } = &entry.view else {
            panic!("not reserved");
        };
        assert_eq!(fallback.as_deref(), Some(&tree("tasks")));
    }

    #[test]
    fn consecutive_ops_for_one_entry_coalesce() {
        let mut registry = registry();
        let lines = |text: &str| EntryRequest {
            view: UiView::Lines {
                lines: vec![text.to_owned()],
            },
            ..request("a", "a/p", Slot::Widget, tree("unused"))
        };
        registry.put(lines("1")).unwrap();
        registry.put(lines("2")).unwrap();
        let patch = registry.take_patch().unwrap();
        assert_eq!(patch.ops.len(), 1, "the later put replaced the earlier one");
        let RegistryOp::Put { entry } = &patch.ops[0] else {
            panic!("expected a put");
        };
        assert_eq!(entry.rev, 2);
        assert_eq!(
            entry.view,
            UiView::Lines {
                lines: vec!["2".to_owned()]
            }
        );
        assert_eq!(entry.extension_id, "a");
    }

    #[test]
    fn patches_coalesce_and_snapshots_drop_pending() {
        let mut registry = registry();
        registry
            .put(request("a", "a/one", Slot::Widget, tree("1")))
            .unwrap();
        registry
            .put(request("a", "a/two", Slot::Widget, tree("2")))
            .unwrap();
        let patch = registry.take_patch().unwrap();
        assert_eq!(patch.rev, 1, "one patch per flush");
        assert_eq!(patch.ops.len(), 2);
        assert_eq!(patch.session_id.as_deref(), Some("s1"));
        assert!(registry.take_patch().is_none());
        registry
            .put(request("a", "a/three", Slot::Widget, tree("3")))
            .unwrap();
        let snapshot = registry.snapshot();
        assert_eq!(snapshot.rev, 1);
        assert_eq!(snapshot.entries.len(), 3);
        assert!(
            !registry.has_pending(),
            "the snapshot supersedes queued ops"
        );
        registry
            .put(request("a", "a/four", Slot::Widget, tree("4")))
            .unwrap();
        assert_eq!(registry.take_patch().unwrap().rev, 2);
    }

    #[test]
    fn a_revision_gap_requests_a_resync() {
        let mut registry = registry();
        registry
            .put(request("a", "a/one", Slot::Widget, tree("1")))
            .unwrap();
        let patch = registry.take_patch().unwrap();
        assert!(!registry.needs_resync(patch.rev));
        assert!(registry.needs_resync(patch.rev - 1));
        assert!(registry.needs_resync(patch.rev + 3));
    }

    #[test]
    fn tree_updates_emit_keyed_patches() {
        let mut registry = registry();
        registry
            .put(request("a", "a/p", Slot::SidePane, tree("one")))
            .unwrap();
        let first = registry.snapshot().entries[0].clone();
        registry
            .put(request("a", "a/p", Slot::SidePane, tree("two")))
            .unwrap();
        let patch = registry.take_patch().unwrap();
        assert_eq!(patch.ops.len(), 1);
        let RegistryOp::Tree { id, rev, ops } = &patch.ops[0] else {
            panic!("expected a tree op, got {:?}", patch.ops[0]);
        };
        assert_eq!(id, "a/p");
        assert_eq!(*rev, 2);
        let UiView::Tree { root } = &first.view else {
            panic!("not a tree");
        };
        assert_eq!(apply(root, ops).unwrap(), tree("two"));
        assert_eq!(registry.get("a/p").unwrap().rev, 2);
    }

    #[test]
    fn foreign_entries_cannot_be_updated_or_closed() {
        let mut registry = registry();
        registry
            .put(request("a", "a/p", Slot::SidePane, tree("1")))
            .unwrap();
        let update = params(serde_json::json!({
            "panelId": "a/p",
            "patch": [{"op": "set", "path": [], "props": {"text": "hijacked"}}]
        }));
        assert_eq!(
            registry.produce("b", "updatePanel", &update).unwrap_err(),
            RegistryError::ForeignId {
                id: "a/p".to_owned(),
                extension: "b".to_owned()
            }
        );
        let close = params(serde_json::json!({"panelId": "a/p"}));
        assert!(matches!(
            registry.produce("b", "closePanel", &close),
            Err(RegistryError::ForeignId { .. })
        ));
        assert!(registry.get("a/p").is_some());
    }

    #[test]
    fn stale_turn_footers_are_invalidated() {
        let mut registry = registry();
        let id = registry.register_turn_footer("a", "files").unwrap();
        assert_eq!(id, "a/turnFooter:files");
        let entry = registry.get(&id).unwrap();
        assert_eq!(entry.slot, Slot::TurnFooter);
        assert_eq!(
            entry.view,
            UiView::Renderer {
                key: "files".to_owned()
            }
        );
        registry.take_patch();
        registry
            .invalidate_turn_footer("a", "files", Some(vec!["t1".to_owned()]))
            .unwrap();
        let patch = registry.take_patch().unwrap();
        assert_eq!(
            patch.ops,
            [RegistryOp::Invalidate {
                id: id.clone(),
                turns: Some(vec!["t1".to_owned()])
            }]
        );
        assert_eq!(registry.get(&id).unwrap().rev, 2);
        assert_eq!(
            registry
                .invalidate_turn_footer("a", "other", None)
                .unwrap_err(),
            RegistryError::NotFound("a/turnFooter:other".to_owned())
        );
    }

    #[test]
    fn visibility_aggregates_over_frontends() {
        let mut registry = registry();
        registry
            .put(request("a", "a/p", Slot::SidePane, tree("1")))
            .unwrap();
        assert_eq!(
            registry.set_visible("tui", "a/p", true),
            Some(VisibilityChange {
                entry_id: "a/p".to_owned(),
                visible: true
            })
        );
        assert_eq!(registry.set_visible("app", "a/p", true), None);
        assert!(registry.is_visible("a/p"));
        assert_eq!(registry.set_visible("tui", "a/p", false), None);
        assert_eq!(
            registry.set_visible("app", "a/p", false),
            Some(VisibilityChange {
                entry_id: "a/p".to_owned(),
                visible: false
            })
        );
        assert!(!registry.is_visible("a/p"));
        assert_eq!(registry.set_visible("tui", "a/unknown", true), None);
    }

    #[test]
    fn producers_map_to_entries() {
        let mut registry = registry();
        let status =
            params(serde_json::json!({"statusKey": "k", "statusText": "1", "priority": 3}));
        let outcome = registry.produce("a", "setStatus", &status).unwrap();
        assert_eq!(
            outcome,
            ProduceOutcome::Entry {
                id: "a/status:k".to_owned(),
                created: true
            }
        );
        let entry = registry.get("a/status:k").unwrap();
        assert_eq!(entry.slot, Slot::Status);
        assert_eq!(entry.order, 3);
        assert_eq!(
            entry.view,
            UiView::Status {
                text: Line::from("1")
            }
        );

        let widget = params(serde_json::json!({
            "widgetKey": "w",
            "widgetLines": ["a", "b"],
            "widgetPlacement": "belowEditor"
        }));
        registry.produce("a", "setWidget", &widget).unwrap();
        let entry = registry.get("a/widget:w").unwrap();
        assert_eq!(entry.slot, Slot::WidgetBelow);
        assert_eq!(
            entry.view,
            UiView::Lines {
                lines: vec!["a".to_owned(), "b".to_owned()]
            }
        );

        let open = params(serde_json::json!({
            "placement": "sidePane",
            "title": "Panel",
            "spec": {"t": "Paragraph", "text": "hi"}
        }));
        let outcome = registry.produce("a", "openPanel", &open).unwrap();
        let ProduceOutcome::Entry { id, created } = outcome else {
            panic!("not an entry");
        };
        assert!(created);
        assert_eq!(id, "a/panel-1");
        assert_eq!(registry.get(&id).unwrap().title.as_deref(), Some("Panel"));

        // `updatePanel` with explicit ops keeps the stored tree current.
        let update = params(serde_json::json!({
            "panelId": "a/panel-1",
            "patch": [{"op": "set", "path": [], "props": {"text": "bye"}}]
        }));
        registry.produce("a", "updatePanel", &update).unwrap();
        registry.take_patch();

        // A clearing producer deletes its entry.
        let clear = params(serde_json::json!({"statusKey": "k"}));
        assert_eq!(
            registry.produce("a", "setStatus", &clear).unwrap(),
            ProduceOutcome::Deleted("a/status:k".to_owned())
        );
        assert!(registry.get("a/status:k").is_none());
        let close = params(serde_json::json!({"panelId": "a/panel-1"}));
        assert_eq!(
            registry.produce("a", "closePanel", &close).unwrap(),
            ProduceOutcome::Deleted("a/panel-1".to_owned())
        );
        assert_eq!(registry.ids(), ["a/widget:w"]);
    }

    #[test]
    fn one_shot_effects_are_not_producers() {
        let mut registry = registry();
        assert!(!is_producer("notify"));
        assert!(is_producer("openPanel"));
        assert!(is_meta_method("setTitle"));
        let notify = params(serde_json::json!({"message": "hi"}));
        assert_eq!(
            registry.produce("a", "notify", &notify).unwrap(),
            ProduceOutcome::Effect
        );
    }

    #[test]
    fn limits_reject_the_65th_entry() {
        let mut registry = registry();
        for index in 0..MAX_ENTRIES {
            registry
                .put(request(
                    "a",
                    &format!("a/widget:{index}"),
                    Slot::Widget,
                    tree("x"),
                ))
                .unwrap();
        }
        assert_eq!(
            registry
                .put(request("a", "a/widget:over", Slot::Widget, tree("x")))
                .unwrap_err(),
            RegistryError::Limit("a".to_owned())
        );
        // Replacing an existing entry never hits the limit.
        registry
            .put(request("a", "a/widget:0", Slot::Widget, tree("y")))
            .unwrap();
    }

    #[test]
    fn settings_namespaces_register_once() {
        let mut registry = registry();
        let namespace = |namespace: &str| oino_ui::settings::SettingsNamespace {
            namespace: namespace.to_owned(),
            title: "Acme".to_owned(),
            extension_id: "oino".to_owned(),
            ..oino_ui::settings::SettingsNamespace::default()
        };
        let id = registry.register_settings(namespace("acme")).unwrap();
        assert_eq!(id, "oino/settings:acme");
        let entry = registry.get(&id).unwrap();
        assert_eq!(entry.slot, Slot::Settings);
        assert_eq!(entry.order, 1000);
        assert!(matches!(entry.view, UiView::Settings { .. }));
        assert!(
            registry
                .register_settings(namespace("acme"))
                .unwrap_err()
                .to_string()
                .contains("already registered")
        );
    }
}