bao-browser 0.1.19

A Rust-native programmable browser runtime built on Servo and SpiderMonkey
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
// @trace REQ-BRW-001 [entity:BrowserContext] [entity:PageHandle]
// @trace REQ-BRW-004 [entity:Worker] [entity:DedicatedWorkerGlobalScope]
// @trace REQ-BRW-4 [entity:Worker] [entity:SharedWorker] [entity:ServiceWorker]
// @trace REQ-CLI-002
#![allow(dead_code, unused_imports)]
// REQ-BRW-001: Browser engine integration with servo
// REQ-BRW-004: Worker constructor bridging to Page Realm (DF-WK-11)
// REQ-BRW-4: Worker/SharedWorker/ServiceWorker constructors on JS global object
// REQ-CLI-002: bao browser 子命令 → servo 初始化 + CDP 端口输出
// REQ-LIB-004: BaoRuntime top-level coordinator
mod cdp_handler;
pub mod cdp_memory;
mod config;
mod delegate;
mod error;
mod page;
mod page_pool;
mod phase_watch;
mod permission;
mod runtime_bridge;
mod screenshot;
mod ws_registry;

pub use config::{BaoConfig, BrowserConfig, PageConfig};
// Bridge-command handler — the servo-side executor that drains
// BridgeCommand during the event loop (run_with_bridge's per-command entry).
// Public for e2e tests that drive the same loop shape as run_browser.
pub use cdp_handler::handle_bridge_command;
pub use delegate::{
    crash_safe_teardown_worker, is_javascript_mime_type, AutoCloseWorker, BaoServoDelegate,
    BaoWebViewDelegate, BaoWebViewState, DedicatedWorkerGlobalScopeState,
    ServiceWorkerFetchInterceptMode, ServiceWorkerGlobalScopeState, ServiceWorkerHandle,
    ServiceWorkerRegistrationId, ServiceWorkerRegistrationState, ServiceWorkerRegistrationTracking,
    ServiceWorkerScopeConfig, SharedWorkerChannelBridge, SharedWorkerConnectEvent,
    SharedWorkerGlobalScopeState, SharedWorkerHandle, SharedWorkerId, SharedWorkerPortChannel,
    SharedWorkerPortEndpoints, SharedWorkerPortRef, SharedWorkerScopeConfig,
    StructuredClonePayload, WorkerChannelBridge, WorkerChannelEndpoints, WorkerErrorEvent,
    WorkerGlobalScopeState, WorkerHandle, WorkerId, WorkerLifecycleState, WorkerLocation,
    WorkerMessageDirection, WorkerMessageEvent, WorkerNavigator, WorkerNetworkInformation,
    WorkerScopeConfig, WorkerScriptLoadError, WorkerScriptLoadResult, WorkerScriptLoadState,
    WorkerScriptLoader, WorkerScriptSource, WorkerScriptType, WorkerStructuredMessage,
    WorkerTeardownPath, WorkerTeardownResult,
};
pub use error::BrowserError;
pub use page::{PageHandle, PageState};
pub use page_pool::PagePool;
pub use permission::{Permission, PermissionDenied, PermissionGuard};
pub use runtime_bridge::{
    register_worker_scope_callback_native, BridgeChannel, BridgeCommand, BridgeReceiver,
    BridgeResponse, EvaluateResult, RuntimeBridge, WorkerScopeInitFn,
};
pub use screenshot::{encode_image, ScreenshotFormat};
pub use ws_registry::BaoWsRegistry;

use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;

use servo::{Opts, Preferences, Servo, ServoBuilder};

use bao_cdp::domains::ServoTargetProvider;
use bao_cdp::servo_bridge::bridge_channel;
use bao_cdp_client::bridge::{translate, ServoEvent};
use cdp_server::{CdpServer, EventBroadcaster, EventSender, ServerConfig};

// BAO PATCH (BCE-20260627-009): Process-global servo opts initialization.
// servo's `opts::initialize_options` uses an `OnceLock<Opts>` that panics on re-init,
// and `opts::get()` lazily fills it with `Default`. If ANY servo code calls `get()`
// before our explicit `initialize_options`, the OnceLock locks to Default and bao's
// config (force_isolate_event_loops=true) can never win.
//
// `BAO_SERVO_OPTS_INIT` is a `LazyLock` that runs `initialize_options` with bao's
// config on first access. `BaoRuntime::new` forces it (`.clone()` triggers init)
// BEFORE constructing `Servo`, winning the OnceLock race process-wide. Multi-instance
// safety: subsequent `BaoRuntime::new` calls hit the idempotent path in the patched
// `initialize_options` (same bao config → no-op).
static BAO_SERVO_OPTS_INIT: std::sync::LazyLock<()> = std::sync::LazyLock::new(|| {
    servo::opts::initialize_options(Opts {
        force_isolate_event_loops: true,
        disable_script_debugger: true,
        ..Opts::default()
    });
});

pub struct BaoRuntime {
    servo: Rc<Servo>,
    delegate: Rc<BaoServoDelegate>,
    page_pool: Rc<PagePool>,
    cdp_port: Option<u16>,
    /// Receiver side of the memory:// CDP bridge installed into
    /// `bao_cdp_client`'s process registry — `run()` drains it so
    /// servo-touching in-process CDP commands get real execution.
    cdp_bridge: Option<std::sync::Arc<cdp_memory::MemoryCdpBridge>>,
    cdp_bridge_rx: Option<bao_cdp::servo_bridge::BridgeReceiver>,
    /// Generation token for registry teardown (Drop clears only if this
    /// runtime's bridge is still the installed one).
    cdp_bridge_token: Option<usize>,
}

