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
use crate::bridge::{self, AppServiceCommand};
use crate::error::LxAppError;
#[cfg(feature = "process")]
use crate::host::ProcessSessionAuthority;
use crate::lx;
use crate::lxapp::LxApp;
use crate::{debug, error, info};

use rong::{JSContext, JSResult, JSRuntime, JSValue, RongJSError, Source, error::HostError};
#[cfg(feature = "process")]
use rong_command::ProcessAuthority;
use rong_console as console;
use rong_http as http;

use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, mpsc};
use std::time::Duration;
use tokio::sync::oneshot;

#[path = "app.rs"]
mod app;
use crate::lifecycle::AppServiceEvent;

#[path = "context_lifecycle.rs"]
mod context_lifecycle;

#[path = "event_bus.rs"]
pub(crate) mod event_bus;

#[path = "page.rs"]
mod page;
use crate::lifecycle::PageLifecycleEvent;
pub use page::PageSvc;

#[path = "plugin.rs"]
mod plugin;

#[path = "runtime_ctx.rs"]
mod runtime_ctx;
pub(crate) use runtime_ctx::set_app_svc_for_ctx;
use runtime_ctx::{register_app_ctx, remove_app_ctx, with_app_svc, with_page_svc_map};

pub(crate) async fn shutdown_app_context(ctx: &JSContext) {
    context_lifecycle::shutdown(ctx).await;
    console::clear_trace_context(ctx);
    remove_app_ctx(ctx);
    // Drain VM-resident jobs while the context still owns its CTX_OPAQUE
    // entry: the pooled worker reuses this JS runtime for the next app, and a
    // leftover engine callback firing after the last owner drops panics in
    // `from_borrowed_raw_ptr` and aborts across the FFI boundary.
    let _ = ctx.runtime().run_pending_jobs();
}

/// Rong modules initialized in every Logic worker. Every name must be backed
/// by an enabled `rong_modules` Cargo feature: resolution fail-fasts on an
/// uncompiled module and the worker aborts before `lx` exists (see the
/// `requested_rong_modules_resolve` test).
const RONG_MODULES: [&str; 14] = [
    "timer",
    "cron",
    "event",
    "exception",
    "abort",
    "encoding",
    "console",
    "url",
    "buffer",
    "stream",
    "http",
    "compression",
    "storage",
    "crypto",
];

#[cfg(test)]
mod rong_modules_tests {
    #[test]
    fn requested_rong_modules_resolve() {
        rong_modules::resolve_modules(super::RONG_MODULES)
            .expect("every requested Rong module must be compiled into this build");
    }

    #[test]
    fn command_is_neither_compiled_requested_nor_extension_installable() {
        assert!(!rong_modules::is_compiled("command"));
        assert!(!super::RONG_MODULES.contains(&"command"));
        let source = include_str!("js_runtime.rs");
        let seal = source
            .find("Object.defineProperty(globalThis, 'Rong'")
            .expect("reserved Rong namespace seal");
        let extensions = source
            .find("with_registered_extensions(")
            .expect("extension dispatch");
        assert!(
            seal < extensions,
            "Rong must be sealed before extensions run"
        );
    }
}

