lingxia-lxapp 0.18.0

LxApp (lightweight application) container and runtime for LingXia framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
//! Host API runtime and extension surface.
//!
//! Built-in host capabilities and third-party host extensions share the same
//! registry. External crates can define handlers and register them here.

use crate::ControlDocumentAuthority;
use crate::error::LxAppError;
use crate::lxapp::{AppSessionClass, LxApp, LxAppSessionStatus};

use futures::Stream;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::future::Future;
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::{Arc, Mutex, OnceLock, Weak};
use tokio::sync::{mpsc, oneshot};

#[macro_use]
mod macros;

mod device;
mod navigation;
mod navigator;

pub type HostResult<T> = Result<T, LxAppError>;
pub type JsonValue = serde_json::Value;

pub type HostCancel = oneshot::Receiver<()>;
pub type HostStream =
    Pin<Box<dyn Stream<Item = Result<HostStreamItem, LxAppError>> + Send + 'static>>;
pub type HostFuture<'a> = Pin<Box<dyn Future<Output = Result<HostOutput, LxAppError>> + Send + 'a>>;

pub enum HostStreamItem {
    Event(String),
    Return(String),
}

pub enum HostOutput {
    Json(String),
    Stream(HostStream),
}

#[doc(hidden)]
pub mod __native {
    use super::{Future, HostResult, LxAppError};

    pub fn spawn<F>(future: F) -> tokio::task::JoinHandle<F::Output>
    where
        F: Future + Send + 'static,
        F::Output: Send + 'static,
    {
        crate::executor::spawn(future)
    }

    pub async fn spawn_blocking<F, R>(f: F) -> HostResult<R>
    where
        F: FnOnce() -> R + Send + 'static,
        R: Send + 'static,
    {
        rong_rt::RongExecutor::global()
            .spawn_blocking(f)
            .await
            .map_err(|err| LxAppError::Runtime(err.to_string()))
    }
}

/// Wire-level method kind generated for unary and stream handlers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostMethodKind {
    Call,
    Stream,
}

/// Route family stored in the effective inventory and Ready schema.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum HostRouteKind {
    Call,
    Stream,
    Channel,
}

/// The admission constraint attached to a host route.
///
/// This is deliberately a closed SDK enum. Dispatch policy determines
/// the caller set for each constraint; callers cannot select one from a bridge
/// payload or an app manifest.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RouteAudience {
    /// Any lxapp session, of any class.
    AppSessionOnly,
    /// Any lxapp session, plus a browser control document. Constrains the
    /// caller class only; it does not make the route read-only.
    AnyAuthenticated,
    /// The `ControlApp` session only.
    ControlAppOnly,
    /// Only the host-bundled `ControlSurface` session (Terminal Settings).
    /// Deliberately disjoint from `ControlAppOnly`: neither class reaches the
    /// other's routes.
    ControlSurfaceOnly,
    /// A browser control document only.
    BrowserControlOnly,
    /// The `ControlApp` session, plus a browser control document. The
    /// `ControlSurface` is a distinct class and is not admitted.
    ControlAppOrBrowserOnly,
}

/// A privileged native resource that may be assigned to one lxapp session.
///
/// The permission provider (or its default allow) is the request. The native
/// host seals the granted subset once that snapshot is ready, not from the
/// pending deny.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AppResourceGrant {
    Process,
    Downloads,
    Automation,
    AutomationHost,
}

impl AppResourceGrant {
    pub const fn manifest_privilege(self) -> &'static str {
        match self {
            Self::Process => "process",
            Self::Downloads => "downloads",
            Self::Automation => "automation",
            Self::AutomationHost => "host",
        }
    }
}

/// One-shot authority for assigning privileged resources to a newly created
/// app session. Only the lxapp session bootstrap constructs it.
pub struct NativeHostRuntimeAuthority<'a> {
    app_id: &'a str,
    session_id: u64,
    session_class: AppSessionClass,
    requested: HashSet<AppResourceGrant>,
    grants: &'a mut HashSet<AppResourceGrant>,
}

impl NativeHostRuntimeAuthority<'_> {
    pub fn app_id(&self) -> &str {
        self.app_id
    }

    pub const fn session_id(&self) -> u64 {
        self.session_id
    }

    pub const fn session_class(&self) -> AppSessionClass {
        self.session_class
    }

    pub fn requested(&self, grant: AppResourceGrant) -> bool {
        self.requested.contains(&grant)
    }

    pub fn grant(&mut self, grant: AppResourceGrant) -> bool {
        // Process execution stays ControlApp-only even when a host addon
        // vouches for another session that requested it.
        if grant == AppResourceGrant::Process && self.session_class != AppSessionClass::ControlApp {
            return false;
        }
        if !self.requested(grant) {
            return false;
        }
        self.grants.insert(grant);
        true
    }

    #[cfg(test)]
    pub(crate) fn for_test<'a>(
        app_id: &'a str,
        session_id: u64,
        session_class: AppSessionClass,
        requested: impl IntoIterator<Item = AppResourceGrant>,
        grants: &'a mut HashSet<AppResourceGrant>,
    ) -> NativeHostRuntimeAuthority<'a> {
        NativeHostRuntimeAuthority {
            app_id,
            session_id,
            session_class,
            requested: requested.into_iter().collect(),
            grants,
        }
    }
}

/// One-shot authority reserved for native devtools bootstrap. It cannot grant
/// process execution or Downloads access.
pub struct NativeDevtoolsAuthority<'a> {
    app_id: &'a str,
    session_id: u64,
    session_class: AppSessionClass,
    requested: HashSet<AppResourceGrant>,
    grants: &'a mut HashSet<AppResourceGrant>,
}

impl NativeDevtoolsAuthority<'_> {
    pub fn app_id(&self) -> &str {
        self.app_id
    }

    pub const fn session_id(&self) -> u64 {
        self.session_id
    }

    pub const fn session_class(&self) -> AppSessionClass {
        self.session_class
    }

    pub fn requested(&self, grant: AppResourceGrant) -> bool {
        self.requested.contains(&grant)
    }

    pub fn grant(&mut self, grant: AppResourceGrant) -> bool {
        if !matches!(
            grant,
            AppResourceGrant::Automation | AppResourceGrant::AutomationHost
        ) || !self.requested(grant)
        {
            return false;
        }
        self.grants.insert(grant);
        true
    }

    pub fn grant_automation(&mut self) -> bool {
        let automation = self.grant(AppResourceGrant::Automation);
        let host = self.grant(AppResourceGrant::AutomationHost);
        automation | host
    }

    #[cfg(test)]
    pub(crate) fn for_test<'a>(
        app_id: &'a str,
        session_id: u64,
        session_class: AppSessionClass,
        requested: impl IntoIterator<Item = AppResourceGrant>,
        grants: &'a mut HashSet<AppResourceGrant>,
    ) -> NativeDevtoolsAuthority<'a> {
        NativeDevtoolsAuthority {
            app_id,
            session_id,
            session_class,
            requested: requested.into_iter().collect(),
            grants,
        }
    }
}

pub(crate) type AppResourceGrantResolver =
    dyn for<'a> Fn(&Arc<LxApp>, &mut NativeHostRuntimeAuthority<'a>) + Send + Sync + 'static;
pub(crate) type DevtoolsResourceGrantResolver =
    dyn for<'a> Fn(&Arc<LxApp>, &mut NativeDevtoolsAuthority<'a>) + Send + Sync + 'static;

static APP_RESOURCE_GRANT_RESOLVER: OnceLock<Arc<AppResourceGrantResolver>> = OnceLock::new();
static DEVTOOLS_RESOURCE_GRANT_RESOLVER: OnceLock<Arc<DevtoolsResourceGrantResolver>> =
    OnceLock::new();

/// Seal the native host's per-session grant resolvers during the lxapp
/// bootstrap transaction. There is deliberately no downstream installer:
/// extensions can contribute through `HostAddon`, but cannot win a race for
/// these process-wide slots.
pub(crate) fn install_bootstrap_resource_grant_resolvers(
    app: Option<Arc<AppResourceGrantResolver>>,
    devtools: Option<Arc<DevtoolsResourceGrantResolver>>,
) -> Result<(), &'static str> {
    if APP_RESOURCE_GRANT_RESOLVER.get().is_some()
        || (devtools.is_some() && DEVTOOLS_RESOURCE_GRANT_RESOLVER.get().is_some())
    {
        return Err("native resource grant resolvers were already installed");
    }
    if let Some(resolver) = app {
        APP_RESOURCE_GRANT_RESOLVER
            .set(resolver)
            .map_err(|_| "native app resource grant resolver was already installed")?;
    }
    if let Some(resolver) = devtools {
        DEVTOOLS_RESOURCE_GRANT_RESOLVER
            .set(resolver)
            .map_err(|_| "native devtools grant resolver was already installed")?;
    }
    Ok(())
}