impl BaoRuntime {
    pub fn new(config: BaoConfig) -> Result<Self, BrowserError> {
        config.validate().map_err(BrowserError::Init)?;

        // Force-init servo's process-global OnceLock<Opts> BEFORE any servo code
        // calls get() (which would lazily lock in Default). This wins the race
        // against servo's get_or_init(Default::default).
        //
        // Config-derived opts go in FIRST (initialize_options is
        // first-writer-wins): the static LazyLock below only exists to win the
        // same race for code paths that never construct a BaoRuntime, so once
        // this call runs it is a no-op. `ignore_certificate_errors` is the one
        // field tests set non-default (WPT posture against local self-signed
        // TLS fixtures, e.g. the U2 h2 e2e matrix).
        servo::opts::initialize_options(Opts {
            force_isolate_event_loops: true,
            disable_script_debugger: true,
            ignore_certificate_errors: config.ignore_certificate_errors,
            ..Opts::default()
        });
        std::sync::LazyLock::force(&BAO_SERVO_OPTS_INIT);

        // BUG-ENG-366: `force_isolate_event_loops` only governs servo's event-loop
        // multiplexing (per-pipeline ScriptThread vs shared). It does NOT control
        // SpiderMonkey Compartment isolation — every page always gets its own
        // Window global in a distinct Compartment (servo DOM invariant), and the
        // Node Realm is created via NewCompartmentAndZone unconditionally
        // (runtime_bridge::create_node_realm_native). Stealth noise is keyed
        // per-Realm via bao_stealth::engine_props::set_profile_for_global, so
        // even with `force_isolate_event_loops: false` each page's Canvas /
        // Navigator / WebGL / Audio fingerprints remain isolated. The flag is
        // kept `true` here purely to bound servo's resource use (one ScriptThread
        // per page) — disabling it does not regress isolation.
        // @trace REQ-SEC-002 [req:REQ-SEC-002] [req:BUG-ENG-366]
        //
        // BAO PATCH (BCE-20260627-009): Idempotent servo config init.
        // servo's `opts::initialize_options` uses a process-global `OnceLock<Opts>`;
        // re-initializing panics. Each `BaoRuntime::new` → `Servo::new` →
        // `initialize_options`. Multiple BaoRuntime instances (production
        // multi-tenant + concurrent integration tests) therefore collide.
        // Strategy:
        //   (1) Detect whether servo config is already initialized by reading
        //       `servo::opts::get()` (returns `&'static Opts`, never panics —
        //       falls back to `Default` via `get_or_init`).
        //   (2) `force_isolate_event_loops` is `false` in `Opts::default` but
        //       `true` in our desired config, so it is a reliable sentinel for
        //       "already initialized by a prior BaoRuntime".
        //   (3) On the already-initialized path we skip `.opts(...)` — but
        //       `Servo::new` still calls `initialize_options` internally, so the
        //       vendor-side patch (idempotent `initialize_options`) is the real
        //       guarantee. This bao-layer check just avoids passing conflicting
        //       opts when we know a prior instance already configured servo.
        let desired_opts = Opts {
            force_isolate_event_loops: true,
            ignore_certificate_errors: config.ignore_certificate_errors,
            // BAO PATCH (BCE-20260621-002): Skip servo's
            // `JS::Debugger::addDebuggee` path entirely. Bao embeds
            // servo but uses `bao_cdp` (its own CDP) and never connects
            // to servo's devtools server, so the servo Debugger is pure
            // overhead and a SIGSEGV source: `fire_add_debuggee` marks
            // every page's Realm as a debuggee
            // (`Realm::setIsDebuggee`), which toggles
            // BaselineInterpreter debugger instrumentation. Under bao's
            // multi-page + navigate + later-`evaluate` workload, a
            // subsequent JIT OSR dereferences
            // `cx->activation_->prev()->asInterpreter()` as NULL and
            // SIGSEGVs deterministically. Setting this flag bypasses
            // `fire_add_debuggee` (gated upstream in
            // `script_thread.rs`), so `setIsDebuggee` is never called
            // and the JIT toggle never happens. Servo's default `false`
            // keeps devtools working for normal servo embedders.
            disable_script_debugger: true,
            ..Opts::default()
        };
        // `opts::get()` is `get_or_init(Default::default)`: returns the
        // process-wide config if already set, otherwise `Default` (where
        // `force_isolate_event_loops == false`). Our config sets it `true`,
        // so observing `true` here means a prior BaoRuntime already won.
        let servo_already_initialized = servo::opts::is_initialized();

        // Pref override surface (bao is the embedder; vendor defaults stay
        // untouched). `Servo::new` ends with
        // `prefs::set(preferences.unwrap_or_default())` — passing NO builder
        // preferences resets every pref to `Preferences::default()`. So the
        // only durable injection point is `ServoBuilder::preferences`, on
        // BOTH branches (the already-initialized branch would otherwise wipe
        // the flip below on the next BaoRuntime). Both branches start from
        // `Preferences::default()` — exactly what `Servo::new` would install
        // without a builder override — so the only delta is the flip.
        //
        // `dom_indexeddb_enabled` defaults to false upstream (experimental),
        // but bao is a full browser runtime and servo ships a real IDB
        // implementation; `GlobalScope::obtain_storage_key` reads this pref
        // at runtime per IDB open, so every page (and worker) scope gets it.
        let mut preferences = Preferences::default();
        preferences.dom_indexeddb_enabled = true;
        // `dom_offscreen_canvas_enabled` defaults to false upstream
        // (experimental); the vendor OffscreenCanvas implementation
        // (`script/dom/canvas/offscreencanvas.rs`) is complete
        // (Constructor/getContext/transferToImageBitmap/convertToBlob,
        // `Exposed=(Window,Worker)`), so the pref is the only gate.
        // REQ-BRW-004 C13 + user ruling 2026-09-09: stealth pages need a
        // worker-realm canvas surface (CreepJS/fp-collect probe OffscreenCanvas
        // inside Workers; `undefined` there is itself a fingerprint signal).
        preferences.dom_offscreen_canvas_enabled = true;
        // `dom_serviceworker_enabled` defaults to false upstream; the vendor SW
        // implementation is real (`ServiceWorkerContainer.register` → job →
        // `ServiceWorkerGlobalScope::run_serviceworker_scope`). The pref gates
        // `navigator.serviceWorker`, the container interface and the
        // ServiceWorkerGlobalScope global (webidl `Pref=`), so without the flip
        // pages see no SW surface at all and the SW scope's embedder drain
        // (REQ-BRW-004 S1, DF-WK-10 stealth inheritance) can never fire.
        // REQ-BRW-004 C19 prerequisite + user ruling 2026-09-09.
        preferences.dom_serviceworker_enabled = true;
        // `dom_webgl2_enabled` defaults to false upstream; the vendor WebGL2
        // implementation (`script/dom/webgl/webgl2renderingcontext.rs`) is real
        // and the pref is the first gate in
        // `OffscreenCanvas::get_or_init_webgl2_context` (via
        // `WebGL2RenderingContext::is_webgl2_enabled`), before any channel
        // dispatch — without the flip `getContext('webgl2')` returns null in
        // BOTH realms. Real browsers ship WebGL2 on, so a missing webgl2
        // surface is itself a fingerprint signal. REQ-BRW-004 C14 + user
        // ruling 2026-09-09.
        preferences.dom_webgl2_enabled = true;

        let servo: Rc<Servo> = Rc::new(if servo_already_initialized {
            // Already initialized. `Servo::new` (servo.rs:877) ALWAYS calls
            // `initialize_options(opts.unwrap_or_default())` — if we pass no
            // `.opts(...)`, it would invoke `initialize_options(Default)`
            // with (force_isolate_event_loops=false, disable_script_debugger=false),
            // which DIFFERS from the already-set (true, true) and would trip
            // the "conflicting bao config" panic in the patched
            // `initialize_options`. To stay idempotent, we clone the
            // already-stored opts and re-pass them: `Servo::new`'s internal
            // `initialize_options(existing.clone())` then sees identical
            // bao fields and becomes a no-op. This is the only way to keep
            // `Servo::new`'s unconditional `initialize_options` call safe
            // across multiple BaoRuntime instances.
            //
            // NOTE: we use `is_initialized()` (pure read, no side effect),
            // NOT `opts::get()`. `opts::get()` uses `get_or_init(Default)`,
            // which would itself populate the `OnceLock` with defaults on the
            // very first call — racing against `Servo::new`'s real
            // `initialize_options((true, true))` and causing a spurious
            // "conflicting config" panic.
            ServoBuilder::default()
                .opts(servo::opts::get().clone())
                .preferences(preferences)
                .build()
        } else {
            ServoBuilder::default()
                .opts(desired_opts)
                .preferences(preferences)
                .build()
        });

        let delegate = Rc::new(BaoServoDelegate::new());
        servo.set_delegate(Rc::clone(&delegate) as Rc<dyn servo::ServoDelegate>);

        // BCE (page-realm async fetch black hole): wire the embedder
        // event-loop pump bridge — BOTH directions, process-globally (first
        // registration wins, so a second BaoRuntime re-registers no-ops).
        //
        // Page realms install the Node-stack `fetch` override (same stack,
        // same fingerprint — the page-net unification posture), whose resolve
        // ConcurrentTask lands on the ScriptThread's bao MiniEventLoop — a
        // loop servo never ticks: `handle_msgs` blocks on servo's own
        // receivers. Without the bridge the request egressed but the page's
        // `fetch()` Promise never settled (fetch_axis_probe_tests B axis).
        //   pump side: servo calls it on each ScriptThread right after its
        //     blocking recv wakes, with the thread's JSContext.
        //   wake side: the fetch machinery captures the creating thread's
        //     wake closure (a servo `WakeUp` self-send) and fires it from the
        //     HTTPThread on resolve — that is exactly what unblocks the recv
        //     above. Node-realm threads have no servo wake entry (`None`) and
        //     keep their node-loop pumping unchanged.
        servo::register_bao_event_loop_pump(Box::new(|cx_ptr| {
            bun_runtime::timers::pump_embedder_thread(cx_ptr as *mut mozjs::jsapi::JSContext);
        }));
        // RED-1 P-A (user ruling 2026-09-10): same-registered-domain
        // navigation discards the old page realm on the REUSED
        // ScriptThread — servo cancels its own task sources in
        // `Window::clear_js_runtime`, but bao timers registered against the
        // old realm's global survived it: deadlines fired zombie callbacks
        // into the WindowState::Zombie realm, re-arming setImmediate chains
        // ran forever, and the raw-rooted `global_root` pinned the realm
        // against GC (per-navigation accumulation). Bridge the discard
        // (vendor patch, same registration face as the pump above) to bao's
        // per-thread timer registry purge — a document's timers die with
        // the document (browser navigation semantics).
        servo::register_bao_realm_discard_cancel(Box::new(|cx_ptr, global_ptr| {
            bun_runtime::timers::cancel_timers_for_global(
                cx_ptr as *mut mozjs::jsapi::JSContext,
                global_ptr as *mut mozjs::jsapi::JSObject,
            );
        }));
        // BCE-20260910-004 (settings-stack push — the missing half of the
        // pump bridge): the pump fires page-realm bao timers outside any
        // servo script settings-stack entry, so a page callback touching
        // `location.*` / `document.open()` / canvas origin-clean hit
        // `entry_global().unwrap()` on an empty stack and panicked
        // (settings_stack.rs:36, Script#3 meituan). Lend servo's own
        // "prepare to run script" wrapper (`run_a_script`) to bao's timer
        // dispatch — the same contract every servo JS entry honors.
        bun_runtime::timers::register_bao_settings_runner(Box::new(
            |cx, global, f| {
                servo::bao_run_in_script_settings(
                    cx as *mut std::ffi::c_void,
                    global as *mut std::ffi::c_void,
                    f,
                );
            },
        ));
        bun_runtime::fetch_async::set_thread_wakeup_bridge(|| {
            servo::bao_current_thread_wake_fn().map(|wake| {
                wake as bun_runtime::fetch_async::ThreadWakeup
            })
        });

        // BCE-20260910-002 (embedder pump gap — webview-less fetch): SW/worker
        // realms carry no webview, so their fetches round-trip
        // `WebResourceRequested(target_webview_id=None)` through the
        // net→embedder channel, which ONLY `Servo::spin_event_loop` drains —
        // and bao pumps that solely from PageHandle interaction APIs. With the
        // owning page idle (no evaluate/screenshot in flight), the round-trip
        // was never answered and the SW's fetch parked forever (the
        // fetchevent 25s stall). A resident pump thread is structurally
        // impossible: `Servo(Rc<ServoInner>)` is !Send/!Sync (RefCell/Rc
        // state), so only the creating thread may spin — and that thread can
        // be asleep in user code no bao hook can reach. Instead the net
        // interceptor consults this process-global handler for webview-less
        // requests; `PassThrough` is byte-equivalent to what the embedder
        // path produces for bao today (BaoServoDelegate inherits the no-op
        // `ServoDelegate::load_web_resource` → `WebResourceLoad` drop →
        // default DoNotIntercept). Webview-owned requests keep the full
        // embedder round-trip (CDP/stealth mediation unchanged). If bao ever
        // overrides `load_web_resource` for webview-less loads, that logic
        // belongs in this handler.
        servo::set_webviewless_resource_handler(Some(Arc::new(
            |_request| servo::BaoWebviewlessResourceVerdict::PassThrough,
        )));

        let page_pool = Rc::new(PagePool::new(
            Rc::clone(&servo),
            Rc::clone(&delegate),
            &config,
        ));

        // #40 page-pipeline stall watchdog: every page op runs on this
        // thread; when one wedges inside a never-returning primitive the
        // process hangs silently (soak MTBF≈46min). The watchdog thread is
        // the only in-process witness that can still speak — it dumps the
        // stalled phase + thread wchan snapshot to the log (idempotent,
        // process-wide, pure observer).
        phase_watch::spawn_watchdog();

        // memory:// CDP transport (published consumer contract:
        // `Browser::connect("memory://bao")` → `version()`/`pages()`).
        // Install the host-side bridge into bao_cdp_client's process
        // registry (last-writer-wins across runtimes); `run()` drains the
        // receiver so servo-routed commands execute for real.
        let (cdp_bridge, cdp_bridge_rx) = cdp_memory::MemoryCdpBridge::new("");
        let cdp_bridge_token =
            bao_cdp_client::browser::set_process_memory_bridge(
                cdp_bridge.clone() as std::sync::Arc<dyn bao_cdp_client::transport::InMemoryBridge>,
            );

        Ok(BaoRuntime {
            servo,
            delegate,
            page_pool,
            cdp_port: config.cdp_port,
            cdp_bridge: Some(cdp_bridge),
            cdp_bridge_rx: Some(cdp_bridge_rx),
            cdp_bridge_token: Some(cdp_bridge_token),
        })
    }

