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
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
use dashmap::DashMap;
use http::Uri as HttpUri;
use lingxia_platform::Platform;
use lingxia_platform::traits::app_runtime::AppRuntime;
use lingxia_platform::traits::ui::UIUpdate;
#[cfg(feature = "js-appservice")]
use rong::{JSContext, JSResult, Source, error::HostError};
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::collections::{HashMap, HashSet, VecDeque};
use std::fs;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, Weak};
use std::time::{Duration, Instant};
use tokio::sync::oneshot;
use tokio::time;
use uuid::Uuid;

use self::navbar::NavigationBarState;
use self::page_chrome::{
    AppearancePreference, EffectivePageChromeLayout, LxAppAppearanceState, TabBarPresentation,
    TabBarVisibilityPreference, VisibilityPreference,
};
use crate::appservice::LxAppWorkers;
use crate::error::LxAppError;
use crate::page::config::{OrientationConfig, PageConfig};
use crate::page::{PageInstance, PageInstanceId, ViewCallOptions};
use crate::startup::{LxAppStartupOptions, Scene};
use crate::update::UpdateManager;
use crate::{debug, error, info, warn};

pub mod config;
pub mod host_class;
use config::{LxAppConfig, LxAppLogicEntry, LxAppPageEntry};
mod content;
mod display_language;
pub mod host_appearance;
pub(crate) mod metadata;
pub mod navbar;
pub mod page_chrome;
pub(crate) mod page_discard;
mod page_instance_host;
mod permissions;
pub(crate) mod registry;
mod runtime_bootstrap;
mod runtime_ops;
pub(crate) mod runtime_registry;
mod scheme;
mod shutdown;
pub use shutdown::{
    block_lxapp_admission, drain_lxapps, resume_lxapp_admission, shutdown_lxapps_except,
};
pub(crate) mod security;
mod surface;
pub use security::{LxAppSecurityPrivilege, is_public_network_address};
pub mod tabbar;
pub mod uri;
pub(crate) mod version;
use crate::lifecycle::AppServiceEvent;
pub use crate::page::runtime::{
    CloseReason, CreatePageInstanceRequest, CreatedPageInstance, PageDefinition, PageInstanceEvent,
    PageInstanceRuntimeInfo, PageOwner, PageQueryInput, PageTarget, PresentationKind, ResolvedPage,
    SceneId,
};
use crate::page::runtime::{
    PageInstanceLifecycleState, PageInstanceRuntimeRecord, transition_page_instance_lifecycle,
};
pub use display_language::{
    DisplayLanguageEffectiveSource, DisplayLanguageEffectiveUpdate, DisplayLanguagePreference,
    DisplayLanguageSessionOwner, DisplayLanguageState, DisplayLanguageStateUpdate, LanguageTag,
    add_display_language_effective_listener, add_display_language_state_listener,
    clear_active_display_language_session_override, clear_display_language_session_override,
    display_language, display_language_state, display_language_state_update,
    initialize_display_language, install_display_language_session_override,
    refresh_display_language_system, set_display_language_preference,
    set_display_language_preference_in, subscribe_display_language_effective,
    subscribe_display_language_state,
};
pub use host_appearance::{
    HostAppearanceState, HostAppearanceUpdate, host_appearance_dark, host_appearance_state,
    initialize_host_appearance, refresh_host_appearance_system, set_host_appearance_preference,
    subscribe_host_appearance,
};
pub use lingxia_platform::traits::ui::{SurfaceKind, SurfacePosition};
pub use lingxia_surface::Role as SurfaceRole;
pub use lingxia_update::Channel;
use lingxia_webview::runtime::destroy_webview_if_matches;
pub use runtime_bootstrap::dev_session_active as is_dev_session;
pub use runtime_bootstrap::init;
pub use runtime_bootstrap::register_runner_host;
pub use runtime_bootstrap::runner_active as is_runner;
pub use runtime_ops::{
    close_lxapp, create_page_instance, dispose_page_instance, dispose_page_instance_by_id,
    ensure_builtin_lxapp, ensure_control_lxapp, ensure_control_surface_lxapp,
    ensure_host_surface_owner, ensure_lxapp, get_current_lxapp, installed_lxapp_path,
    is_lxapp_open, is_pull_down_refresh_enabled, list_lxapps, mark_lxapp_active,
    notify_lxapp_host_visibility, notify_page_host_visibility, notify_page_instance,
    notify_page_instance_by_id, on_low_memory, open_control_lxapp_page, open_lxapp,
    refresh_auto_appearances, restart_lxapp, terminate_lxapp, touch_page_instance_by_id,
    uninstall_lxapp,
};
pub(crate) use runtime_registry::get_lxapps_manager;
pub use runtime_registry::{find_page_by_instance_id, get_platform, try_get};
pub(crate) use surface::SurfaceRecords;
pub use surface::{
    HostMainSurfaceRegistration, HostSurfaceMenuExecution, LxAppRuntimeSurfaceInfo,
    ManagedNativeSurface, PageSurface, PageSurfaceRequest, PageSurfaceTarget, UrlCallbackSurface,
    UrlCallbackWaitError, register_surface_active_main_observer, register_surface_close_observer,
    register_surface_context_observer, register_surface_visibility_observer,
};
use version::Version;

/// Constants for lxapp storage layout
pub(crate) const LINGXIA_DIR: &str = "lingxia";
pub(crate) const LXAPPS_DIR: &str = "lxapps";
pub(crate) const PLUGINS_DIR: &str = "plugins";
pub(crate) const STORAGE_DIR: &str = "storage";
pub(crate) const USER_DATA_DIR: &str = "userdata";
pub(crate) const USER_CACHE_DIR: &str = "usercache";
pub(crate) const TEMP_DIR: &str = "temp";

const LXAPPS_DB_FILE: &str = "lxapps.redb";
type PendingPageServiceRestart = (PageInstance, oneshot::Receiver<Result<(), String>>);
const DEFAULT_VERSION: &str = "0.0.1";

const LXAPP_STACK_MAX: usize = 5;
const PAGE_STACK_MAX: usize = 10;

/// Configured worker/stack count override. Must be set before runtime initialization.
static NUM_WORKERS: OnceLock<usize> = OnceLock::new();
static LXAPP_SOURCE_OVERRIDES: OnceLock<Mutex<HashMap<String, LxAppBundleSource>>> =
    OnceLock::new();
static TRANSIENT_FILE_GRANTS: OnceLock<DashMap<(String, LxAppSessionId, String), PathBuf>> =
    OnceLock::new();
static TRANSIENT_FILE_REFERENCE_GRANTS: OnceLock<DashMap<(String, LxAppSessionId, String), ()>> =
    OnceLock::new();

#[derive(Debug, Clone, Copy)]
enum TransientPathKind {
    File,
    Directory,
}

fn normalize_transient_path(path: &Path, kind: TransientPathKind) -> Result<PathBuf, LxAppError> {
    let normalized = std::fs::canonicalize(path).map_err(|e| {
        LxAppError::ResourceNotFound(format!("transient path {}: {}", path.display(), e))
    })?;
    let metadata = std::fs::metadata(&normalized)?;
    let valid = match kind {
        TransientPathKind::File => metadata.is_file(),
        TransientPathKind::Directory => metadata.is_dir(),
    };
    if !valid {
        return Err(LxAppError::InvalidParameter(format!(
            "invalid transient path kind: {}",
            normalized.display()
        )));
    }
    Ok(normalized)
}

fn normalize_transient_file_reference(reference: &str) -> Result<String, LxAppError> {
    let normalized = reference.trim();
    let scheme = normalized
        .split_once(':')
        .map(|(scheme, _)| scheme.to_ascii_lowercase());
    if normalized.is_empty()
        || normalized.chars().any(char::is_control)
        || !matches!(scheme.as_deref(), Some("content" | "datashare" | "file"))
    {
        return Err(LxAppError::InvalidParameter(
            "invalid transient file reference".to_string(),
        ));
    }
    Ok(normalized.to_string())
}

/// Set the number of JS workers (and lxapp navigation stack capacity).
///
/// Must be called **before** [`init()`]. Defaults to [`LXAPP_STACK_MAX`] (5) if not set.
/// A value of 0 is clamped to 1.
pub fn set_num_workers(n: usize) {
    let n = n.max(1);
    if NUM_WORKERS.set(n).is_err() {
        warn!("set_num_workers: value already set, ignoring");
    }
}

/// Read the configured worker count, falling back to `LXAPP_STACK_MAX`.
fn get_num_workers() -> usize {
    NUM_WORKERS.get().copied().unwrap_or(LXAPP_STACK_MAX)
}

/// Register an lxapp whose pages/logic are bundled at `<appid>/...` inside the
/// platform asset root (Android `assets/`, iOS bundle, etc.). The on-disk asset
/// prefix is always the appid — no separate `asset_root` argument.
pub fn register_builtin_asset_bundle(appid: impl Into<String>) {
    register_lxapp_bundle_source(appid, LxAppBundleSource::BuiltinAssets);
}

/// True when the host actually shipped `{appid}/lxapp.json` as a bundled asset.
pub fn bundled_lxapp_asset_available(appid: &str) -> bool {
    let Some(runtime) = runtime_registry::get_platform() else {
        return false;
    };
    runtime
        .read_asset(&format!("{}/lxapp.json", appid.trim_end_matches('/')))
        .is_ok()
}

/// Drop a stale BuiltinAssets override so a catalog install is read from disk.
pub(crate) fn forget_builtin_bundle_source(appid: &str) {
    let Some(registry) = LXAPP_SOURCE_OVERRIDES.get() else {
        return;
    };
    let mut guard = registry.lock().unwrap_or_else(|e| e.into_inner());
    if matches!(guard.get(appid), Some(LxAppBundleSource::BuiltinAssets)) {
        guard.remove(appid);
    }
}

/// Register a content-less builtin lxapp host. The LxApp is created with default
/// empty config (no pages/plugins/logic). A later [`register_builtin_asset_bundle`]
/// call for the same appid upgrades to a disk-backed bundle — used by browser-shell
/// to swap in the real browser shell webui on macOS.
pub fn register_synthetic_lxapp(appid: impl Into<String>) {
    register_lxapp_bundle_source(appid, LxAppBundleSource::Synthetic);
}

/// SDK-internal, content-less owner for a desktop host surface graph when the
/// product does not configure a home lxapp.
pub const HOST_SURFACE_OWNER_APP_ID: &str = "app.lingxia.host-surface-owner";

pub fn register_dev_bundle_source(appid: impl Into<String>, root: impl Into<PathBuf>) {
    register_lxapp_bundle_source(appid, LxAppBundleSource::DevPath { root: root.into() });
}

fn register_lxapp_bundle_source(appid: impl Into<String>, source: LxAppBundleSource) {
    let appid = appid.into();
    let registry = LXAPP_SOURCE_OVERRIDES.get_or_init(|| Mutex::new(HashMap::new()));
    let mut guard = registry.lock().unwrap_or_else(|e| e.into_inner());
    guard.insert(appid, source);
}

/// Whether `appid`'s bundle is managed by the update system. Answers for an
/// appid with no live instance too — first install runs before one exists.
pub(crate) fn is_ota_managed_appid(appid: &str) -> bool {
    !matches!(
        lxapp_bundle_source_for(appid),
        Some(LxAppBundleSource::DevPath { .. })
    )
}

fn lxapp_bundle_source_for(appid: &str) -> Option<LxAppBundleSource> {
    LXAPP_SOURCE_OVERRIDES
        .get()
        .and_then(|registry| registry.lock().ok())
        .and_then(|guard| guard.get(appid).cloned())
}

/// A control surface must come from the host itself: its bundled assets, or
/// the dev-served bundle of that same package. Installed, downloaded, and
/// synthetic sources never qualify.
fn control_surface_bundle_source_allowed(source: Option<&LxAppBundleSource>) -> bool {
    matches!(
        source,
        Some(LxAppBundleSource::BuiltinAssets | LxAppBundleSource::DevPath { .. })
    )
}

/// Manages a collection of lxapp applications
pub struct LxApps {
    /// Collection of lxapps, keyed by app ID
    /// Uses DashMap for thread-safe concurrent access
    lxapps: DashMap<String, Arc<LxApp>>,
    // Includes removed instances until their Logic has acknowledged shutdown.
    instances: Mutex<HashMap<LxAppSessionId, Arc<LxApp>>>,
    admission: Arc<shutdown::Admission>,

    /// LxApp navigation stack for tracking app navigation history
    /// Uses VecDeque for efficient push/pop operations
    lxapp_stack: Mutex<VecDeque<String>>,

    /// Reference to the platform-specific app runtime
    /// Provides file system access, UI callbacks, etc.
    runtime: Arc<Platform>,

    /// Reference to the executor
    /// Handles async task execution for lxapp apps
    pub(crate) executor: Arc<LxAppWorkers>,

    /// Pending delayed-destroy timers keyed by appid
    pending_destroy: Mutex<HashMap<String, PendingDestroy>>,
    next_destroy_generation: AtomicU64,

    /// Serializes replacement of one app's session so its native-assigned class
    /// cannot be lost between removal and reinsertion.
    session_transition_locks: DashMap<String, Arc<Mutex<()>>>,
}

struct PendingDestroy {
    generation: u64,
    cancel: oneshot::Sender<()>,
}

fn replace_pending_destroy(
    pending: &mut HashMap<String, PendingDestroy>,
    appid: String,
    replacement: PendingDestroy,
) {
    if let Some(previous) = pending.insert(appid, replacement) {
        let _ = previous.cancel.send(());
    }
}

fn claim_pending_destroy(
    pending: &mut HashMap<String, PendingDestroy>,
    appid: &str,
    generation: u64,
) -> bool {
    if pending
        .get(appid)
        .is_some_and(|entry| entry.generation == generation)
    {
        pending.remove(appid);
        true
    } else {
        false
    }
}

fn first_evictable_appid(
    stack: &[String],
    mut is_evictable: impl FnMut(&str) -> bool,
) -> Option<String> {
    stack.iter().find(|appid| is_evictable(appid)).cloned()
}

impl LxApps {
    fn new(runtime: Platform, executor: Arc<LxAppWorkers>, capacity: usize) -> Self {
        info!("LxApps manager initialized with {} workers", capacity);
        let runtime = Arc::new(runtime);

        Self {
            lxapps: DashMap::new(),
            instances: Mutex::new(HashMap::new()),
            admission: Arc::new(shutdown::Admission::default()),
            runtime,
            executor,
            lxapp_stack: Mutex::new(VecDeque::with_capacity(capacity)),
            pending_destroy: Mutex::new(HashMap::new()),
            next_destroy_generation: AtomicU64::new(1),
            session_transition_locks: DashMap::new(),
        }
    }

    fn session_transition_lock(&self, appid: &str) -> Arc<Mutex<()>> {
        self.session_transition_locks
            .entry(appid.to_string())
            .or_insert_with(|| Arc::new(Mutex::new(())))
            .clone()
    }

    fn cleanup_session_transition_lock(&self, appid: &str) {
        // The map owns one strong reference. A transition in progress (or
        // waiting for this lock) owns another, so remove only idle entries.
        // `remove_if` evaluates and removes while holding the map shard write
        // lock, preventing a concurrent lookup from acquiring a stale lock
        // between the count check and removal.
        self.session_transition_locks
            .remove_if(appid, |_, lock| Arc::strong_count(lock) == 1);
    }

    fn with_session_transition<T>(&self, appid: &str, operation: impl FnOnce() -> T) -> T {
        let transition_lock = self.session_transition_lock(appid);
        let result = {
            let _transition_guard = transition_lock.lock().unwrap();
            operation()
        };
        drop(transition_lock);
        self.cleanup_session_transition_lock(appid);
        result
    }

    /// Ensure an LxApp instance exists for the given appid.
    pub(crate) fn ensure_lxapp(
        &self,
        appid: String,
        release_type: Channel,
    ) -> Result<Arc<LxApp>, LxAppError> {
        let _admission = self.admission.enter(&appid)?;
        let transition_appid = appid.clone();
        self.with_session_transition(&transition_appid, move || {
            let session_class = self.session_class_for(&appid);
            self.ensure_lxapp_with_session_class(appid, release_type, session_class)
        })
    }

    /// The class a session for `appid` must be created with.
    ///
    /// ControlApp follows the native-sealed home identity rather than whatever
    /// session happens to be live: a home destroyed by eviction, uninstall, or
    /// the delayed-destroy timer must not come back as an ordinary guest.
    /// ControlSurface is not an identity — a host-bundled lxapp is only a
    /// surface while the ControlApp keeps one open — so it is inherited.
    fn session_class_for(&self, appid: &str) -> AppSessionClass {
        let live = self.lxapps.get(appid).map(|app| app.app_session_class());
        Self::session_class_for_identity(appid, lingxia_app_context::home_app_id(), live)
    }

    fn session_class_for_identity(
        appid: &str,
        home_app_id: Option<&str>,
        live: Option<AppSessionClass>,
    ) -> AppSessionClass {
        if home_app_id == Some(appid) {
            return AppSessionClass::ControlApp;
        }
        live.unwrap_or(AppSessionClass::StandardApp)
    }

    /// Only the native-sealed home app id ever becomes the ControlApp.
    pub(crate) fn ensure_lxapp_for_native_control(
        &self,
        appid: String,
        release_type: Channel,
    ) -> Result<Arc<LxApp>, LxAppError> {
        let _admission = self.admission.enter(&appid)?;
        let transition_appid = appid.clone();
        self.with_session_transition(&transition_appid, move || {
            if lingxia_app_context::home_app_id() != Some(appid.as_str()) {
                return Err(LxAppError::InvalidParameter(format!(
                    "control app identity mismatch: {appid} is not the native-sealed home app"
                )));
            }
            if let Some(app) = self.lxapps.get(&appid) {
                if app.is_control_app() {
                    return Ok(app.clone());
                }
                drop(app);
                self.destroy_lxapp_with_options(&appid, true);
            }
            self.ensure_lxapp_with_session_class(appid, release_type, AppSessionClass::ControlApp)
        })
    }

    /// Host-bundled control surface (Terminal Settings). Only a bundle the host
    /// ships itself qualifies, and never the home app id: that session is the
    /// ControlApp and must not be downgraded to a surface.
    pub(crate) fn ensure_lxapp_for_control_surface(
        &self,
        appid: String,
        release_type: Channel,
    ) -> Result<Arc<LxApp>, LxAppError> {
        let _admission = self.admission.enter(&appid)?;
        let transition_appid = appid.clone();
        self.with_session_transition(&transition_appid, move || {
            if lingxia_app_context::home_app_id() == Some(appid.as_str()) {
                return Err(LxAppError::InvalidParameter(format!(
                    "control surface identity mismatch: {appid} is the home app"
                )));
            }
            if !control_surface_bundle_source_allowed(lxapp_bundle_source_for(&appid).as_ref()) {
                return Err(LxAppError::InvalidParameter(format!(
                    "control surface must be a host-bundled lxapp: {appid}"
                )));
            }
            if let Some(app) = self.lxapps.get(&appid) {
                if app.app_session_class() == AppSessionClass::ControlSurface {
                    return Ok(app.clone());
                }
                drop(app);
                self.destroy_lxapp_with_options(&appid, true);
            }
            self.ensure_lxapp_with_session_class(
                appid,
                release_type,
                AppSessionClass::ControlSurface,
            )
        })
    }