pub(crate) fn seal_app_resource_grants(app: &Arc<LxApp>) {
    if !app.permissions_ready() {
        // Pending is deny. Sealing that into the OnceLock would stick even
        // after the registry answers.
        return;
    }
    if !app.claim_resource_grant_seal() {
        return;
    }
    let requested: HashSet<_> = [
        AppResourceGrant::Process,
        AppResourceGrant::Downloads,
        AppResourceGrant::Automation,
        AppResourceGrant::AutomationHost,
    ]
    .into_iter()
    .filter(|grant| {
        let privilege = crate::LxAppSecurityPrivilege::new(grant.manifest_privilege())
            .expect("resource grants use valid manifest privilege ids");
        app.has_security_privilege(&privilege)
    })
    .collect();
    let mut grants = HashSet::new();
    if let Some(resolver) = APP_RESOURCE_GRANT_RESOLVER.get() {
        let mut authority = NativeHostRuntimeAuthority {
            app_id: &app.appid,
            session_id: app.session_id(),
            session_class: app.app_session_class(),
            requested: requested.clone(),
            grants: &mut grants,
        };
        resolver(app, &mut authority);
    }
    if let Some(resolver) = DEVTOOLS_RESOURCE_GRANT_RESOLVER.get() {
        let mut authority = NativeDevtoolsAuthority {
            app_id: &app.appid,
            session_id: app.session_id(),
            session_class: app.app_session_class(),
            requested,
            grants: &mut grants,
        };
        resolver(app, &mut authority);
    }
    app.seal_resource_grants(grants);
}

/// Native identity of one authenticated lxapp session.
///
/// The constructor is crate-private: an app id in a bridge payload or manifest
/// cannot create or replace this identity.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AppIdentity {
    app_id: Arc<str>,
    session_id: u64,
}

impl AppIdentity {
    pub fn app_id(&self) -> &str {
        &self.app_id
    }

    pub const fn session_id(&self) -> u64 {
        self.session_id
    }
}

/// Filesystem namespace assigned to an lxapp by the native runtime.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AppStorageNamespace {
    storage_file: PathBuf,
    user_data: PathBuf,
    user_cache: PathBuf,
    temporary: PathBuf,
}

impl AppStorageNamespace {
    pub fn storage_file(&self) -> &Path {
        &self.storage_file
    }

    pub fn user_data(&self) -> &Path {
        &self.user_data
    }

    pub fn user_cache(&self) -> &Path {
        &self.user_cache
    }

    pub fn temporary(&self) -> &Path {
        &self.temporary
    }
}

/// Native-issued resource grants attached to one live lxapp session.
///
/// Transient paths and references are issued by native pickers and keyed by
/// the immutable app/session identity. A retained scope fails closed once the
/// native app session is gone.
#[derive(Clone)]
pub struct AppResourceGrants {
    app_id: Arc<str>,
    session_id: u64,
    owner: Weak<LxApp>,
}

impl fmt::Debug for AppResourceGrants {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("AppResourceGrants")
            .field("app_id", &self.app_id)
            .field("session_id", &self.session_id)
            .finish_non_exhaustive()
    }
}

impl AppResourceGrants {
    fn live_owner(&self) -> Result<Arc<LxApp>, LxAppError> {
        let app = self.owner.upgrade().ok_or_else(|| {
            LxAppError::ResourceNotFound("lxapp resource scope is no longer live".to_string())
        })?;
        if app.appid != self.app_id.as_ref()
            || app.session_id() != self.session_id
            || matches!(
                app.status(),
                LxAppSessionStatus::Closed
                    | LxAppSessionStatus::Closing
                    | LxAppSessionStatus::Restarting
            )
        {
            return Err(LxAppError::ResourceNotFound(
                "lxapp resource scope no longer matches its native session".to_string(),
            ));
        }
        Ok(app)
    }

    /// Resolve a native-issued transient `lx://temp/...` grant.
    pub fn resolve_transient_file(&self, resource: &str) -> Result<PathBuf, LxAppError> {
        if !resource.trim().starts_with("lx://temp/") {
            return Err(LxAppError::InvalidParameter(
                "expected a native-issued lx://temp resource grant".to_string(),
            ));
        }
        self.live_owner()?.resolve_accessible_path(resource)
    }

    /// Test a native-issued opaque file reference for this exact app session.
    pub fn contains_file_reference(&self, reference: &str) -> bool {
        self.live_owner()
            .is_ok_and(|app| app.has_transient_file_reference(reference))
    }

    /// Whether the native host assigned this privileged resource to this live
    /// session. A manifest declaration alone never makes this return true.
    pub fn contains(&self, grant: AppResourceGrant) -> bool {
        self.live_owner()
            .is_ok_and(|app| app.has_resource_grant(grant))
    }
}

/// Native-derived resource scope of an authenticated lxapp session.
///
/// This value is constructed from the owning [`LxApp`], never from bridge
/// payload fields. Route audience admission and resource authorization remain
/// distinct: handlers use this scope after admission to resolve app-owned
/// storage or native-issued resource grants.
#[derive(Debug, Clone)]
pub struct AppScope {
    identity: AppIdentity,
    storage: AppStorageNamespace,
    resource_grants: AppResourceGrants,
}

impl AppScope {
    pub(crate) fn from_lxapp(app: &Arc<LxApp>) -> Self {
        let app_id: Arc<str> = Arc::from(app.appid.as_str());
        let session_id = app.session_id();
        Self {
            identity: AppIdentity {
                app_id: Arc::clone(&app_id),
                session_id,
            },
            storage: AppStorageNamespace {
                storage_file: app.storage_file_path.clone(),
                user_data: app.user_data_dir.clone(),
                user_cache: app.user_cache_dir.clone(),
                temporary: app.temp_dir.clone(),
            },
            resource_grants: AppResourceGrants {
                app_id,
                session_id,
                owner: Arc::downgrade(app),
            },
        }
    }

    pub fn identity(&self) -> &AppIdentity {
        &self.identity
    }

    pub fn storage(&self) -> &AppStorageNamespace {
        &self.storage
    }

    pub fn resource_grants(&self) -> &AppResourceGrants {
        &self.resource_grants
    }

    /// Resolve a path only within this app's native storage namespace or its
    /// native-issued transient grants.
    pub fn resolve_accessible_path(&self, resource: &str) -> Result<PathBuf, LxAppError> {
        self.resource_grants
            .live_owner()?
            .resolve_accessible_path(resource)
    }

    fn belongs_to(&self, app: &Arc<LxApp>) -> bool {
        self.identity.app_id() == app.appid
            && self.identity.session_id() == app.session_id()
            && self.resource_grants.owner.ptr_eq(&Arc::downgrade(app))
    }

    #[cfg(any(test, feature = "test-utils"))]
    fn for_test(app_id: &str, session_id: u64) -> Self {
        let app_id: Arc<str> = Arc::from(app_id);
        Self {
            identity: AppIdentity {
                app_id: Arc::clone(&app_id),
                session_id,
            },
            storage: AppStorageNamespace {
                storage_file: PathBuf::new(),
                user_data: PathBuf::new(),
                user_cache: PathBuf::new(),
                temporary: PathBuf::new(),
            },
            resource_grants: AppResourceGrants {
                app_id,
                session_id,
                owner: Weak::new(),
            },
        }
    }
}

#[cfg(feature = "process")]
pub(crate) struct ProcessSessionAuthority {
    scope: AppScope,
}

#[cfg(feature = "process")]
impl ProcessSessionAuthority {
    pub(crate) fn for_lxapp(app: &Arc<LxApp>) -> Self {
        Self {
            scope: AppScope::from_lxapp(app),
        }
    }
}

#[cfg(feature = "process")]
impl ProcessSessionAuthority {
    pub(crate) fn authorize(&self) -> Result<(), String> {
        if self
            .scope
            .resource_grants()
            .contains(AppResourceGrant::Process)
        {
            Ok(())
        } else {
            Err(format!(
                "process execution requires a live native Process grant for app session {}:{}",
                self.scope.identity().app_id(),
                self.scope.identity().session_id()
            ))
        }
    }
}

#[cfg(feature = "process")]
impl rong_command::ProcessAuthority for ProcessSessionAuthority {
    fn authorize(&self) -> Result<(), String> {
        ProcessSessionAuthority::authorize(self)
    }
}

/// Authenticated source for a native route invocation.
///
/// Browser construction is reserved for the browser document lifecycle TCB:
/// ordinary bridge frames derive only the `LxAppSession` variant from their
/// owning native `LxApp` session.
#[derive(Clone)]
pub struct AuthenticatedCaller {
    source: AuthenticatedCallerSource,
}

#[derive(Clone)]
enum AuthenticatedCallerSource {
    LxAppSession {
        class: AppSessionClass,
        scope: AppScope,
    },
    BrowserDocument {
        _authority: ControlDocumentAuthority,
    },
}

impl AuthenticatedCaller {
    pub(crate) fn for_lxapp(app: &Arc<LxApp>) -> Self {
        Self {
            source: AuthenticatedCallerSource::LxAppSession {
                class: app.app_session_class(),
                scope: AppScope::from_lxapp(app),
            },
        }
    }

    /// Host-TCB constructor used only after the browser registry has promoted
    /// the exact document binding to Active.
    #[doc(hidden)]
    pub fn active_browser_document(
        native_authority: &crate::NativeControlPlaneAuthority,
        authority: ControlDocumentAuthority,
    ) -> Result<Self, LxAppError> {
        if !native_authority.validate() {
            return Err(LxAppError::UnsupportedOperation(
                "browser caller promotion requires the live native host authority".to_string(),
            ));
        }
        Ok(Self {
            source: AuthenticatedCallerSource::BrowserDocument {
                _authority: authority,
            },
        })
    }

    pub fn app_scope(&self) -> Option<&AppScope> {
        match &self.source {
            AuthenticatedCallerSource::LxAppSession { scope, .. } => Some(scope),
            AuthenticatedCallerSource::BrowserDocument { .. } => None,
        }
    }