    pub fn page_pool(&self) -> &Rc<PagePool> {
        &self.page_pool
    }

    pub fn create_page(&self, config: &PageConfig) -> Result<PageHandle, BrowserError> {
        // ALL page injection (engine/Web APIs + stealth props + Worker-scope
        // callback) happens exactly ONCE inside PagePool::create_page — the
        // single true source. This method used to re-run
        // inject_all_with_profile on the already-injected page; the second
        // install_webgl_override re-saved the first pass's JS hook as
        // "__originalGetParameter__", dead-looping every un-intercepted
        // getParameter into literal `undefined` in the Window realm (e36).
        // Pipeline readiness is established inside PagePool::create_page
        // (wait_for_pipeline_ready + drain_callbacks) before that injection.
        let page = self.page_pool.create_page(config)?;

        // The memory:// flat client face follows the newest page.
        if let Some(bridge) = &self.cdp_bridge {
            bridge.set_default_target(page.id().to_string());
        }
        Ok(page)
    }

    /// Create a Dedicated Worker bridged to a page's servo Realm.
    ///
    /// This is the primary entry point for the Worker constructor bridging
    /// Create a Dedicated Worker via servo's native Worker::Constructor.
    ///
    /// Per DEC-WK-001 (BCE-20260627-008), bao no longer spawns a
    /// `bao_engine::WebWorker` bypass thread. Instead, this method dispatches
    /// `new Worker(url)` into the page via servo's DOM binding, and servo
    /// constructs the Worker thread + DedicatedWorkerGlobalScope internally.
    /// bao's role is reduced to:
    ///   1. Steering stealth profile + DedicatedWorkerGlobalScope Web APIs by
    ///      registering the scope callback via
    ///      `register_worker_scope_callback_native` (per-worker, see
    ///      `create_worker_with_url`; page-init registration for page-script
    ///      created Workers lives in `inject_all_with_profile`). The callback
    ///      runs on the Worker thread via the servo vendor patch
    ///      `drain_worker_scope_callbacks`.
    ///   2. Tracking the WorkerHandle for CDP observability + page-unload
    ///      termination (criterion #10, AutoCloseWorker).
    ///   3. Providing a WorkerChannelBridge for page↔worker postMessage
    ///      (criterion #6, DF-WK-4/5) so the bao side can still observe
    ///      structured-clone traffic even though the thread is servo-owned.
    ///
    /// The `script` argument is treated as a Worker script URL. For inline
    /// scripts, callers should materialize a `data:`/`blob:` URL and pass it
    /// here (or call `create_worker_with_url`).
    ///
    /// @trace DEC-WK-001 servo-native Worker path (bypass removed)
    /// @trace REQ-BRW-004 [entity:Worker] [criterion:1..10] [criterion:12..18]
    /// @trace REQ-BRW-4 [criterion:C1..C4]
    pub fn create_worker(
        &self,
        page: &PageHandle,
        script: &str,
    ) -> Result<WorkerHandle, BrowserError> {
        self.create_worker_with_url(page, script)
    }