    fn ensure_builtin_lxapp(&self, appid: &str) -> Result<Arc<LxApp>, LxAppError> {
        let _admission = self.admission.enter(appid)?;
        self.with_session_transition(appid, || {
            if let Some(app) = self.lxapps.get(appid) {
                return Ok(app.clone());
            }
            if !matches!(
                lxapp_bundle_source_for(appid),
                Some(LxAppBundleSource::BuiltinAssets | LxAppBundleSource::Synthetic)
            ) {
                return Err(LxAppError::ResourceNotFound(format!(
                    "builtin lxapp source not registered: {appid}"
                )));
            }

            let app = Arc::new(LxApp::new(
                appid.to_string(),
                self.runtime.clone(),
                self.executor.clone(),
                Channel::Release,
            )?);
            self.track_instance(&app);
            app.bind_and_seal_resource_grants();
            self.lxapps.insert(appid.to_string(), app.clone());
            Ok(app)
        })
    }

    fn initialize_home_lxapp(&self, appid: String) -> Result<Arc<LxApp>, LxAppError> {
        let _admission = self.admission.enter(&appid)?;
        let transition_appid = appid.clone();
        self.with_session_transition(&transition_appid, move || {
            if let Some(app) = self.lxapps.get(&appid) {
                if app.is_control_app() {
                    return Ok(app.clone());
                }
                drop(app);
                self.destroy_lxapp_with_options(&appid, true);
            }

            let app = Arc::new(LxApp::new_as_home(
                appid.clone(),
                self.runtime.clone(),
                self.executor.clone(),
            )?);
            self.track_instance(&app);
            app.bind_and_seal_resource_grants();
            self.lxapps.insert(appid, app.clone());
            Ok(app)
        })
    }

    fn ensure_lxapp_with_session_class(
        &self,
        appid: String,
        release_type: Channel,
        session_class: AppSessionClass,
    ) -> Result<Arc<LxApp>, LxAppError> {
        let has_pending_update = metadata::downloaded_get(&appid, release_type)
            .map(|opt| opt.is_some())
            .unwrap_or(false);

        if has_pending_update {
            // A live session that chose Later still has the zip on disk. Applying
            // it here would hide+tear down the current WebView — "right now", not
            // "next cold start". Restart, a real close, and process bootstrap
            // still apply through this path once the instance is gone.
            if let Some(app_arc) = self.lxapps.get(&appid)
                && app_arc.status() != LxAppSessionStatus::Closed
            {
                return Ok(app_arc.clone());
            }
            self.destroy_lxapp(&appid);
            if let Err(e) =
                UpdateManager::apply_downloaded_update(self.runtime.clone(), &appid, release_type)
            {
                error!(
                    "Failed to apply downloaded update before opening app: {}",
                    e
                )
                .with_appid(appid.clone());
                return Err(e);
            }
        } else if let Some(app_arc) = self.lxapps.get(&appid) {
            return Ok(app_arc.clone());
        }

        // Create new LxApp
        let new_lxapp = Arc::new(match session_class {
            AppSessionClass::StandardApp => LxApp::new(
                appid.clone(),
                self.runtime.clone(),
                self.executor.clone(),
                release_type,
            )?,
            AppSessionClass::ControlApp => {
                LxApp::new_as_home(appid.clone(), self.runtime.clone(), self.executor.clone())?
            }
            AppSessionClass::ControlSurface => LxApp::new_control_surface(
                appid.clone(),
                self.runtime.clone(),
                self.executor.clone(),
                release_type,
            )?,
        });
        self.track_instance(&new_lxapp);
        new_lxapp.bind_and_seal_resource_grants();

        // Publish with the map entry API. Two concurrent cold opens must both
        // receive the same LxApp instance; otherwise each instance could claim
        // a different shell region and defeat the one-app/one-region invariant.
        match self.lxapps.entry(appid) {
            dashmap::mapref::entry::Entry::Occupied(entry) => Ok(entry.get().clone()),
            dashmap::mapref::entry::Entry::Vacant(entry) => {
                entry.insert(new_lxapp.clone());
                Ok(new_lxapp)
            }
        }
    }

    pub(crate) fn live_logic_instances(&self) -> Vec<Arc<LxApp>> {
        self.instances
            .lock()
            .unwrap()
            .values()
            .filter(|app| *app.logic_contexts.borrow() != 0)
            .cloned()
            .collect()
    }

    fn track_instance(&self, app: &Arc<LxApp>) {
        let _ = app.admission.set(self.admission.clone());
        let mut instances = self.instances.lock().unwrap();
        instances.retain(|_, old| {
            self.lxapps
                .get(&old.appid)
                .is_some_and(|live| Arc::ptr_eq(live.value(), old))
                || !old.session.is_cancelled()
                || *old.logic_contexts.borrow() != 0
        });
        instances.insert(app.session_id(), app.clone());
    }

    /// Full shutdown must also retire capsule-closed and previously removed instances.
    pub(crate) fn retire_lxapp(&self, appid: &str) -> Result<Arc<LxApp>, LxAppError> {
        // Resolve under the transition lock so a concurrent recreate cannot swap
        // in a replacement that outlives this termination.
        self.with_session_transition(appid, || {
            let app = self
                .lxapps
                .get(appid)
                .map(|entry| entry.value().clone())
                .ok_or_else(|| LxAppError::ResourceNotFound(appid.to_string()))?;
            self.retire_locked(&app)?;
            Ok(app)
        })
    }

    fn retire_instance(&self, app: &Arc<LxApp>) -> Result<(), LxAppError> {
        self.with_session_transition(&app.appid, || self.retire_locked(app))
    }

    fn retire_locked(&self, app: &Arc<LxApp>) -> Result<(), LxAppError> {
        let _open = app
            .presentation_open_lock
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        // Retain before removing from the live map, including on timeout/cancellation.
        self.instances
            .lock()
            .unwrap()
            .insert(app.session_id(), app.clone());
        app.session.retired.store(true, Ordering::SeqCst);
        let is_current = self
            .lxapps
            .get(&app.appid)
            .is_some_and(|current| Arc::ptr_eq(current.value(), app));
        if is_current {
            self.remove_from_stack(&app.appid);
            self.cancel_delayed_destroy(&app.appid);
        }
        app.shutdown()?;
        app.complete_programmatic_close(app.session_id());
        if is_current {
            self.lxapps.remove(&app.appid);
        }
        Ok(())
    }

    /// Completely destroy an LxApp (shutdown + removal from manager and stack).
    fn destroy_lxapp_with_options(&self, appid: &str, skip_hide: bool) {
        if let Some(app_arc) = self.lxapps.get(appid) {
            let _ = app_arc.shutdown_with_options(skip_hide);
        }
        self.remove_from_stack(appid);
        self.lxapps.remove(appid);
    }

    /// Completely destroy an LxApp with normal hide behavior.
    fn destroy_lxapp(&self, appid: &str) {
        self.destroy_lxapp_with_options(appid, false);
    }

    /// Recreate the LxApp instance for a given appid with a brand new instance.
    /// Used by restart to force a fresh session and runtime state.
    fn recreate_lxapp(
        &self,
        appid: String,
        release_type: Channel,
    ) -> Result<Arc<LxApp>, LxAppError> {
        let _admission = self.admission.enter(&appid)?;
        let transition_appid = appid.clone();
        self.with_session_transition(&transition_appid, move || {
            let session_class = self.session_class_for(&appid);

            // Close handshake is handled by restart state machine; avoid a second hide while recreating.
            self.destroy_lxapp_with_options(&appid, true);

            // Delegate to ensure_lxapp so pending downloaded updates are applied
            // consistently (same path as cold-start navigation).
            self.ensure_lxapp_with_session_class(appid, release_type, session_class)
        })
    }

    /// Finds and evicts the least recently used LxApp to free up memory.
    /// Selects the first non-home live app from the least-recently-used end.
    fn evict_lru_lxapp(&self) {
        let candidates = {
            let Ok(stack) = self.lxapp_stack.lock() else {
                return;
            };
            stack.iter().cloned().collect::<Vec<_>>()
        };
        let Some(appid_to_destroy) = first_evictable_appid(&candidates, |appid| {
            self.lxapps.get(appid).is_some_and(|app| !app.is_home_lxapp)
        }) else {
            warn!("No non-home lxapp is available for eviction");
            return;
        };

        info!("Evicting least recently used lxapp").with_appid(appid_to_destroy.clone());

        // Explicitly shutdown the app before removing it from the map so that
        // UI/JSContext/PageInstance/WebView/AppService are cleaned up deterministically.
        self.destroy_lxapp(&appid_to_destroy);
    }

    /// Schedule a delayed destroy for an app; cancel on reopen.
    pub(crate) fn schedule_delayed_destroy(self: &Arc<Self>, appid: String) {
        let generation = self.next_destroy_generation.fetch_add(1, Ordering::Relaxed);
        let (cancel, rx) = oneshot::channel();
        {
            let mut pending = self
                .pending_destroy
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            replace_pending_destroy(
                &mut pending,
                appid.clone(),
                PendingDestroy { generation, cancel },
            );
        }

        let mgr_weak = Arc::downgrade(self);
        std::mem::drop(crate::executor::spawn(async move {
            let sleep = time::sleep(Duration::from_secs(1800));
            tokio::pin!(rx);
            tokio::pin!(sleep);
            tokio::select! {
                _ = &mut sleep => {},
                _ = &mut rx => return,
            }

            if let Some(mgr) = mgr_weak.upgrade() {
                let should_destroy = {
                    let mut pending = mgr
                        .pending_destroy
                        .lock()
                        .unwrap_or_else(|poisoned| poisoned.into_inner());
                    claim_pending_destroy(&mut pending, &appid, generation)
                };
                if should_destroy {
                    info!("Delayed destroy triggered after inactivity").with_appid(appid.clone());
                    mgr.destroy_lxapp(&appid);
                }
            }
        }));
    }

    /// Cancel any pending delayed destroy for the given app.
    pub(crate) fn cancel_delayed_destroy(&self, appid: &str) {
        let mut pending = self
            .pending_destroy
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if let Some(entry) = pending.remove(appid) {
            let _ = entry.cancel.send(());
        }
    }

    /// Pushes an app onto the back of the navigation stack.
    /// This signifies that it is the most recently used app.
    /// If the stack is already at full capacity, the operation is aborted and a warning is logged.
    pub(crate) fn push_lxapp_stack(&self, appid: String) {
        let max = get_num_workers();
        if let Ok(mut stack) = self.lxapp_stack.lock() {
            if stack.len() < max {
                stack.push_back(appid);
            } else {
                warn!(
                    "LxApp navigation stack is full (capacity: {}). Cannot push app: {}",
                    max, appid
                );
            }
        }
    }

    /// Peek at the top app on the navigation stack without removing it
    fn peek_lxapp_stack(&self) -> Option<String> {
        if let Ok(stack) = self.lxapp_stack.lock() {
            stack.back().cloned()
        } else {
            None
        }
    }

    /// Remove a specific app from the navigation stack
    pub(crate) fn remove_from_stack(&self, appid: &str) {
        if let Ok(mut stack) = self.lxapp_stack.lock() {
            stack.retain(|id| id != appid);
        }
    }

    /// Whether an app is anywhere on the navigation stack.
    pub(crate) fn stack_contains(&self, appid: &str) -> bool {
        self.lxapp_stack
            .lock()
            .map(|stack| stack.iter().any(|id| id == appid))
            .unwrap_or(false)
    }

    /// Check if the navigation stack is full
    fn is_lxapp_stack_full(&self) -> bool {
        let max = get_num_workers();
        if let Ok(stack) = self.lxapp_stack.lock() {
            stack.len() >= max
        } else {
            // If the lock is poisoned, it's safer to consider it full
            // to prevent further pushes.
            true
        }
    }
}

/// Mutable state of a LxApp that requires synchronization
pub(crate) struct LxAppState {
    /// Runtime page instances keyed by stable instance id — the single owner
    /// of every live PageInstance (stack pages, pins, isolated surfaces).
    pub(crate) pages_by_id: Mutex<HashMap<String, PageInstance>>,

    /// Path-pinned singleton instances: tab pages and headless services.
    /// These survive off-stack and resolve by path when no stack entry does.
    pub(crate) path_pins: Mutex<HashMap<String, String>>,

    /// Runtime metadata and lifecycle state keyed by page instance id.
    page_instance_runtime: Mutex<HashMap<String, PageInstanceRuntimeRecord>>,

    /// Delayed dispose timers for hidden page instances.
    page_instance_dispose_timers: Mutex<HashMap<String, oneshot::Sender<()>>>,
    /// Pending in-place resets for pages that left the stack, keyed by page
    /// instance id. Cancelled when the page is navigated to again.
    page_reset_timers: Mutex<HashMap<String, oneshot::Sender<()>>>,

    /// PageInstance navigation stack: instance ids, oldest → newest. The
    /// instance id is the page's identity; its path is route metadata read
    /// from the instance itself.
    pub(crate) page_stack: Mutex<VecDeque<String>>,

    /// Time when this app was last active
    /// Used for LRU (Least Recently Used) eviction when memory is low
    pub(crate) last_active_time: Instant,

    /// TabBar runtime state
    /// Contains TabBar configuration and dynamic state (badges, red dots, visibility)
    pub tabbar: Option<tabbar::TabBar>,

    /// Lxapp-scoped appearance and the latest committed Page Chrome revision.
    pub(crate) appearance: LxAppAppearanceState,
    pub(crate) page_chrome_revision: u64,
    pub(crate) page_chrome_layouts: HashMap<String, EffectivePageChromeLayout>,

    /// Startup options for the app
    pub(crate) startup_options: LxAppStartupOptions,

    /// Shell region currently owned by this live lxapp presentation. This is
    /// claimed atomically before platform presentation starts and released only
    /// by a real close; hide/show keeps the claim.
    open_region: Option<LxAppOpenRegion>,

    /// Dynamic page surfaces created by lx.openSurface.
    pub(crate) surfaces: Mutex<SurfaceRecords>,

    /// App-level orientation override (runtime + persisted)
    pub(crate) orientation_override: Option<OrientationConfig>,

    /// App-declared actions surfaced by the host's secondary action affordance.
    more_actions: LxAppMoreActionState,
}

impl LxAppState {
    fn new() -> Self {
        Self {
            pages_by_id: Mutex::new(HashMap::new()),
            path_pins: Mutex::new(HashMap::new()),
            page_instance_runtime: Mutex::new(HashMap::new()),
            page_instance_dispose_timers: Mutex::new(HashMap::new()),
            page_reset_timers: Mutex::new(HashMap::new()),
            page_stack: Mutex::new(VecDeque::with_capacity(PAGE_STACK_MAX)),
            last_active_time: Instant::now(),
            tabbar: None,
            appearance: LxAppAppearanceState::default(),
            page_chrome_revision: 0,
            page_chrome_layouts: HashMap::new(),
            startup_options: LxAppStartupOptions::default(),
            open_region: None,
            surfaces: Mutex::new(SurfaceRecords::new()),
            orientation_override: None,
            more_actions: LxAppMoreActionState::default(),
        }
    }
}

/// Represents a single lxapplication
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum LxAppBundleSource {
    Installed,
    DevPath {
        root: PathBuf,
    },
    /// Pages/logic bundled at `<appid>/...` inside the platform asset root.
    BuiltinAssets,
    /// Content-less host. `LxAppConfig` stays at default (empty pages/plugins,
    /// `logic_enabled() == false`). Used for SDK-internal hosts with no UI bundle.
    Synthetic,
}

/// Native-assigned class for a live LxApp session.
///
/// This is not inferred from an app id, bundle source, or manifest.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AppSessionClass {
    StandardApp,
    /// The one native-sealed home session; the only class admitted to
    /// app-control routes.
    ControlApp,
    /// A host-bundled control UI (Terminal Settings) that the ControlApp opens.
    /// Never home, and only its own `ControlSurfaceOnly` routes admit it.
    ControlSurface,
}

pub struct LxApp {
    // Immutable data - initialized once and never changed
    pub appid: String,
    pub runtime: Arc<Platform>,
    pub lxapp_dir: PathBuf,
    pub(crate) bundle_source: LxAppBundleSource,
    pub storage_file_path: PathBuf,
    pub user_data_dir: PathBuf,
    pub user_cache_dir: PathBuf,
    pub temp_dir: PathBuf,
    temp_cleanup_protection: Option<crate::cache::CleanupProtection>,
    usercache_cleanup_protection: Option<crate::cache::CleanupProtection>,
    pub fingermark: String,
    pub is_home_lxapp: bool,
    app_session_class: AppSessionClass,
    pub(crate) release_type: Channel,
    /// Manifest. Dev reload re-reads `lxapp.json` so `pages` / `tabBar` apply
    /// without a new `lingxia dev` session.
    pub(crate) config: Mutex<LxAppConfig>,
    pub(crate) executor: Arc<LxAppWorkers>,
    host_permissions: permissions::HostPermissions,
    home_update_check_dispatched: AtomicBool,
    app_launch_dispatched: AtomicBool,
    pending_restart_request: AtomicBool,
    /// Last app-level visibility event was OnShow. OnHide also fires on
    /// capsule close and app switch, not only when the host backgrounds.
    shown: AtomicBool,
    /// When the app last left the screen; a tab's idle clock starts no earlier.
    hidden_since: Mutex<Option<Instant>>,
    /// Session being torn down for a restart, or 0. Page instances must not be
    /// (re)created on it; the recreated instance starts fresh at 0.
    restart_closing_session: AtomicU64,
    /// Feature support frozen per live Logic context, keyed by context id.
    logic_feature_snapshots: Mutex<std::collections::BTreeMap<String, Vec<String>>>,

    /// Current runtime session of this app (id + status)
    pub(crate) session: LxAppSession,
    pub(crate) logic_contexts: tokio::sync::watch::Sender<usize>,
    admission: OnceLock<Arc<shutdown::Admission>>,

    // Mutable state - protected by mutex for fine-grained locking
    pub(crate) state: Mutex<LxAppState>,

    /// Serializes presentation opens so a failed cold open cannot release a
    /// same-region claim that a concurrent reopen has already made live.
    presentation_open_lock: Mutex<()>,

    /// Serializes public appearance/navbar/tabbar mutations per lxapp.
    pub(crate) page_chrome_mutation_lock: tokio::sync::Mutex<()>,

    self_weak: OnceLock<Weak<LxApp>>,

    /// Native-issued privileged resources, sealed once for this exact session.
    resource_grants: OnceLock<HashSet<crate::host::AppResourceGrant>>,
    /// Claims the seal. Both the creation path and every waiter on the
    /// permission snapshot reach it, and the resolvers behind it are host
    /// callbacks — a prompt, an audit entry — that must run once.
    resource_grants_claimed: std::sync::atomic::AtomicBool,

    // Scripts injected as soon as a page document starts loading.
    document_start_scripts: Mutex<Vec<Arc<str>>>,

    // Scripts injected into every page owned by this LxApp on page load.
    page_scripts: Mutex<Vec<Arc<str>>>,
}

/// Unique id for a single LxApp runtime session within the process.
pub(crate) type LxAppSessionId = u64;

/// Lifecycle status of a LxApp session (replacing LxAppStatus).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(u8)]
pub(crate) enum LxAppSessionStatus {
    Closed = 0,
    Opening = 1,
    Opened = 2,
    Closing = 3,
    Restarting = 4,
}

impl LxAppSessionStatus {
    fn as_str(self) -> &'static str {
        match self {
            Self::Closed => "closed",
            Self::Opening => "opening",
            Self::Opened => "opened",
            Self::Closing => "closing",
            Self::Restarting => "restarting",
        }
    }
}

/// A single runtime session of a LxApp: id + status.
pub(crate) struct LxAppSession {
    pub(crate) id: LxAppSessionId,
    status: AtomicU8,
    retired: AtomicBool,
    // Replaced on reopen: a closed instance stays in the manager for 30 minutes
    // and is handed back as-is, so the cancellation must not outlive the close.
    shutdown: Mutex<tokio::sync::watch::Sender<bool>>,
}