    #[cfg(test)]
    fn app_session_for_test(&self) -> Option<(AppSessionClass, &AppScope)> {
        match &self.source {
            AuthenticatedCallerSource::LxAppSession { class, scope } => Some((*class, scope)),
            AuthenticatedCallerSource::BrowserDocument { .. } => None,
        }
    }

    #[cfg(test)]
    pub(crate) fn standard_for_test(session_id: u64) -> Self {
        Self {
            source: AuthenticatedCallerSource::LxAppSession {
                class: AppSessionClass::StandardApp,
                scope: AppScope::for_test("test.standard", session_id),
            },
        }
    }

    #[cfg(test)]
    pub(crate) fn control_for_test(session_id: u64) -> Self {
        Self {
            source: AuthenticatedCallerSource::LxAppSession {
                class: AppSessionClass::ControlApp,
                scope: AppScope::for_test("test.control", session_id),
            },
        }
    }

    #[cfg(test)]
    pub(crate) fn surface_for_test(session_id: u64) -> Self {
        Self {
            source: AuthenticatedCallerSource::LxAppSession {
                class: AppSessionClass::ControlSurface,
                scope: AppScope::for_test("test.surface", session_id),
            },
        }
    }

    #[cfg(feature = "test-utils")]
    pub(crate) fn lxapp_session_for_test(
        app_id: &str,
        session_id: u64,
        class: AppSessionClass,
    ) -> Self {
        Self {
            source: AuthenticatedCallerSource::LxAppSession {
                class,
                scope: AppScope::for_test(app_id, session_id),
            },
        }
    }

    #[cfg(feature = "test-utils")]
    pub(crate) fn browser_document_for_test() -> Self {
        let native_authority = crate::NativeControlPlaneAuthority::for_test_harness();
        let (_, authority) = crate::issue_control_document_bootstrap(
            &native_authority,
            &ring::rand::SystemRandom::new(),
        )
        .expect("native test entropy");
        Self::active_browser_document(&native_authority, authority).expect("native test authority")
    }
}

/// Authenticated, native-created context passed to every host handler.
///
/// Its constructor is private to bridge dispatch. Third-party handlers may
/// inspect or clone it, but cannot mint a different caller or app scope.
#[derive(Clone)]
pub struct HostInvocationContext {
    caller: AuthenticatedCaller,
    lxapp: Arc<LxApp>,
}

impl HostInvocationContext {
    /// Derive an invocation context from a live Logic worker context.
    ///
    /// Browser documents do not carry the private app-service context, so this
    /// cannot turn a browser invocation into its owning app's authority.
    #[doc(hidden)]
    #[cfg(feature = "js-appservice")]
    pub fn for_logic_context(ctx: &rong::JSContext) -> rong::JSResult<Self> {
        let lxapp = LxApp::from_ctx(ctx)?;
        Ok(Self {
            caller: AuthenticatedCaller::for_lxapp(&lxapp),
            lxapp,
        })
    }

    pub(crate) fn for_dispatch(lxapp: Arc<LxApp>, caller: &AuthenticatedCaller) -> Option<Self> {
        if let AuthenticatedCallerSource::LxAppSession { scope, .. } = &caller.source
            && !scope.belongs_to(&lxapp)
        {
            return None;
        }
        Some(Self {
            caller: caller.clone(),
            lxapp,
        })
    }

    pub fn caller(&self) -> &AuthenticatedCaller {
        &self.caller
    }

    pub fn app_scope(&self) -> Option<&AppScope> {
        self.caller.app_scope()
    }

    pub fn lxapp(&self) -> Arc<LxApp> {
        Arc::clone(&self.lxapp)
    }
}

/// The sole route-audience decision point.
pub fn authorize(caller: &AuthenticatedCaller, audience: RouteAudience) -> bool {
    matches!(
        (&caller.source, audience),
        (
            AuthenticatedCallerSource::LxAppSession { .. },
            RouteAudience::AppSessionOnly
        ) | (
            AuthenticatedCallerSource::LxAppSession { .. },
            RouteAudience::AnyAuthenticated
        ) | (
            AuthenticatedCallerSource::LxAppSession {
                class: AppSessionClass::ControlApp,
                ..
            },
            RouteAudience::ControlAppOnly | RouteAudience::ControlAppOrBrowserOnly
        ) | (
            AuthenticatedCallerSource::LxAppSession {
                class: AppSessionClass::ControlSurface,
                ..
            },
            RouteAudience::ControlSurfaceOnly
        ) | (
            AuthenticatedCallerSource::BrowserDocument { .. },
            RouteAudience::AnyAuthenticated
                | RouteAudience::BrowserControlOnly
                | RouteAudience::ControlAppOrBrowserOnly
        )
    )
}

/// The admission policy resolved when a route is registered.
///
/// Policy evaluation is intentionally separate from registration so every
/// route family can carry the same immutable metadata before dispatch starts
/// using it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct EffectiveRoutePolicy {
    audience: RouteAudience,
}

/// Read-only metadata for one production route.
///
/// Handlers are deliberately absent: callers can inspect the effective
/// registration without gaining an invocation capability.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct EffectiveRouteMetadata {
    kind: HostRouteKind,
    policy: EffectiveRoutePolicy,
}

impl EffectiveRouteMetadata {
    pub const fn kind(self) -> HostRouteKind {
        self.kind
    }

    pub const fn policy(self) -> EffectiveRoutePolicy {
        self.policy
    }

    pub const fn audience(self) -> RouteAudience {
        self.policy.audience()
    }
}

impl EffectiveRoutePolicy {
    pub const fn new(audience: RouteAudience) -> Self {
        Self { audience }
    }

    pub const fn audience(self) -> RouteAudience {
        self.audience
    }
}

pub struct HostRegistration {
    namespace: &'static str,
    method: &'static str,
    handler: Arc<dyn HostHandler>,
    kind: HostMethodKind,
    policy: EffectiveRoutePolicy,
}

impl HostRegistration {
    pub fn new(
        namespace: &'static str,
        method: &'static str,
        audience: RouteAudience,
        handler: Arc<dyn HostHandler>,
    ) -> Self {
        Self {
            namespace,
            method,
            handler,
            kind: HostMethodKind::Call,
            policy: EffectiveRoutePolicy::new(audience),
        }
    }

    pub fn stream(
        namespace: &'static str,
        method: &'static str,
        audience: RouteAudience,
        handler: Arc<dyn HostHandler>,
    ) -> Self {
        Self {
            namespace,
            method,
            handler,
            kind: HostMethodKind::Stream,
            policy: EffectiveRoutePolicy::new(audience),
        }
    }

    pub const fn policy(&self) -> EffectiveRoutePolicy {
        self.policy
    }

    pub const fn audience(&self) -> RouteAudience {
        self.policy.audience()
    }
}

/// Host API handler trait - for view layer to call host app capabilities.
///
/// Design constraints:
/// - `input` is owned to avoid capturing borrows in `'static` futures.
/// - `cancel` is reachable so handlers can stop work early.
/// - `call` only constructs a lazy future; it must not perform a side effect
///   before that future is first polled. Bridge admission commits that poll
///   against document revocation and may cancel it before polling begins.
pub trait HostHandler: Send + Sync + 'static {
    fn call<'a>(
        &'a self,
        invocation: HostInvocationContext,
        input: Option<String>,
        cancel: HostCancel,
    ) -> HostFuture<'a>;
}

enum RouteHandler {
    Host(Arc<dyn HostHandler>),
    Channel(Arc<dyn ChannelHandler>),
}

/// One fully resolved production route. There is no constructor for a handler
/// without its immutable effective metadata.
struct EffectiveRouteRecord {
    metadata: EffectiveRouteMetadata,
    handler: RouteHandler,
}

/// Shared inventory for unary, stream, notification, and channel dispatch.
struct EffectiveRouteRegistry {
    routes: HashMap<String, EffectiveRouteRecord>,
}

impl EffectiveRouteRegistry {
    fn new() -> Self {
        Self {
            routes: HashMap::new(),
        }
    }

    fn try_register(&mut self, key: String, route: EffectiveRouteRecord) -> bool {
        if let std::collections::hash_map::Entry::Vacant(entry) = self.routes.entry(key) {
            entry.insert(route);
            true
        } else {
            false
        }
    }

    fn inventory_for_caller(
        &self,
        caller: &AuthenticatedCaller,
    ) -> HashMap<String, EffectiveRouteMetadata> {
        self.routes
            .iter()
            .filter(|(_, route)| authorize(caller, route.metadata.audience()))
            .map(|(key, route)| (key.clone(), route.metadata))
            .collect()
    }

    fn schema_for_caller(&self, caller: &AuthenticatedCaller) -> HostRouteSchema {
        HostRouteSchema::from_inventory(self.inventory_for_caller(caller))
    }

    fn host_for_caller(
        &self,
        name: &str,
        caller: &AuthenticatedCaller,
    ) -> Option<Arc<dyn HostHandler>> {
        let route = self.routes.get(name)?;
        if !authorize(caller, route.metadata.audience()) {
            return None;
        }
        match &route.handler {
            RouteHandler::Host(handler) => Some(Arc::clone(handler)),
            RouteHandler::Channel(_) => None,
        }
    }

    fn channel_for_caller(
        &self,
        name: &str,
        caller: &AuthenticatedCaller,
    ) -> Option<Arc<dyn ChannelHandler>> {
        let route = self.routes.get(name)?;
        if !authorize(caller, route.metadata.audience()) {
            return None;
        }
        match &route.handler {
            RouteHandler::Channel(handler) => Some(Arc::clone(handler)),
            RouteHandler::Host(_) => None,
        }
    }
}