    /// Create a Dedicated Worker with a script URL resolved by servo's native
    /// script loading pipeline.
    ///
    /// Per DEC-WK-001 (BCE-20260627-008) the bypass `bao_engine::WebWorker`
    /// path is removed. The Worker is constructed by servo's DOM
    /// `Worker::Constructor` when `new Worker(url)` is evaluated in the page.
    /// This method:
    ///   1. Builds the WorkerId + WorkerHandle (closing/terminated flags +
    ///      REALM_PROFILES global_addr_slot, criterion #18).
    ///   2. Wires up the WorkerChannelBridge (criterion #6, DF-WK-4/5).
    ///   3. Registers DedicatedWorkerGlobalScope state for CDP observability
    ///      (criteria #8, #12-17 stealth consistency).
    ///   4. Tracks the Worker with AutoCloseWorker (criterion #10).
    ///   5. Dispatches `new Worker(url)` into the page via servo's DOM binding.
    ///
    /// @trace DEC-WK-001 servo-native Worker path (bypass removed)
    /// @trace REQ-BRW-004 [entity:Worker] [DF-WK-2]
    /// @trace REQ-BRW-4 [criterion:C1..C4]
    pub fn create_worker_with_url(
        &self,
        page: &PageHandle,
        url: &str,
    ) -> Result<WorkerHandle, BrowserError> {
        let webview_state = page.webview_state();

        // Get the page's WorkerScopeConfig for stealth consistency.
        // The per-worker scope callback registered below inherits this profile
        // onto the Worker's DedicatedWorkerGlobalScope.
        // @trace REQ-BRW-004 [criterion:12..17] CRIT-STL-WK
        let scope_config = webview_state.borrow().worker_scope_config.clone();

        // Generate WorkerId
        let worker_id = crate::delegate::WorkerId(url.to_string());

        // Create WorkerHandle — tracks closing/terminated state via
        // Arc<AtomicBool> and the worker_global_addr for REALM_PROFILES
        // cleanup (criterion #18). The per-worker scope callback registered
        // below (before the `new Worker(url)` dispatch) writes the Worker's
        // global address into this handle's slot on its first run on the
        // Worker thread, making crash-safe teardown's REALM_PROFILES
        // unregistration production-reachable (E22 audit defect C).
        // @trace REQ-BRW-004 [criterion:18] REALM_PROFILES 条目注销
        let handle = WorkerHandle::new(url.to_string());

        // Register a per-worker scope callback carrying this handle's
        // global-addr slot, keyed to THIS page's WebViewId so only Workers
        // created by this page drain it (cross-page crosstalk fix: without
        // the key a global queue drain let one page's Worker consume another
        // page's queued callback). Registered strictly before the
        // `new Worker(url)` dispatch so the callback is queued when servo's
        // Worker thread drains EMBEDDER_WORKER_SCOPE_CALLBACKS at scope
        // construction (DEC-WK-001). On the callback's first run the Worker
        // global's address is backfilled into the handle and the page's
        // stealth profile is installed (criteria #12-17).
        // @trace REQ-BRW-004 [criterion:18] REALM_PROFILES 条目注销
        let webview_id = page
            .webview_id()
            .ok_or_else(|| BrowserError::Init("page has no webview".into()))?;
        runtime_bridge::register_worker_scope_callback_native(
            webview_id,
            scope_config.stealth_profile.clone(),
            Some(handle.worker_global_addr_arc()),
        );
        // Second-phase per-worker registration RETIRED (REQ-BRW-004, e43
        // multi-worker gap fix): the page-init per-Worker interfaces-ready
        // INJECTOR (registered in PagePool::create_page, non-consuming) now
        // covers EVERY Worker of this page at the same post-interfaces drain
        // point — including this bao-created one. Keeping BOTH made the first
        // Worker run the W1a JS hooks blob twice at that point, and the audio
        // getChannelData wrapper (closure-based, no property-slot idempotency
        // guard) double-applied the deterministic noise, breaking cross-realm
        // digest equality. The scope callback above (slot backfill) stays
        // consume-once.
        // @trace REQ-BRW-004 [criterion:15] worker JS-hook per-Worker delivery

        // Create channel bridge (DF-WK-4/5). Even though servo owns the Worker
        // thread, bao still tracks the bidirectional structured-clone traffic
        // for CDP observability and message logging.
        // @trace REQ-BRW-004 [criterion:6] DF-WK-4 / DF-WK-5
        let _endpoints = webview_state
            .borrow_mut()
            .create_worker_channel(worker_id.clone());

        // Register DedicatedWorkerGlobalScope state for CDP observability
        // and stealth consistency verification.
        // @trace REQ-BRW-004 [entity:DedicatedWorkerGlobalScope]
        let scope_state =
            crate::delegate::DedicatedWorkerGlobalScopeState::new(worker_id.clone(), &scope_config);
        webview_state
            .borrow_mut()
            .register_dedicated_worker_scope(worker_id.clone(), scope_state);

        // Track the WorkerHandle with AutoCloseWorker — ensures termination on
        // page unload (SPEC criterion #10: GlobalScope::track_worker).
        // @trace REQ-BRW-004 [criterion:10] GlobalScope::track_worker + AutoCloseWorker
        webview_state.borrow_mut().track_worker(handle.clone());

        // Dispatch `new Worker(url)` into the page via servo's DOM binding.
        // servo's Worker::Constructor runs the full DF-WK-2 pipeline
        // (fetch → MIME check → decode → compile) and spawns the Worker thread
        // internally; bao's scope callback fires on the Worker thread to install
        // DedicatedWorkerGlobalScope APIs + stealth properties (criteria #8, #12-17).
        // @trace DEC-WK-001 servo-native Worker path
        // @trace REQ-BRW-004 [criterion:1] new Worker(url) creates worker thread
        // @trace REQ-BRW-004 [DF-WK-2] Worker script loading pipeline
        let new_worker_js = format!(
            "(function() {{ var w = new Worker({}); return ''; }})();",
            serde_json::Value::String(url.to_string())
        );
        page.evaluate_js_web(&new_worker_js).map_err(|e| {
            BrowserError::Init(format!(
                "Failed to dispatch new Worker({:?}) via servo DOM: {}",
                url, e
            ))
        })?;

        log::debug!(
            "[bao] dispatched new Worker({:?}) via servo DOM (tracked via AutoCloseWorker, DEC-WK-001 native path)",
            url
        );

        Ok(handle)
    }