/// Message type for LxApp service system
pub(crate) enum ServiceMessage {
    // Create a new AppService (JS runtime) for this LxApp instance
    CreateAppSvc {
        lxapp: Arc<LxApp>,
    },
    // Terminate AppService for this LxApp instance. ACK returned when cleanup completes.
    TerminateAppSvc {
        lxapp: Arc<LxApp>,
        worker_id: usize,
        ack_tx: oneshot::Sender<()>,
    },
    // Create a new page service
    CreatePage {
        lxapp: Arc<LxApp>,
        path: String,
        page_instance_id: Option<String>,
        ack_tx: oneshot::Sender<Result<(), String>>,
    },
    // Delete a page service (object-identity safe)
    TerminatePage {
        lxapp: Arc<LxApp>,
        path: String,
        page_instance_id: Option<String>,
    },
    // Call predefined AppService event (typed)
    CallAppSvcEvent {
        lxapp: Arc<LxApp>,
        event: AppServiceEvent,
        args: Option<String>,
    },
    // Call function of PageInstance service with different sources
    CallPageSvc {
        lxapp: Arc<LxApp>,
        path: String,
        page_instance_id: Option<String>,
        source: PageSvcSource,
    },
    // Call typed page event
    CallPageSvcEvent {
        lxapp: Arc<LxApp>,
        path: String,
        page_instance_id: Option<String>,
        event: PageLifecycleEvent,
        args: Option<String>,
    },
    // Native -> JS event dispatch via event bus (e.g., video context)
    DispatchAppBusEvent {
        lxapp: Arc<LxApp>,
        event: event_bus::AppBusEvent,
    },
    Eval {
        /// Report which `lx.*` members the script reached, alongside its value.
        capture_calls: bool,
        lxapp: Arc<LxApp>,
        script: String,
        tx: oneshot::Sender<Result<String, LxAppError>>,
    },
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum WorkerAssignment {
    Active(usize),
    Terminating { worker_id: usize, token: u64 },
}

impl WorkerAssignment {
    pub(crate) fn worker_id(self) -> usize {
        match self {
            Self::Active(worker_id) | Self::Terminating { worker_id, .. } => worker_id,
        }
    }
}

static NEXT_TERMINATION_TOKEN: AtomicU64 = AtomicU64::new(1);

/// Enum representing different sources of PageInstance service calls
pub enum PageSvcSource {
    /// Call from view layer after the top-level bridge has parsed and routed it.
    Bridge {
        message: crate::bridge::AppServiceCommand,
    },
    /// Call from native layer with explicit function name and args
    Native {
        name: String,
        args: Option<String>, // JSON string of arguments
    },
}

pub(crate) struct WorkerService {
    pub(crate) svc: ServiceMessage,
}

// Handles a typed AppService event
async fn handle_app_service_event(
    worker_id: usize,
    ctx: &JSContext,
    appid: String,
    event: AppServiceEvent,
    args: Option<String>,
) {
    // Resolve AppSvc from registry via JSContext and clone it for use in this async handler.
    let svc = match with_app_svc(ctx, |svc| Ok(svc.clone())) {
        Ok(svc) => svc,
        Err(e) => {
            info!(
                "[Worker {}] Dropping app service event '{}': {}",
                worker_id, event, e
            )
            .with_appid(appid);
            return;
        }
    };

    if matches!(
        event,
        AppServiceEvent::OnLaunch
            | AppServiceEvent::OnShow
            | AppServiceEvent::OnHide
            | AppServiceEvent::OnUserCaptureScreen
    ) && let Err(e) = svc.call_event(ctx, event, args.clone()).await
    {
        error!(
            "[Worker {}] App service event '{}' failed, Error: {}",
            worker_id, event, e
        )
        .with_appid(appid);
    }
}

fn js_value_to_json_string(value: JSValue) -> Result<String, LxAppError> {
    if value.is_undefined() || value.is_null() {
        return Ok("null".to_string());
    }
    if value.is_boolean() {
        let value: bool = value.into_value().try_into().map_err(LxAppError::from)?;
        return Ok(if value { "true" } else { "false" }.to_string());
    }
    if value.is_number() {
        let value: f64 = value.into_value().try_into().map_err(LxAppError::from)?;
        let number = serde_json::Number::from_f64(value)
            .ok_or_else(|| LxAppError::Runtime("eval returned invalid number".to_string()))?;
        return Ok(number.to_string());
    }
    if value.is_string() {
        let value: String = value.into_value().try_into().map_err(LxAppError::from)?;
        return serde_json::to_string(&value).map_err(LxAppError::from);
    }
    if let Some(object) = value.into_object() {
        return object.to_json_string().map_err(LxAppError::from);
    }
    Ok("null".to_string())
}

pub(crate) fn eval_error_from_rong(ctx: &JSContext, error: RongJSError) -> LxAppError {
    if let Some(thrown) = error.thrown_value(ctx) {
        if thrown.is_string() {
            let value: Result<String, RongJSError> = thrown.into_value().try_into();
            if let Ok(value) = value {
                return LxAppError::RongJS(value);
            }
        } else if let Some(object) = thrown.into_object() {
            let name = object
                .get::<_, String>("name")
                .unwrap_or_else(|_| "Error".to_string());
            if let Ok(message) = object.get::<_, String>("message") {
                return LxAppError::RongJS(format!("{name}: {message}"));
            }
        }
    }
    LxAppError::from(error)
}

/// Wraps the caller's script so that `lx` inside it is a recording proxy.
///
/// The binding is **local**, which is the whole point: a direct `eval` inherits
/// the enclosing scope, so the evaluated script sees the proxy while the lxapp's
/// own concurrently running code still sees the real global `lx`. Swapping the
/// global instead would record every background call the app happened to make
/// and credit it to whatever spec was running.
///
/// Primitive members (`lx.env.USER_DATA_PATH`) are published capabilities too;
/// recording only functions and objects would miss the get that reached them.
const RECORDER_PRELUDE: &str = r#"
const __lxCalls = new Set();
const __lxRecord = (target, path) => {
  if (target === null || (typeof target !== "object" && typeof target !== "function")) {
    return target;
  }
  return new Proxy(target, {
    get(obj, key, receiver) {
      const value = Reflect.get(obj, key, receiver);
      if (typeof key === "symbol") return value;
      const next = path + "." + String(key);
      __lxCalls.add(next);
      if (typeof value === "function") {
        return (...args) => Reflect.apply(value, obj, args);
      }
      if (value && typeof value === "object") {
        return __lxRecord(value, next);
      }
      return value;
    },
  });
};
const lx = __lxRecord(globalThis.lx, "lx");
"#;

async fn eval_logic_script_inner(
    ctx: &JSContext,
    script: &str,
    capture_calls: bool,
) -> Result<String, LxAppError> {
    let expression_json = serde_json::to_string(script).map_err(LxAppError::from)?;
    let (prelude, wrap_result) = if capture_calls {
        (RECORDER_PRELUDE, true)
    } else {
        ("", false)
    };
    let expression = if wrap_result {
        format!(
            r#"(async () => {{
{prelude}
  const __lxValue = await eval({expression_json});
  return {{ __lxEval: 1, value: __lxValue, calls: [...__lxCalls] }};
}})()"#
        )
    } else {
        format!(
            r#"(async () => {{
  return await eval({expression_json});
}})()"#
        )
    };
    match ctx
        .eval_async::<JSValue>(Source::from_bytes(expression))
        .await
    {
        Ok(value) => js_value_to_json_string(value),
        Err(expression_error) if script_may_be_function_body(ctx, script, &expression_error) => {
            let body = if wrap_result {
                format!(
                    r#"(async () => {{
{prelude}
  const __lxValue = await (async () => {{
{script}
  }})();
  return {{ __lxEval: 1, value: __lxValue, calls: [...__lxCalls] }};
}})()"#
                )
            } else {
                format!(
                    r#"(async () => {{
{script}
}})()"#
                )
            };
            let value = ctx
                .eval_async::<JSValue>(Source::from_bytes(body))
                .await
                .map_err(|body_error| eval_error_from_rong(ctx, body_error))?;
            js_value_to_json_string(value)
        }
        Err(expression_error) => Err(eval_error_from_rong(ctx, expression_error)),
    }
}

fn script_may_be_function_body(
    ctx: &JSContext,
    script: &str,
    expression_error: &RongJSError,
) -> bool {
    let is_syntax_error = expression_error
        .thrown_value(ctx)
        .and_then(|value| value.into_object())
        .and_then(|object| object.get::<_, String>("name").ok())
        .is_some_and(|name| name == "SyntaxError");
    is_syntax_error && script_looks_like_function_body(script)
}

fn script_looks_like_function_body(script: &str) -> bool {
    let trimmed = script.trim_start();
    trimmed.starts_with("return")
        || trimmed.starts_with("const ")
        || trimmed.starts_with("let ")
        || trimmed.starts_with("var ")
        || trimmed.starts_with("if ")
        || trimmed.starts_with("for ")
        || trimmed.starts_with("while ")
        || trimmed.starts_with("try ")
        || trimmed.starts_with("await ")
        || trimmed.starts_with("await(")
        || trimmed.contains(';')
}