/// Global effective route inventory and handler registry.
static GLOBAL_ROUTE_REGISTRY: OnceLock<Mutex<EffectiveRouteRegistry>> = OnceLock::new();

fn get_route_registry() -> &'static Mutex<EffectiveRouteRegistry> {
    GLOBAL_ROUTE_REGISTRY.get_or_init(|| Mutex::new(EffectiveRouteRegistry::new()))
}

fn validate_host_namespace(namespace: &str) {
    assert_ne!(
        namespace, "channel",
        "host namespace 'channel' is reserved by the JS API; choose a different namespace"
    );
}

fn register_effective_route(key: String, route: EffectiveRouteRecord) {
    let inserted = {
        let mut registry = get_route_registry().lock().unwrap();
        registry.try_register(key.clone(), route)
    };
    assert!(
        inserted,
        "duplicate effective route registration for host.{key}"
    );
}

pub fn register_host_route(
    namespace: &str,
    method: &str,
    audience: RouteAudience,
    handler: Arc<dyn HostHandler>,
) {
    validate_host_namespace(namespace);
    let key = format!("{namespace}.{method}");
    register_effective_route(
        key,
        EffectiveRouteRecord {
            metadata: EffectiveRouteMetadata {
                kind: HostRouteKind::Call,
                policy: EffectiveRoutePolicy::new(audience),
            },
            handler: RouteHandler::Host(handler),
        },
    );
}

pub fn register_host(registration: HostRegistration) {
    validate_host_namespace(registration.namespace);
    let key = format!("{}.{}", registration.namespace, registration.method);
    register_effective_route(
        key,
        EffectiveRouteRecord {
            metadata: EffectiveRouteMetadata {
                kind: match registration.kind {
                    HostMethodKind::Call => HostRouteKind::Call,
                    HostMethodKind::Stream => HostRouteKind::Stream,
                },
                policy: registration.policy,
            },
            handler: RouteHandler::Host(registration.handler),
        },
    );
}

/// Unified registration entry returned by the `#[native]` macro for all modes
/// (unary, stream, channel). Runtime assembly seals every entry into the shared
/// effective route inventory.
pub enum HostRegistrationEntry {
    Handler(HostRegistration),
    Channel(ChannelRegistration),
}

impl HostRegistrationEntry {
    pub const fn policy(&self) -> EffectiveRoutePolicy {
        match self {
            Self::Handler(registration) => registration.policy(),
            Self::Channel(registration) => registration.policy(),
        }
    }

    pub const fn audience(&self) -> RouteAudience {
        self.policy().audience()
    }
}

pub fn register_host_entry(entry: HostRegistrationEntry) {
    match entry {
        HostRegistrationEntry::Handler(reg) => register_host(reg),
        HostRegistrationEntry::Channel(reg) => register_channel_handler(reg),
    }
}

pub(crate) fn get_host_for_caller(
    name: &str,
    caller: &AuthenticatedCaller,
) -> Option<Arc<dyn HostHandler>> {
    let registry = get_route_registry();
    let registry = registry.lock().unwrap();
    registry.host_for_caller(name, caller)
}

/// Inspect only immutable route policy. Browser ingress uses this while its
/// lifecycle registry lock is held; cloning a handler is deliberately deferred
/// until after that lock is released.
pub(crate) fn host_route_is_authorized(name: &str, caller: &AuthenticatedCaller) -> bool {
    get_route_registry()
        .lock()
        .unwrap()
        .routes
        .get(name)
        .is_none_or(|route| {
            !matches!(
                route.metadata.kind(),
                HostRouteKind::Call | HostRouteKind::Stream
            ) || authorize(caller, route.metadata.audience())
        })
}

/// Returns a caller-filtered snapshot of production route metadata.
pub fn effective_route_inventory(
    caller: &AuthenticatedCaller,
) -> HashMap<String, EffectiveRouteMetadata> {
    get_route_registry()
        .lock()
        .unwrap()
        .inventory_for_caller(caller)
}

/// Ready schema derived from the same effective inventory used by dispatch.
pub struct HostRouteSchema {
    pub methods: HashMap<String, &'static str>,
    pub channels: Vec<String>,
}

impl HostRouteSchema {
    fn from_inventory(inventory: HashMap<String, EffectiveRouteMetadata>) -> Self {
        let mut methods = HashMap::new();
        let mut channels = Vec::new();
        for (name, metadata) in inventory {
            match metadata.kind() {
                HostRouteKind::Call => {
                    methods.insert(name, "call");
                }
                HostRouteKind::Stream => {
                    methods.insert(name, "stream");
                }
                HostRouteKind::Channel => channels.push(name),
            }
        }
        channels.sort();
        Self { methods, channels }
    }
}

pub fn host_route_schema(caller: &AuthenticatedCaller) -> HostRouteSchema {
    get_route_registry()
        .lock()
        .unwrap()
        .schema_for_caller(caller)
}

#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("route '{name}' was registered with conflicting audiences {first:?} and {second:?}")]
pub struct RoutePolicyConflict {
    pub name: String,
    pub first: RouteAudience,
    pub second: RouteAudience,
}

/// Read one route's immutable admission policy without cloning or invoking its
/// handler. The unified registry rejects every duplicate before it can replace
/// the first route, so a readable record always has one sealed policy.
pub fn route_policy(name: &str) -> Result<Option<EffectiveRoutePolicy>, RoutePolicyConflict> {
    Ok(get_route_registry()
        .lock()
        .unwrap()
        .routes
        .get(name)
        .map(|route| route.metadata.policy()))
}

pub fn parse_input<T: DeserializeOwned>(input: Option<&str>) -> HostResult<T> {
    match input {
        Some(json) => serde_json::from_str(json)
            .map_err(|e| LxAppError::InvalidParameter(format!("Invalid input JSON: {}", e))),
        None => Err(LxAppError::InvalidParameter("Missing input".to_string())),
    }
}

pub fn serialize_result<T: Serialize>(result: HostResult<T>) -> HostResult<HostOutput> {
    let value = result?;
    serde_json::to_string(&value)
        .map(HostOutput::Json)
        .map_err(|e| LxAppError::Bridge(e.to_string()))
}

/// Imperative stream context passed to `#[native(..., stream)]` handlers.
///
/// Handlers emit zero or more events with [`send`](Self::send), then finish
/// with [`end`](Self::end) or [`error`](Self::error).
pub struct StreamContext<TEvent, TResult = ()> {
    tx: mpsc::UnboundedSender<HostResult<HostStreamItem>>,
    cancel: HostCancel,
    canceled: bool,
    _marker: PhantomData<fn(TEvent) -> TResult>,
}

impl<TEvent, TResult> StreamContext<TEvent, TResult> {
    /// Resolves when the view cancels the stream.
    pub async fn canceled(&mut self) -> bool {
        if self.canceled {
            return true;
        }
        let _ = (&mut self.cancel).await;
        self.canceled = true;
        true
    }

    #[doc(hidden)]
    pub fn error_sender(&self) -> mpsc::UnboundedSender<HostResult<HostStreamItem>> {
        self.tx.clone()
    }
}

impl<TEvent, TResult> StreamContext<TEvent, TResult>
where
    TEvent: Serialize,
    TResult: Serialize,
{
    /// Emit one event chunk to the view.
    pub fn send(&mut self, event: TEvent) -> HostResult<()> {
        let payload =
            serde_json::to_string(&event).map_err(|e| LxAppError::Bridge(e.to_string()))?;
        self.tx
            .send(Ok(HostStreamItem::Event(payload)))
            .map_err(|_| LxAppError::Bridge("Stream closed".to_string()))
    }

    /// Finish the stream with a final result.
    pub fn end(self, result: TResult) -> HostResult<()> {
        let payload =
            serde_json::to_string(&result).map_err(|e| LxAppError::Bridge(e.to_string()))?;
        self.tx
            .send(Ok(HostStreamItem::Return(payload)))
            .map_err(|_| LxAppError::Bridge("Stream closed".to_string()))
    }

    /// Finish the stream with a structured bridge error.
    pub fn error(self, code: impl Into<String>, message: impl Into<String>) -> HostResult<()> {
        self.tx
            .send(Err(LxAppError::RongJSHost {
                code: code.into(),
                message: message.into(),
                data: None,
            }))
            .map_err(|_| LxAppError::Bridge("Stream closed".to_string()))
    }
}

#[doc(hidden)]
pub fn new_stream_context<TEvent, TResult>(
    cancel: HostCancel,
) -> (
    StreamContext<TEvent, TResult>,
    mpsc::UnboundedReceiver<HostResult<HostStreamItem>>,
) {
    let (tx, rx) = mpsc::unbounded_channel();
    (
        StreamContext {
            tx,
            cancel,
            canceled: false,
            _marker: PhantomData,
        },
        rx,
    )
}

#[doc(hidden)]
pub fn stream_output_from_rx(
    rx: mpsc::UnboundedReceiver<HostResult<HostStreamItem>>,
) -> HostOutput {
    HostOutput::Stream(Box::pin(futures::stream::unfold(rx, |mut rx| async move {
        rx.recv().await.map(|item| (item, rx))
    })))
}

pub async fn await_or_cancel<T>(
    cancel: &mut HostCancel,
    fut: impl Future<Output = HostResult<T>>,
) -> HostResult<T> {
    tokio::select! {
        _ = cancel => Err(LxAppError::Bridge("Canceled".to_string()))?,
        res = fut => res,
    }
}