#[derive(Debug, Clone, Serialize)]
pub struct LxAppRuntimeInfo {
    pub appid: String,
    pub app_name: String,
    pub version: String,
    pub release_type: String,
    pub session_id: u64,
    pub status: String,
    /// Whether the app is on the runtime navigation stack — i.e. open from
    /// the user's perspective. A hidden (capsule-closed) app keeps an
    /// "opened" session but is not on the stack.
    pub in_stack: bool,
    pub is_home: bool,
    pub current_page: Option<String>,
    pub initial_route: String,
    pub pages_count: usize,
    pub page_entries: Vec<LxAppRuntimePageInfo>,
    pub page_stack: Vec<String>,
    pub tab_bar: Option<LxAppRuntimeTabBarInfo>,
    pub navigation_bar: Option<LxAppRuntimeNavigationBarInfo>,
    pub lxapp_dir: String,
    pub data_dir: String,
    pub cache_dir: String,
    /// Sorted supported features keyed by the owning Logic context id.
    pub logic_features: std::collections::BTreeMap<String, Vec<String>>,
}

#[derive(Debug, Clone, Serialize)]
pub struct LxAppRuntimeTabBarInfo {
    pub presentation: TabBarPresentation,
    pub visibility: TabBarVisibilityPreference,
    pub route_visible: bool,
    pub effective_visible: bool,
    pub selected_index: i32,
    pub items: Vec<LxAppRuntimeTabBarItemInfo>,
}

#[derive(Debug, Clone, Serialize)]
pub struct LxAppRuntimeNavigationBarInfo {
    pub title: String,
    pub home_button: VisibilityPreference,
    pub home_button_visible: bool,
    pub runtime_style: LxAppRuntimeNavigationBarStyleInfo,
}

#[derive(Debug, Clone, Serialize)]
pub struct LxAppRuntimeNavigationBarStyleInfo {
    pub background_color: Option<String>,
    pub foreground_color: Option<String>,
    pub divider_color: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct LxAppRuntimeTabBarItemInfo {
    pub index: usize,
    pub text: Option<String>,
    pub icon_path: Option<String>,
    pub badge: Option<String>,
    pub red_dot: bool,
}

#[derive(Debug, Clone, Serialize)]
pub struct LxAppRuntimePageInfo {
    pub name: String,
    pub path: String,
}

/// One app-declared action after its icon path has been resolved inside the
/// lxapp sandbox. The callback remains in the Logic context and is addressed by
/// the snapshot generation plus this item's index.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LxAppMoreAction {
    pub label: String,
    pub icon_path: String,
}

/// Immutable native-facing snapshot used to build a More action menu/sheet.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LxAppMoreActions {
    pub generation: u64,
    pub items: Vec<LxAppMoreAction>,
}

/// Three host lifecycle actions plus these app actions fill a two-row,
/// five-column capsule menu.
pub const LXAPP_MORE_ACTION_LIMIT: usize = 7;

#[derive(Debug, Default)]
struct LxAppMoreActionState {
    generation: u64,
    items: Vec<LxAppMoreAction>,
}

impl LxAppSession {
    pub(crate) fn new() -> Self {
        // Process-wide monotonically increasing session id.
        use std::sync::atomic::AtomicU64;
        static SESSION_SEQ: AtomicU64 = AtomicU64::new(1);
        let id = SESSION_SEQ.fetch_add(1, Ordering::Relaxed);
        Self {
            id,
            status: AtomicU8::new(LxAppSessionStatus::Closed as u8),
            retired: AtomicBool::new(false),
            shutdown: Mutex::new(tokio::sync::watch::channel(false).0),
        }
    }

    fn shutdown_sender(&self) -> std::sync::MutexGuard<'_, tokio::sync::watch::Sender<bool>> {
        self.shutdown.lock().unwrap_or_else(|err| err.into_inner())
    }

    pub(crate) fn cancel(&self) {
        self.shutdown_sender().send_replace(true);
    }

    /// Re-arm a cancelled session for a fresh open. Waiters from the closed run
    /// keep the old channel and stay cancelled by its sender being dropped.
    pub(crate) fn revive(&self) {
        if self.is_retired() {
            return;
        }
        let mut sender = self.shutdown_sender();
        if *sender.borrow() {
            *sender = tokio::sync::watch::channel(false).0;
        }
    }

    pub(crate) fn is_cancelled(&self) -> bool {
        *self.shutdown_sender().borrow()
    }

    pub(crate) fn is_retired(&self) -> bool {
        self.retired.load(Ordering::SeqCst)
    }

    pub(crate) async fn while_alive<F: std::future::Future>(&self, future: F) -> Option<F::Output> {
        let mut shutdown = self.shutdown_sender().subscribe();
        tokio::select! {
            biased;
            _ = shutdown.wait_for(|cancelled| *cancelled) => None,
            result = future => (!self.is_cancelled()).then_some(result),
        }
    }

    pub(crate) fn status(&self) -> LxAppSessionStatus {
        match self.status.load(Ordering::SeqCst) {
            1 => LxAppSessionStatus::Opening,
            2 => LxAppSessionStatus::Opened,
            3 => LxAppSessionStatus::Closing,
            4 => LxAppSessionStatus::Restarting,
            _ => LxAppSessionStatus::Closed,
        }
    }

    pub(crate) fn set_status(&self, s: LxAppSessionStatus) {
        self.status.store(s as u8, Ordering::SeqCst);
    }

    pub(crate) fn cas_status(&self, from: LxAppSessionStatus, to: LxAppSessionStatus) -> bool {
        self.status
            .compare_exchange(from as u8, to as u8, Ordering::SeqCst, Ordering::SeqCst)
            .is_ok()
    }
}

/// Session helpers and lifecycle utilities for LxApp.
impl LxApp {
    /// Helper to clone Arc<Self> from within methods needing Arc
    pub(crate) fn clone_arc(&self) -> Arc<LxApp> {
        self.self_weak
            .get()
            .and_then(Weak::upgrade)
            .expect("LxApp Arc binding missing")
    }

    pub(crate) fn bind_arc(self: &Arc<Self>) {
        let _ = self.self_weak.set(Arc::downgrade(self));
    }

    /// Bind the Arc, then seal native resource grants from the permission
    /// snapshot. A still-pending lookup is sealed when it lands — sealing the
    /// pending deny would stick in the OnceLock.
    pub(crate) fn bind_and_seal_resource_grants(self: &Arc<Self>) {
        self.bind_arc();
        crate::host::seal_app_resource_grants(self);
        // Ask whether the seal happened, not whether the grant is ready: a
        // lookup that lands between those two reads would leave a logic-free
        // app — which never sends `CreateAppSvc` — with no waiter and no seal.
        if self.resource_grants_claimed() {
            return;
        }
        let app = Arc::clone(self);
        crate::executor::spawn(async move {
            app.wait_permissions_ready().await;
        });
    }

    pub(crate) fn status(&self) -> LxAppSessionStatus {
        self.session.status()
    }

    pub fn session_id(&self) -> LxAppSessionId {
        self.session.id
    }

    /// Returns the native-assigned class for this live app session.
    pub fn app_session_class(&self) -> AppSessionClass {
        self.app_session_class
    }

    /// Whether this session is the native-bootstrapped ControlApp.
    pub fn is_control_app(&self) -> bool {
        self.app_session_class == AppSessionClass::ControlApp
    }

    pub fn sync_host_ui(&self) {
        let revision = self.next_page_chrome_revision();
        if let Err(err) = self.runtime.update_navbar_ui(self.appid.clone()) {
            warn!("Failed to update host NavigationBar UI: {}", err).with_appid(self.appid.clone());
        }
        if let Err(err) = self.runtime.update_tabbar_ui(self.appid.clone()) {
            warn!("Failed to update host TabBar UI: {}", err).with_appid(self.appid.clone());
        }
        if let Ok(page) = self.current_page() {
            let appearance = self.appearance_state().resolved;
            let app = self.clone_arc();
            std::mem::drop(crate::executor::spawn(async move {
                if let Err(err) = app
                    .publish_realized_page_chrome(&page, revision, appearance)
                    .await
                {
                    warn!("Failed to publish Page Chrome View snapshot: {}", err)
                        .with_appid(app.appid.clone());
                }
            }));
        }
    }

    pub fn grant_transient_file_access(&self, path: &Path) -> Result<uri::LxUri, LxAppError> {
        self.grant_transient_path_access(path, TransientPathKind::File)
    }

    pub fn grant_transient_file_reference(&self, reference: &str) -> Result<String, LxAppError> {
        let normalized = normalize_transient_file_reference(reference)?;
        TRANSIENT_FILE_REFERENCE_GRANTS
            .get_or_init(DashMap::new)
            .insert(
                (self.appid.clone(), self.session_id(), normalized.clone()),
                (),
            );
        Ok(normalized)
    }

    pub fn has_transient_file_reference(&self, reference: &str) -> bool {
        let Ok(normalized) = normalize_transient_file_reference(reference) else {
            return false;
        };
        TRANSIENT_FILE_REFERENCE_GRANTS
            .get_or_init(DashMap::new)
            .contains_key(&(self.appid.clone(), self.session_id(), normalized))
    }

    pub fn register_temp_file(&self, path: &Path) -> Result<uri::LxUri, LxAppError> {
        self.cleanup_temp_size(Some(path))?;
        let uri = self.grant_transient_file_access(path)?;
        Ok(uri)
    }

    pub fn temp_output_path(
        &self,
        category: &str,
        ext: Option<&str>,
    ) -> Result<PathBuf, LxAppError> {
        let category = category
            .chars()
            .map(|ch| match ch {
                'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' => ch,
                _ => '_',
            })
            .collect::<String>();
        let dir = self.temp_dir.join(category);
        std::fs::create_dir_all(&dir).map_err(|e| {
            LxAppError::IoError(format!("Failed to create temp output directory: {}", e))
        })?;
        let mut name = Uuid::new_v4().simple().to_string();
        if let Some(ext) = ext
            .map(str::trim)
            .map(|value| value.trim_start_matches('.'))
            .filter(|value| !value.is_empty())
        {
            name.push('.');
            name.push_str(ext);
        }
        Ok(dir.join(name))
    }

    pub fn grant_transient_directory_access(&self, path: &Path) -> Result<uri::LxUri, LxAppError> {
        self.grant_transient_path_access(path, TransientPathKind::Directory)
    }

    fn grant_transient_path_access(
        &self,
        path: &Path,
        kind: TransientPathKind,
    ) -> Result<uri::LxUri, LxAppError> {
        let normalized = normalize_transient_path(path, kind)?;
        let token = Uuid::new_v4().simple().to_string();
        TRANSIENT_FILE_GRANTS.get_or_init(DashMap::new).insert(
            (self.appid.clone(), self.session_id(), token.clone()),
            normalized,
        );
        uri::LxUri::from_str(&format!(
            "{}://{}/{}",
            uri::LX_SCHEME,
            uri::HOST_TEMP,
            token
        ))
        .map_err(LxAppError::InvalidParameter)
    }

    fn resolve_transient_file(&self, token: &str) -> Option<PathBuf> {
        TRANSIENT_FILE_GRANTS
            .get_or_init(DashMap::new)
            .get(&(self.appid.clone(), self.session_id(), token.to_string()))
            .map(|entry| entry.value().clone())
    }

    pub(crate) fn clear_transient_files(&self) {
        let appid = self.appid.clone();
        let session_id = self.session_id();
        if let Some(grants) = TRANSIENT_FILE_GRANTS.get() {
            grants.retain(|key, _| key.0 != appid || key.1 != session_id);
        }
        if let Some(grants) = TRANSIENT_FILE_REFERENCE_GRANTS.get() {
            grants.retain(|key, _| key.0 != appid || key.1 != session_id);
        }
        if !self.temp_dir.as_os_str().is_empty() {
            let _ = std::fs::remove_dir_all(&self.temp_dir);
        }
    }

    fn cleanup_temp_size(&self, keep: Option<&Path>) -> Result<(), LxAppError> {
        if self.temp_dir.as_os_str().is_empty() {
            return Ok(());
        }
        let Some(keep) = keep else {
            return Ok(());
        };
        let incoming = lingxia_service::storage::path_size(keep);
        lingxia_service::storage::ensure_temp_quota(&self.temp_dir, keep, incoming)
            .map_err(|err| LxAppError::ResourceExhausted(err.detail().to_string()))
    }