// Handles a bridge-routed message that must enter the JS runtime worker.
async fn handle_bridge_source(
    page_svc: &PageSvc,
    message: AppServiceCommand,
) -> Result<(), LxAppError> {
    match message {
        AppServiceCommand::BeginSessionWork { work_id } => {
            page_svc.begin_session_work(work_id).await;
            Ok(())
        }
        AppServiceCommand::CancelSessionWork { work_id } => {
            page_svc.cancel_session_work(work_id).await;
            Ok(())
        }
        AppServiceCommand::Ready { work_id, outbound } => {
            page_svc.handle_bridge_ready(work_id, outbound).await;
            Ok(())
        }
        AppServiceCommand::StateSnapshot {
            work_id,
            outbound,
            id,
            scope,
        } => {
            if !page_svc.session_work_is_active(work_id).await {
                return Ok(());
            }
            let bridge = page_svc.bridge();
            match page_svc.get_state_snapshot(scope.as_deref()).await {
                Ok(snapshot) => bridge.send_res_ok_for_context(
                    page_svc,
                    work_id,
                    outbound.as_ref(),
                    id,
                    snapshot,
                )?,
                Err(err) => bridge.send_res_err_for_context(
                    page_svc,
                    work_id,
                    outbound.as_ref(),
                    id,
                    bridge::BRIDGE_INTERNAL_ERROR,
                    Some(err.to_string()),
                    None,
                )?,
            }
            Ok(())
        }
        AppServiceCommand::Req {
            work_id,
            outbound,
            id,
            method,
            params_json,
            cancel_rx,
            pending_request,
        } => {
            if !page_svc.session_work_is_active(work_id).await {
                return Ok(());
            }
            let bridge = page_svc.bridge();
            let result = page::with_document_callback_work(
                work_id,
                outbound.clone(),
                page_svc.handle_req(
                    work_id,
                    outbound.clone(),
                    &id,
                    &method,
                    params_json.as_deref(),
                    cancel_rx,
                ),
            )
            .await;
            drop(pending_request);
            match result {
                Ok(json) => bridge.send_res_ok_for_context(
                    page_svc,
                    work_id,
                    outbound.as_ref(),
                    id,
                    json,
                )?,
                Err(err) if err.code == bridge::BRIDGE_CANCELED => {
                    // Cancellation is teardown control flow. Reply while a cached
                    // View still exists, but tolerate a concurrent WebView detach.
                    let _ = bridge.send_res_err_for_context(
                        page_svc,
                        work_id,
                        outbound.as_ref(),
                        id,
                        &err.code,
                        err.message,
                        err.data,
                    );
                }
                Err(err) => bridge.send_res_err_for_context(
                    page_svc,
                    work_id,
                    outbound.as_ref(),
                    id,
                    &err.code,
                    err.message,
                    err.data,
                )?,
            }
            Ok(())
        }
        AppServiceCommand::Notify {
            work_id,
            outbound,
            method,
            params_json,
        } => {
            if !page_svc.session_work_is_active(work_id).await {
                return Ok(());
            }
            page_svc
                .handle_notify(work_id, outbound, &method, params_json.as_deref())
                .await;
            Ok(())
        }
        AppServiceCommand::ChOpen {
            work_id,
            outbound,
            id,
            topic,
            params_json,
        } => {
            if !page_svc.session_work_is_active(work_id).await {
                return Ok(());
            }
            let bridge = page_svc.bridge();
            match page_svc
                .handle_ch_open(
                    work_id,
                    outbound.clone(),
                    &id,
                    &topic,
                    params_json.as_deref(),
                )
                .await
            {
                Ok(result_rx) => {
                    let ctx = page_svc.get_ctx();
                    let page_svc = page_svc.clone();
                    context_lifecycle::spawn(&ctx, move |_ctx| async move {
                        let result = result_rx.await.unwrap_or_else(|_| {
                            Err(bridge::RpcError::new(bridge::BRIDGE_CANCELED, None))
                        });
                        match result {
                            Ok(()) => {
                                let _ = bridge.send_ch_ack_ok_for_context(
                                    &page_svc,
                                    work_id,
                                    outbound.as_ref(),
                                    id,
                                );
                            }
                            Err(err) => {
                                let _ = bridge.send_ch_ack_err_for_context(
                                    &page_svc,
                                    work_id,
                                    outbound.as_ref(),
                                    id,
                                    &err.code,
                                    err.message,
                                    err.data,
                                );
                            }
                        }
                    });
                }
                Err(err) => bridge.send_ch_ack_err_for_context(
                    page_svc,
                    work_id,
                    outbound.as_ref(),
                    id,
                    &err.code,
                    err.message,
                    err.data,
                )?,
            }
            Ok(())
        }
        AppServiceCommand::ChData {
            work_id,
            id,
            payload_json,
        } => {
            if !page_svc.session_work_is_active(work_id).await {
                return Ok(());
            }
            if let Err(err) = page_svc.handle_ch_data(work_id, &id, &payload_json).await {
                error!("channel '{}' data handler failed: {}", id, err.code)
                    .with_appid(page_svc.page.appid())
                    .with_path(page_svc.page.path());
            }
            Ok(())
        }
        AppServiceCommand::ChClose {
            work_id,
            id,
            code,
            reason,
        } => {
            if !page_svc.session_work_is_active(work_id).await {
                return Ok(());
            }
            page_svc
                .handle_ch_close(work_id, &id, code.as_deref(), reason.as_deref())
                .await;
            Ok(())
        }
        AppServiceCommand::StateAck {
            work_id,
            scope,
            rev,
        } => {
            page_svc.handle_state_ack(work_id, scope, rev).await;
            Ok(())
        }
    }
}

// Handles a call from native code to a PageInstance service function
fn handle_native_source(page_svc: &PageSvc, appid: String, name: String, args: Option<String>) {
    let ctx = page_svc.get_ctx();
    let page_svc_clone = page_svc.clone();
    let name_clone = name.clone();

    context_lifecycle::spawn(&ctx, move |ctx| async move {
        if let Err(e) = page_svc_clone
            .call_or_event_from_native(&ctx, &name, args.as_deref())
            .await
        {
            crate::error!("PageInstance service call '{}' failed: {}", name_clone, e)
                .with_appid(appid)
                .with_path(page_svc_clone.page.path());
        }
    });
}