/// Inbound message from the View layer delivered to the channel handler.
pub(crate) enum RawChannelInbound {
    Data(String),
    Close {
        code: Option<String>,
        reason: Option<String>,
    },
}

/// Typed inbound message received from [`ChannelContext::recv_json`].
pub enum ChannelMessage<T> {
    Data(T),
    Close {
        code: Option<String>,
        reason: Option<String>,
    },
}

/// Outbound message from the channel handler to the View layer.
pub(crate) enum ChannelOutbound {
    Data(String),
    Close {
        code: Option<String>,
        reason: Option<String>,
    },
}

/// Context passed to a channel handler when a channel is opened.
///
/// Handlers receive messages via [`recv`](Self::recv) and push messages back
/// via [`send`](Self::send). Dropping or calling [`close`](Self::close) ends
/// the channel from the Logic side.
pub struct ChannelContext<TIn = JsonValue, TOut = TIn> {
    id: String,
    inbound_rx: mpsc::UnboundedReceiver<RawChannelInbound>,
    outbound_tx: mpsc::UnboundedSender<ChannelOutbound>,
    close_on_drop: bool,
    _marker: PhantomData<fn(TIn) -> TOut>,
}

impl<TIn, TOut> ChannelContext<TIn, TOut> {
    /// The channel identifier (matches the `id` field in the wire protocol).
    pub fn id(&self) -> &str {
        &self.id
    }

    #[doc(hidden)]
    pub fn with_types<TNextIn, TNextOut>(mut self) -> ChannelContext<TNextIn, TNextOut> {
        let (dummy_inbound_tx, dummy_inbound_rx) = mpsc::unbounded_channel();
        let (dummy_outbound_tx, _dummy_outbound_rx) = mpsc::unbounded_channel();
        let id = std::mem::take(&mut self.id);
        let inbound_rx = std::mem::replace(&mut self.inbound_rx, dummy_inbound_rx);
        let outbound_tx = std::mem::replace(&mut self.outbound_tx, dummy_outbound_tx);
        let close_on_drop = self.close_on_drop;
        self.close_on_drop = false;
        drop(dummy_inbound_tx);

        ChannelContext {
            id,
            inbound_rx,
            outbound_tx,
            close_on_drop,
            _marker: PhantomData,
        }
    }

    pub(crate) async fn recv_raw(&mut self) -> Option<RawChannelInbound> {
        self.inbound_rx.recv().await
    }

    pub(crate) fn send_raw_json(&self, payload_json: String) -> HostResult<()> {
        self.outbound_tx
            .send(ChannelOutbound::Data(payload_json))
            .map_err(|_| LxAppError::Bridge("Channel closed".to_string()))
    }

    #[doc(hidden)]
    pub fn close_handle(&self) -> ChannelCloseHandle {
        ChannelCloseHandle {
            outbound_tx: self.outbound_tx.clone(),
        }
    }

    #[doc(hidden)]
    pub fn disable_close_on_drop(&mut self) {
        self.close_on_drop = false;
    }
}

impl<TIn, TOut> ChannelContext<TIn, TOut>
where
    TIn: DeserializeOwned,
    TOut: Serialize,
{
    /// Receive the next inbound message from the view.
    ///
    /// Returns `None` when the channel has been closed from the View side or
    /// the session was reset.
    pub async fn recv(&mut self) -> HostResult<Option<ChannelMessage<TIn>>> {
        match self.recv_raw().await {
            Some(RawChannelInbound::Data(payload_json)) => {
                let payload = serde_json::from_str(&payload_json).map_err(|e| {
                    LxAppError::InvalidParameter(format!("Invalid channel payload JSON: {}", e))
                })?;
                Ok(Some(ChannelMessage::Data(payload)))
            }
            Some(RawChannelInbound::Close { code, reason }) => {
                Ok(Some(ChannelMessage::Close { code, reason }))
            }
            None => Ok(None),
        }
    }

    /// Send a JSON-serialisable payload to the view.
    pub fn send(&self, payload: TOut) -> HostResult<()> {
        let payload_json =
            serde_json::to_string(&payload).map_err(|e| LxAppError::Bridge(e.to_string()))?;
        self.send_raw_json(payload_json)
    }
}

impl<TIn, TOut> ChannelContext<TIn, TOut> {
    /// Close the channel cleanly from the Logic side.
    pub fn close(mut self) {
        self.close_on_drop = false;
        let _ = self.outbound_tx.send(ChannelOutbound::Close {
            code: None,
            reason: None,
        });
    }

    /// Close the channel with an error code and human-readable reason.
    pub fn close_with(mut self, code: impl Into<String>, reason: impl Into<String>) {
        self.close_on_drop = false;
        let _ = self.outbound_tx.send(ChannelOutbound::Close {
            code: Some(code.into()),
            reason: Some(reason.into()),
        });
    }
}

impl<TIn, TOut> Drop for ChannelContext<TIn, TOut> {
    fn drop(&mut self) {
        if !self.close_on_drop {
            return;
        }
        let _ = self.outbound_tx.send(ChannelOutbound::Close {
            code: None,
            reason: None,
        });
    }
}

#[doc(hidden)]
pub struct ChannelCloseHandle {
    outbound_tx: mpsc::UnboundedSender<ChannelOutbound>,
}

impl ChannelCloseHandle {
    pub fn close(&self) {
        let _ = self.outbound_tx.send(ChannelOutbound::Close {
            code: None,
            reason: None,
        });
    }

    pub fn close_with(&self, code: impl Into<String>, reason: impl Into<String>) {
        let _ = self.outbound_tx.send(ChannelOutbound::Close {
            code: Some(code.into()),
            reason: Some(reason.into()),
        });
    }
}

/// Bridge-internal sender half for a host channel. Held in `PageBridgeState`
/// so inbound wire messages can be forwarded to the handler's `ChannelContext`.
pub(crate) struct ChannelContextSender {
    inbound_tx: mpsc::UnboundedSender<RawChannelInbound>,
}

impl ChannelContextSender {
    pub(crate) fn send_data(&self, payload_json: String) {
        let _ = self.inbound_tx.send(RawChannelInbound::Data(payload_json));
    }

    pub(crate) fn send_close(&self, code: Option<String>, reason: Option<String>) {
        let _ = self
            .inbound_tx
            .send(RawChannelInbound::Close { code, reason });
    }
}

/// Channel handler trait — invoked when a View opens a host channel.
pub trait ChannelHandler: Send + Sync + 'static {
    /// Called once when the channel is opened. The implementation must spawn
    /// its own async task if it needs to do async work (e.g. via
    /// `tokio::task::spawn`). The method is synchronous so the bridge is not
    /// blocked waiting for the handler.
    fn on_open(
        &self,
        invocation: HostInvocationContext,
        ctx: ChannelContext,
        params: Option<String>,
    );
}

/// A channel handler ready to be inserted into the effective route inventory.
pub struct ChannelRegistration {
    namespace: &'static str,
    method: &'static str,
    handler: Arc<dyn ChannelHandler>,
    policy: EffectiveRoutePolicy,
}

impl ChannelRegistration {
    pub fn new(
        namespace: &'static str,
        method: &'static str,
        audience: RouteAudience,
        handler: Arc<dyn ChannelHandler>,
    ) -> Self {
        Self {
            namespace,
            method,
            handler,
            policy: EffectiveRoutePolicy::new(audience),
        }
    }

    pub const fn policy(&self) -> EffectiveRoutePolicy {
        self.policy
    }

    pub const fn audience(&self) -> RouteAudience {
        self.policy.audience()
    }
}

pub fn register_channel_handler(registration: ChannelRegistration) {
    validate_host_namespace(registration.namespace);
    let key = format!("{}.{}", registration.namespace, registration.method);
    register_effective_route(
        key,
        EffectiveRouteRecord {
            metadata: EffectiveRouteMetadata {
                kind: HostRouteKind::Channel,
                policy: registration.policy,
            },
            handler: RouteHandler::Channel(registration.handler),
        },
    );
}

pub(crate) fn get_channel_handler_for_caller(
    name: &str,
    caller: &AuthenticatedCaller,
) -> Option<Arc<dyn ChannelHandler>> {
    let registry = get_route_registry();
    let registry = registry.lock().unwrap();
    registry.channel_for_caller(name, caller)
}

/// See [`host_route_is_authorized`]. Unknown channels remain eligible for the
/// normal post-lock "not found" response.
pub(crate) fn channel_route_is_authorized(name: &str, caller: &AuthenticatedCaller) -> bool {
    get_route_registry()
        .lock()
        .unwrap()
        .routes
        .get(name)
        .is_none_or(|route| {
            route.metadata.kind() != HostRouteKind::Channel
                || authorize(caller, route.metadata.audience())
        })
}

/// Create a linked `(ChannelContext, ChannelContextSender, outbound_rx)` triple.
///
/// - `ChannelContext` goes to the handler.
/// - `ChannelContextSender` is stored in `PageBridgeState`.
/// - `outbound_rx` is consumed by the bridge's outbound forwarding task.
pub(crate) fn new_channel_context(
    id: String,
) -> (
    ChannelContext,
    ChannelContextSender,
    mpsc::UnboundedReceiver<ChannelOutbound>,
) {
    let (inbound_tx, inbound_rx) = mpsc::unbounded_channel();
    let (outbound_tx, outbound_rx) = mpsc::unbounded_channel();
    let ctx = ChannelContext {
        id,
        inbound_rx,
        outbound_tx,
        close_on_drop: true,
        _marker: PhantomData,
    };
    let sender = ChannelContextSender { inbound_tx };
    (ctx, sender, outbound_rx)
}