    pub fn spin_event_loop(&self) {
        self.servo.spin_event_loop();
    }

    /// Set the console log forwarding channel on the servo delegate.
    /// Console messages from servo will be sent to this channel.
    pub fn set_console_log_channel(&self, tx: std::sync::mpsc::Sender<cdp_server::ConsoleMessage>) {
        self.delegate.set_console_log_tx(tx.clone());
        // Retro-propagate to every existing page's webview state, exactly
        // like set_event_channel below: servo routes console messages
        // per-webview (ShowConsoleApiMessage → the webview delegate reads
        // state.console_log_tx), so a channel set only on the runtime-level
        // delegate never reaches pages created before this call — in
        // run_browser that is precisely the initial page, whose
        // `__BAO_EVT__` CDP-event texts (Debugger.scriptParsed/.paused,
        // SM-EVOLUTION #27 裁决 2 transport) would die in the webview
        // delegate's unset state.
        // @trace REQ-CDP-006 [entity:ServoDelegateHooks]
        let stats = self.page_pool.stats();
        for id in 1..=(stats.active + stats.idle) {
            if let Some(page) = self.page_pool.get_page(id) {
                page.webview_state().borrow_mut().console_log_tx = Some(tx.clone());
            }
        }
    }

    /// Set the structured event forwarding channel on the servo delegate.
    /// When set, servo callbacks push ServoEvent (Path B) as the primary event path.
    /// Also propagates the sender to every existing page's webview state —
    /// servo routes per-webview callbacks (console/url/load) through the
    /// per-webview delegate, which reads `state.event_tx`, so the channel
    /// must live on each state, not only the runtime-level delegate.
    /// @trace REQ-CDP-006 [entity:ServoDelegateHooks]
    pub fn set_event_channel(&self, tx: std::sync::mpsc::Sender<ServoEvent>) {
        self.delegate.set_event_tx(tx.clone());
        let stats = self.page_pool.stats();
        for id in 1..=(stats.active + stats.idle) {
            if let Some(page) = self.page_pool.get_page(id) {
                page.webview_state().borrow_mut().event_tx = Some(tx.clone());
            }
        }
    }