/// The core logic for a persistent worker task.
/// This function is a handler for messages received by the worker.
pub(crate) async fn lxapp_service_handler(
    worker_id: usize,
    runtime: JSRuntime,
    message: ServiceMessage,
    current_ctx: &mut Option<JSContext>,
) {
    match message {
        ServiceMessage::CreateAppSvc { lxapp } => {
            if lxapp
                .session
                .while_alive(lxapp.wait_permissions_ready())
                .await
                .is_none()
            {
                return;
            }
            let ctx = runtime.context();

            // Register LxApp runtime context and bind identity to JSContext
            register_app_ctx(&ctx, &lxapp);

            // register PageInstance, App and getApp function
            if let Err(e) = app::init(&ctx) {
                error!(
                    "[Worker {}] Failed to initialize App runtime: {}",
                    worker_id, e
                )
                .with_appid(lxapp.appid.clone());
                return;
            }
            if let Err(e) = page::init(&ctx) {
                error!(
                    "[Worker {}] Failed to initialize PageInstance runtime: {}",
                    worker_id, e
                )
                .with_appid(lxapp.appid.clone());
                return;
            }
            if let Err(e) = plugin::init(&ctx) {
                error!(
                    "[Worker {}] Failed to initialize Plugin runtime: {}",
                    worker_id, e
                )
                .with_appid(lxapp.appid.clone());
                return;
            }
            event_bus::init(&ctx);

            let app_ctx = LxAppCtx::new(lxapp.clone());

            console::set_trace_context(
                &ctx,
                console::ConsoleTraceContext {
                    namespace: Some(lxapp.appid.clone()),
                    scope: Some("appservice".to_string()),
                },
            );

            // Set network access guard to prevent unauthorized domain access
            http::set_network_access_guard(Box::new(app_ctx));

            if let Err(e) = rong_modules::init(&ctx, RONG_MODULES) {
                error!(
                    "[Worker {}] Failed to initialize Rong modules: {}",
                    worker_id, e
                )
                .with_appid(lxapp.appid.clone());
                return;
            }
            #[cfg(feature = "process")]
            if lxapp.process_supported() {
                // Namespace presence is stable. ProcessSessionAuthority still
                // checks the current grant for every operation.
                let authority: Arc<dyn ProcessAuthority> =
                    Arc::new(ProcessSessionAuthority::for_lxapp(&lxapp));
                if let Err(e) = rong_command::init_with_authority(&ctx, authority) {
                    error!(
                        "[Worker {}] Failed to initialize process capability: {}",
                        worker_id, e
                    )
                    .with_appid(lxapp.appid.clone());
                    return;
                }
            }
            let _ = lx::init(&ctx);
            if let Err(e) = ctx.eval::<()>(Source::from_bytes(
                "Object.defineProperty(globalThis, 'Rong', { value: globalThis.Rong, writable: false, configurable: false }); Object.freeze(globalThis.Rong)",
            )) {
                error!(
                    "[Worker {}] Failed to seal reserved Rong namespace: {}",
                    worker_id, e
                )
                .with_appid(lxapp.appid.clone());
                return;
            }

            // Execute a closure with access to the list of registered extensions.
            crate::lx::extension::with_registered_extensions(
                lxapp.app_session_class(),
                |user_extensions| {
                    info!(
                        "[Worker {}] Initializing {} user-registered extensions",
                        worker_id,
                        user_extensions.len()
                    )
                    .with_appid(lxapp.appid.clone());

                    // Iterate through the list and initialize each extension.
                    for (index, user_extension) in user_extensions.iter().enumerate() {
                        if let Err(e) = user_extension.init(&ctx) {
                            error!(
                                "[Worker {}] Failed to initialize user extension #{}: {}",
                                worker_id, index, e
                            )
                            .with_appid(lxapp.appid.clone());
                        }
                    }
                },
            );

            info!("[Worker {}] Created JS context", worker_id).with_appid(lxapp.appid.clone());

            let Some(source) = lxapp
                .session
                .while_alive(lxapp.logic_entry_source(&ctx))
                .await
            else {
                shutdown_app_context(&ctx).await;
                return;
            };
            match source {
                Ok(Some(js)) => match ctx.eval::<()>(js) {
                    Ok(_) => {
                        info!("[Worker {}] Successfully loaded logic JS", worker_id)
                            .with_appid(lxapp.appid.clone());
                    }
                    Err(e) => {
                        info!("[Worker {}] eval logic JS  failed: {}", worker_id, e)
                            .with_appid(lxapp.appid.clone());
                    }
                },
                Ok(None) => {
                    info!(
                        "[Worker {}] Logic disabled; skipping JS bootstrap",
                        worker_id
                    )
                    .with_appid(lxapp.appid.clone());
                }
                Err(e) => {
                    error!("[Worker {}] Failed to load logic source: {}", worker_id, e)
                        .with_appid(lxapp.appid.clone());
                }
            }

            *current_ctx = Some(ctx.clone());
        }
        ServiceMessage::TerminateAppSvc { lxapp, ack_tx, .. } => {
            if let Some(ctx) = current_ctx.as_ref() {
                shutdown_app_context(ctx).await;
                *current_ctx = None;
                info!("[Worker {}] Removed LxApp context ", worker_id)
                    .with_appid(lxapp.appid.clone());
            }
            // Clear guards on app terminate so the previous LxAppCtx is dropped immediately.
            http::set_network_access_guard(Box::new(DenyAllNetworkAccessGuard));
            lxapp
                .logic_contexts
                .send_modify(|count| *count = count.saturating_sub(1));
            // ACK back to the caller that cleanup is complete
            let _ = ack_tx.send(());
        }
        ServiceMessage::CreatePage {
            lxapp,
            path,
            page_instance_id,
            ack_tx,
        } => {
            let result = if let Some(ctx) = current_ctx.as_ref() {
                // A CreatePage for an older session can land on the recycled
                // worker after its app context was replaced; like TerminatePage,
                // drop it quietly instead of failing against the new context.
                let same_app = LxApp::from_ctx(ctx)
                    .map(|ctx_app| ctx_app.session.id == lxapp.session.id)
                    .unwrap_or(false);
                if !same_app {
                    info!(
                        "[Worker {}] Ignored CreatePage for different LxApp instance",
                        worker_id
                    )
                    .with_appid(lxapp.appid.clone())
                    .with_path(path.clone());
                    let _ = ack_tx.send(Ok(()));
                    return;
                }
                debug!(
                    "[Worker {}] Creating page svc (instance {:?})",
                    worker_id, page_instance_id
                )
                .with_appid(lxapp.appid.clone())
                .with_path(path.clone());
                // The instance can be disposed between queueing and execution
                // (a relaunch tearing the stack down races a queued rebuild);
                // that is churn, not a failure.
                if let Some(id) = page_instance_id.as_deref()
                    && lxapp.get_page_by_instance_id_str(id).is_none()
                {
                    info!(
                        "[Worker {}] Skipped CreatePage for disposed instance {}",
                        worker_id, id
                    )
                    .with_appid(lxapp.appid.clone())
                    .with_path(path.clone());
                    let _ = ack_tx.send(Err("page instance disposed".to_string()));
                    return;
                }
                match PageSvc::create_in_ctx(ctx, &path, page_instance_id.as_deref()).await {
                    Ok(()) => Ok(()),
                    Err(e) => {
                        let msg = e.to_string();
                        // The instance can also be disposed DURING creation
                        // (the preflight raced the disposal) — still churn.
                        let disposed_during_create = page_instance_id
                            .as_deref()
                            .is_some_and(|id| lxapp.get_page_by_instance_id_str(id).is_none());
                        if disposed_during_create {
                            info!(
                                "[Worker {}] Dropped CreatePage for instance disposed mid-create: {}",
                                worker_id, msg
                            )
                            .with_appid(lxapp.appid.clone())
                            .with_path(&path);
                        } else {
                            error!("[Worker {}] create_in_ctx failed: {}", worker_id, e)
                                .with_appid(lxapp.appid.clone())
                                .with_path(&path);
                        }
                        Err(msg)
                    }
                }
            } else {
                let msg = "JS context not available".to_string();
                error!("[Worker {}] create_in_ctx: {}", worker_id, msg)
                    .with_appid(lxapp.appid.clone())
                    .with_path(&path);
                Err(msg)
            };
            let _ = ack_tx.send(result);
        }
        ServiceMessage::TerminatePage {
            lxapp,
            path,
            page_instance_id,
        } => {
            if let Some(ctx) = current_ctx.as_ref() {
                // Ensure this TerminatePage belongs to the same LxApp
                let same_app = LxApp::from_ctx(ctx)
                    .map(|ctx_app| ctx_app.session.id == lxapp.session.id)
                    .unwrap_or(false);
                if !same_app {
                    info!(
                        "[Worker {}] Ignored TerminatePage for different LxApp instance",
                        worker_id
                    )
                    .with_appid(lxapp.appid.clone())
                    .with_path(path.clone());
                    return;
                }

                // Services register under their instance id alone; a path can
                // have several live instances.
                let page_svc = with_page_svc_map(ctx, |page_svc_map| {
                    Ok(page_instance_id
                        .as_deref()
                        .and_then(|id| page_svc_map.borrow_mut().remove(id)))
                })
                .unwrap_or(None);

                if let Some(page_svc) = page_svc {
                    page_svc.mark_terminated();
                    page_svc
                        .close_channels(bridge::BRIDGE_CANCELED, "Page terminated")
                        .await;
                    // Instance-scoped: terminating one instance must not clear
                    // a same-path sibling's subscriptions.
                    event_bus::clear_page(ctx, &page_svc.get_page().instance_id_string());

                    info!("[Worker {}] Removed page", worker_id)
                        .with_appid(lxapp.appid.clone())
                        .with_path(path);
                }
            }
        }
        ServiceMessage::CallAppSvcEvent { lxapp, event, args } => {
            if let Some(ctx) = current_ctx.as_ref() {
                // Ensure this event targets the same LxApp bound to ctx
                let same_app = LxApp::from_ctx(ctx)
                    .map(|ctx_app| ctx_app.session.id == lxapp.session.id)
                    .unwrap_or(false);
                if same_app {
                    // Don't block the worker message pump on user JS lifecycle handlers.
                    // If an app handler awaits network/IO, blocking here can starve bridge handshake
                    // and other view messages, causing "Handshake timeout" even when transport is OK.
                    let appid = lxapp.appid.clone();
                    context_lifecycle::spawn(ctx, move |ctx| async move {
                        handle_app_service_event(worker_id, &ctx, appid, event, args).await;
                    });
                }
            }
        }
        ServiceMessage::CallPageSvc {
            lxapp,
            path,
            page_instance_id,
            source,
        } => {
            if let Some(ctx) = current_ctx.as_ref() {
                match source {
                    PageSvcSource::Bridge { message } => {
                        let page_svc = with_page_svc_map(ctx, |page_svc_map| {
                            Ok(page_instance_id
                                .as_deref()
                                .and_then(|id| page_svc_map.borrow().get(id).cloned()))
                        })
                        .unwrap_or(None);

                        if let Some(page_svc) = page_svc {
                            if let Err(e) = handle_bridge_source(&page_svc, message).await {
                                let page = page_svc.get_page();
                                if page.document_is_departing() || page.webview().is_none() {
                                    debug!(
                                        "[Worker {}] Dropping bridge response for departed page: {}",
                                        worker_id, e
                                    )
                                    .with_appid(lxapp.appid.clone())
                                    .with_path(path.clone());
                                } else {
                                    error!(
                                        "[Worker {}] Handle bridge message error: {}",
                                        worker_id, e
                                    )
                                    .with_appid(lxapp.appid.clone())
                                    .with_path(path.clone());
                                }
                            }
                        } else {
                            info!(
                                "[Worker {}] Dropping bridge message: page service not loaded",
                                worker_id
                            )
                            .with_appid(lxapp.appid.clone())
                            .with_path(path);
                        }
                    }
                    PageSvcSource::Native { name, args } => {
                        let page_svc = with_page_svc_map(ctx, |page_svc_map| {
                            Ok(page_instance_id
                                .as_deref()
                                .and_then(|id| page_svc_map.borrow().get(id).cloned()))
                        })
                        .unwrap_or(None);

                        if let Some(page_svc) = page_svc {
                            handle_native_source(&page_svc, lxapp.appid.clone(), name, args);
                        } else {
                            info!(
                                "[Worker {}] Dropping native call: page service not loaded",
                                worker_id
                            )
                            .with_appid(lxapp.appid.clone())
                            .with_path(path);
                        }
                    }
                }
            }
        }
        ServiceMessage::CallPageSvcEvent {
            lxapp,
            path,
            page_instance_id,
            event,
            args,
        } => {
            if let Some(ctx) = current_ctx.as_ref() {
                // Resolve PageSvc from registry
                let page_svc = with_page_svc_map(ctx, |page_svc_map| {
                    let page_svc_map = page_svc_map.borrow();
                    Ok(page_instance_id
                        .as_deref()
                        .and_then(|id| page_svc_map.get(id).cloned()))
                })
                .unwrap_or(None);

                if let Some(page_svc) = page_svc {
                    debug!(
                        "[Worker {}] page event '{}' → instance {}",
                        worker_id,
                        event,
                        page_svc.get_page().instance_id_string()
                    )
                    .with_appid(lxapp.appid.clone())
                    .with_path(path.clone());
                    // Keeps user lifecycle handlers off the worker pump while
                    // preserving per-page dispatch order.
                    page_svc.enqueue_lifecycle_event(ctx, event, args);
                } else {
                    info!(
                        "[Worker {}] Dropping page event: page service not loaded",
                        worker_id
                    )
                    .with_appid(lxapp.appid.clone())
                    .with_path(path);
                }
            }
        }
        ServiceMessage::DispatchAppBusEvent { lxapp, event } => {
            if let Some(ctx) = current_ctx.as_ref() {
                let same_app = LxApp::from_ctx(ctx)
                    .map(|ctx_app| ctx_app.session.id == lxapp.session.id)
                    .unwrap_or(false);
                if same_app {
                    // Don't block the worker message pump on user JS event handlers. Like app/page
                    // lifecycle events, event bus handlers can await network/IO and would
                    // otherwise starve view messages (including handshake retries).
                    let appid = lxapp.appid.clone();
                    context_lifecycle::spawn(ctx, move |ctx| async move {
                        if let Err(e) = event_bus::dispatch_app_bus_event(&ctx, &event).await {
                            error!(
                                "[Worker {}] Dispatch app bus event failed: {}",
                                worker_id, e
                            )
                            .with_appid(appid);
                        }
                    });
                }
            }
        }
        ServiceMessage::Eval {
            capture_calls,
            lxapp,
            script,
            tx,
        } => {
            let result = if let Some(ctx) = current_ctx.as_ref() {
                let same_app = LxApp::from_ctx(ctx)
                    .map(|ctx_app| ctx_app.session.id == lxapp.session.id)
                    .unwrap_or(false);
                if same_app {
                    eval_logic_script_inner(ctx, &script, capture_calls).await
                } else {
                    Err(LxAppError::Runtime(format!(
                        "logic runtime is bound to a different lxapp than {}",
                        lxapp.appid
                    )))
                }
            } else {
                Err(LxAppError::Runtime(format!(
                    "logic runtime is not ready for {}",
                    lxapp.appid
                )))
            };
            let _ = tx.send(result);
        }
    }
}