    fn status_name(&self) -> &'static str {
        self.status().as_str()
    }

    pub fn release_type(&self) -> Channel {
        self.release_type
    }

    /// Whether this lxapp's code was supplied by the host build (or its local
    /// development source), rather than installed or updated independently.
    pub fn is_host_bundled(&self) -> bool {
        matches!(
            self.bundle_source,
            LxAppBundleSource::BuiltinAssets | LxAppBundleSource::DevPath { .. }
        )
    }

    /// Whether `lx.process` is actually reachable from this lxapp — the answer
    /// `lx.supports` reports, so the query and the module's presence cannot
    /// disagree. False wherever the feature is not compiled in.
    pub fn process_supported(&self) -> bool {
        #[cfg(feature = "process")]
        {
            let privilege = LxAppSecurityPrivilege::new("process")
                .expect("process is a valid security privilege id");
            self.is_control_app()
                && lingxia_app_context::process_enabled()
                && self.has_security_privilege(&privilege)
        }
        #[cfg(not(feature = "process"))]
        {
            false
        }
    }

    /// Diagnostic copy only; the authoritative set is private to the JS context.
    #[doc(hidden)]
    pub fn record_logic_feature_snapshot(&self, context: String, features: Vec<String>) {
        self.logic_feature_snapshots
            .lock()
            .unwrap()
            .insert(context, features);
    }

    #[doc(hidden)]
    pub fn remove_logic_feature_snapshot(&self, context: &str) {
        self.logic_feature_snapshots.lock().unwrap().remove(context);
    }

    pub fn app_data_dir(&self) -> PathBuf {
        self.runtime.app_data_dir()
    }

    pub(crate) fn config(&self) -> std::sync::MutexGuard<'_, LxAppConfig> {
        self.config
            .lock()
            .unwrap_or_else(|error| error.into_inner())
    }

    pub fn page_entries(&self) -> Vec<LxAppRuntimePageInfo> {
        self.config()
            .page_entries()
            .into_iter()
            .map(|LxAppPageEntry { name, path }| LxAppRuntimePageInfo { name, path })
            .collect()
    }

    pub fn runtime_info(&self) -> LxAppRuntimeInfo {
        let info = self.get_lxapp_info();
        let page_entries = self.page_entries();
        let tab_bar = self.get_tabbar().map(|tabbar| LxAppRuntimeTabBarInfo {
            presentation: tabbar.presentation,
            visibility: tabbar.visibility,
            route_visible: tabbar.route_visible,
            effective_visible: tabbar.is_effectively_visible(),
            selected_index: tabbar.selected_index,
            items: tabbar
                .items
                .into_iter()
                .enumerate()
                .map(|(index, item)| LxAppRuntimeTabBarItemInfo {
                    index,
                    text: item.text,
                    icon_path: item.icon_path,
                    badge: item.badge,
                    red_dot: item.has_red_dot,
                })
                .collect(),
        });
        let navigation_bar = self.peek_current_page_path().map(|path| {
            let state = self.get_navbar_state(&path);
            LxAppRuntimeNavigationBarInfo {
                title: state.title().to_string(),
                home_button: state.home_button,
                home_button_visible: state.home_button_visible(),
                runtime_style: LxAppRuntimeNavigationBarStyleInfo {
                    background_color: state
                        .runtime_style
                        .background_color
                        .map(|color| color.to_string()),
                    foreground_color: state
                        .runtime_style
                        .foreground_color
                        .map(|color| color.to_string()),
                    divider_color: state
                        .runtime_style
                        .divider_color
                        .map(|color| color.to_string()),
                },
            }
        });
        // On the navigation stack = open from the user's perspective. A
        // capsule-closed app keeps its "opened" session (stateful hide) but
        // leaves the stack, so hosts must read `in_stack` — not `status` —
        // for open-app lists.
        let in_stack = crate::lxapp::get_lxapps_manager()
            .map(|manager| manager.stack_contains(&self.appid))
            .unwrap_or(false);
        LxAppRuntimeInfo {
            appid: self.appid.clone(),
            app_name: info.app_name,
            version: info.version,
            release_type: info.release_type,
            session_id: self.session_id(),
            status: self.status_name().to_string(),
            in_stack,
            is_home: self.is_home_lxapp,
            current_page: self.peek_current_page_path(),
            initial_route: self.initial_route(),
            pages_count: page_entries.len(),
            page_entries,
            page_stack: self.get_page_stack_paths(),
            tab_bar,
            navigation_bar,
            lxapp_dir: self.lxapp_dir.to_string_lossy().into_owned(),
            data_dir: self.user_data_dir.to_string_lossy().into_owned(),
            cache_dir: self.user_cache_dir.to_string_lossy().into_owned(),
            logic_features: self.logic_feature_snapshots.lock().unwrap().clone(),
        }
    }

    /// Atomically replace this lxapp's app-declared More actions.
    pub fn replace_more_actions(&self, generation: u64, mut items: Vec<LxAppMoreAction>) {
        items.truncate(LXAPP_MORE_ACTION_LIMIT);
        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
        state.more_actions = LxAppMoreActionState { generation, items };
    }

    /// Clear actions only when the shutting-down Logic context still owns the
    /// current generation. A newer context must not be erased by an older one.
    pub fn clear_more_actions_if_generation(&self, generation: u64) {
        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
        if state.more_actions.generation == generation {
            state.more_actions.generation = generation.saturating_add(1);
            state.more_actions.items.clear();
        }
    }

    pub fn more_actions(&self) -> LxAppMoreActions {
        let state = self.state.lock().unwrap_or_else(|error| error.into_inner());
        LxAppMoreActions {
            generation: state.more_actions.generation,
            items: state.more_actions.items.clone(),
        }
    }

    pub fn more_actions_json(&self) -> String {
        serde_json::to_string(&self.more_actions())
            .unwrap_or_else(|_| r#"{"generation":0,"items":[]}"#.to_string())
    }

    /// Validate a native selection against the currently displayed generation,
    /// then enqueue its callback on this app's Logic thread.
    pub fn activate_more_action(&self, generation: u64, index: usize) -> bool {
        let valid = {
            let state = self.state.lock().unwrap_or_else(|error| error.into_inner());
            state.more_actions.generation == generation && index < state.more_actions.items.len()
        };
        if !valid {
            return false;
        }
        crate::publish_app_event(
            &self.appid,
            &format!("lx.moreActions:{generation}:{index}"),
            None,
        )
    }

    pub async fn eval_logic(&self, script: String) -> Result<serde_json::Value, LxAppError> {
        let json = self
            .executor
            .eval_app_service(self.clone_arc(), script, false)
            .await?;
        serde_json::from_str(&json).map_err(LxAppError::from)
    }

    /// Evaluate, and report which `lx.*` members the script reached.
    ///
    /// Resolves to `{ value, calls }`. The test runner uses `calls` to tell a
    /// spec that exercised an API from one that only declared it covered.
    pub async fn eval_logic_capturing_calls(
        &self,
        script: String,
    ) -> Result<serde_json::Value, LxAppError> {
        let json = self
            .executor
            .eval_app_service(self.clone_arc(), script, true)
            .await?;
        serde_json::from_str(&json).map_err(LxAppError::from)
    }

    pub(crate) fn set_status(&self, s: LxAppSessionStatus) {
        self.session.set_status(s);
    }

    pub(crate) fn cas_status(&self, from: LxAppSessionStatus, to: LxAppSessionStatus) -> bool {
        self.session.cas_status(from, to)
    }

    /// Whether this lxapp's bundle is managed by the update system. A
    /// dev-served bundle is served live from a local `dist`, so there is no
    /// installed package to check or replace.
    pub(crate) fn is_ota_managed(&self) -> bool {
        !matches!(self.bundle_source, LxAppBundleSource::DevPath { .. })
    }

    pub(crate) fn trigger_home_update_check_once(&self) {
        if !self.is_home_lxapp {
            return;
        }
        if matches!(self.bundle_source, LxAppBundleSource::DevPath { .. }) {
            return;
        }
        if self
            .home_update_check_dispatched
            .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
            .is_ok()
        {
            UpdateManager::spawn_lxapp_update_check(self.appid.clone(), self.release_type);
        }
    }

    pub(crate) fn has_pending_restart_request(&self) -> bool {
        self.pending_restart_request.load(Ordering::SeqCst)
    }

    /// True while `session_id` is this instance's restart-closing session.
    pub fn is_restart_closing_session(&self, session_id: u64) -> bool {
        session_id != 0 && self.restart_closing_session.load(Ordering::SeqCst) == session_id
    }

    fn cancel_page_instance_dispose_timer(&self, id: &PageInstanceId) {
        self.cancel_page_instance_dispose_timer_by_id(id.as_str());
    }

    fn cancel_page_instance_dispose_timer_by_id(&self, id: &str) {
        if let Ok(state) = self.state.lock()
            && let Some(cancel) = state
                .page_instance_dispose_timers
                .lock()
                .unwrap()
                .remove(id)
        {
            let _ = cancel.send(());
        }
    }

    /// How long to wait past a back/replace transition before tearing down the
    /// page that left. Long enough for the native container's pop animation to
    /// finish, so the outgoing page is never blanked while it is on screen.
    const PAGE_RESET_DELAY: Duration = Duration::from_millis(500);

    /// Schedules the teardown of a page that just left the stack.
    ///
    /// Leaving a page ends its instance: the next entry must see fresh `data`
    /// and a fresh document, which is what `onLoad` has always promised. The
    /// teardown is deliberately lazy — the Logic service dies and the document
    /// is parked blank, but nothing is rebuilt until an entry asks for it.
    /// Rebuilding speculatively would run page code off-screen (view mount
    /// hooks, native components, media) and queue Logic work for pages nobody
    /// is returning to.
    pub(crate) fn schedule_page_reset(&self, page: &PageInstance) {
        let instance_id = page.instance_id_string();
        self.cancel_page_reset(&instance_id);
        {
            let _transition = page.reset_transition_guard();
            page.mark_reset_pending();
        }

        let (tx, rx) = oneshot::channel();
        if let Ok(state) = self.state.lock() {
            state
                .page_reset_timers
                .lock()
                .unwrap()
                .insert(instance_id.clone(), tx);
        }

        let appid = self.appid.clone();
        std::mem::drop(crate::executor::spawn(async move {
            let sleep = time::sleep(Self::PAGE_RESET_DELAY);
            tokio::pin!(sleep);
            tokio::pin!(rx);
            tokio::select! {
                _ = &mut sleep => {}
                _ = &mut rx => return,
            }

            let Some(app) = crate::lxapp::try_get(&appid) else {
                return;
            };
            app.cancel_page_reset(&instance_id);
            // The instance can be back on the stack already: a re-entry inside
            // the delay window, which `flush_page_reset` will service, or an
            // entry that landed between the pop and its `onLoad`. Either way
            // the reset stays owed and is claimed there, not here.
            if app
                .get_page_stack()
                .iter()
                .any(|entry| entry == &instance_id)
            {
                return;
            }
            // Resolve by id: a same-path sibling may still be live on the
            // stack, and its presence must not shield this instance from its
            // own teardown.
            let Some(page) = app.get_page_by_instance_id_str(&instance_id) else {
                return;
            };
            let _transition = page.reset_transition_guard();
            if page.take_reset_pending() {
                app.teardown_page(&page);
            }
        }));
    }

    /// Cancels a pending reset, reporting whether one was outstanding.
    pub(crate) fn cancel_page_reset(&self, instance_id: &str) -> bool {
        let Ok(state) = self.state.lock() else {
            return false;
        };
        let cancel = state.page_reset_timers.lock().unwrap().remove(instance_id);
        match cancel {
            Some(cancel) => {
                let _ = cancel.send(());
                true
            }
            None => false,
        }
    }

    /// Settles the reset a page owes at the moment an entry lands on it.
    ///
    /// Entering a page again inside the delay window must still give the user
    /// a fresh instance — the deferred teardown is claimed here if the timer
    /// has not run, and the rebuild the teardown left owing is started. The
    /// entry's own `onLoad` is already requested by the caller; the fresh
    /// document's handshake releases it.
    pub(crate) fn flush_page_reset(&self, page: &PageInstance) {
        let _ = self.flush_page_reset_awaited(page);
    }

    /// Like [`Self::flush_page_reset`], but hands back a receiver that
    /// resolves once the rebuilt Logic service is registered — for in-Logic
    /// navigation, which must look the target's service up immediately after
    /// the flush. `None` means no rebuild was owed.
    pub(crate) fn flush_page_reset_awaited(
        &self,
        page: &PageInstance,
    ) -> Option<oneshot::Receiver<Result<(), String>>> {
        let _transition = page.reset_transition_guard();
        if page.take_reset_pending() {
            self.cancel_page_reset(&page.instance_id_string());
            self.teardown_page(page);
        }
        if page.take_reset_awaiting_entry() {
            Some(self.rebuild_page_on_entry(page))
        } else {
            None
        }
    }

    /// Ends the instance that left the stack, keeping its WebView warm.
    ///
    /// Order matters: cancelling bridge work first drops in-flight view calls
    /// (they would otherwise hang to their 15s timeout against a document that
    /// is about to be replaced), parking swaps the document for an inert blank
    /// one, and terminating closes the old service's channels and page event
    /// bus. Nothing is created here — the rebuild belongs to the next entry.
    fn teardown_page(&self, page: &PageInstance) {
        debug!(
            "Tearing down left page (instance {})",
            page.instance_id_string()
        )
        .with_appid(self.appid.clone())
        .with_path(page.path());
        page.prepare_for_service_restart();
        page.park_view();
        if let Err(err) = self.executor.terminate_page_svc(
            self.clone_arc(),
            page.path().to_string(),
            Some(page.instance_id_string()),
        ) {
            warn!(
                "Failed to terminate page service for {}: {}",
                page.path(),
                err
            )
            .with_appid(self.appid.clone());
        }
    }

    /// Rebuilds a torn-down page for the entry now standing on it: a fresh
    /// Logic service first — bound to this instance id — then the document,
    /// so the new
    /// document's handshake finds the new service.
    ///
    /// The returned receiver resolves after the service is registered and its
    /// document reload has been dispatched; document loading continues
    /// independently. This ordering keeps a caller's first view command from
    /// racing ahead of the reload into the parked document.
    fn rebuild_page_on_entry(&self, page: &PageInstance) -> oneshot::Receiver<Result<(), String>> {
        debug!(
            "Rebuilding page for entry (instance {})",
            page.instance_id_string()
        )
        .with_appid(self.appid.clone())
        .with_path(page.path());
        let (done_tx, done_rx) = oneshot::channel::<Result<(), String>>();
        let path = page.path().to_string();
        let (ack_tx, ack_rx) = oneshot::channel::<Result<(), String>>();
        if let Err(err) = self.executor.create_page_svc_with_ack(
            self.clone_arc(),
            path.clone(),
            Some(page.instance_id_string()),
            ack_tx,
        ) {
            warn!("Failed to recreate page service for {}: {}", path, err)
                .with_appid(self.appid.clone());
            let _ = done_tx.send(Err(err.to_string()));
            return done_rx;
        }

        let appid = self.appid.clone();
        let page = page.clone();
        std::mem::drop(crate::executor::spawn(async move {
            match ack_rx.await {
                Ok(Ok(())) => {
                    // load_html, not WebView::reload: the document came from
                    // loadHTMLString with a logical base URL, and a reload would
                    // fetch that URL's raw source, losing the bridge config and
                    // nonce.
                    let result = page.load_html().map_err(|err| {
                        warn!("Failed to reload {} for re-entry: {}", path, err).with_appid(appid);
                        err.to_string()
                    });
                    let _ = done_tx.send(result);
                }
                Ok(Err(err)) => {
                    warn!("Page service rebuild failed for {}: {}", path, err).with_appid(appid);
                    let _ = done_tx.send(Err(err));
                }
                Err(_) => {}
            }
        }));
        done_rx
    }

    fn cancel_all_page_resets(&self) {
        if let Ok(state) = self.state.lock() {
            let mut timers = state.page_reset_timers.lock().unwrap();
            for (_id, cancel) in timers.drain() {
                let _ = cancel.send(());
            }
        }
    }

    fn cancel_all_page_instance_dispose_timers(&self) {
        if let Ok(state) = self.state.lock() {
            let mut timers = state.page_instance_dispose_timers.lock().unwrap();
            for (_id, cancel) in timers.drain() {
                let _ = cancel.send(());
            }
        }
    }

    fn schedule_page_instance_dispose_timer(
        &self,
        id: &PageInstanceId,
        dispose_ttl: Duration,
    ) -> Result<(), LxAppError> {
        // When the TTL fires, the page is being reclaimed by the SDK because
        // it stayed hidden too long — not because the consumer asked for it.
        // Always carry `Reclaimed` so JS-side close listeners can distinguish
        // SDK-initiated cleanup from a user/programmatic close.
        let reclaim_reason = CloseReason::Reclaimed;
        if dispose_ttl.is_zero() {
            return self.dispose_page_instance_internal(id, reclaim_reason, false);
        }

        self.cancel_page_instance_dispose_timer(id);

        let (tx, rx) = oneshot::channel();
        if let Ok(state) = self.state.lock() {
            state
                .page_instance_dispose_timers
                .lock()
                .unwrap()
                .insert(id.to_string(), tx);
        }

        let appid = self.appid.clone();
        let page_instance_id = id.to_string();
        std::mem::drop(crate::executor::spawn(async move {
            let sleep = time::sleep(dispose_ttl);
            tokio::pin!(sleep);
            tokio::pin!(rx);
            tokio::select! {
                _ = &mut sleep => {}
                _ = &mut rx => return,
            }

            let Some(app) = crate::lxapp::try_get(&appid) else {
                return;
            };
            let Some(id) = PageInstanceId::parse(page_instance_id.clone()) else {
                return;
            };
            if let Err(err) = app.dispose_page_instance_internal(&id, reclaim_reason, false) {
                warn!(
                    "Delayed dispose failed for page instance {}: {}",
                    page_instance_id, err
                )
                .with_appid(appid);
            }
        }));

        Ok(())
    }

    fn refresh_page_instance_dispose_ttl(&self, id: &PageInstanceId) -> Result<(), LxAppError> {
        let (lifecycle, dispose_ttl) = {
            let state = self.state.lock().unwrap();
            let records = state.page_instance_runtime.lock().unwrap();
            let record = records.get(id.as_str()).ok_or_else(|| {
                LxAppError::ResourceNotFound(format!("page instance id: {}", id.as_str()))
            })?;
            (record.lifecycle, record.dispose_ttl)
        };

        if lifecycle != PageInstanceLifecycleState::Hidden {
            self.cancel_page_instance_dispose_timer(id);
            return Ok(());
        }

        if let Some(ttl) = dispose_ttl {
            self.schedule_page_instance_dispose_timer(id, ttl)?;
        } else {
            self.cancel_page_instance_dispose_timer(id);
        }

        Ok(())
    }

    // AppService state subscriptions removed for simplicity; rely on FIFO ordering.
    /// Shutdown this LxApp completely. Idempotent.
    ///
    /// Order:
    /// 1) Mark Closing to suppress page terminations
    /// 2) Close UI window
    /// 3) Break PageInstance↔WebView delegate links and clear pages
    /// 4) Destroy platform WebViews
    /// 5) Clear page stack and surfaces
    /// 6) Send TerminateAppSvc (receiver handles teardown)
    pub fn shutdown_with_options(&self, skip_hide: bool) -> Result<(), LxAppError> {
        self.session.cancel();
        // Mark closing to suppress TerminatePage from PageInstance drops
        self.set_status(LxAppSessionStatus::Closing);
        self.cancel_all_page_bridge_work();
        self.clear_transient_files();
        self.cancel_all_page_instance_dispose_timers();
        self.cancel_all_page_resets();
        self.close_all_surfaces(CloseReason::AppClosed);
        crate::lifecycle::key_events::clear(&self.appid, self.session.id);

        // Close UI window
        if !skip_hide {
            let _ = self
                .runtime
                .hide_lxapp(self.appid.clone(), self.session.id)
                .map_err(LxAppError::from);
        }

        // Collect current pages
        let pages = {
            let state = self.state.lock().unwrap();
            state
                .pages_by_id
                .lock()
                .unwrap()
                .values()
                .cloned()
                .collect::<Vec<_>>()
        };
        let page_webviews = pages
            .iter()
            .map(|page| (page.webtag(), page.webview()))
            .collect::<Vec<_>>();
        let page_instance_ids = pages
            .iter()
            .map(|page| page.instance_id_string())
            .collect::<Vec<_>>();
        crate::view_call::cancel_view_calls_for_page_instances(
            &page_instance_ids,
            "PageInstance removed while waiting for view response",
        );

        // Break PageInstance <-> WebView links early and detach WebViews, then drop pages by clearing the map
        for page in pages {
            page.detach_webview();
        }
        if let Ok(mut state) = self.state.lock() {
            state.pages_by_id.lock().unwrap().clear();
            if let Ok(mut pins) = state.path_pins.lock() {
                pins.clear();
            }
            state.page_instance_runtime.lock().unwrap().clear();
            state.page_chrome_layouts.clear();
        }
        for (webtag, webview) in &page_webviews {
            if let Some(webview) = webview {
                destroy_webview_if_matches(webtag, webview);
            }
        }
        let _ = self.clear_page_stack();
        // Terminate AppService (receiver handles its own state)
        let _ = self.executor.terminate_app_svc(self.clone_arc());
        self.app_launch_dispatched.store(false, Ordering::SeqCst);
        self.clear_open_region();
        Ok(())
    }

    pub fn shutdown(&self) -> Result<(), LxAppError> {
        self.shutdown_with_options(false)
    }

    fn _new(
        appid: String,
        runtime: Arc<Platform>,
        executor: Arc<LxAppWorkers>,
        release_type: Channel,
        app_session_class: AppSessionClass,
    ) -> Self {
        let session = LxAppSession::new();
        let bundle_source = lxapp_bundle_source_for(&appid).unwrap_or(LxAppBundleSource::Installed);
        // A dev-sourced bundle is a draft: served live from a local `dist`
        // and never installed or OTA-updated. Derive the channel from the
        // source so update gating and scope keys stay consistent.
        let release_type = match bundle_source {
            LxAppBundleSource::DevPath { .. } => Channel::Draft,
            _ => release_type,
        };
        Self {
            appid,
            runtime,
            lxapp_dir: PathBuf::new(),
            bundle_source,
            storage_file_path: PathBuf::new(),
            user_data_dir: PathBuf::new(),
            user_cache_dir: PathBuf::new(),
            temp_dir: PathBuf::new(),
            temp_cleanup_protection: None,
            usercache_cleanup_protection: None,
            fingermark: String::new(),
            is_home_lxapp: false,
            app_session_class,
            release_type,
            config: Mutex::new(LxAppConfig::default()),
            executor,
            host_permissions: permissions::HostPermissions::default(),
            home_update_check_dispatched: AtomicBool::new(false),
            app_launch_dispatched: AtomicBool::new(false),
            pending_restart_request: AtomicBool::new(false),
            shown: AtomicBool::new(true),
            hidden_since: Mutex::new(None),
            restart_closing_session: AtomicU64::new(0),
            logic_feature_snapshots: Mutex::new(Default::default()),
            session,
            logic_contexts: tokio::sync::watch::channel(0).0,
            admission: OnceLock::new(),
            state: Mutex::new(LxAppState::new()),
            presentation_open_lock: Mutex::new(()),
            page_chrome_mutation_lock: tokio::sync::Mutex::new(()),
            self_weak: OnceLock::new(),
            resource_grants: OnceLock::new(),
            resource_grants_claimed: std::sync::atomic::AtomicBool::new(false),
            document_start_scripts: Mutex::new(Vec::new()),
            page_scripts: Mutex::new(Vec::new()),
        }
    }

    /// Create a new regular mini-app (not home app)
    pub(crate) fn new(
        appid: String,
        runtime: Arc<Platform>,
        executor: Arc<LxAppWorkers>,
        release_type: Channel,
    ) -> Result<Self, LxAppError> {
        let mut app = Self::_new(
            appid,
            runtime,
            executor,
            release_type,
            AppSessionClass::StandardApp,
        );
        app.setup().inspect_err(|e| {
            error!("Setup failed: {}", e).with_appid(&app.appid);
        })?;
        Ok(app)
    }

    /// Create a new LxApp instance marked as the home lxapp
    fn new_as_home(
        appid: String,
        runtime: Arc<Platform>,
        executor: Arc<LxAppWorkers>,
    ) -> Result<Self, LxAppError> {
        let mut app = Self::_new(
            appid,
            runtime,
            executor,
            crate::default_channel(),
            AppSessionClass::ControlApp,
        );

        // Mark as home lxapp
        app.is_home_lxapp = true;

        app.setup().inspect_err(|e| {
            error!("Setup failed for home app: {}", e).with_appid(&app.appid);
        })?;
        app.state.lock().unwrap().startup_options.path = app.config().get_initial_route();
        Ok(app)
    }

    /// Create a host-bundled control surface. Unlike `new_as_home` the home flag
    /// stays false, so capsule close, LRU eviction, the home OTA check, and
    /// `lx.process` all treat it as an ordinary guest.
    fn new_control_surface(
        appid: String,
        runtime: Arc<Platform>,
        executor: Arc<LxAppWorkers>,
        release_type: Channel,
    ) -> Result<Self, LxAppError> {
        let mut app = Self::_new(
            appid,
            runtime,
            executor,
            release_type,
            AppSessionClass::ControlSurface,
        );
        app.setup().inspect_err(|e| {
            error!("Setup failed for control surface: {}", e).with_appid(&app.appid);
        })?;
        Ok(app)
    }

    #[cfg(test)]
    pub(crate) fn new_with_session_class_for_test(
        appid: String,
        runtime: Arc<Platform>,
        executor: Arc<LxAppWorkers>,
        class: AppSessionClass,
    ) -> Result<Self, LxAppError> {
        match class {
            AppSessionClass::StandardApp => Self::new(appid, runtime, executor, Channel::Release),
            AppSessionClass::ControlApp => Self::new_as_home(appid, runtime, executor),
            AppSessionClass::ControlSurface => {
                Self::new_control_surface(appid, runtime, executor, Channel::Release)
            }
        }
    }

    /// Approve public network and every privilege class, as home / default would.
    /// Test apps skip `setup`, so their grant would otherwise deny.
    #[cfg(test)]
    pub(crate) fn approve_unrestricted_permissions_for_test(&mut self) {
        self.host_permissions =
            permissions::HostPermissions::start(&self.appid, self.release_type.into(), true);
    }

    /// Leave the grant pending, as a cold registry lookup does, and hand back
    /// the handle that lands it.
    #[cfg(test)]
    pub(crate) fn defer_permissions_for_test(&mut self) -> permissions::DeferredGrant {
        let (pending, resolver) = permissions::HostPermissions::deferred();
        self.host_permissions = pending;
        resolver
    }

    #[cfg(test)]
    pub(crate) fn resource_grants_sealed_for_test(&self) -> bool {
        self.resource_grants.get().is_some()
    }

    /// Initialize paths and directories for the lxapp
    fn initialize_paths(&mut self) -> Result<(), LxAppError> {
        // Load metadata if available to determine version and install path
        let meta = metadata::get(&self.appid, self.release_type).ok().flatten();
        self.fingermark = meta
            .as_ref()
            .map(|record| record.fingermark.clone())
            .unwrap_or_else(|| lxapp_fingermark(&self.appid, self.release_type));
        let dir_name = self.fingermark.clone();
        // Set up app directory (default path)
        let base_dir = self
            .runtime
            .app_data_dir()
            .join(LINGXIA_DIR)
            .join(LXAPPS_DIR);
        self.lxapp_dir = base_dir.join(&dir_name);

        match &self.bundle_source {
            LxAppBundleSource::Installed => {
                if let Some(install_path) = meta
                    .as_ref()
                    .map(|record| record.install_path.trim())
                    .filter(|path| !path.is_empty())
                {
                    self.lxapp_dir = PathBuf::from(install_path);
                }
            }
            LxAppBundleSource::DevPath { root } => {
                info!("Using dev path for lxapp bundle: {}", root.display())
                    .with_appid(self.appid.clone());
                self.lxapp_dir = root.clone();
            }
            LxAppBundleSource::BuiltinAssets | LxAppBundleSource::Synthetic => {
                let usable_install = meta.as_ref().and_then(|record| {
                    let path = record.install_path.trim();
                    if path.is_empty() {
                        return None;
                    }
                    let dir = PathBuf::from(path);
                    dir.join("lxapp.json").is_file().then_some(dir)
                });
                // A catalog install must not stay pinned to bundled assets just
                // because a prior lookup registered the appid as builtin.
                if matches!(self.bundle_source, LxAppBundleSource::BuiltinAssets)
                    && !bundled_lxapp_asset_available(&self.appid)
                    && let Some(install_path) = usable_install
                {
                    self.bundle_source = LxAppBundleSource::Installed;
                    self.lxapp_dir = install_path;
                } else {
                    self.lxapp_dir = self
                        .runtime
                        .app_data_dir()
                        .join(LINGXIA_DIR)
                        .join("builtin")
                        .join(&dir_name);
                }
            }
        }

        // Compute storage file path: <data>/lingxia/storage/<fingermark>.redb
        self.storage_file_path = self
            .runtime
            .app_data_dir()
            .join(LINGXIA_DIR)
            .join(STORAGE_DIR)
            .join(format!("{}.redb", self.fingermark));

        // Set up userdata directory
        let userdata_base_dir = self
            .runtime
            .app_data_dir()
            .join(LINGXIA_DIR)
            .join(USER_DATA_DIR);

        self.user_data_dir = userdata_base_dir.join(&dir_name);
        if !self.user_data_dir.exists() {
            std::fs::create_dir_all(&self.user_data_dir).map_err(|e| {
                LxAppError::IoError(format!("Failed to create user data directory: {}", e))
            })?;
        }

        // Set up LingXia-managed user cache directory. This is intentionally under app data,
        // not the OS cache directory, because LingXia owns usercache cleanup policy.
        let cache_base_dir = self
            .runtime
            .app_data_dir()
            .join(LINGXIA_DIR)
            .join(USER_CACHE_DIR);

        self.user_cache_dir = cache_base_dir.join(&dir_name);
        // Claim before creating the directory, under the same lock as cleanup.
        self.usercache_cleanup_protection = Some(crate::cache::protect_from_cleanup([self
            .user_cache_dir
            .clone()]));
        if !self.user_cache_dir.exists() {
            std::fs::create_dir_all(&self.user_cache_dir).map_err(|e| {
                LxAppError::IoError(format!("Failed to create cache directory: {}", e))
            })?;
        }

        let temp_base_dir = self
            .runtime
            .app_cache_dir()
            .join(LINGXIA_DIR)
            .join(LXAPPS_DIR)
            .join(TEMP_DIR)
            .join(&dir_name);
        let _ = std::fs::create_dir_all(&temp_base_dir);
        if let Ok(entries) = std::fs::read_dir(&temp_base_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                let stale = path
                    .file_name()
                    .and_then(|name| name.to_str())
                    .is_some_and(|name| name != self.session_id().to_string());
                if stale && path.is_dir() && !crate::cache::is_protected_from_cleanup(&path) {
                    let _ = std::fs::remove_dir_all(path);
                }
            }
        }
        self.temp_dir = temp_base_dir.join(self.session_id().to_string());
        self.temp_cleanup_protection =
            Some(crate::cache::protect_from_cleanup([self.temp_dir.clone()]));
        if !self.temp_dir.exists() {
            std::fs::create_dir_all(&self.temp_dir).map_err(|e| {
                LxAppError::IoError(format!("Failed to create temp directory: {}", e))
            })?;
        }

        Ok(())
    }

    /// Load and parse lxapp.json configuration
    pub fn load_config(&mut self) -> Result<(), LxAppError> {
        self.apply_lxapp_json(true)
    }

    /// Re-read `lxapp.json` from the live bundle. Dev reload uses this so
    /// `pages` / `tabBar` edits apply without a new `lingxia dev` session.
    pub(crate) fn reload_manifest(&self) -> Result<(), LxAppError> {
        if matches!(self.bundle_source, LxAppBundleSource::Synthetic) {
            return Ok(());
        }
        self.apply_lxapp_json(false)
    }

    fn apply_lxapp_json(&self, first_load: bool) -> Result<(), LxAppError> {
        let lxapp_json_path = self.lxapp_dir.join("lxapp.json");
        info!(
            " [{}] Loading lxapp.json from: {}",
            self.appid,
            lxapp_json_path.display()
        );

        let app_json = self.read_json("lxapp.json")?;
        let config = LxAppConfig::from_value(app_json)
            .map_err(|e| LxAppError::InvalidJsonFile(format!("lxapp.json: {}", e)))?;

        // An absent `appId` is not a claim to be another app, and failing
        // the load would leave an installed package with no way back: the
        // instance never comes up, so the update that replaces it never runs.
        if !config.appId.is_empty() && config.appId != self.appid {
            return Err(LxAppError::InvalidJsonFile(format!(
                "lxapp.json appId '{}' does not match the host-selected application '{}'",
                config.appId, self.appid
            )));
        }

        // Install refuses a downloaded package below its floor, so reaching
        // here means a bundled or already-committed one: refusing the load
        // would leave no instance to run the update that replaces it.
        if let Err(error) = config.ensure_runtime_satisfies(&self.appid, crate::SDK_RUNTIME_VERSION)
        {
            error!("Loading despite runtime floor: {}", error).with_appid(self.appid.clone());
        }

        let mut tabbar = config
            .tabBar
            .as_ref()
            .map(|tabbar| tabbar.with_absolute_paths(&self.lxapp_dir));
        if !first_load && let Some(tabbar) = tabbar.as_mut() {
            // `with_absolute_paths` always starts at Home. In-place reload
            // keeps the current page, so re-select that tab (or clear if the
            // page is no longer in the bar).
            let previous = self.get_tabbar();
            if let Some(path) = self.peek_current_page_path() {
                if let Some(index) = tabbar.find_index_by_path(&path) {
                    tabbar.set_selected_index(index);
                } else {
                    tabbar.clear_selected_index();
                }
            } else if let Some(previous) = previous.as_ref() {
                if previous.selected_index < 0 {
                    tabbar.clear_selected_index();
                } else {
                    tabbar.set_selected_index(previous.selected_index);
                }
            }
        }
        let preference = config.appearance;
        let resolved = page_chrome::resolve_appearance(preference);
        *self
            .config
            .lock()
            .unwrap_or_else(|error| error.into_inner()) = config;

        {
            let mut state = self.state.lock().unwrap();
            state.tabbar = tabbar;
            if first_load {
                state.appearance = LxAppAppearanceState {
                    preference,
                    resolved,
                    revision: 0,
                };
            } else {
                state.appearance.preference = preference;
                state.appearance.resolved = resolved;
            }
        }
        self.runtime
            .apply_lxapp_appearance(&self.appid, resolved.is_dark())?;
        if first_load {
            self.document_start_scripts.lock().unwrap().push(Arc::from(
                page_chrome::bootstrap_script(&EffectivePageChromeLayout::default(), resolved),
            ));
        }
        Ok(())
    }

    /// Re-read each live page's JSON so `navigationStyle` and the rest of the
    /// native chrome follow a reload.
    fn refresh_live_page_config(&self) {
        for page in self.live_page_instances() {
            page.apply_reloaded_page_json(self);
        }
    }

    /// Initialize paths and load configuration
    fn setup(&mut self) -> Result<(), LxAppError> {
        self.initialize_paths()?;
        if matches!(self.bundle_source, LxAppBundleSource::Synthetic) {
            // No `lxapp.json` to read. The default `LxAppConfig.logic = None` resolves to
            // `Some("logic.js")` (documented default for normal lxapps); force it off so
            // `logic_enabled()` / `logic_entry_source` don't spin up JS workers we have
            // no source for.
            self.config().logic = Some(LxAppLogicEntry::Enabled(false));
        } else {
            self.load_config()?;
            self.host_permissions = permissions::HostPermissions::start(
                &self.appid,
                self.release_type.into(),
                self.is_home_lxapp && !is_runner(),
            );
        }
        Ok(())
    }

    /// Get the current installed version of this app variant from storage
    pub fn current_version(&self) -> String {
        metadata::get(&self.appid, self.release_type)
            .ok()
            .flatten()
            .map(|record| record.version_string())
            .filter(|version| !version.is_empty())
            .unwrap_or_else(|| DEFAULT_VERSION.to_string())
    }

    pub fn logic_enabled(&self) -> bool {
        self.config().logic_entry().is_some()
    }

    #[cfg(feature = "js-appservice")]
    pub async fn logic_entry_source(&self, ctx: &JSContext) -> JSResult<Option<Source>> {
        let Some(entry) = self.config().logic_entry() else {
            return Ok(None);
        };
        if Path::new(&entry).extension().and_then(|ext| ext.to_str()) != Some("js") {
            return Err(HostError::new(
                rong::error::E_NOT_SUPPORTED,
                format!("lxapp logic entry must be a .js file: {}", entry),
            )
            .into());
        }

        match &self.bundle_source {
            LxAppBundleSource::Installed | LxAppBundleSource::DevPath { .. } => {
                let source_path = self.lxapp_dir.join(&entry);
                Source::from_path(ctx, &source_path).await.map(Some)
            }
            LxAppBundleSource::Synthetic => unreachable!(
                "synthetic lxapp {} forces logic=false at setup(); logic_entry() must be None",
                self.appid
            ),
            LxAppBundleSource::BuiltinAssets => {
                let asset_path = format!(
                    "{}/{}",
                    self.appid.trim_end_matches('/'),
                    entry.trim_start_matches('/')
                );
                let mut reader = self.runtime.read_asset(&asset_path).map_err(|err| {
                    HostError::new(
                        rong::error::E_NOT_FOUND,
                        format!("builtin lxapp logic not found: {} ({})", asset_path, err),
                    )
                })?;
                let mut data = Vec::new();
                reader.read_to_end(&mut data).map_err(|err| {
                    HostError::new(
                        rong::error::E_IO,
                        format!(
                            "failed to read builtin lxapp logic: {} ({})",
                            asset_path, err
                        ),
                    )
                })?;
                Ok(Some(Source::from_bytes(data).with_name(asset_path)))
            }
        }
    }

    pub fn get_app_orientation(&self) -> OrientationConfig {
        let state = self.state.lock().unwrap();
        state.orientation_override.unwrap_or_default()
    }

    pub fn set_app_orientation(&self, orientation: OrientationConfig) {
        let orientation = OrientationConfig::normalize(orientation.mode, orientation.rotation);
        let mut state = self.state.lock().unwrap();
        state.orientation_override = Some(orientation);
    }

    /// Get resolved orientation for a page; falls back to app-level config.
    pub fn get_page_orientation(&self, path: &str) -> OrientationConfig {
        let app_orientation = self.get_app_orientation();
        let page_override = self
            .get_page(path)
            .and_then(|page| page.get_orientation_override())
            .unwrap_or_default();
        page_override.apply(app_orientation)
    }

    // Reads binary data from the specified relative path
    fn read_bytes(&self, relative_path: &str) -> Result<Vec<u8>, LxAppError> {
        if matches!(self.bundle_source, LxAppBundleSource::Synthetic) {
            return Err(LxAppError::ResourceNotFound(format!(
                "{relative_path}: synthetic lxapp host {} has no on-disk content",
                self.appid
            )));
        }
        let plugins = self.config().plugins.clone();
        let file_path = match crate::plugin::resolve_plugin_resource_path_from_internal_path(
            &self.runtime,
            &plugins,
            relative_path,
        )? {
            Some(path) => path,
            None => {
                if matches!(self.bundle_source, LxAppBundleSource::BuiltinAssets) {
                    let asset_path = format!(
                        "{}/{}",
                        self.appid.trim_end_matches('/'),
                        relative_path.trim_start_matches('/')
                    );
                    let mut reader = self.runtime.read_asset(&asset_path).map_err(|e| {
                        LxAppError::ResourceNotFound(format!(
                            "{relative_path}:{e} (asset: {asset_path})"
                        ))
                    })?;
                    let mut data = Vec::new();
                    reader.read_to_end(&mut data).map_err(|e| {
                        LxAppError::ResourceNotFound(format!(
                            "{relative_path}:{e} (asset: {asset_path})"
                        ))
                    })?;
                    return Ok(data);
                }
                self.lxapp_dir.join(relative_path)
            }
        };

        // Try to read from the filesystem
        fs::read(&file_path).map_err(|e| {
            LxAppError::ResourceNotFound(format!(
                "{}:{} (resolved: {})",
                relative_path,
                e,
                file_path.display()
            ))
        })
    }

    /// Resolve an "allowed" lxapp path (package dir, user data, user cache) to a physical path.
    ///
    /// Installed resources use logical mapping and prefix validation. Built-in package
    /// resources are materialized into the app cache for native filesystem consumers.
    pub fn resolve_accessible_path(&self, path: &str) -> Result<PathBuf, LxAppError> {
        let path = path.trim();
        if path.is_empty() {
            return Err(LxAppError::ResourceNotFound("empty path".to_string()));
        }

        // 1. Handle lx:// URIs (Internal helper already does logical joining and ".." check)
        if path.starts_with("lx://") {
            let lx_uri = uri::LxUri::from_str(path)
                .map_err(|e| LxAppError::InvalidParameter(format!("invalid lx uri: {}", e)))?;
            return self.resolve_lx_path_uri(&lx_uri);
        }

        let path_ref = Path::new(path);

        // 2. A network URL is the one wrong answer worth naming. It trips the
        // traversal rule below purely because it contains a colon, and being
        // told a URL is directory traversal sends the caller hunting for a path
        // bug that is not there. Native chrome cannot fetch, so the remedy is
        // always the same and belongs in the message.
        if let Some(scheme) = uri::network_scheme(path) {
            return Err(LxAppError::InvalidParameter(format!(
                "{scheme} URLs are not supported here: download the file first \
                 (for example with lx.downloadFile) and pass the returned lx:// path"
            )));
        }

        // 3. Prevent traversal for relative logical paths on every platform,
        // and catch native parent components in absolute chooser paths.
        if path_ref
            .components()
            .any(|component| matches!(component, std::path::Component::ParentDir))
            || (!path_ref.is_absolute() && uri::has_invalid_segment(path))
        {
            return Err(LxAppError::ResourceNotFound(
                "directory traversal not allowed".to_string(),
            ));
        }

        // 4. Handle Relative path: search in order user data -> user cache -> package
        if !path_ref.is_absolute() && !path.contains(':') {
            let rel = path.trim_start_matches('/');

            // In a simple logical resolve, we prioritize user data for relative paths
            // or we could stick to a specific root. Here we check existence only for
            // relative path "discovery" if we want to maintain the old search behavior,
            // otherwise we default to a specific root.

            // To keep it simple and predictable for "creation", relative paths
            // without lx:// prefix are resolved against the app bundle root by default.
            if matches!(self.bundle_source, LxAppBundleSource::BuiltinAssets) {
                return self.materialize_builtin_resource(rel);
            }
            return Ok(self.lxapp_dir.join(rel));
        }

        // 5. Handle Absolute paths: Must start with one of the trusted roots.
        //
        // On Apple platforms, the same sandbox path may appear with different
        // spellings (for example `/var/...` vs `/private/var/...`). When the
        // target exists, compare canonicalized paths as well so chooser-returned
        // absolute paths remain accessible.
        let trusted_roots = [
            (&self.lxapp_dir, "app bundle"),
            (&self.user_data_dir, "user data"),
            (&self.user_cache_dir, "user cache"),
            (&self.temp_dir, "temp"),
        ];

        let resolved_target = std::fs::canonicalize(path_ref).ok();

        for (root, _name) in trusted_roots {
            if root.as_os_str().is_empty() {
                continue;
            }
            if path_ref.starts_with(root) {
                if let Some(target) = resolved_target.as_ref()
                    && let Ok(canonical_root) = std::fs::canonicalize(root)
                {
                    if target.starts_with(&canonical_root) {
                        return Ok(target.to_path_buf());
                    }
                    continue;
                }
                return Ok(path_ref.to_path_buf());
            }
            if let (Some(target), Ok(canonical_root)) =
                (resolved_target.as_ref(), std::fs::canonicalize(root))
                && target.starts_with(&canonical_root)
            {
                return Ok(target.to_path_buf());
            }
        }

        Err(LxAppError::ResourceNotFound(format!(
            "Access denied: {}",
            path
        )))
    }

    fn materialize_builtin_resource(&self, relative: &str) -> Result<PathBuf, LxAppError> {
        let data = self.read_bytes(relative)?;
        let destination = self.user_cache_dir.join("native-resources").join(relative);
        let parent = destination.parent().ok_or_else(|| {
            LxAppError::InvalidParameter(format!(
                "native resource has no parent: {}",
                destination.display()
            ))
        })?;
        fs::create_dir_all(parent).map_err(|err| {
            LxAppError::IoError(format!("failed to create {}: {err}", parent.display()))
        })?;
        fs::write(&destination, data).map_err(|err| {
            LxAppError::IoError(format!("failed to write {}: {err}", destination.display()))
        })?;
        Ok(destination)
    }

    pub fn to_uri(&self, path: &Path) -> Option<uri::LxUri> {
        if !self.temp_dir.as_os_str().is_empty() && path.starts_with(&self.temp_dir) {
            return self.register_temp_file(path).ok();
        }
        uri::try_convert_path_to_uri(path, self)
    }

    fn resolve_lx_path_uri(&self, lx_uri: &uri::LxUri) -> Result<PathBuf, LxAppError> {
        let uri = HttpUri::from_str(lx_uri.as_str())
            .map_err(|_| LxAppError::InvalidParameter("invalid lx uri".to_string()))?;

        if uri.scheme_str() != Some(uri::LX_SCHEME) {
            return Err(LxAppError::InvalidParameter(
                "invalid lx uri scheme".to_string(),
            ));
        }

        match uri.host() {
            Some(uri::HOST_TEMP) => {
                if uri.query().is_some() {
                    return Err(LxAppError::ResourceNotFound(lx_uri.as_str().to_string()));
                }
                let token = uri.path().trim_matches('/');
                if token.is_empty() || token.contains('/') || token.contains('\\') {
                    return Err(LxAppError::ResourceNotFound(lx_uri.as_str().to_string()));
                }
                self.resolve_transient_file(token).ok_or_else(|| {
                    LxAppError::ResourceNotFound(format!(
                        "temporary file grant not found: {}",
                        lx_uri.as_str()
                    ))
                })
            }
            Some(uri::HOST_USER_CACHE) | Some(uri::HOST_USER_DATA) => {
                let base_dir = match uri.host() {
                    Some(uri::HOST_USER_CACHE) => &self.user_cache_dir,
                    Some(uri::HOST_USER_DATA) => &self.user_data_dir,
                    _ => unreachable!(),
                };

                let decoded_path = uri::decode_lx_path(uri.path());
                let rel = decoded_path.trim_matches('/');
                if rel.is_empty() {
                    return Ok(base_dir.clone());
                }
                if uri::has_invalid_segment(rel) || rel.contains(':') || rel.contains('\\') {
                    return Err(LxAppError::ResourceNotFound(lx_uri.as_str().to_string()));
                }

                Ok(base_dir.join(rel))
            }
            Some(uri::HOST_LXAPP) => {
                let decoded_path = uri::decode_lx_path(uri.path());
                let raw = decoded_path.trim_start_matches('/');
                let (appid, rest) = raw
                    .split_once('/')
                    .ok_or_else(|| LxAppError::ResourceNotFound(lx_uri.as_str().to_string()))?;
                if appid != self.appid.as_str() {
                    return Err(LxAppError::ResourceNotFound(lx_uri.as_str().to_string()));
                }

                let rel = rest.trim_matches('/');
                if rel.is_empty() {
                    return Err(LxAppError::ResourceNotFound(lx_uri.as_str().to_string()));
                }
                if uri::has_invalid_segment(rel) || rel.contains(':') || rel.contains('\\') {
                    return Err(LxAppError::ResourceNotFound(lx_uri.as_str().to_string()));
                }

                if matches!(self.bundle_source, LxAppBundleSource::BuiltinAssets) {
                    self.materialize_builtin_resource(rel)
                } else {
                    Ok(self.lxapp_dir.join(rel))
                }
            }
            _ => Err(LxAppError::ResourceNotFound(format!(
                "unsupported lx uri host: {}",
                lx_uri.as_str()
            ))),
        }
    }

    /// Reads text content from the specified relative path
    fn read_text(&self, relative_path: &str) -> Result<String, LxAppError> {
        self.read_bytes(relative_path)
            .map(|content| String::from_utf8_lossy(&content).to_string())
    }

    /// Reads and parses JSON content from the specified relative path
    pub(crate) fn read_json(&self, relative_path: &str) -> Result<serde_json::Value, LxAppError> {
        self.read_text(relative_path).and_then(|content| {
            serde_json::from_str(&content)
                .map_err(|_| LxAppError::InvalidJsonFile(relative_path.to_string()))
        })
    }

    pub fn is_opened(&self) -> bool {
        matches!(self.status(), LxAppSessionStatus::Opened)
    }

    pub(crate) fn is_shown(&self) -> bool {
        self.shown.load(Ordering::SeqCst)
    }

    pub(crate) fn mark_hidden(&self) {
        if self.shown.swap(false, Ordering::SeqCst)
            && let Ok(mut since) = self.hidden_since.lock()
        {
            *since = Some(Instant::now());
        }
    }

    pub(crate) fn hidden_since(&self) -> Option<Instant> {
        self.hidden_since.lock().ok().and_then(|since| *since)
    }

    pub(crate) fn document_start_scripts_snapshot(&self) -> Vec<Arc<str>> {
        self.document_start_scripts
            .lock()
            .map(|scripts| scripts.clone())
            .unwrap_or_default()
    }

    /// Snapshot page scripts for a new PageInstance.
    pub(crate) fn page_scripts_snapshot(&self) -> Vec<Arc<str>> {
        self.page_scripts
            .lock()
            .map(|scripts| scripts.clone())
            .unwrap_or_default()
    }

    /// Hosts apply this list to island media URLs (`src` / `poster` / quality / commands).
    pub fn trusted_network_domains(&self) -> Vec<String> {
        self.host_permissions.domains()
    }

    pub(crate) fn permissions_ready(&self) -> bool {
        self.host_permissions.is_ready()
    }

    /// Wait for this instance's permission decision, including a deny on failure.
    /// Native hosts can await this before invoking network-dependent code.
    /// Native resource grants are sealed from that snapshot, not from pending deny.
    pub async fn wait_permissions_ready(&self) {
        self.host_permissions.wait_ready().await;
        if let Some(app) = self.self_weak.get().and_then(Weak::upgrade) {
            crate::host::seal_app_resource_grants(&app);
        }
    }

    /// Check if a domain is allowed for network access
    pub fn is_domain_allowed(&self, domain: &str) -> bool {
        self.host_permissions
            .is_domain_allowed(domain, crate::is_dev_session())
    }

    /// Whether this instance may use a high-risk capability class.
    ///
    /// Home, and a guest with no provider, allow every class. A registered
    /// provider's privilege allowlist is the only restriction. Ordinary APIs
    /// such as camera, media and location stay on host/platform flows.
    pub fn has_security_privilege(&self, privilege: &LxAppSecurityPrivilege) -> bool {
        self.host_permissions.allows_privilege(privilege.as_str())
    }

    /// Take the right to resolve this session's grants. Only the first caller
    /// gets it.
    pub(crate) fn claim_resource_grant_seal(&self) -> bool {
        use std::sync::atomic::Ordering;
        self.resource_grants_claimed
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_ok()
    }

    pub(crate) fn resource_grants_claimed(&self) -> bool {
        self.resource_grants_claimed
            .load(std::sync::atomic::Ordering::Acquire)
    }

    pub(crate) fn seal_resource_grants(&self, grants: HashSet<crate::host::AppResourceGrant>) {
        let _ = self.resource_grants.set(grants);
    }

    /// Whether this live native session owns a sealed privileged resource.
    pub fn has_resource_grant(&self, grant: crate::host::AppResourceGrant) -> bool {
        matches!(
            self.status(),
            LxAppSessionStatus::Opening | LxAppSessionStatus::Opened
        ) && self
            .resource_grants
            .get()
            .is_some_and(|grants| grants.contains(&grant))
    }

    /// Resolve a path to its live page instance.
    ///
    /// Identity lives in the instance id; a path is route metadata. The path
    /// resolves to, in order: the topmost stack entry on that route, the
    /// path-pinned singleton (tab pages, headless services), and finally an
    /// off-stack cached instance (a page that left the stack and is parked
    /// for re-entry). Surface-isolated instances never resolve by path.
    pub fn get_page(&self, path: &str) -> Option<PageInstance> {
        let state = self.state.lock().ok()?;
        let pages_by_id = state.pages_by_id.lock().ok()?;

        if let Ok(stack) = state.page_stack.lock() {
            for id in stack.iter().rev() {
                if let Some(page) = pages_by_id.get(id)
                    && page.path() == path
                {
                    return Some(page.clone());
                }
            }
        }

        if let Ok(pins) = state.path_pins.lock()
            && let Some(id) = pins.get(path)
            && let Some(page) = pages_by_id.get(id)
        {
            return Some(page.clone());
        }

        pages_by_id
            .values()
            .filter(|page| !page.is_isolated() && page.path() == path)
            .max_by_key(|page| page.get_last_active_time())
            .cloned()
    }

    /// Whether the route has a live surface-isolated instance. Those never
    /// resolve by bare path, so a path-keyed report naming one is unaddressable
    /// rather than wrong — the owning surface drives that instance through
    /// `notify_page_instance`.
    pub(crate) fn has_isolated_page(&self, path: &str) -> bool {
        let Ok(state) = self.state.lock() else {
            return false;
        };
        let Ok(pages_by_id) = state.pages_by_id.lock() else {
            return false;
        };
        pages_by_id
            .values()
            .any(|page| page.is_isolated() && page.path() == path)
    }

    /// The path's pinned singleton instance, when one is registered.
    pub(crate) fn pinned_page(&self, path: &str) -> Option<PageInstance> {
        let state = self.state.lock().ok()?;
        let id = state.path_pins.lock().ok()?.get(path)?.clone();
        state.pages_by_id.lock().ok()?.get(&id).cloned()
    }

    /// The most recently active off-stack instance on the route — the warm
    /// re-entry candidate. Instances currently on the stack are excluded.
    pub(crate) fn most_recent_off_stack_page(&self, path: &str) -> Option<PageInstance> {
        let state = self.state.lock().ok()?;
        let stack_ids: std::collections::HashSet<String> =
            state.page_stack.lock().ok()?.iter().cloned().collect();
        state
            .pages_by_id
            .lock()
            .ok()?
            .values()
            .filter(|page| {
                !page.is_isolated()
                    && page.path() == path
                    && !stack_ids.contains(&page.instance_id_string())
            })
            .max_by_key(|page| page.get_last_active_time())
            .cloned()
    }

    /// Pin a page instance as the path's singleton (tab pages, headless
    /// services): it stays resolvable by path while off the stack.
    pub(crate) fn pin_page_path(&self, page: &PageInstance) {
        if let Ok(state) = self.state.lock()
            && let Ok(mut pins) = state.path_pins.lock()
        {
            pins.insert(page.path(), page.instance_id_string());
        }
    }

    pub fn get_page_by_instance_id(&self, id: &PageInstanceId) -> Option<PageInstance> {
        self.get_page_by_instance_id_str(id.as_str())
    }

    pub fn get_page_by_instance_id_str(&self, id: &str) -> Option<PageInstance> {
        self.state
            .lock()
            .unwrap()
            .pages_by_id
            .lock()
            .unwrap()
            .get(id)
            .cloned()
    }

    pub(crate) fn cancel_all_page_bridge_work(&self) {
        let pages = {
            let state = self.state.lock().unwrap();
            state
                .pages_by_id
                .lock()
                .unwrap()
                .values()
                .cloned()
                .collect::<Vec<_>>()
        };
        for page in pages {
            page.cancel_bridge_work();
        }
    }

    pub fn page_instance_id_for_path(&self, path: &str) -> Option<String> {
        self.get_page(path).map(|page| page.instance_id_string())
    }

    pub fn initial_route(&self) -> String {
        self.config().get_initial_route()
    }

    /// Ensure the JS app service worker is running for this app.
    pub fn ensure_app_service_running(&self) -> Result<(), LxAppError> {
        self.executor.create_app_svc(self.clone_arc())
    }

    /// Dispatch `App.onLaunch` once for the current worker-backed app instance.
    /// The worker creation and event messages share one FIFO queue, so callers
    /// may invoke this immediately after `ensure_app_service_running`.
    pub fn ensure_app_launch_dispatched(&self) -> Result<(), LxAppError> {
        if self
            .app_launch_dispatched
            .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
            .is_err()
        {
            return Ok(());
        }
        let payload = self
            .state
            .lock()
            .unwrap_or_else(|err| err.into_inner())
            .startup_options
            .launch_options_json();
        if let Err(error) = self.appservice_notify(AppServiceEvent::OnLaunch, Some(payload)) {
            self.app_launch_dispatched.store(false, Ordering::SeqCst);
            return Err(error);
        }
        // Cold AppLink is delivered once via onLaunch. Clear so the following
        // onShow is not a second `scene === 8003` hop.
        self.consume_app_link_scene();
        Ok(())
    }

    /// Restart the app service without closing the host surface or recreating
    /// the LxApp instance. Dev runners use this for an in-place lxapp restart:
    /// logic is recreated, while the existing window/frame stays put.
    pub fn restart_app_service_in_place(&self) -> Result<(), LxAppError> {
        self.executor.restart_app_svc(self.clone_arc())?;
        self.app_launch_dispatched.store(false, Ordering::SeqCst);
        // Re-run onLaunch so app-service state (globalData, network init) is
        // rebuilt. onLaunch normally fires only during open(); an in-place
        // restart skips that lifecycle, so fire it explicitly. It is enqueued
        // before the page reload, so the reloaded page's first globalData read
        // (which arrives only after the page re-loads) observes the fresh state.
        self.ensure_app_launch_dispatched()
    }

    /// Reload the current page's WebView in place (without recreating the host
    /// window), so a dev "restart" reloads the page rather than flashing the
    /// screen. Errors when the page stack is empty or its WebView is not ready.
    pub fn reload_current_page(&self) -> Result<(), LxAppError> {
        self.current_page()?
            .webview()
            .ok_or_else(|| LxAppError::WebView("page WebView is not ready".to_string()))?
            .reload()
            .map_err(LxAppError::from)
    }

    /// In-place restart: recreate the JS app service, rebuild the live page
    /// services, then regenerate HTML in their retained WebViews — without closing or
    /// recreating the host surface.
    /// The steps belong together: restarting the app service alone leaves the
    /// page bound to the terminated worker, and reloading without rebuilding the
    /// page services drops the page's bridge messages ("page service not
    /// loaded"). Reloading waits for every new PageSvc acknowledgement so a
    /// fast WebView cannot send its ready handshake before the service exists.
    pub fn restart_in_place(&self) -> Result<(), LxAppError> {
        let pending = self.begin_in_place_restart()?;
        let appid = self.appid.clone();
        std::mem::drop(crate::executor::spawn(async move {
            if let Err(error) = Self::finish_in_place_restart(pending).await {
                error!("Failed to finish in-place lxapp restart: {error}").with_appid(appid);
            }
        }));
        Ok(())
    }

    /// Awaitable form used by devtools, which must not report success before
    /// the retained page has completed the new document load.
    pub async fn restart_in_place_and_wait(&self) -> Result<(), LxAppError> {
        let pending = self.begin_in_place_restart()?;
        Self::finish_in_place_restart(pending).await
    }

    fn begin_in_place_restart(&self) -> Result<Vec<PendingPageServiceRestart>, LxAppError> {
        self.restart_app_service_in_place()?;
        self.reload_manifest()?;
        self.refresh_live_page_config();
        self.sync_host_ui();
        self.recreate_retained_page_services(false)
    }

    fn recreate_retained_page_services(
        &self,
        include_isolated: bool,
    ) -> Result<Vec<PendingPageServiceRestart>, LxAppError> {
        let pages: Vec<PageInstance> = {
            let state = self
                .state
                .lock()
                .map_err(|_| LxAppError::Runtime("lxapp state lock poisoned".to_string()))?;
            let pages_by_id = state
                .pages_by_id
                .lock()
                .map_err(|_| LxAppError::Runtime("page registry lock poisoned".to_string()))?;
            pages_by_id.values().cloned().collect()
        };
        let mut pending = Vec::with_capacity(pages.len());
        for page in pages {
            if !include_isolated && page.is_isolated() {
                continue;
            }
            {
                let _transition = page.reset_transition_guard();
                page.prepare_for_service_restart();
            }
            let (ack_tx, ack_rx) = oneshot::channel::<Result<(), String>>();
            self.executor.create_page_svc_with_ack(
                self.clone_arc(),
                page.path().to_string(),
                Some(page.instance_id_string()),
                ack_tx,
            )?;
            pending.push((page, ack_rx));
        }
        Ok(pending)
    }

    async fn finish_in_place_restart(
        pending: Vec<PendingPageServiceRestart>,
    ) -> Result<(), LxAppError> {
        let mut pages = Vec::with_capacity(pending.len());
        for (page, ack_rx) in pending {
            let result = ack_rx.await;
            let app = page.owning_lxapp();
            if app.session.is_cancelled()
                || app
                    .get_page_by_instance_id_str(&page.instance_id_string())
                    .is_none()
            {
                continue;
            }
            result
                .map_err(|_| LxAppError::Runtime("page service restart cancelled".to_string()))?
                .map_err(LxAppError::Runtime)?;
            pages.push(page);
        }
        for page in pages {
            if page
                .owning_lxapp()
                .get_page_by_instance_id_str(&page.instance_id_string())
                .is_none()
                || page.webview_controller().is_none()
                || page.document_is_departing()
            {
                continue;
            }
            // These pages originate from loadHTMLString + a logical base URL.
            // WebView::reload would request that base URL's raw source and skip
            // generate_page_html, losing the bridge config and nonce.
            page.load_html()?;
        }
        Ok(())
    }

    /// Drain the old worker before the Runner publishes a different capability environment.
    pub(crate) async fn quiesce_for_device_change(&self) -> Result<(), LxAppError> {
        let mut contexts = self.logic_contexts.subscribe();
        self.executor.terminate_app_svc(self.clone_arc())?;
        tokio::time::timeout(Duration::from_secs(10), async {
            while *contexts.borrow_and_update() != 0 {
                contexts
                    .changed()
                    .await
                    .map_err(|_| LxAppError::Runtime("Logic shutdown observer closed".into()))?;
            }
            Ok::<_, LxAppError>(())
        })
        .await
        .map_err(|_| LxAppError::Runtime("timed out draining Logic for device change".into()))?
    }

    /// Recreate every retained PageSvc, including isolated surface pages.
    pub(crate) async fn resume_after_device_change(&self) -> Result<(), LxAppError> {
        if self.session.is_cancelled() {
            return Ok(());
        }
        self.ensure_app_service_running()?;
        self.app_launch_dispatched.store(false, Ordering::SeqCst);
        self.ensure_app_launch_dispatched()?;
        // A device transition must rebuild isolated surface pages too.
        let pending = self.recreate_retained_page_services(true)?;
        let pages = pending
            .iter()
            .map(|(page, _)| page.clone())
            .collect::<Vec<_>>();
        tokio::time::timeout(Duration::from_secs(30), async {
            // Also acknowledge worker startup when this app has no page services.
            self.executor
                .eval_app_service(self.clone_arc(), "return true;".into(), false)
                .await?;
            Self::finish_in_place_restart(pending).await?;
            loop {
                if self.session.is_cancelled() {
                    return Ok(());
                }
                let mut ready = true;
                for page in &pages {
                    // A surface closed during the transition has no document to await.
                    if self
                        .get_page_by_instance_id_str(&page.instance_id_string())
                        .is_none()
                        || page.webview_controller().is_none()
                        || page.document_is_departing()
                    {
                        continue;
                    }
                    let state = page.automation_state();
                    if let Some(error) = state.webview_error {
                        return Err(LxAppError::Runtime(error));
                    }
                    // Hidden/preloaded documents cannot dispatch onReady until shown.
                    ready &= state.webview_ready
                        && state.bridge_ready
                        && state.render_state == "finished";
                }
                if ready {
                    return Ok(());
                }
                tokio::time::sleep(Duration::from_millis(25)).await;
            }
        })
        .await
        .map_err(|_| LxAppError::Runtime("timed out restoring pages after device change".into()))?
    }

    /// Clears this lxapp's user cache directory, recreating it empty. Dev
    /// runners and the shell "clean cache" action use this before an in-place
    /// restart.
    pub fn clear_user_cache(&self) -> Result<(), LxAppError> {
        if self.user_cache_dir.exists() {
            std::fs::remove_dir_all(&self.user_cache_dir).map_err(|err| {
                LxAppError::IoError(format!(
                    "failed to remove {}: {err}",
                    self.user_cache_dir.display()
                ))
            })?;
        }
        std::fs::create_dir_all(&self.user_cache_dir).map_err(|err| {
            LxAppError::IoError(format!(
                "failed to recreate {}: {err}",
                self.user_cache_dir.display()
            ))
        })
    }

    /// Remove a page instance whose setup failed: it never became usable and
    /// must not stay resolvable.
    fn remove_failed_page(&self, page: &PageInstance) {
        let id = page.instance_id_string();
        if let Ok(state) = self.state.lock() {
            let _ =
                self.executor
                    .terminate_page_svc(self.clone_arc(), page.path(), Some(id.clone()));
            state.pages_by_id.lock().unwrap().remove(id.as_str());
            // A failed setup can land after the entry pushed the instance; a
            // dangling stack slot would wedge current_page() and navigation.
            if let Ok(mut stack) = state.page_stack.lock() {
                stack.retain(|entry| entry != &id);
            }
            if let Ok(mut pins) = state.path_pins.lock() {
                pins.retain(|_, pinned| pinned != &id);
            }
            state
                .page_instance_runtime
                .lock()
                .unwrap()
                .remove(id.as_str());
            if let Some(cancel) = state
                .page_instance_dispose_timers
                .lock()
                .unwrap()
                .remove(id.as_str())
            {
                let _ = cancel.send(());
            }
        }

        page.cancel_bridge_work();
        let webview = page.webview();
        page.detach_webview();
        if let Some(webview) = webview {
            destroy_webview_if_matches(&page.webtag(), &webview);
        }
    }

    pub fn ensure_headless_page_service(&self, path: &str) -> Result<PageInstance, LxAppError> {
        if let Some(page) = self.get_page(path) {
            return Ok(page);
        }

        let candidate = PageInstance::new_headless(self.appid.clone(), path.to_string(), self);
        // Headless services are path-pinned singletons like tab pages.
        let page = {
            let state = self.state.lock().unwrap();
            let mut pages_by_id = state.pages_by_id.lock().unwrap();
            let existing = pages_by_id
                .values()
                .find(|page| !page.is_isolated() && page.path() == path)
                .cloned();
            if let Some(page) = existing {
                page
            } else {
                pages_by_id.insert(candidate.instance_id_string(), candidate.clone());
                candidate
            }
        };
        self.pin_page_path(&page);

        let (ack_tx, ack_rx) = oneshot::channel::<Result<(), String>>();
        if let Err(err) = self.executor.create_page_svc_with_ack(
            self.clone_arc(),
            path.to_string(),
            Some(page.instance_id_string()),
            ack_tx,
        ) {
            page.mark_webview_ready(Err(err.to_string()));
            self.remove_failed_page(&page);
            return Err(err);
        }

        let page_clone = page.clone();
        let lxapp = self.clone_arc();
        crate::executor::spawn(async move {
            let result = match ack_rx.await {
                Ok(Ok(())) => Ok(()),
                Ok(Err(e)) => Err(e),
                Err(err) => Err(err.to_string()),
            };
            if result.is_err() {
                lxapp.remove_failed_page(&page_clone);
            }
            page_clone.mark_webview_ready(result);
        });

        Ok(page)
    }

    /// Check if pull-to-refresh is enabled for a specific page
    pub fn is_pull_down_refresh_enabled(&self, path: &str) -> bool {
        self.get_page(path)
            .map(|page| page.is_pull_down_refresh_enabled())
            .unwrap_or(false)
    }

    /// Get navigation bar state for a page; returns default if page not found.
    pub fn get_navbar_state(&self, path: &str) -> NavigationBarState {
        let resolved_path = self
            .find_page_path(
                path.split('?')
                    .next()
                    .unwrap_or(path)
                    .split('#')
                    .next()
                    .unwrap_or(path),
            )
            .unwrap_or_else(|| path.to_string());

        self.get_page(path)
            .or_else(|| self.get_page(&resolved_path))
            .and_then(|page| page.get_navbar_state())
            .unwrap_or_default()
    }

    pub(crate) fn open(&self, options: LxAppStartupOptions) -> Result<(), LxAppError> {
        let _admission = self
            .admission
            .get()
            .map(|gate| gate.enter(&self.appid))
            .transpose()?;
        let _open_guard = self
            .presentation_open_lock
            .lock()
            .unwrap_or_else(|err| err.into_inner());
        if self.session.is_retired() {
            return Err(LxAppError::Runtime(
                "LxApp instance has been terminated".into(),
            ));
        }
        // A reused session (close then navigateToApp before delayed destroy)
        // still carries the scheme from last show. Re-resolve Auto now so the
        // capsule and overlays paint in the product's current scheme.
        self.adopt_host_appearance();
        let requested_region = LxAppOpenRegion::from(options.open_mode);
        let claimed = self.claim_open_region(requested_region)?;
        // Already showing this lxapp, and the link did not name a page: keep
        // the current page and let Logic route from query (`App.onShow`).
        if !claimed && options.path.is_empty() && options.page.is_none() {
            return self.reenter_from_link(options);
        }
        let began_opening =
            self.cas_status(LxAppSessionStatus::Closed, LxAppSessionStatus::Opening);
        // Re-arm on cancellation, not on that one transition: a close the
        // platform has not confirmed yet leaves the status at `Closing`, so the
        // CAS misses while the session is still cancelled — and the reopened
        // instance would come up with a live WebView and no Logic.
        if self.session.is_cancelled() {
            self.session.revive();
        }
        let result = self.open_claimed(options);
        if result.is_err() {
            if began_opening {
                let _ = self.cas_status(LxAppSessionStatus::Opening, LxAppSessionStatus::Closed);
            }
            if claimed {
                // A platform can fail after it has attached the controller (for
                // example while finalizing a Windows page instance). Roll back the
                // cold presentation before releasing the region claim; otherwise
                // another role could open while the first View is still visible.
                let _ = self.runtime.hide_lxapp(self.appid.clone(), self.session.id);
                self.release_open_region(requested_region);
            }
        }
        result
    }

    fn reenter_from_link(&self, options: LxAppStartupOptions) -> Result<(), LxAppError> {
        let current_path = self
            .peek_current_page_path()
            .unwrap_or_else(|| self.initial_route());
        {
            let mut state = self.state.lock().unwrap_or_else(|err| err.into_inner());
            state.startup_options.query = options.query;
            state.startup_options.scene = options.scene;
            state.startup_options.link_url = options.link_url;
            if state.startup_options.path.is_empty() {
                state.startup_options.path = current_path.clone();
            }
        }

        let (current_appid, _, _) = get_current_lxapp();
        if current_appid != self.appid {
            let page = self.get_or_create_page(&current_path);
            let title = self.listing_name();
            let stored = self
                .state
                .lock()
                .unwrap_or_else(|err| err.into_inner())
                .startup_options
                .clone();
            // Match first-open: put this lxapp on the switcher before the
            // webview covers the previous main, or the row lands a frame late.
            #[cfg(target_os = "windows")]
            if !matches!(
                stored.open_mode,
                lingxia_platform::traits::app_runtime::LxAppOpenMode::Panel
            ) {
                self.set_active_main();
            }
            self.runtime.show_lxapp(
                self.appid.clone(),
                title,
                current_path,
                page.webtag().key().to_string(),
                self.session.id,
                stored.open_mode,
                stored.panel_id.clone(),
            )?;
        } else {
            self.runtime.request_lxapp_main_activation(&self.appid);
            self.emit_app_show(true);
        }
        Ok(())
    }

    fn emit_app_show(&self, already_open: bool) {
        let options = self
            .state
            .lock()
            .unwrap_or_else(|err| err.into_inner())
            .startup_options
            .clone();
        let mut args = options.launch_options_value();
        if let serde_json::Value::Object(map) = &mut args {
            map.insert(
                "source".to_string(),
                serde_json::to_value(crate::lifecycle::AppServiceEventSource::Lxapp)
                    .unwrap_or_else(|_| serde_json::Value::String("lxapp".to_string())),
            );
            map.insert(
                "reason".to_string(),
                serde_json::to_value(if already_open {
                    crate::lifecycle::AppServiceEventReason::SwitchBack
                } else {
                    crate::lifecycle::AppServiceEventReason::Open
                })
                .unwrap_or_else(|_| serde_json::Value::String("unknown".to_string())),
            );
        }
        let _ = self.appservice_notify(AppServiceEvent::OnShow, Some(args.to_string()));
        self.consume_app_link_scene();
    }

    pub(crate) fn consume_app_link_scene(&self) {
        let mut state = self.state.lock().unwrap_or_else(|err| err.into_inner());
        if state.startup_options.scene == Scene::AppLink {
            state.startup_options.scene = Scene::System;
            state.startup_options.link_url.clear();
        }
    }

    fn open_claimed(&self, options: LxAppStartupOptions) -> Result<(), LxAppError> {
        if self.logic_enabled() && !crate::js_appservice_supported() {
            return Err(LxAppError::UnsupportedOperation(
                "this host app was built without JS AppService runtime".to_string(),
            ));
        }

        let mut startup_options = options;

        // Record startup options on this instance
        // Resolve path early so we can keep native/view/AppService consistent.
        let raw_url = startup_options.resolved_url(self)?;
        startup_options.page = None;

        let resolved = crate::route::resolve_route(self, &raw_url).unwrap_or_else(|e| {
            error!("Failed to resolve startup url '{}': {}", raw_url, e)
                .with_appid(self.appid.clone());
            crate::route::ResolvedRoute {
                original: raw_url.clone(),
                query: None,
                target: crate::route::RouteTarget::Normal {
                    path: raw_url.clone(),
                },
            }
        });

        startup_options.path = resolved.internal_path();
        if startup_options.query.is_empty()
            && let Some(query) = resolved.query.clone()
        {
            startup_options.query = query;
        }

        self.state.lock().unwrap().startup_options = startup_options.clone();

        // Ensure the target app's JS worker is created and mapped before creating pages.
        // View-only lxapps (`logic: false`) skip this path.
        self.executor.create_app_svc(self.clone_arc())?;

        // Create native PageInstance + WebView
        let page = self.get_or_create_page(&startup_options.path);
        page.set_query(startup_options.query.clone());

        // Open UI
        let title = self.listing_name();

        // Windows: seed the switcher graph before `show_lxapp` presents the
        // webview. Present-first left the page on screen while the new row
        // waited on `set_active_main` + `present_layout`.
        #[cfg(target_os = "windows")]
        let is_panel = matches!(
            startup_options.open_mode,
            lingxia_platform::traits::app_runtime::LxAppOpenMode::Panel
        );
        #[cfg(target_os = "windows")]
        {
            let surface = if is_panel {
                PresentationKind::Panel
            } else {
                PresentationKind::Window
            };
            let query = (!startup_options.query.is_empty())
                .then(|| PageQueryInput::Raw(startup_options.query.clone()));
            self.create_page_instance(
                PageOwner::Scene(SceneId("system".to_string())),
                PageTarget::Path(startup_options.path.clone()),
                query,
                surface,
                None,
            )?;
            if !is_panel {
                self.set_active_main();
            }
        }

        self.runtime.show_lxapp(
            self.appid.clone(),
            title,
            startup_options.path.clone(),
            page.webtag().key().to_string(),
            self.session.id,
            startup_options.open_mode,
            startup_options.panel_id.clone(),
        )?;

        #[cfg(target_os = "windows")]
        if !is_panel {
            self.sync_host_ui();
        }
        Ok(())
    }

    /// Claim the app's one live shell region. Returning `true` means this call
    /// created the claim and therefore owns rollback if platform open fails.
    fn claim_open_region(&self, requested: LxAppOpenRegion) -> Result<bool, LxAppError> {
        let mut state = self.state.lock().unwrap_or_else(|err| err.into_inner());
        match state.open_region {
            None => {
                state.open_region = Some(requested);
                Ok(true)
            }
            Some(current) if current == requested => Ok(false),
            Some(current) => Err(LxAppError::SurfaceConflict(format!(
                "lxapp '{}' is already open as {}; close it before opening as {}",
                self.appid,
                current.as_str(),
                requested.as_str()
            ))),
        }
    }

    fn release_open_region(&self, expected: LxAppOpenRegion) {
        let mut state = self.state.lock().unwrap_or_else(|err| err.into_inner());
        if state.open_region == Some(expected) {
            state.open_region = None;
        }
    }

    pub(crate) fn clear_open_region(&self) {
        self.state
            .lock()
            .unwrap_or_else(|err| err.into_inner())
            .open_region = None;
    }

    fn current_open_region(&self) -> Option<LxAppOpenRegion> {
        self.state
            .lock()
            .unwrap_or_else(|err| err.into_inner())
            .open_region
    }

    /// Host surface id currently used for an aside presentation.
    pub fn open_panel_id(&self) -> Option<String> {
        let state = self.state.lock().unwrap_or_else(|error| error.into_inner());
        (state.open_region == Some(LxAppOpenRegion::Aside))
            .then(|| state.startup_options.panel_id.trim().to_string())
            .filter(|panel_id| !panel_id.is_empty())
    }

    /// Navigates to another LxApp (forward navigation).
    ///
    /// If the provided path is empty, it will navigate to the target app's initial route.
    /// If the navigation stack is already full, this operation will be ignored.
    ///
    /// This is a forward navigation that will push the target app onto the navigation stack.
    /// The initial state of the target app is controlled by the `options` parameter.
    /// If the app navigation stack is full, this operation will be ignored.
    ///
    /// # Arguments
    ///
    /// * `appid` - The ID of the target `LxApp` to navigate to.
    /// * `options` - The startup options for the target app.
    pub fn navigate_to(
        &self,
        appid: String,
        options: LxAppStartupOptions,
    ) -> Result<(), LxAppError> {
        if let Some(manager) = get_lxapps_manager() {
            // Cancel any pending destroy for the target app since it is about to be opened.
            manager.cancel_delayed_destroy(&appid);

            if manager.is_lxapp_stack_full() {
                warn!(
                    "LxApp navigation stack is full (capacity: {}). Cannot navigate to app: {}",
                    get_num_workers(),
                    appid
                );
                return Ok(());
            }

            let app = manager.ensure_lxapp(appid.clone(), options.release_type)?;
            app.open(options)?;
        }
        Ok(())
    }

    /// Navigates back to the previous LxApp in the history stack.
    pub fn navigate_back(&self) -> Result<(), LxAppError> {
        // The on_lxapp_closed delegate will then handle removing it from the navigation stack.
        // The underlying UI framework should detect the app closure and automatically display the new app at the top of the stack.
        self.runtime
            .hide_lxapp(self.appid.clone(), self.session.id)?;
        Ok(())
    }

    /// Restarts the current LxApp with cleanup + reopen.
    /// This offloads the sequence to the service executor to avoid blocking JS worker.
    pub fn restart(&self) -> Result<(), LxAppError> {
        let _admission = self
            .admission
            .get()
            .map(|gate| gate.enter(&self.appid))
            .transpose()?;
        let from_session = self.session.id;
        let current_status = self.status();

        match current_status {
            // If restart is requested during Opening (e.g. applyUpdate in onLaunch),
            // queue it and consume once on_lxapp_opened finalizes status=Opened.
            LxAppSessionStatus::Opening
            | LxAppSessionStatus::Closed
            | LxAppSessionStatus::Closing => {
                self.pending_restart_request.store(true, Ordering::SeqCst);
                return Ok(());
            }
            LxAppSessionStatus::Opened => {}
            LxAppSessionStatus::Restarting => return Ok(()),
        }

        // Prevent overlapping restarts from races with other state transitions.
        if !self.cas_status(LxAppSessionStatus::Opened, LxAppSessionStatus::Restarting) {
            let current = self.status();
            if current == LxAppSessionStatus::Opening {
                self.pending_restart_request.store(true, Ordering::SeqCst);
            }
            return Ok(());
        }
        self.pending_restart_request.store(false, Ordering::SeqCst);

        // Mark the session restart-closing so a premature reopen can't pre-create
        // its pages on the dying worker; the recreated instance starts clean.
        self.restart_closing_session
            .store(from_session, Ordering::SeqCst);

        if let Err(e) = self.runtime.hide_lxapp(self.appid.clone(), from_session) {
            error!(
                "Restart transition: failed to request close for session {}: {}",
                from_session, e
            )
            .with_appid(self.appid.clone());
        }

        // Always relaunch to initial route after restart, but keep the region
        // (aside/panel vs main) so applyUpdate does not promote a panel guest
        // into the main slot.
        let relaunch_path = self.config().get_initial_route();
        let (open_mode, panel_id) = {
            let state = self.state.lock().unwrap_or_else(|error| error.into_inner());
            (
                state.startup_options.open_mode,
                state.startup_options.panel_id.clone(),
            )
        };
        let appid = self.appid.clone();
        let release_type = self.release_type;
        std::mem::drop(crate::executor::spawn(async move {
            let wait_deadline = Instant::now() + Duration::from_millis(1500);
            loop {
                let Some(current) = crate::lxapp::try_get(&appid) else {
                    break;
                };

                if current.session_id() != from_session {
                    return;
                }

                if current.status() == LxAppSessionStatus::Closed {
                    break;
                }

                if Instant::now() >= wait_deadline {
                    warn!(
                        "Restart transition: close wait timeout for session {}, forcing recreate",
                        from_session
                    )
                    .with_appid(appid.clone());
                    break;
                }

                time::sleep(Duration::from_millis(20)).await;
            }

            // 1) Replace LxApp instance in manager with a brand new one for this appid.
            if let Some(manager) = get_lxapps_manager() {
                let new_app = match manager.recreate_lxapp(appid.clone(), release_type) {
                    Ok(app) => app,
                    Err(e) => {
                        error!("Failed to recreate lxapp after restart: {}", e)
                            .with_appid(appid.clone());
                        return;
                    }
                };

                // 2) Initialize startup options for the new app session and open it.
                let options = LxAppStartupOptions::new(&relaunch_path)
                    .set_release_type(release_type)
                    .set_open_mode(open_mode)
                    .set_panel_id(panel_id);
                if let Err(e) = new_app.open(options) {
                    error!("Failed to start lxapp after restart: {}", e);
                }
            }
            // Status will be driven back to Opened by on_lxapp_opened delegate after reopen.
        }));
        Ok(())
    }

    pub fn get_lxapp_info(&self) -> config::LxAppInfo {
        self.config().get_lxapp_info(self.release_type.as_str())
    }

    /// Name shown in host chrome. The registry record wins; the package
    /// `appName` is only the fallback when the registry has never answered.
    pub fn listing_name(&self) -> String {
        registry::display_name(&self.appid).unwrap_or_else(|| self.get_lxapp_info().app_name)
    }
}