    pub fn run(&self) -> Result<(), BrowserError> {
        let max_wait = Duration::from_secs(300);
        let start = std::time::Instant::now();

        while start.elapsed() < max_wait {
            self.servo.spin_event_loop();
            self.page_pool.check_idle_pages();
            // memory:// CDP commands (process-registry bridge) execute here:
            // the drain answers every in-process client command that routed
            // through the bridge channel (Runtime.evaluate, Target listing…).
            if let Some(rx) = &self.cdp_bridge_rx {
                rx.drain(|cmd| cdp_handler::handle_bridge_command(cmd, &self.page_pool));
            }
            // Yield instead of sleep — servo spin_event_loop is non-blocking.
            std::thread::yield_now();
        }

        let _stats = self.page_pool.stats();

        Ok(())
    }

    /// Bounded single-thread CDP pump: spin the servo loop and drain the
    /// memory:// CDP bridge for `duration`. This is the single-threaded
    /// consumer contract for in-process CDP — the `BaoRuntime` is `!Send`
    /// (per-thread JSContext model), so the runtime thread pumps while a
    /// helper thread holds the `Browser` client whose dispatches arrive
    /// through the bridge channel this drain answers.
    ///
    /// `BaoRuntime::run` is the unbounded version (it also drains).
    pub fn pump_cdp(&self, duration: std::time::Duration) {
        let start = std::time::Instant::now();
        while start.elapsed() < duration {
            self.servo.spin_event_loop();
            self.page_pool.check_idle_pages();
            if let Some(rx) = &self.cdp_bridge_rx {
                rx.drain(|cmd| cdp_handler::handle_bridge_command(cmd, &self.page_pool));
            }
            std::thread::yield_now();
        }
    }