/// Create a new mini-app service - enforces 1:1 appid->worker mapping
pub(crate) fn create_app_svc(
    lxapp: Arc<crate::lxapp::LxApp>,
    sender: &mpsc::Sender<ServiceMessage>,
    instance_assignments: &Arc<Mutex<HashMap<usize, WorkerAssignment>>>,
    free_workers: &Arc<Mutex<VecDeque<usize>>>,
) -> Result<(), LxAppError> {
    let _creation = crate::device::logic_creation_guard()?;
    let appid = lxapp.appid.clone();

    let key = lxapp.as_ref() as *const _ as usize;
    if reactivate_or_reuse_assignment(&lxapp, sender, instance_assignments, key)? {
        return Ok(());
    }

    // Check if we have free workers available
    let worker_id = {
        let mut free_workers_guard = free_workers.lock().unwrap();
        if free_workers_guard.is_empty() {
            return Err(LxAppError::ResourceExhausted(
                "No available workers for new mini-app".to_string(),
            ));
        }
        free_workers_guard.pop_front().unwrap()
    };

    // Publish the worker mapping only after the CreateAppSvc message has been
    // enqueued. A concurrent page creation treats the mapping as readiness to
    // route CreatePage, so exposing it before this send can let CreatePage reach
    // the worker before Page.js and the app logic have registered page definitions.
    {
        let mut assignments = instance_assignments.lock().unwrap();
        if reactivate_or_reuse_locked(&lxapp, sender, &mut assignments, key)? {
            free_workers.lock().unwrap().push_front(worker_id);
            return Ok(());
        }
        lxapp.logic_contexts.send_modify(|count| *count += 1);
        if let Err(e) = sender.send(ServiceMessage::CreateAppSvc {
            lxapp: lxapp.clone(),
        }) {
            release_logic_context(&lxapp);
            free_workers.lock().unwrap().push_front(worker_id);
            return Err(e.into());
        }
        assignments.insert(key, WorkerAssignment::Active(worker_id));
    }

    info!("Assigned dedicated worker {} to app {}", worker_id, appid);
    Ok(())
}