/// Compute a stable hash id for lxapp-scoped data separation.
/// Includes lxappid + release_type + device_fingerprint to ensure isolation across variants and devices.
pub(crate) fn lxapp_fingermark(lxappid: &str, release_type: Channel) -> String {
    // Fingermark uses appid + release_type + device fingerprint (version excluded)
    let device_fp = match crate::provider::get_provider().get_fingerprint() {
        Ok(fp) => fp,
        Err(e) => {
            warn!("Device fingerprint unavailable: {}", e);
            String::new()
        }
    };
    let combined = format!("{}|{}|{}", lxappid, release_type.as_str(), device_fp);
    let mut hasher = DefaultHasher::new();
    combined.hash(&mut hasher);
    format!("{:x}", hasher.finish())
}

impl Drop for LxApp {
    fn drop(&mut self) {
        // Don't destroy home app
        if self.is_home_lxapp {
            return;
        }
        // At this point all strong Arc references have been released. Explicit shutdown
        // should have been invoked via restart, navigate_back, or LRU eviction paths.
        // Avoid calling shutdown() here to prevent accidentally targeting a newer
        // instance with the same appid after restart.
        info!("Dropping LxApp").with_appid(self.appid.clone());
    }
}

/// The shell region an OPEN lxapp currently occupies. One lxapp lives in
/// exactly one region (main or aside); the shell never silently copies or
/// moves an instance between them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LxAppOpenRegion {
    Main,
    Aside,
}