    /// Run with a CDP bridge that processes commands during the event loop.
    /// Also drains ServoEvent from the EventSubscriber path (Path B) and
    /// broadcasts translated CdpEvents via the shared EventBroadcaster.
    /// @trace REQ-CDP-006 [entity:ServoDelegateHooks]
    pub fn run_with_bridge(
        &self,
        bridge_rx: bao_cdp::servo_bridge::BridgeReceiver,
        servo_event_rx: std::sync::mpsc::Receiver<ServoEvent>,
        broadcaster: Arc<EventBroadcaster>,
    ) -> Result<(), BrowserError> {
        let max_wait = Duration::from_secs(3600);
        let start = std::time::Instant::now();

        while start.elapsed() < max_wait {
            self.servo.spin_event_loop();
            self.page_pool.check_idle_pages();

            // Process pending CDP bridge commands
            bridge_rx.drain(|cmd| cdp_handler::handle_bridge_command(cmd, &self.page_pool));

            // Drain ServoEvent from EventSubscriber (Path B) and broadcast
            // as CDP events via the shared EventBroadcaster.
            // @trace REQ-CDP-006 [entity:ServoDelegateHooks]
            while let Ok(servo_event) = servo_event_rx.try_recv() {
                let cdp_events = translate(servo_event);
                for cdp_event in cdp_events {
                    broadcaster.send_event(&cdp_event.method, cdp_event.params);
                }
            }

            // Yield instead of sleep — check bridge commands more frequently.
            std::thread::yield_now();
        }

        Ok(())
    }
}

impl Drop for BaoRuntime {
    fn drop(&mut self) {
        self.page_pool.close_all();
        // Remove this runtime's memory bridge unless a newer runtime has
        // already replaced it in the process registry.
        if let Some(token) = self.cdp_bridge_token.take() {
            bao_cdp_client::browser::clear_process_memory_bridge(token);
        }
    }
}