fn reactivate_or_reuse_assignment(
    lxapp: &Arc<LxApp>,
    sender: &mpsc::Sender<ServiceMessage>,
    instance_assignments: &Arc<Mutex<HashMap<usize, WorkerAssignment>>>,
    key: usize,
) -> Result<bool, LxAppError> {
    let mut assignments = instance_assignments.lock().unwrap();
    reactivate_or_reuse_locked(lxapp, sender, &mut assignments, key)
}

fn reactivate_or_reuse_locked(
    lxapp: &Arc<LxApp>,
    sender: &mpsc::Sender<ServiceMessage>,
    assignments: &mut HashMap<usize, WorkerAssignment>,
    key: usize,
) -> Result<bool, LxAppError> {
    if lxapp.session.is_cancelled() {
        return Err(LxAppError::Runtime(
            "Cannot start a terminated LxApp session".into(),
        ));
    }
    let Some(assignment) = assignments.get(&key).copied() else {
        return Ok(false);
    };

    if matches!(assignment, WorkerAssignment::Terminating { .. }) {
        // The terminate message is already ahead of this create in the same
        // queue. Marking the assignment active also prevents its old ACK task
        // from releasing the worker after the new context has been requested.
        lxapp.logic_contexts.send_modify(|count| *count += 1);
        if let Err(e) = sender.send(ServiceMessage::CreateAppSvc {
            lxapp: lxapp.clone(),
        }) {
            release_logic_context(lxapp);
            return Err(e.into());
        }
        assignments.insert(key, WorkerAssignment::Active(assignment.worker_id()));
        info!("Reactivating worker for app {}", lxapp.appid);
    } else {
        info!("Reusing existing worker for app {}", lxapp.appid);
    }
    Ok(true)
}

/// Terminate a mini-app service - breaks 1:1 mapping and returns worker to pool
pub(crate) fn terminate_app_svc(
    lxapp_arc: Arc<LxApp>,
    sender: &mpsc::Sender<ServiceMessage>,
    instance_assignments: &Arc<Mutex<HashMap<usize, WorkerAssignment>>>,
    free_workers: &Arc<Mutex<VecDeque<usize>>>,
) -> Result<(), LxAppError> {
    let appid = lxapp_arc.appid.clone();
    let key = lxapp_arc.as_ref() as *const _ as usize;
    let (worker_id, token, rx) = {
        let mut assignments = instance_assignments.lock().unwrap();
        let Some(assignment) = assignments.get(&key).copied() else {
            info!(
                "No active worker mapping for app {}; skipping terminate",
                appid
            );
            return Ok(());
        };
        if matches!(assignment, WorkerAssignment::Terminating { .. }) {
            info!("Worker termination already pending for app {}", appid);
            return Ok(());
        }

        let worker_id = assignment.worker_id();
        let token = NEXT_TERMINATION_TOKEN.fetch_add(1, Ordering::Relaxed);
        let (tx, rx) = oneshot::channel();
        // Enqueue and publish Terminating under one lock so a concurrent reopen
        // cannot put CreateAppSvc ahead of this termination.
        sender.send(ServiceMessage::TerminateAppSvc {
            lxapp: lxapp_arc.clone(),
            worker_id,
            ack_tx: tx,
        })?;
        assignments.insert(key, WorkerAssignment::Terminating { worker_id, token });
        (worker_id, token, rx)
    };

    let assignments = instance_assignments.clone();
    let free_workers = free_workers.clone();
    crate::executor::spawn(await_termination_ack(
        appid,
        key,
        worker_id,
        token,
        rx,
        assignments,
        free_workers,
        Duration::from_secs(3),
    ));

    Ok(())
}