impl LxAppOpenRegion {
    /// Stable API spelling used in diagnostics and surface metadata.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Main => "main",
            Self::Aside => "aside",
        }
    }
}

impl From<lingxia_platform::traits::app_runtime::LxAppOpenMode> for LxAppOpenRegion {
    fn from(mode: lingxia_platform::traits::app_runtime::LxAppOpenMode) -> Self {
        match mode {
            lingxia_platform::traits::app_runtime::LxAppOpenMode::Panel => Self::Aside,
            lingxia_platform::traits::app_runtime::LxAppOpenMode::Normal => Self::Main,
        }
    }
}

/// `None` means the app owns no live shell presentation. Region ownership is
/// independent from visibility: hide/show keeps the claim; close releases it.
pub fn open_region(appid: &str) -> Option<LxAppOpenRegion> {
    let app = runtime_registry::try_get(appid)?;
    app.current_open_region()
}

#[cfg(test)]
mod startup_cancellation_tests {
    use super::LxAppSession;

    #[test]
    fn shutdown_interrupts_pending_startup_and_drops_its_waiter() {
        tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap()
            .block_on(async {
                let session = LxAppSession::new();
                let (sender, receiver) = tokio::sync::oneshot::channel::<()>();
                let executed = std::cell::Cell::new(false);
                let startup = session.while_alive(async {
                    receiver.await.unwrap();
                    executed.set(true);
                });
                tokio::pin!(startup);
                assert!(futures::poll!(&mut startup).is_pending());
                session.cancel();
                assert_eq!(startup.await, None);
                assert!(!executed.get());
                assert!(sender.send(()).is_err());
            });
    }