/// RETIRED (REQ-BRW-004, e43 multi-worker gap fix): the consume-once
/// interfaces-ready callback registration that used to live here was replaced
/// by the PER-WORKER injector below (`register_worker_interfaces_ready_
/// injector_native`, registered once at page init and delivered to EVERY
/// Dedicated Worker of the page). Keeping both made the first Worker run the
/// W1a JS hooks blob twice at the second drain point — the audio
/// getChannelData wrapper is closure-based with no property-slot idempotency
/// guard (unlike getParameter's e36 __originalGetParameter__ gate), so the
/// double wrap double-applied the deterministic noise and broke cross-realm
/// digest equality (c15_worker_window_cross_realm_noise_consistency). The
/// vendor one-shot queue (`servo::register_worker_interfaces_ready_callback`)
/// remains for any future one-shot consumer; bao no longer registers one.
///
/// Register the second-phase (interfaces-ready) injector with PER-WORKER
/// delivery (REQ-BRW-004, user ruling 2026-09-09 vendor patch).
///
/// Same install as [`register_worker_interfaces_ready_callback_native`]
/// (re-run of the idempotent `set_profile_for_global` +
/// `install_stealth_props`), but delivered to EVERY Dedicated Worker of the
/// webview instead of only the first one that drains the consume-once queue
/// (e43 multi-worker gap: the 2nd+ page-JS `new Worker()` previously got
/// neither the engine getters nor any W1a JS hook — a bare fingerprintable
/// Worker). Never consumed; upserted per webview at page init.
///
/// @trace REQ-BRW-004 [criterion:15] worker JS-hook per-Worker delivery
fn register_worker_interfaces_ready_injector_native(
    webview_id: servo::WebViewId,
    profile: Option<bao_stealth::StealthProfile>,
) {
    let injector: servo::EmbedderWorkerInjector = std::sync::Arc::new(move |cx_ptr, global_ptr| {
        let raw_cx = cx_ptr as *mut mozjs::jsapi::JSContext;
        let raw_global = global_ptr as *mut mozjs::jsapi::JSObject;
        if raw_cx.is_null() || raw_global.is_null() {
            log::warn!(
                "[register_worker_interfaces_ready_injector_native] NULL cx/global — \
                 skipping interfaces-ready install (REQ-BRW-004 per-Worker delivery)"
            );
            return;
        }
        let Some(ref profile) = profile else {
            return;
        };
        unsafe {
            // Realm entry mirrors worker_scope_init_native (runtime_bridge):
            // the worker thread's cx starts in the NULL realm, and any JSAPI
            // that atomizes dereferences a NULL zone and SIGSEGVs without
            // this. AutoRealm roots the global and restores the NULL
            // starting realm on drop (leaveRealm is null-safe).
            use mozjs::context::JSContext;
            use mozjs::realm::AutoRealm;
            use std::ptr::NonNull;
            let cx_nn = NonNull::new_unchecked(raw_cx);
            let mut cx = JSContext::from_ptr(cx_nn);
            let _worker_realm = AutoRealm::new(&mut cx, NonNull::new_unchecked(raw_global));

            bao_stealth::engine_props::set_profile_for_global(raw_global as usize, profile);
            bao_stealth::engine_props::install_stealth_props(raw_cx, raw_global);
            // E22 audit defect A guard (same as the one-shot drain): do NOT
            // re-seed the servo rendering-layer canvas noise here — realm-
            // scoped noise is delivered via set_profile_for_global above.
        }
    });
    servo::register_worker_interfaces_ready_injector(webview_id, injector);
}

pub fn run_browser(config: BrowserConfig) -> Result<(), BrowserError> {
    let _stealth = config.stealth_profile.is_some();
    let url = config.url.clone();
    let bao_config: BaoConfig = config.into();
    let cdp_port = bao_config.cdp_port;

    let runtime = BaoRuntime::new(bao_config)?;

    // Create initial page
    let page_config = PageConfig {
        url: url.clone(),
        stealth_profile: None,
        ..Default::default()
    };
    let page = runtime.create_page(&page_config)?;
    if let Some(ref page_url) = url {
        log::debug!("[bao] navigating to {}", page_url);
    }

    if let Some(port) = cdp_port {
        // Create bridge channel for CDP <-> servo communication
        let (bridge_tx, bridge_rx) = bridge_channel(Duration::from_secs(30));

        // Create console log forwarding channel: servo delegate → CDP Log domain
        let (console_tx, console_rx) = std::sync::mpsc::channel::<cdp_server::ConsoleMessage>();
        runtime.set_console_log_channel(console_tx);

        // Create EventSubscriber pair for structured ServoEvent path (Path B).
        // @trace REQ-CDP-006 [entity:ServoDelegateHooks]
        let (event_subscriber, servo_event_rx) = bao_cdp_client::bridge::EventSubscriber::new();
        runtime.set_event_channel(event_subscriber.sender());

        // Build CdpServer and extract the shared broadcaster BEFORE moving the
        // server into its thread. The broadcaster is Arc<EventBroadcaster> which
        // shares the same SessionMap — events sent via this broadcaster reach all
        // connected WebSocket sessions.
        // @trace REQ-CDP-006 [entity:ServoDelegateHooks]
        //
        // REQ-CDP WS command face: the registry is the real command dispatcher
        // (BaoWsRegistry → bao_cdp::handle_command → servo bridge), not the
        // EmptyHandler placeholder — WS sessions get real Page.navigate /
        // Runtime.evaluate / Target.* round-trips (Playwright direct connect).
        let registry = Arc::new(BaoWsRegistry::new(bridge_tx.clone()));
        let config = ServerConfig::builder().host("127.0.0.1").port(port).build();
        // The default target is the initial page's real id (cdp_handler parses
        // decimal page ids — a timestamp hex would never resolve to a page).
        let target_id = page.id().to_string();
        let mut server = CdpServer::with_registry(config, registry);
        let provider = Arc::new(ServoTargetProvider::new(
            bridge_tx,
            target_id,
            "127.0.0.1".into(),
            port,
        ));
        server.set_target_provider(provider);
        server.set_console_receiver(console_rx);
        // Clone the broadcaster before moving server into the thread.
        // Arc<EventBroadcaster> shares the same SessionMap with the server.
        let broadcaster = server.broadcaster();

        // Grab the stop handle BEFORE moving the server into its thread —
        // the spawner signals shutdown through this shared flag.
        let stop_flag = server.stop_handle();
        let server_thread = std::thread::spawn(move || {
            let _ = server.run();
        });

        let result = runtime.run_with_bridge(bridge_rx, servo_event_rx, broadcaster);
        // Deterministic CDP shutdown (B0 census #3): signal the cooperative
        // stop and join the server thread so the listener port, registry and
        // sessions are released before run_browser returns. Bounded: run()
        // checks the flag each iteration (10ms cadence), so the join only
        // waits on the already-signaled exit path.
        stop_flag.store(true, std::sync::atomic::Ordering::Release);
        let _ = server_thread.join();
        return result;
    }

    runtime.run()
}