async fn await_termination_ack(
    appid: String,
    key: usize,
    worker_id: usize,
    token: u64,
    mut rx: oneshot::Receiver<()>,
    assignments: Arc<Mutex<HashMap<usize, WorkerAssignment>>>,
    free_workers: Arc<Mutex<VecDeque<usize>>>,
    ack_timeout: Duration,
) {
    match tokio::time::timeout(ack_timeout, &mut rx).await {
        Ok(Ok(())) => {
            info!("Terminate ACK received").with_appid(appid.clone());
            let released =
                take_terminated_assignment(&mut assignments.lock().unwrap(), key, worker_id, token);
            if let Some(worker_id) = released {
                free_workers.lock().unwrap().push_back(worker_id);
                info!("Released dedicated worker {} from app {}", worker_id, appid);
            }
        }
        Ok(Err(_)) => {
            let quarantined =
                take_terminated_assignment(&mut assignments.lock().unwrap(), key, worker_id, token);
            if quarantined.is_some() {
                error!("Terminate ACK channel closed; quarantining worker {worker_id}")
                    .with_appid(appid);
            }
        }
        Err(_) => {
            let quarantined =
                take_terminated_assignment(&mut assignments.lock().unwrap(), key, worker_id, token);
            if quarantined.is_none() {
                return;
            }

            error!("Terminate ACK timeout; quarantining worker {worker_id}")
                .with_appid(appid.clone());
            // The terminate message carries its original worker id, so it still
            // reaches the quarantined worker after this assignment is removed.
            // A late ACK proves cleanup completed and makes reuse safe again.
            match rx.await {
                Ok(()) => {
                    free_workers.lock().unwrap().push_back(worker_id);
                    info!(
                        "Released quarantined worker {} after late ACK for app {}",
                        worker_id, appid
                    );
                }
                Err(_) => {
                    error!("Quarantined worker {worker_id} never acknowledged termination")
                        .with_appid(appid);
                }
            }
        }
    }
}

fn take_terminated_assignment(
    assignments: &mut HashMap<usize, WorkerAssignment>,
    key: usize,
    worker_id: usize,
    token: u64,
) -> Option<usize> {
    let expected = WorkerAssignment::Terminating { worker_id, token };
    if assignments.get(&key) == Some(&expected) {
        assignments.remove(&key).map(WorkerAssignment::worker_id)
    } else {
        None
    }
}

pub(crate) fn restart_app_svc(
    lxapp: Arc<LxApp>,
    sender: &mpsc::Sender<ServiceMessage>,
    instance_assignments: &Arc<Mutex<HashMap<usize, WorkerAssignment>>>,
) -> Result<(), LxAppError> {
    let _creation = crate::device::logic_creation_guard()?;
    let key = lxapp.as_ref() as *const _ as usize;
    let mut assignments = instance_assignments.lock().unwrap();
    let Some(assignment) = assignments.get(&key).copied() else {
        return Err(LxAppError::Runtime(format!(
            "No active worker mapping for app {}",
            lxapp.appid
        )));
    };

    if lxapp.session.is_cancelled() {
        return Err(LxAppError::Runtime(
            "Cannot restart a terminated LxApp session".into(),
        ));
    }
    // Reserve the replacement before the old termination can acknowledge.
    lxapp.logic_contexts.send_modify(|count| *count += 1);
    let queued = if matches!(assignment, WorkerAssignment::Terminating { .. }) {
        sender
            .send(ServiceMessage::CreateAppSvc {
                lxapp: lxapp.clone(),
            })
            .map(|()| {
                assignments.insert(key, WorkerAssignment::Active(assignment.worker_id()));
            })
    } else {
        let (ack_tx, _ack_rx) = oneshot::channel();
        match sender.send(ServiceMessage::TerminateAppSvc {
            lxapp: lxapp.clone(),
            worker_id: assignment.worker_id(),
            ack_tx,
        }) {
            Ok(()) => sender.send(ServiceMessage::CreateAppSvc {
                lxapp: lxapp.clone(),
            }),
            Err(e) => Err(e),
        }
    };
    if let Err(e) = queued {
        release_logic_context(&lxapp);
        return Err(e.into());
    }
    Ok(())
}

/// Give back a Logic context reserved for a message that never reached the worker.
fn release_logic_context(lxapp: &LxApp) {
    lxapp
        .logic_contexts
        .send_modify(|count| *count = count.saturating_sub(1));
}

#[cfg(test)]
mod worker_assignment_tests {
    use super::{WorkerAssignment, await_termination_ack, take_terminated_assignment};
    use std::collections::{HashMap, VecDeque};
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