    #[test]
    fn reopening_a_closed_instance_rearms_it_and_leaves_the_closed_run_cancelled() {
        tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap()
            .block_on(async {
                let session = LxAppSession::new();
                let (sender, receiver) = tokio::sync::oneshot::channel::<()>();
                let closing = session.while_alive(receiver);
                tokio::pin!(closing);
                assert!(futures::poll!(&mut closing).is_pending());
                session.cancel();
                // The manager keeps a closed instance around; the next open reuses it.
                session.revive();
                assert!(!session.is_cancelled());
                assert_eq!(closing.await, None);
                assert!(sender.send(()).is_err());
                assert_eq!(session.while_alive(async { 42 }).await, Some(42));
            });
    }

    #[test]
    fn cancellation_wins_over_ready_startup_and_does_not_affect_replacement() {
        tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap()
            .block_on(async {
                let old = LxAppSession::new();
                old.cancel();
                let executed = std::cell::Cell::new(false);
                assert_eq!(
                    old.while_alive(async {
                        executed.set(true);
                    })
                    .await,
                    None
                );
                assert!(!executed.get());
                let replacement = LxAppSession::new();
                assert_eq!(replacement.while_alive(async { 42 }).await, Some(42));
                assert_ne!(old.id, replacement.id);
            });
    }