/// Register built-in Host API set.
///
/// Bootstrap invokes this before static target validation so Host API
/// definitions are owned by `lingxia-lxapp` and their policy is inspectable
/// before any lxapp runtime exists.
#[doc(hidden)]
pub fn register_builtin_routes() {
    static REGISTERED: OnceLock<()> = OnceLock::new();
    REGISTERED.get_or_init(|| {
        device::register_all();
        navigation::register_all();
        navigator::register_all();
    });
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::appservice::LxAppWorkers;
    use crate::register_synthetic_lxapp;
    use lingxia_platform::Platform;
    use uuid::Uuid;

    #[test]
    fn native_resource_issuer_cannot_expand_manifest_requests() {
        let mut grants = HashSet::new();
        let mut authority = NativeHostRuntimeAuthority::for_test(
            "same.app",
            7,
            AppSessionClass::ControlApp,
            [AppResourceGrant::Downloads],
            &mut grants,
        );
        assert!(authority.requested(AppResourceGrant::Downloads));
        assert!(!authority.grant(AppResourceGrant::Process));
        assert!(authority.grant(AppResourceGrant::Downloads));
        assert_eq!(grants, HashSet::from([AppResourceGrant::Downloads]));
    }

    #[test]
    fn process_grant_is_refused_outside_the_control_app_class() {
        for class in [
            AppSessionClass::StandardApp,
            AppSessionClass::ControlSurface,
        ] {
            let mut grants = HashSet::new();
            let mut authority = NativeHostRuntimeAuthority::for_test(
                "same.app",
                8,
                class,
                [AppResourceGrant::Process, AppResourceGrant::Downloads],
                &mut grants,
            );
            assert!(authority.requested(AppResourceGrant::Process));
            assert!(!authority.grant(AppResourceGrant::Process));
            assert!(authority.grant(AppResourceGrant::Downloads));
            assert_eq!(grants, HashSet::from([AppResourceGrant::Downloads]));
        }
        let mut grants = HashSet::new();
        let mut authority = NativeHostRuntimeAuthority::for_test(
            "same.app",
            9,
            AppSessionClass::ControlApp,
            [AppResourceGrant::Process],
            &mut grants,
        );
        assert!(authority.grant(AppResourceGrant::Process));
    }

    #[test]
    fn devtools_authority_is_manifest_bounded_and_automation_only() {
        for requested in [
            Vec::new(),
            vec![AppResourceGrant::Automation],
            vec![AppResourceGrant::AutomationHost],
            vec![AppResourceGrant::Process, AppResourceGrant::Downloads],
        ] {
            let mut grants = HashSet::new();
            let mut authority = NativeDevtoolsAuthority::for_test(
                "same.app",
                21,
                AppSessionClass::StandardApp,
                requested.clone(),
                &mut grants,
            );
            authority.grant_automation();
            assert!(!authority.grant(AppResourceGrant::Process));
            assert!(!authority.grant(AppResourceGrant::Downloads));
            assert_eq!(
                grants,
                requested
                    .into_iter()
                    .filter(|grant| matches!(
                        grant,
                        AppResourceGrant::Automation | AppResourceGrant::AutomationHost
                    ))
                    .collect()
            );
        }
    }

    fn same_app_id_with_different_classes() -> (tempfile::TempDir, Arc<LxApp>, Arc<LxApp>) {
        let root = tempfile::tempdir().expect("test app root");
        let runtime = Arc::new(
            Platform::new(
                root.path().join("data").display().to_string(),
                root.path().join("cache").display().to_string(),
                "en-US".to_string(),
            )
            .expect("test platform"),
        );
        let workers = LxAppWorkers::init(1);
        let app_id = format!("app.lingxia.scope-test.{}", Uuid::new_v4());
        register_synthetic_lxapp(app_id.clone());
        let mut standard = LxApp::new_with_session_class_for_test(
            app_id.clone(),
            Arc::clone(&runtime),
            Arc::clone(&workers),
            AppSessionClass::StandardApp,
        )
        .expect("standard app");
        standard.approve_unrestricted_permissions_for_test();
        let standard = Arc::new(standard);
        standard.bind_arc();
        standard.set_status(LxAppSessionStatus::Opened);
        let mut control = LxApp::new_with_session_class_for_test(
            app_id,
            runtime,
            workers,
            AppSessionClass::ControlApp,
        )
        .expect("control app");
        control.approve_unrestricted_permissions_for_test();
        let control = Arc::new(control);
        control.bind_arc();
        control.set_status(LxAppSessionStatus::Opened);
        (root, standard, control)
    }

    #[cfg(not(windows))]
    #[tokio::test]
    async fn native_resource_grants_wait_for_the_registry_snapshot() {
        use crate::provider::LxAppPermissions;

        let root = tempfile::tempdir().expect("test app root");
        let runtime = Arc::new(
            Platform::new(
                root.path().join("data").display().to_string(),
                root.path().join("cache").display().to_string(),
                "en-US".to_string(),
            )
            .expect("test platform"),
        );
        let workers = LxAppWorkers::init(1);
        let app_id = format!("app.lingxia.grant-late.{}", Uuid::new_v4());
        register_synthetic_lxapp(app_id.clone());
        let mut app = LxApp::new_with_session_class_for_test(
            app_id,
            runtime,
            workers,
            AppSessionClass::StandardApp,
        )
        .expect("app");
        let pending_grant = app.defer_permissions_for_test();
        let app = Arc::new(app);
        app.bind_arc();
        app.set_status(LxAppSessionStatus::Opened);

        assert!(!app.permissions_ready());
        super::seal_app_resource_grants(&app);
        assert!(
            !app.resource_grants_sealed_for_test(),
            "pending deny must not occupy the OnceLock"
        );
        assert!(
            !app.has_security_privilege(&crate::LxAppSecurityPrivilege::new("downloads").unwrap())
        );

        pending_grant.resolve(Some(LxAppPermissions::privileges(["downloads"])));
        app.wait_permissions_ready().await;
        assert!(app.permissions_ready());
        assert!(app.resource_grants_sealed_for_test());
        assert!(
            app.has_security_privilege(&crate::LxAppSecurityPrivilege::new("downloads").unwrap())
        );
    }

    struct TestHostHandler;

    impl HostHandler for TestHostHandler {
        fn call<'a>(
            &'a self,
            _invocation: HostInvocationContext,
            _input: Option<String>,
            _cancel: HostCancel,
        ) -> HostFuture<'a> {
            Box::pin(async { Ok(HostOutput::Json("null".to_string())) })
        }
    }

    struct TestChannelHandler;

    impl ChannelHandler for TestChannelHandler {
        fn on_open(
            &self,
            _invocation: HostInvocationContext,
            _ctx: ChannelContext,
            _params: Option<String>,
        ) {
        }
    }

    #[derive(Debug, PartialEq, Eq)]
    struct ObservedScope {
        class: AppSessionClass,
        app_id: String,
        session_id: u64,
    }

    fn observe_scope(invocation: &HostInvocationContext) -> ObservedScope {
        let (class, scope) = invocation
            .caller()
            .app_session_for_test()
            .expect("expected lxapp caller");
        ObservedScope {
            class,
            app_id: scope.identity().app_id().to_string(),
            session_id: scope.identity().session_id(),
        }
    }

    struct ScopeRecordingHostHandler {
        observed: Arc<Mutex<Vec<ObservedScope>>>,
    }

    impl HostHandler for ScopeRecordingHostHandler {
        fn call<'a>(
            &'a self,
            invocation: HostInvocationContext,
            _input: Option<String>,
            _cancel: HostCancel,
        ) -> HostFuture<'a> {
            Box::pin(async move {
                self.observed
                    .lock()
                    .unwrap()
                    .push(observe_scope(&invocation));
                Ok(HostOutput::Json("null".to_string()))
            })
        }
    }

    struct ScopeRecordingChannelHandler {
        observed: Arc<Mutex<Vec<ObservedScope>>>,
    }

    impl ChannelHandler for ScopeRecordingChannelHandler {
        fn on_open(
            &self,
            invocation: HostInvocationContext,
            _ctx: ChannelContext,
            _params: Option<String>,
        ) {
            self.observed
                .lock()
                .unwrap()
                .push(observe_scope(&invocation));
        }
    }

    #[tokio::test]
    async fn invocation_context_carries_native_scope_to_unary_stream_and_channel_handlers() {
        let (_root, standard, control) = same_app_id_with_different_classes();
        let standard_caller = AuthenticatedCaller::for_lxapp(&standard);
        let control_caller = AuthenticatedCaller::for_lxapp(&control);

        assert!(
            HostInvocationContext::for_dispatch(Arc::clone(&control), &standard_caller).is_none()
        );

        let host_observed = Arc::new(Mutex::new(Vec::new()));
        let host_handler = Arc::new(ScopeRecordingHostHandler {
            observed: Arc::clone(&host_observed),
        });
        let stream_registration = HostRegistration::stream(
            "scope",
            "stream",
            RouteAudience::AppSessionOnly,
            host_handler.clone(),
        );
        assert_eq!(stream_registration.kind, HostMethodKind::Stream);

        for (app, caller) in [
            (Arc::clone(&standard), &standard_caller),
            (Arc::clone(&control), &control_caller),
        ] {
            let invocation =
                HostInvocationContext::for_dispatch(app, caller).expect("matching scope");
            let (_cancel_tx, cancel) = oneshot::channel();
            host_handler
                .call(invocation, None, cancel)
                .await
                .expect("handler result");
        }

        let channel_observed = Arc::new(Mutex::new(Vec::new()));
        let channel_handler = ScopeRecordingChannelHandler {
            observed: Arc::clone(&channel_observed),
        };
        for (index, (app, caller)) in [
            (Arc::clone(&standard), &standard_caller),
            (Arc::clone(&control), &control_caller),
        ]
        .into_iter()
        .enumerate()
        {
            let invocation =
                HostInvocationContext::for_dispatch(app, caller).expect("matching scope");
            let (channel, _sender, _outbound) = new_channel_context(format!("scope-{index}"));
            channel_handler.on_open(invocation, channel, None);
        }

        let host_observed = host_observed.lock().unwrap();
        let channel_observed = channel_observed.lock().unwrap();
        assert_eq!(host_observed.as_slice(), channel_observed.as_slice());
        assert_eq!(host_observed.len(), 2);
        assert_eq!(host_observed[0].app_id, host_observed[1].app_id);
        assert_ne!(host_observed[0].session_id, host_observed[1].session_id);
        assert_eq!(host_observed[0].class, AppSessionClass::StandardApp);
        assert_eq!(host_observed[1].class, AppSessionClass::ControlApp);
    }

    #[test]
    fn same_app_id_does_not_share_storage_or_native_resource_grants_between_sessions() {
        let (_root, standard, control) = same_app_id_with_different_classes();
        let standard_caller = AuthenticatedCaller::for_lxapp(&standard);
        let control_caller = AuthenticatedCaller::for_lxapp(&control);
        let standard_scope = standard_caller.app_scope().expect("standard scope");
        let control_scope = control_caller.app_scope().expect("control scope");

        assert_eq!(
            standard_scope.identity().app_id(),
            control_scope.identity().app_id()
        );
        assert_ne!(
            standard_scope.identity().session_id(),
            control_scope.identity().session_id()
        );
        assert_eq!(standard_scope.storage().user_data(), standard.user_data_dir);
        assert_eq!(control_scope.storage().temporary(), control.temp_dir);

        let file = standard.temp_dir.join("native-grant.txt");
        std::fs::create_dir_all(&standard.temp_dir).expect("create grant fixture directory");
        std::fs::write(&file, b"scope-owned").expect("write grant fixture");
        let granted = standard
            .grant_transient_file_access(&file)
            .expect("native grant")
            .to_string();
        assert_eq!(
            standard_scope
                .resource_grants()
                .resolve_transient_file(&granted)
                .expect("owner resolves grant"),
            file.canonicalize().expect("canonical grant fixture")
        );
        assert!(
            control_scope
                .resource_grants()
                .resolve_transient_file(&granted)
                .is_err(),
            "same app id must not confer another session's native grant"
        );
    }

    #[test]
    fn privileged_resource_grants_are_native_session_bound_and_expire_on_teardown() {
        let (_root, standard, takeover) = same_app_id_with_different_classes();
        let declared_downloads = crate::LxAppSecurityPrivilege::new("downloads").unwrap();
        let declared_host = crate::LxAppSecurityPrivilege::new("host").unwrap();

        assert!(standard.has_security_privilege(&declared_downloads));
        assert!(standard.has_security_privilege(&declared_host));
        assert!(!standard.has_resource_grant(AppResourceGrant::Downloads));
        assert!(!standard.has_resource_grant(AppResourceGrant::AutomationHost));

        standard.seal_resource_grants(HashSet::from([
            AppResourceGrant::Downloads,
            AppResourceGrant::AutomationHost,
        ]));
        assert!(standard.has_resource_grant(AppResourceGrant::Downloads));
        assert!(standard.has_resource_grant(AppResourceGrant::AutomationHost));

        let scope = AuthenticatedCaller::for_lxapp(&standard)
            .app_scope()
            .expect("app scope")
            .clone();
        assert!(
            scope
                .resource_grants()
                .contains(AppResourceGrant::Downloads)
        );
        assert!(
            !takeover.has_resource_grant(AppResourceGrant::Downloads),
            "same app id on a different native session must not inherit grants"
        );

        let native = crate::terminal_automation::TerminalAutomationAuthority::native_for_test();
        let surface_id = format!("terminal-session-{}", standard.session_id());
        crate::terminal_automation::publish_snapshot(
            &native,
            &surface_id,
            r#"{"surfaceId":"terminal-session"}"#,
        )
        .unwrap();
        let terminal_authority =
            crate::terminal_automation::TerminalAutomationAuthority::for_lxapp(&standard).unwrap();
        let terminal_handle =
            crate::terminal_automation::bind_surface(&terminal_authority, &surface_id).unwrap();
        assert!(terminal_handle.snapshot().is_ok());

        standard.set_status(LxAppSessionStatus::Closing);
        assert!(!standard.has_resource_grant(AppResourceGrant::Downloads));
        assert!(
            !scope
                .resource_grants()
                .contains(AppResourceGrant::AutomationHost),
            "retained resource handles must fail as teardown begins"
        );
        assert!(terminal_handle.snapshot().is_err());
        crate::terminal_automation::remove_workspace(&native, &surface_id);
    }

    #[test]
    fn terminal_handle_stays_revoked_after_same_app_id_session_takeover() {
        let (_root, original, successor) = same_app_id_with_different_classes();
        original.seal_resource_grants(HashSet::from([AppResourceGrant::AutomationHost]));
        successor.seal_resource_grants(HashSet::from([AppResourceGrant::AutomationHost]));

        let native = crate::terminal_automation::TerminalAutomationAuthority::native_for_test();
        let surface_id = format!("terminal-takeover-{}", original.session_id());
        crate::terminal_automation::publish_snapshot(
            &native,
            &surface_id,
            r#"{"surfaceId":"terminal-takeover"}"#,
        )
        .unwrap();

        let original_authority =
            crate::terminal_automation::TerminalAutomationAuthority::for_lxapp(&original).unwrap();
        let original_handle =
            crate::terminal_automation::bind_surface(&original_authority, &surface_id).unwrap();
        assert!(original_handle.snapshot().is_ok());

        original.set_status(LxAppSessionStatus::Restarting);
        assert!(original_handle.snapshot().is_err());

        let successor_authority =
            crate::terminal_automation::TerminalAutomationAuthority::for_lxapp(&successor).unwrap();
        let successor_handle =
            crate::terminal_automation::bind_surface(&successor_authority, &surface_id).unwrap();
        assert!(successor_handle.snapshot().is_ok());
        assert!(
            original_handle.snapshot().is_err(),
            "a live same-app successor must not reactivate the stale session handle"
        );

        crate::terminal_automation::remove_workspace(&native, &surface_id);
    }

    #[cfg(feature = "process")]
    #[test]
    fn process_authority_rejects_manifest_only_and_stale_same_app_id_sessions() {
        let (_root, original, successor) = same_app_id_with_different_classes();
        let original_authority = ProcessSessionAuthority::for_lxapp(&original);

        assert!(
            original
                .has_security_privilege(&crate::LxAppSecurityPrivilege::new("process").unwrap())
        );
        assert!(original_authority.authorize().is_err());

        original.seal_resource_grants(HashSet::from([AppResourceGrant::Process]));
        assert!(original_authority.authorize().is_ok());

        for status in [
            LxAppSessionStatus::Closing,
            LxAppSessionStatus::Restarting,
            LxAppSessionStatus::Closed,
        ] {
            original.set_status(status);
            assert!(original_authority.authorize().is_err());
        }

        successor.seal_resource_grants(HashSet::from([AppResourceGrant::Process]));
        let successor_authority = ProcessSessionAuthority::for_lxapp(&successor);
        assert!(successor_authority.authorize().is_ok());
        assert!(original_authority.authorize().is_err());
    }

    #[test]
    fn duplicate_same_policy_registration_cannot_replace_the_original_handler() {
        let original: Arc<dyn HostHandler> = Arc::new(TestHostHandler);
        register_host_route(
            "inventory_replacement",
            "same",
            RouteAudience::AppSessionOnly,
            Arc::clone(&original),
        );
        let replacement: Arc<dyn HostHandler> = Arc::new(TestHostHandler);
        let rejected = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            register_host_route(
                "inventory_replacement",
                "same",
                RouteAudience::AppSessionOnly,
                Arc::clone(&replacement),
            );
        }));

        assert!(rejected.is_err());
        let active = get_host_for_caller(
            "inventory_replacement.same",
            &AuthenticatedCaller::standard_for_test(80),
        )
        .expect("original handler remains active");
        assert!(Arc::ptr_eq(&active, &original));
        assert!(!Arc::ptr_eq(&active, &replacement));
    }

    #[test]
    fn same_name_across_handler_families_with_conflicting_policy_fails_registration() {
        let original: Arc<dyn HostHandler> = Arc::new(TestHostHandler);
        register_host_route(
            "inventory_cross_family",
            "same",
            RouteAudience::AppSessionOnly,
            Arc::clone(&original),
        );
        let rejected = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            register_channel_handler(ChannelRegistration::new(
                "inventory_cross_family",
                "same",
                RouteAudience::BrowserControlOnly,
                Arc::new(TestChannelHandler),
            ));
        }));

        assert!(rejected.is_err());
        let caller = AuthenticatedCaller::standard_for_test(85);
        let inventory = effective_route_inventory(&caller);
        assert_eq!(
            inventory["inventory_cross_family.same"].kind(),
            HostRouteKind::Call
        );
        let active = get_host_for_caller("inventory_cross_family.same", &caller)
            .expect("original family remains active");
        assert!(Arc::ptr_eq(&active, &original));
        assert!(get_channel_handler_for_caller("inventory_cross_family.same", &caller).is_none());
    }

    #[test]
    fn duplicate_registration_cannot_change_effective_policy() {
        let mut registry = EffectiveRouteRegistry::new();
        for (index, audience) in [RouteAudience::AppSessionOnly, RouteAudience::ControlAppOnly]
            .into_iter()
            .enumerate()
        {
            assert_eq!(
                registry.try_register(
                    "test.route".to_string(),
                    EffectiveRouteRecord {
                        metadata: EffectiveRouteMetadata {
                            kind: HostRouteKind::Call,
                            policy: EffectiveRoutePolicy::new(audience),
                        },
                        handler: RouteHandler::Host(Arc::new(TestHostHandler)),
                    },
                ),
                index == 0,
            );
        }
    }

    #[test]
    fn registration_entry_exposes_its_effective_policy() {
        let handler = HostRegistrationEntry::Handler(HostRegistration::new(
            "test",
            "call",
            RouteAudience::ControlAppOnly,
            Arc::new(TestHostHandler),
        ));
        let channel = HostRegistrationEntry::Channel(ChannelRegistration::new(
            "test",
            "channel",
            RouteAudience::ControlAppOrBrowserOnly,
            Arc::new(TestChannelHandler),
        ));

        assert_eq!(handler.audience(), RouteAudience::ControlAppOnly);
        assert_eq!(handler.policy().audience(), RouteAudience::ControlAppOnly);
        assert_eq!(channel.audience(), RouteAudience::ControlAppOrBrowserOnly);
        assert_eq!(
            channel.policy().audience(),
            RouteAudience::ControlAppOrBrowserOnly
        );
    }

    #[test]
    fn every_production_registration_path_populates_the_shared_inventory() {
        register_host_route(
            "inventory_direct",
            "call",
            RouteAudience::AppSessionOnly,
            Arc::new(TestHostHandler),
        );
        register_host_entry(HostRegistrationEntry::Handler(HostRegistration::stream(
            "inventory_macro",
            "stream",
            RouteAudience::ControlAppOnly,
            Arc::new(TestHostHandler),
        )));
        register_host_entry(HostRegistrationEntry::Channel(ChannelRegistration::new(
            "inventory_macro",
            "channel",
            RouteAudience::ControlAppOnly,
            Arc::new(TestChannelHandler),
        )));

        let standard = effective_route_inventory(&AuthenticatedCaller::standard_for_test(81));
        assert_eq!(
            standard["inventory_direct.call"].kind(),
            HostRouteKind::Call
        );
        assert!(!standard.contains_key("inventory_macro.stream"));
        assert!(!standard.contains_key("inventory_macro.channel"));

        let control = effective_route_inventory(&AuthenticatedCaller::control_for_test(82));
        assert_eq!(
            control["inventory_macro.stream"].kind(),
            HostRouteKind::Stream
        );
        assert_eq!(
            control["inventory_macro.channel"].kind(),
            HostRouteKind::Channel
        );
        assert_eq!(
            control["inventory_macro.channel"].audience(),
            RouteAudience::ControlAppOnly
        );
    }

    #[test]
    fn denied_route_does_not_clone_its_handler() {
        let handler = Arc::new(TestHostHandler);
        let mut registry = EffectiveRouteRegistry::new();
        assert!(registry.try_register(
            "test.control".to_string(),
            EffectiveRouteRecord {
                metadata: EffectiveRouteMetadata {
                    kind: HostRouteKind::Call,
                    policy: EffectiveRoutePolicy::new(RouteAudience::ControlAppOnly),
                },
                handler: RouteHandler::Host(handler.clone()),
            },
        ));
        let baseline = Arc::strong_count(&handler);

        assert!(
            registry
                .host_for_caller("test.control", &AuthenticatedCaller::standard_for_test(83))
                .is_none()
        );
        assert_eq!(Arc::strong_count(&handler), baseline);

        let admitted = registry
            .host_for_caller("test.control", &AuthenticatedCaller::control_for_test(84))
            .expect("control handler");
        assert_eq!(Arc::strong_count(&handler), baseline + 1);
        drop(admitted);
    }

    #[test]
    fn audience_matrix_uses_authenticated_caller_class() {
        let standard = AuthenticatedCaller::standard_for_test(1);
        let control = AuthenticatedCaller::control_for_test(1);
        let native_authority = crate::NativeControlPlaneAuthority::for_test();
        let (_, authority) = crate::issue_control_document_bootstrap(
            &native_authority,
            &ring::rand::SystemRandom::new(),
        )
        .expect("native entropy");
        let browser = AuthenticatedCaller::active_browser_document(&native_authority, authority)
            .expect("native test authority");

        let surface = AuthenticatedCaller::surface_for_test(1);

        let audiences = [
            RouteAudience::AppSessionOnly,
            RouteAudience::AnyAuthenticated,
            RouteAudience::ControlAppOnly,
            RouteAudience::ControlSurfaceOnly,
            RouteAudience::BrowserControlOnly,
            RouteAudience::ControlAppOrBrowserOnly,
        ];
        assert_eq!(
            audiences.map(|audience| authorize(&standard, audience)),
            [true, true, false, false, false, false]
        );
        assert_eq!(
            audiences.map(|audience| authorize(&control, audience)),
            [true, true, true, false, false, true]
        );
        assert_eq!(
            audiences.map(|audience| authorize(&surface, audience)),
            [true, true, false, true, false, false]
        );
        assert_eq!(
            audiences.map(|audience| authorize(&browser, audience)),
            [false, true, false, false, true, true]
        );
    }

    #[test]
    fn same_app_id_schema_and_all_dispatch_families_use_authenticated_caller_class() {
        let native_authority = crate::NativeControlPlaneAuthority::for_test();
        let (_, authority) = crate::issue_control_document_bootstrap(
            &native_authority,
            &ring::rand::SystemRandom::new(),
        )
        .expect("native entropy");
        let callers = [
            AuthenticatedCaller {
                source: AuthenticatedCallerSource::LxAppSession {
                    class: AppSessionClass::StandardApp,
                    scope: AppScope::for_test("same.app", 42),
                },
            },
            AuthenticatedCaller {
                source: AuthenticatedCallerSource::LxAppSession {
                    class: AppSessionClass::ControlApp,
                    scope: AppScope::for_test("same.app", 43),
                },
            },
            AuthenticatedCaller::active_browser_document(&native_authority, authority)
                .expect("native test authority"),
        ];
        let audiences = [
            RouteAudience::AppSessionOnly,
            RouteAudience::AnyAuthenticated,
            RouteAudience::ControlAppOnly,
            RouteAudience::BrowserControlOnly,
            RouteAudience::ControlAppOrBrowserOnly,
        ];
        let mut registry = EffectiveRouteRegistry::new();
        for (index, audience) in audiences.into_iter().enumerate() {
            for kind in [
                HostRouteKind::Call,
                HostRouteKind::Stream,
                HostRouteKind::Channel,
            ] {
                let family = match kind {
                    HostRouteKind::Call => "call",
                    HostRouteKind::Stream => "stream",
                    HostRouteKind::Channel => "channel",
                };
                let handler = match kind {
                    HostRouteKind::Call | HostRouteKind::Stream => {
                        RouteHandler::Host(Arc::new(TestHostHandler))
                    }
                    HostRouteKind::Channel => RouteHandler::Channel(Arc::new(TestChannelHandler)),
                };
                assert!(registry.try_register(
                    format!("test.{family}{index}"),
                    EffectiveRouteRecord {
                        metadata: EffectiveRouteMetadata {
                            kind,
                            policy: EffectiveRoutePolicy::new(audience),
                        },
                        handler,
                    },
                ));
            }
        }

        for caller in &callers {
            let schema = registry.schema_for_caller(caller);
            for (index, audience) in audiences.iter().copied().enumerate() {
                let expected = authorize(caller, audience);
                let call = format!("test.call{index}");
                let stream = format!("test.stream{index}");
                let channel = format!("test.channel{index}");
                assert_eq!(
                    schema.methods.get(&call).copied(),
                    expected.then_some("call"),
                    "unary schema diverged for {call}",
                );
                assert_eq!(
                    schema.methods.get(&stream).copied(),
                    expected.then_some("stream"),
                    "stream schema diverged for {stream}",
                );
                assert_eq!(
                    schema.channels.contains(&channel),
                    expected,
                    "channel schema diverged for {channel}",
                );
                assert_eq!(
                    registry.host_for_caller(&call, caller).is_some(),
                    expected,
                    "request dispatch diverged for {call}",
                );
                assert_eq!(
                    registry.host_for_caller(&call, caller).is_some(),
                    expected,
                    "notification dispatch diverged for {call}",
                );
                assert_eq!(
                    registry.host_for_caller(&stream, caller).is_some(),
                    expected,
                    "stream dispatch diverged for {stream}",
                );
                assert_eq!(
                    registry.channel_for_caller(&channel, caller).is_some(),
                    expected,
                    "channel-open dispatch diverged for {channel}",
                );
            }
        }
    }
}