    #[tokio::test(flavor = "current_thread")]
    async fn termination_ack_follows_context_task_cancellation() {
        use rong::{JSEngine, RongJS};
        use std::sync::atomic::{AtomicBool, Ordering};
        tokio::task::LocalSet::new()
            .run_until(async {
                let root = tempfile::tempdir().unwrap();
                let platform = Arc::new(
                    lingxia_platform::Platform::new(
                        root.path().join("data").display().to_string(),
                        root.path().join("cache").display().to_string(),
                        "en-US".to_string(),
                    )
                    .unwrap(),
                );
                let appid = format!("app.lingxia.logic-termination.{}", uuid::Uuid::new_v4());
                crate::lxapp::register_synthetic_lxapp(appid.clone());
                let app = Arc::new(
                    crate::LxApp::new_with_session_class_for_test(
                        appid,
                        platform,
                        crate::appservice::LxAppWorkers::init(1),
                        crate::lxapp::AppSessionClass::StandardApp,
                    )
                    .unwrap(),
                );
                app.bind_arc();
                let runtime = RongJS::runtime();
                let ctx = runtime.context();
                super::register_app_ctx(&ctx, &app);
                assert!(crate::LxApp::from_ctx(&ctx).is_ok());
                let dropped = Arc::new(AtomicBool::new(false));
                struct Pending(Arc<AtomicBool>);
                impl Drop for Pending {
                    fn drop(&mut self) {
                        self.0.store(true, Ordering::SeqCst);
                    }
                }
                let pending = Pending(dropped.clone());
                ctx.spawn_task(async move {
                    let _pending = pending;
                    std::future::pending::<()>().await;
                });
                tokio::task::yield_now().await;
                app.logic_contexts.send_replace(1);
                app.session.cancel();
                assert!(
                    crate::LxApp::from_ctx(&ctx).is_err(),
                    "native access must stop before worker teardown"
                );
                let (ack_tx, ack_rx) = tokio::sync::oneshot::channel();
                let mut current = Some(ctx);
                super::lxapp_service_handler(
                    0,
                    runtime,
                    super::ServiceMessage::TerminateAppSvc {
                        lxapp: app.clone(),
                        worker_id: 0,
                        ack_tx,
                    },
                    &mut current,
                )
                .await;
                ack_rx.await.unwrap();
                assert!(current.is_none());
                assert!(dropped.load(Ordering::SeqCst));
                assert_eq!(*app.logic_contexts.borrow(), 0);
            })
            .await;
    }

    #[test]
    fn reactivated_assignment_is_not_released_by_old_termination() {
        let mut assignments = HashMap::from([(7, WorkerAssignment::Active(3))]);

        assert_eq!(take_terminated_assignment(&mut assignments, 7, 3, 11), None);
        assert_eq!(assignments.get(&7), Some(&WorkerAssignment::Active(3)));
    }

    #[test]
    fn only_matching_termination_releases_worker() {
        let mut assignments = HashMap::from([(
            7,
            WorkerAssignment::Terminating {
                worker_id: 3,
                token: 12,
            },
        )]);

        assert_eq!(take_terminated_assignment(&mut assignments, 7, 3, 11), None);
        assert_eq!(
            take_terminated_assignment(&mut assignments, 7, 3, 12),
            Some(3)
        );
        assert!(!assignments.contains_key(&7));
    }

    #[tokio::test]
    async fn timeout_quarantines_worker_until_late_ack() {
        let assignments = Arc::new(Mutex::new(HashMap::from([(
            7,
            WorkerAssignment::Terminating {
                worker_id: 3,
                token: 12,
            },
        )])));
        let free_workers = Arc::new(Mutex::new(VecDeque::new()));
        let (tx, rx) = tokio::sync::oneshot::channel();

        let wait = tokio::spawn(await_termination_ack(
            "test.app".to_string(),
            7,
            3,
            12,
            rx,
            assignments.clone(),
            free_workers.clone(),
            Duration::from_millis(1),
        ));
        tokio::time::timeout(Duration::from_secs(1), async {
            loop {
                let quarantined = !assignments.lock().unwrap().contains_key(&7);
                if quarantined {
                    break;
                }
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("worker assignment should be quarantined after the ACK timeout");

        assert!(!assignments.lock().unwrap().contains_key(&7));
        assert!(free_workers.lock().unwrap().is_empty());

        tx.send(()).unwrap();
        wait.await.unwrap();
        assert_eq!(free_workers.lock().unwrap().pop_front(), Some(3));
    }

    #[tokio::test]
    async fn acknowledged_termination_releases_worker_immediately() {
        let assignments = Arc::new(Mutex::new(HashMap::from([(
            7,
            WorkerAssignment::Terminating {
                worker_id: 3,
                token: 12,
            },
        )])));
        let free_workers = Arc::new(Mutex::new(VecDeque::new()));
        let (tx, rx) = tokio::sync::oneshot::channel();
        tx.send(()).unwrap();

        await_termination_ack(
            "test.app".to_string(),
            7,
            3,
            12,
            rx,
            assignments.clone(),
            free_workers.clone(),
            Duration::from_secs(1),
        )
        .await;

        assert!(!assignments.lock().unwrap().contains_key(&7));
        assert_eq!(free_workers.lock().unwrap().pop_front(), Some(3));
    }
}

#[cfg(test)]
mod eval_script_shape_tests {
    use super::script_looks_like_function_body;

    #[test]
    fn await_without_semicolon_is_a_function_body() {
        assert!(script_looks_like_function_body(
            r#"await lx.host.control.displayLanguage.setPreference("zh-CN")"#
        ));
        assert!(script_looks_like_function_body(
            "await(lx.host.cache.clear())"
        ));
    }

    #[test]
    fn return_and_declarations_are_function_bodies() {
        assert!(script_looks_like_function_body(
            "return lx.host.control.displayLanguage.getPreference()"
        ));
        assert!(script_looks_like_function_body("const x = 1; return x"));
    }

    #[test]
    fn a_plain_expression_is_not_a_function_body() {
        assert!(!script_looks_like_function_body("lx.host.getBaseInfo()"));
    }
}

/// Wrapper for LxApp to implement external traits
#[derive(Clone)]
struct LxAppCtx {
    lxapp: Arc<LxApp>,
}

#[derive(Debug)]
struct DenyAllNetworkAccessGuard;

impl http::NetworkAccessGuard for DenyAllNetworkAccessGuard {
    fn check_access(&self, _domain: &str) -> JSResult<()> {
        Err(network_access_denied_error("network access is denied"))
    }
}

impl LxAppCtx {
    pub fn new(lxapp: Arc<LxApp>) -> Self {
        Self { lxapp }
    }
}

impl std::fmt::Debug for LxAppCtx {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LxAppCtx")
            .field("appid", &self.lxapp.appid)
            .finish()
    }
}

impl http::NetworkAccessGuard for LxAppCtx {
    /// Check if the mini app has access to the specified domain
    /// Returns Ok(()) if access is granted, Err with error message if denied
    fn check_access(&self, domain: &str) -> JSResult<()> {
        if !self.lxapp.session.is_cancelled() && self.lxapp.is_domain_allowed(domain) {
            Ok(())
        } else {
            Err(network_access_denied_error(format!(
                "domain '{domain}' is not allowed by lxapp security policy"
            )))
        }
    }
}

fn network_access_denied_error(detail: impl AsRef<str>) -> RongJSError {
    HostError::new(rong::error::E_PERMISSION_DENIED, "Permission denied")
        .with_data(rong::err_data!({ bizCode: (3000), detail: (detail.as_ref()) }))
        .into()
}