    #[test]
    fn cancellation_during_source_resolution_discards_the_result() {
        tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap()
            .block_on(async {
                let session = LxAppSession::new();
                assert_eq!(session.while_alive(async {}).await, Some(()));
                let source = session
                    .while_alive(async {
                        session.cancel();
                        "must not evaluate"
                    })
                    .await;
                assert_eq!(source, None);
            });
    }
}

#[cfg(test)]
mod delayed_destroy_tests {
    use super::*;
    use tokio::sync::oneshot::error::TryRecvError;

    fn class_test_runtime() -> Arc<Platform> {
        let root = std::env::temp_dir().join(format!("lingxia-lxapp-class-{}", Uuid::new_v4()));
        Arc::new(
            Platform::new(
                root.join("data").display().to_string(),
                root.join("cache").display().to_string(),
                "en-US".to_string(),
            )
            .expect("test platform"),
        )
    }

    #[test]
    fn capsule_closed_app_is_recallable_but_retired_app_gets_a_new_session() {
        #[cfg(target_vendor = "apple")]
        let _host = crate::apple_host_stubs::headless_lifecycle();
        let appid = format!("app.lingxia.retirement.{}", Uuid::new_v4());
        register_synthetic_lxapp(appid.clone());
        let runtime = class_test_runtime();
        let manager = LxApps::new((*runtime).clone(), LxAppWorkers::init(1), 2);
        let app = manager
            .ensure_lxapp(appid.clone(), Channel::Release)
            .unwrap();
        app.set_status(LxAppSessionStatus::Opened);
        crate::delegate::LxAppDelegate::on_lxapp_closed(&app, app.session_id());
        assert_eq!(app.status(), LxAppSessionStatus::Closed);
        assert!(!app.session.is_cancelled(), "capsule close preserves Logic");
        let recalled = manager
            .ensure_lxapp(appid.clone(), Channel::Release)
            .unwrap();
        assert!(Arc::ptr_eq(&app, &recalled));

        let retired = manager.retire_lxapp(&appid).unwrap();
        assert!(Arc::ptr_eq(&app, &retired));
        assert!(
            app.session.is_cancelled(),
            "Closed must not skip force shutdown"
        );
        assert!(!manager.lxapps.contains_key(&appid));
        app.session.revive();
        assert!(
            app.session.is_cancelled(),
            "retirement is permanent even through a retained Arc"
        );
        assert!(app.open(LxAppStartupOptions::default()).is_err());

        let replacement = manager
            .ensure_lxapp(appid.clone(), Channel::Release)
            .unwrap();
        assert_ne!(replacement.session_id(), app.session_id());
        replacement.set_status(LxAppSessionStatus::Opened);
        crate::delegate::LxAppDelegate::on_lxapp_closed(&replacement, app.session_id());
        assert_eq!(
            replacement.status(),
            LxAppSessionStatus::Opened,
            "old native close must not affect replacement"
        );
        manager.retire_lxapp(&appid).unwrap();
    }

    #[test]
    fn app_session_class_is_constructor_assigned_and_preserved_on_rebuild() {
        let appid = format!("app.lingxia.class-test.{}", Uuid::new_v4());
        register_synthetic_lxapp(appid.clone());

        let runtime = class_test_runtime();
        let workers = LxAppWorkers::init(1);
        let manager = LxApps::new((*runtime).clone(), workers, 1);
        let standard = manager
            .ensure_lxapp(appid.clone(), Channel::Release)
            .expect("standard app");
        assert!(!manager.session_transition_locks.contains_key(&appid));
        let control = manager
            .initialize_home_lxapp(appid.clone())
            .expect("control app");
        assert!(!manager.session_transition_locks.contains_key(&appid));

        assert_eq!(standard.appid, control.appid);
        assert_eq!(standard.bundle_source, control.bundle_source);
        assert_eq!(standard.app_session_class(), AppSessionClass::StandardApp);
        assert!(!standard.is_control_app());
        assert_eq!(control.app_session_class(), AppSessionClass::ControlApp);
        assert!(control.is_control_app());
        assert_eq!(
            control.state.lock().unwrap().startup_options.path,
            control.config().get_initial_route()
        );

        let rebuilt = manager
            .recreate_lxapp(appid.clone(), Channel::Release)
            .expect("rebuilt control app");
        assert!(!manager.session_transition_locks.contains_key(&appid));
        assert_eq!(rebuilt.app_session_class(), AppSessionClass::ControlApp);
        assert!(rebuilt.is_control_app());

        let ensured = manager
            .ensure_lxapp(appid, Channel::Release)
            .expect("ordinary ensure after rebuild");
        assert_eq!(ensured.app_session_class(), AppSessionClass::ControlApp);
    }

    #[test]
    fn control_app_class_follows_the_home_identity_not_the_live_session() {
        const HOME: &str = "app.lingxia.home";
        const GUEST: &str = "app.lingxia.guest";

        // The crux: a destroyed home — evicted, uninstalled, or reaped by the
        // delayed-destroy timer — must not be rebuilt as an ordinary guest.
        assert_eq!(
            LxApps::session_class_for_identity(HOME, Some(HOME), None),
            AppSessionClass::ControlApp
        );
        assert_eq!(
            LxApps::session_class_for_identity(
                HOME,
                Some(HOME),
                Some(AppSessionClass::StandardApp)
            ),
            AppSessionClass::ControlApp
        );

        // ControlSurface is not an identity, so it is inherited, never derived.
        assert_eq!(
            LxApps::session_class_for_identity(
                GUEST,
                Some(HOME),
                Some(AppSessionClass::ControlSurface)
            ),
            AppSessionClass::ControlSurface
        );
        assert_eq!(
            LxApps::session_class_for_identity(GUEST, Some(HOME), None),
            AppSessionClass::StandardApp
        );
        // A host with no home lxapp has no ControlApp to derive.
        assert_eq!(
            LxApps::session_class_for_identity(HOME, None, None),
            AppSessionClass::StandardApp
        );
    }

    #[test]
    fn control_surface_is_not_home_and_keeps_its_class_on_ordinary_ensure() {
        let appid = format!("app.lingxia.surface-test.{}", Uuid::new_v4());
        register_synthetic_lxapp(appid.clone());

        let runtime = class_test_runtime();
        let workers = LxAppWorkers::init(1);
        let manager = LxApps::new((*runtime).clone(), workers.clone(), 1);
        let surface = Arc::new(
            LxApp::new_with_session_class_for_test(
                appid.clone(),
                runtime.clone(),
                workers,
                AppSessionClass::ControlSurface,
            )
            .expect("control surface"),
        );
        surface.bind_arc();
        assert_eq!(surface.app_session_class(), AppSessionClass::ControlSurface);
        assert!(!surface.is_control_app());
        assert!(!surface.is_home_lxapp);

        manager.lxapps.insert(appid.clone(), surface.clone());
        let ensured = manager
            .ensure_lxapp(appid.clone(), Channel::Release)
            .expect("ordinary ensure keeps the live surface");
        assert!(Arc::ptr_eq(&ensured, &surface));
        let rebuilt = manager
            .recreate_lxapp(appid, Channel::Release)
            .expect("rebuilt surface");
        assert_eq!(rebuilt.app_session_class(), AppSessionClass::ControlSurface);
        assert!(!rebuilt.is_home_lxapp);
    }

    #[test]
    fn control_classes_refuse_unsealed_identities() {
        let appid = format!("app.lingxia.unsealed-test.{}", Uuid::new_v4());
        register_synthetic_lxapp(appid.clone());
        let runtime = class_test_runtime();
        let manager = LxApps::new((*runtime).clone(), LxAppWorkers::init(1), 1);

        // Not the native-sealed home id: never a ControlApp.
        assert!(
            manager
                .ensure_lxapp_for_native_control(appid.clone(), Channel::Release)
                .is_err()
        );
        // Synthetic (and installed/downloaded) bundles are not host-shipped
        // control surfaces either.
        assert!(
            manager
                .ensure_lxapp_for_control_surface(appid.clone(), Channel::Release)
                .is_err()
        );
        assert!(!manager.lxapps.contains_key(&appid));
        assert!(!manager.session_transition_locks.contains_key(&appid));

        assert!(control_surface_bundle_source_allowed(Some(
            &LxAppBundleSource::BuiltinAssets
        )));
        assert!(!control_surface_bundle_source_allowed(Some(
            &LxAppBundleSource::Installed
        )));
        assert!(!control_surface_bundle_source_allowed(Some(
            &LxAppBundleSource::Synthetic
        )));
        assert!(!control_surface_bundle_source_allowed(None));
    }

    #[test]
    fn session_transition_locks_are_reused_while_live_and_removed_when_idle() {
        let runtime = class_test_runtime();
        let manager = LxApps::new((*runtime).clone(), LxAppWorkers::init(1), 1);
        let appid = format!("app.lingxia.transition-lock-test.{}", Uuid::new_v4());

        let first = manager.session_transition_lock(&appid);
        manager.cleanup_session_transition_lock(&appid);
        assert!(manager.session_transition_locks.contains_key(&appid));

        let second = manager.session_transition_lock(&appid);
        assert!(Arc::ptr_eq(&first, &second));

        drop(second);
        drop(first);
        manager.cleanup_session_transition_lock(&appid);
        assert!(!manager.session_transition_locks.contains_key(&appid));
    }

    #[test]
    fn first_timer_is_registered_and_replacement_is_cancelled() {
        let mut pending = HashMap::new();
        let (first_cancel, mut first_rx) = oneshot::channel();
        replace_pending_destroy(
            &mut pending,
            "app".to_string(),
            PendingDestroy {
                generation: 1,
                cancel: first_cancel,
            },
        );

        assert_eq!(pending.get("app").map(|entry| entry.generation), Some(1));
        assert!(matches!(first_rx.try_recv(), Err(TryRecvError::Empty)));

        let (second_cancel, mut second_rx) = oneshot::channel();
        replace_pending_destroy(
            &mut pending,
            "app".to_string(),
            PendingDestroy {
                generation: 2,
                cancel: second_cancel,
            },
        );

        assert_eq!(first_rx.try_recv(), Ok(()));
        assert!(matches!(second_rx.try_recv(), Err(TryRecvError::Empty)));
        assert_eq!(pending.get("app").map(|entry| entry.generation), Some(2));
    }

    #[test]
    fn only_current_timer_can_claim_delayed_destroy() {
        let mut pending = HashMap::new();
        let (cancel, _rx) = oneshot::channel();
        replace_pending_destroy(
            &mut pending,
            "app".to_string(),
            PendingDestroy {
                generation: 2,
                cancel,
            },
        );

        assert!(!claim_pending_destroy(&mut pending, "app", 1));
        assert!(pending.contains_key("app"));
        assert!(claim_pending_destroy(&mut pending, "app", 2));
        assert!(!pending.contains_key("app"));
    }

    #[test]
    fn lru_eviction_skips_home_and_stale_entries() {
        let stack = vec![
            "home".to_string(),
            "stale".to_string(),
            "app-b".to_string(),
            "app-c".to_string(),
        ];

        assert_eq!(
            first_evictable_appid(&stack, |appid| matches!(appid, "app-b" | "app-c")),
            Some("app-b".to_string())
        );
        assert_eq!(first_evictable_appid(&stack, |_| false), None);
    }

    #[test]
    fn session_status_compare_exchange_has_one_winner() {
        const CONTENDERS: usize = 16;
        let session = Arc::new(LxAppSession::new());
        session.set_status(LxAppSessionStatus::Opened);
        let barrier = Arc::new(std::sync::Barrier::new(CONTENDERS));

        let handles = (0..CONTENDERS)
            .map(|_| {
                let session = session.clone();
                let barrier = barrier.clone();
                std::thread::spawn(move || {
                    barrier.wait();
                    session.cas_status(LxAppSessionStatus::Opened, LxAppSessionStatus::Restarting)
                })
            })
            .collect::<Vec<_>>();

        let winners = handles
            .into_iter()
            .map(|handle| usize::from(handle.join().unwrap()))
            .sum::<usize>();
        assert_eq!(winners, 1);
        assert_eq!(session.status(), LxAppSessionStatus::Restarting);
    }
}

#[cfg(test)]
mod manifest_reload_tests {
    use super::*;
    use crate::page::PageInstance;

    fn write_manifest(root: &std::path::Path, appid: &str, body: &str) {
        std::fs::write(root.join("lxapp.json"), body.replace("APPID", appid)).unwrap();
    }

    fn test_runtime() -> Arc<Platform> {
        let root = std::env::temp_dir().join(format!("lingxia-lxapp-reload-{}", Uuid::new_v4()));
        let data = root.join("data");
        let cache = root.join("cache");
        std::fs::create_dir_all(&data).unwrap();
        std::fs::create_dir_all(&cache).unwrap();
        Arc::new(
            Platform::new(
                data.display().to_string(),
                cache.display().to_string(),
                "en-US".to_string(),
            )
            .expect("test platform"),
        )
    }

    fn dev_app(root: &std::path::Path, appid: &str) -> Arc<LxApp> {
        register_dev_bundle_source(appid, root);
        let runtime = test_runtime();
        let workers = LxAppWorkers::init(1);
        let app =
            LxApp::new(appid.to_string(), runtime, workers, Channel::Draft).expect("dev lxapp");
        let app = Arc::new(app);
        app.bind_arc();
        app
    }

    #[test]
    fn reload_manifest_picks_up_pages_and_tabbar() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path();
        let appid = format!("app.lingxia.reload-pages.{}", Uuid::new_v4());
        write_manifest(
            root,
            &appid,
            r#"{
              "appId": "APPID",
              "appName": "Reload",
              "version": "1.0.0",
              "security": {"network":{"trustedDomains":[]},"privileges":[]},
              "pages": [
                {"name": "home", "path": "pages/home/index"},
                {"name": "list", "path": "pages/list/index"}
              ]
            }"#,
        );
        let app = dev_app(root, &appid);
        assert_eq!(
            app.page_entries()
                .into_iter()
                .map(|page| page.name)
                .collect::<Vec<_>>(),
            ["home", "list"]
        );
        assert!(app.get_tabbar().is_none());

        write_manifest(
            root,
            &appid,
            r#"{
              "appId": "APPID",
              "appName": "Reload",
              "version": "1.0.0",
              "security": {"network":{"trustedDomains":[]},"privileges":[]},
              "pages": [
                {"name": "home", "path": "pages/home/index"},
                {"name": "list", "path": "pages/list/index"},
                {"name": "settings", "path": "pages/settings/index"}
              ],
              "tabBar": {
                "items": [
                  {"page": "home", "text": "Home"},
                  {"page": "settings", "text": "Settings"}
                ]
              }
            }"#,
        );
        app.reload_manifest().expect("reload manifest");
        assert_eq!(
            app.page_entries()
                .into_iter()
                .map(|page| page.name)
                .collect::<Vec<_>>(),
            ["home", "list", "settings"]
        );
        assert_eq!(
            app.find_page_path_by_name("settings").as_deref(),
            Some("pages/settings/index")
        );
        let tabbar = app.get_tabbar().expect("tabbar after reload");
        assert_eq!(tabbar.items.len(), 2);
        assert_eq!(tabbar.items[0].page, "home");
        assert_eq!(tabbar.items[1].page, "settings");
        assert_eq!(tabbar.items[1].text.as_deref(), Some("Settings"));

        write_manifest(
            root,
            &appid,
            r#"{
              "appId": "APPID",
              "appName": "Reload",
              "version": "1.0.0",
              "security": {"network":{"trustedDomains":[]},"privileges":[]},
              "pages": [
                {"name": "home", "path": "pages/home/index"},
                {"name": "list", "path": "pages/list/index"},
                {"name": "settings", "path": "pages/settings/index"}
              ],
              "tabBar": {
                "items": [
                  {"page": "home", "text": "Home"},
                  {"page": "settings", "text": "Settings2"}
                ]
              }
            }"#,
        );
        app.with_tabbar_mut(|tabbar| {
            tabbar.set_selected_index(1);
        });
        assert_eq!(app.get_tabbar().expect("tabbar").selected_index, 1);

        app.reload_manifest().expect("reload tabBar text");
        let tabbar = app.get_tabbar().expect("tabbar after text reload");
        assert_eq!(tabbar.items[1].text.as_deref(), Some("Settings2"));
        assert_eq!(tabbar.selected_index, 1);
    }

    #[test]
    fn reload_applies_page_json_navigation_style() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path();
        let appid = format!("app.lingxia.reload-navbar.{}", Uuid::new_v4());
        write_manifest(
            root,
            &appid,
            r#"{
              "appId": "APPID",
              "appName": "Reload",
              "version": "1.0.0",
              "security": {"network":{"trustedDomains":[]},"privileges":[]},
              "pages": [{"name": "home", "path": "pages/home/index"}]
            }"#,
        );
        let page_dir = root.join("pages/home");
        std::fs::create_dir_all(&page_dir).unwrap();
        std::fs::write(
            page_dir.join("index.json"),
            r#"{"navigationStyle":"default"}"#,
        )
        .unwrap();
        let app = dev_app(root, &appid);
        let page =
            PageInstance::new_headless(app.appid.clone(), "pages/home/index".to_string(), &app);
        assert!(
            page.get_page_state()
                .expect("page state")
                .navbar_state
                .show_navbar
        );

        std::fs::write(
            page_dir.join("index.json"),
            r#"{"navigationStyle":"custom"}"#,
        )
        .unwrap();
        page.apply_reloaded_page_json(&app);
        assert!(
            !page
                .get_page_state()
                .expect("page state")
                .navbar_state
                .show_navbar
        );
    }
}