Skip to main content

vs_engine_webkit/
runtime.rs

1//! Engine thread + channel bridge.
2//!
3//! WebKit on either platform must be driven from the thread that owns
4//! its run loop (`GMainLoop` on Linux, `CFRunLoop` on macOS). The
5//! daemon's Tokio workers can not call WebKit directly. [`EngineRuntime`]
6//! owns a dedicated OS thread, lets the platform construct the engine
7//! on that thread, and dispatches every call from the daemon over an
8//! `mpsc` channel.
9//!
10//! Every wrapper method on [`EngineRuntime`] (e.g. [`EngineRuntime::open`])
11//! is synchronous and blocks until the engine thread replies. The
12//! daemon wraps these in `tokio::task::spawn_blocking` to keep them
13//! off Tokio's worker threads.
14
15#![allow(clippy::result_unit_err, clippy::must_use_candidate)]
16
17use std::path::PathBuf;
18use std::sync::mpsc;
19use std::thread::{self, JoinHandle};
20use std::time::Duration;
21
22use vs_protocol::{Ref, Tree};
23
24use crate::engine::{
25    ActTarget, Action, AuthBlob, CaptureScope, DataStore, Download, DownloadEntry, DownloadSource,
26    Engine, EngineCapabilities, EngineError, EngineResult, LayoutBox, OpenStart, PageHandle,
27    Viewport, WaitCondition,
28};
29
30/// An engine call that returned before its result was ready. Polled on
31/// the engine thread between jobs; returns true once it has replied.
32type Waiter = Box<dyn FnMut(&mut dyn Engine) -> bool>;
33
34/// One unit of work for the engine thread. It may leave a [`Waiter`]
35/// behind instead of replying at once.
36type Job = Box<dyn FnOnce(&mut dyn Engine, &mut Vec<Waiter>) + Send>;
37
38/// Run an engine op, turning a panic into an error. On macOS the op runs
39/// on the Cocoa main thread inside an Obj-C run-loop frame, where an
40/// unwinding panic is undefined behavior that can take the whole daemon
41/// down ("could not connect to the server" on the next request); a
42/// message-bearing error is far better than the bare `ENGINE_CRASH` a
43/// dropped reply channel would produce.
44fn guarded<R>(f: impl FnOnce() -> EngineResult<R>) -> EngineResult<R> {
45    std::panic::catch_unwind(std::panic::AssertUnwindSafe(f))
46        .unwrap_or_else(|payload| Err(EngineError::Other(panic_message(&payload))))
47}
48
49/// Poll every waiter once, dropping the ones that replied.
50fn poll_waiters(engine: &mut dyn Engine, waiters: &mut Vec<Waiter>) {
51    waiters.retain_mut(|w| !w(engine));
52}
53
54/// Extract a human-readable message from a `catch_unwind` payload.
55fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
56    let detail = payload
57        .downcast_ref::<&str>()
58        .map(|s| (*s).to_string())
59        .or_else(|| payload.downcast_ref::<String>().cloned())
60        .unwrap_or_else(|| "unknown panic".to_string());
61    format!("engine panicked: {detail}")
62}
63
64/// Owns the engine thread and exposes a synchronous facade.
65///
66/// Drop semantics: dropping the runtime closes the command channel,
67/// which causes the engine thread to exit its loop and drop the
68/// engine. The destructor joins the thread.
69/// Called after a job is queued, to nudge a host loop that is asleep.
70///
71/// An `mpsc` send is invisible to a platform run loop, so a
72/// [`MainThreadDispatcher`] host cannot block waiting for work — it has
73/// to wake periodically and poll, trading idle CPU against how long a
74/// queued job sits. With a waker installed the host can sleep properly
75/// and be woken the moment a job lands, which removes both costs.
76///
77/// Must be safe to call from any thread.
78pub type Waker = Box<dyn Fn() + Send + Sync>;
79
80pub struct EngineRuntime {
81    sender: Option<mpsc::Sender<Job>>,
82    handle: Option<JoinHandle<()>>,
83    waker: Option<Waker>,
84}
85
86impl std::fmt::Debug for EngineRuntime {
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        f.debug_struct("EngineRuntime")
89            .field("running", &self.sender.is_some())
90            .finish_non_exhaustive()
91    }
92}
93
94impl EngineRuntime {
95    /// Spawn the engine thread and construct the engine *on that thread*
96    /// via `make`. This is the only correct construction point: the
97    /// platform run loop must be initialized on the same thread that
98    /// later drives WebKit.
99    ///
100    /// Returns once the engine thread has signaled it is ready.
101    pub fn spawn<F>(make: F) -> EngineResult<Self>
102    where
103        F: FnOnce() -> EngineResult<Box<dyn Engine>> + Send + 'static,
104    {
105        let (tx, rx) = mpsc::channel::<Job>();
106        let (ready_tx, ready_rx) = mpsc::sync_channel::<EngineResult<()>>(1);
107
108        let handle = thread::Builder::new()
109            .name("vibesurfer-engine".into())
110            .spawn(move || {
111                let mut engine = match make() {
112                    Ok(e) => {
113                        let _ = ready_tx.send(Ok(()));
114                        e
115                    }
116                    Err(e) => {
117                        let _ = ready_tx.send(Err(e));
118                        return;
119                    }
120                };
121
122                let mut waiters: Vec<Waiter> = Vec::new();
123                loop {
124                    // With calls pending, look in on them between jobs
125                    // rather than block on the next job.
126                    let job = if waiters.is_empty() {
127                        match rx.recv() {
128                            Ok(job) => Some(job),
129                            Err(_) => break,
130                        }
131                    } else {
132                        match rx.recv_timeout(Duration::from_millis(1)) {
133                            Ok(job) => Some(job),
134                            Err(mpsc::RecvTimeoutError::Timeout) => None,
135                            Err(mpsc::RecvTimeoutError::Disconnected) => break,
136                        }
137                    };
138                    if let Some(job) = job {
139                        job(engine.as_mut(), &mut waiters);
140                    }
141                    poll_waiters(engine.as_mut(), &mut waiters);
142                }
143                // Channel closed: drop the engine on this thread and exit.
144                drop(engine);
145            })
146            .map_err(|e| EngineError::Other(format!("spawn engine thread: {e}")))?;
147
148        match ready_rx.recv() {
149            Ok(Ok(())) => {}
150            Ok(Err(e)) => {
151                let _ = handle.join();
152                return Err(e);
153            }
154            Err(_) => {
155                let _ = handle.join();
156                return Err(EngineError::Crashed);
157            }
158        }
159
160        Ok(Self {
161            sender: Some(tx),
162            handle: Some(handle),
163            // The spawned-thread runtime blocks on `rx.recv()`, so it is
164            // already woken by the send itself.
165            waker: None,
166        })
167    }
168
169    /// Construct a runtime whose engine runs on the *caller'\''s* thread.
170    /// No internal thread is spawned. The returned [`MainThreadDispatcher`]
171    /// drives the engine: call [`MainThreadDispatcher::tick`] in the
172    /// caller'\''s loop to drain one queued job, or [`MainThreadDispatcher::run_until`]
173    /// to block until a stop flag fires.
174    ///
175    /// Use this when the engine is bound to a specific OS thread (e.g.
176    /// the macOS Cocoa main thread, where `WKWebView` must run).
177    pub fn dispatcher(engine: Box<dyn Engine>) -> (Self, MainThreadDispatcher) {
178        let (tx, rx) = mpsc::channel::<Job>();
179        let runtime = Self {
180            sender: Some(tx),
181            handle: None,
182            waker: None,
183        };
184        let dispatcher = MainThreadDispatcher {
185            engine,
186            rx,
187            waiters: Vec::new(),
188        };
189        (runtime, dispatcher)
190    }
191
192    /// Install the [`Waker`] the host loop is woken by.
193    ///
194    /// Call before the runtime is shared. Without one the host must
195    /// poll; with one it can sleep until there is actually work.
196    #[must_use]
197    pub fn with_waker(mut self, waker: Waker) -> Self {
198        self.waker = Some(waker);
199        self
200    }
201
202    /// Cleanly shut down: close the channel and join the thread.
203    /// Idempotent — calling shutdown twice is a no-op.
204    pub fn shutdown(&mut self) {
205        drop(self.sender.take());
206        if let Some(handle) = self.handle.take() {
207            let _ = handle.join();
208        }
209    }
210
211    fn dispatch<R, F>(&self, f: F) -> EngineResult<R>
212    where
213        F: FnOnce(&mut dyn Engine) -> EngineResult<R> + Send + 'static,
214        R: Send + 'static,
215    {
216        let (reply_tx, reply_rx) = mpsc::sync_channel::<EngineResult<R>>(1);
217        self.send(Box::new(move |engine, _| {
218            let _ = reply_tx.send(guarded(|| f(engine)));
219        }))?;
220        reply_rx.recv().map_err(|_| EngineError::Crashed)?
221    }
222
223    /// Queue `job` and wake the host loop.
224    fn send(&self, job: Job) -> EngineResult<()> {
225        let sender = self.sender.as_ref().ok_or(EngineError::Closed)?;
226        sender.send(job).map_err(|_| EngineError::Closed)?;
227        // Wake the host loop *after* the job is queued, so it cannot
228        // wake, find nothing, and go back to sleep past this job.
229        if let Some(waker) = &self.waker {
230            waker();
231        }
232        Ok(())
233    }
234
235    // -----------------------------------------------------------------
236    // Synchronous facade for every Engine method.
237    // -----------------------------------------------------------------
238
239    /// Open a page. The engine thread serves other calls while the
240    /// page's first load runs (see [`Engine::open_start`]); this caller
241    /// gets its reply when the load is done.
242    pub fn open(&self, url: &str, store: &DataStore) -> EngineResult<PageHandle> {
243        let url = url.to_string();
244        let store = store.clone();
245        let (reply_tx, reply_rx) = mpsc::sync_channel::<EngineResult<PageHandle>>(1);
246        self.send(Box::new(move |engine, waiters| {
247            match guarded(|| engine.open_start(&url, &store)) {
248                Ok(OpenStart::Done(page)) => {
249                    let _ = reply_tx.send(Ok(page));
250                }
251                Err(e) => {
252                    let _ = reply_tx.send(Err(e));
253                }
254                Ok(OpenStart::Pending(ticket)) => waiters.push(Box::new(move |engine| {
255                    let result = match guarded(|| Ok(engine.open_poll(ticket))) {
256                        Ok(None) => return false,
257                        Ok(Some(result)) => result,
258                        Err(e) => Err(e),
259                    };
260                    let _ = reply_tx.send(result);
261                    true
262                })),
263            }
264        }))?;
265        reply_rx.recv().map_err(|_| EngineError::Crashed)?
266    }
267
268    pub fn drop_store(&self, key: &str) -> EngineResult<()> {
269        let key = key.to_string();
270        self.dispatch(move |e| e.drop_store(&key))
271    }
272
273    pub fn navigate(&self, page: PageHandle, url: &str) -> EngineResult<()> {
274        let url = url.to_string();
275        self.dispatch(move |e| e.navigate(page, &url))
276    }
277
278    pub fn load_html(&self, page: PageHandle, url: &str, html: &str) -> EngineResult<()> {
279        let url = url.to_string();
280        let html = html.to_string();
281        self.dispatch(move |e| e.load_html(page, &url, &html))
282    }
283
284    pub fn close(&self, page: PageHandle) -> EngineResult<()> {
285        self.dispatch(move |e| e.close(page))
286    }
287
288    pub fn enable_webauthn(&self, page: PageHandle) -> EngineResult<()> {
289        self.dispatch(move |e| e.enable_webauthn(page))
290    }
291
292    pub fn add_init_script(&self, page: PageHandle, source: &str) -> EngineResult<()> {
293        let source = source.to_string();
294        self.dispatch(move |e| e.add_init_script(page, &source))
295    }
296
297    pub fn snapshot(&self, page: PageHandle) -> EngineResult<Tree> {
298        self.dispatch(move |e| e.snapshot(page))
299    }
300
301    /// Snapshot the tree and read the console buffer in a single
302    /// main-thread hop. `vs_view` needs both (the tree, plus the
303    /// console entries behind its `? console_error` warning); folding
304    /// the cheap native console read into the snapshot dispatch avoids
305    /// a second round trip on every view. The console read is a buffer
306    /// borrow, so it adds no measurable cost.
307    pub fn snapshot_with_console(
308        &self,
309        page: PageHandle,
310    ) -> EngineResult<(Tree, Vec<crate::inspector::ConsoleEntry>)> {
311        self.dispatch(move |e| {
312            let tree = e.snapshot(page)?;
313            let console = e.console_entries(page)?;
314            Ok((tree, console))
315        })
316    }
317
318    pub fn act(
319        &self,
320        page: PageHandle,
321        target: ActTarget,
322        action: Action,
323        mode: crate::engine::InputMode,
324    ) -> EngineResult<()> {
325        self.dispatch(move |e| e.act(page, target, action, mode))
326    }
327
328    /// Perform an action and snapshot the resulting tree in a single
329    /// main-thread hop. `vs_act` always snapshots right after acting, so
330    /// folding the two into one dispatch removes a full engine round
331    /// trip (~10ms) from every action. The backend's `act` already
332    /// settles input + flushes rAF before returning, so the snapshot
333    /// sees the post-action DOM exactly as the two-call form did.
334    pub fn act_and_snapshot(
335        &self,
336        page: PageHandle,
337        target: ActTarget,
338        action: Action,
339        mode: crate::engine::InputMode,
340    ) -> EngineResult<Tree> {
341        self.dispatch(move |e| {
342            e.act(page, target, action, mode)?;
343            e.snapshot(page)
344        })
345    }
346
347    pub fn wait(
348        &self,
349        page: PageHandle,
350        cond: WaitCondition,
351        budget: Duration,
352    ) -> EngineResult<()> {
353        self.dispatch(move |e| e.wait(page, cond, budget))
354    }
355
356    pub fn capture(&self, page: PageHandle, scope: CaptureScope) -> EngineResult<PathBuf> {
357        self.dispatch(move |e| e.capture(page, scope))
358    }
359
360    pub fn capture_live(&self, page: PageHandle, max_width: u32) -> EngineResult<PathBuf> {
361        self.dispatch(move |e| e.capture_live(page, max_width))
362    }
363
364    pub fn record_begin(
365        &self,
366        page: PageHandle,
367        tx: std::sync::mpsc::Sender<crate::engine::RecFrame>,
368        fps: u32,
369        max_width: u32,
370    ) -> EngineResult<()> {
371        self.dispatch(move |e| e.record_begin(page, tx, fps, max_width))
372    }
373
374    pub fn record_end(&self, page: PageHandle) -> EngineResult<()> {
375        self.dispatch(move |e| e.record_end(page))
376    }
377
378    pub fn layout(&self, page: PageHandle, refs: Vec<Ref>) -> EngineResult<Vec<LayoutBox>> {
379        self.dispatch(move |e| e.layout(page, &refs))
380    }
381
382    pub fn download(
383        &self,
384        page: PageHandle,
385        source: DownloadSource,
386        budget: Duration,
387    ) -> EngineResult<Download> {
388        self.dispatch(move |e| e.download(page, source, budget))
389    }
390
391    pub fn download_list(&self, page: PageHandle) -> EngineResult<Vec<DownloadEntry>> {
392        self.dispatch(move |e| e.download_list(page))
393    }
394
395    pub fn set_viewport(&self, page: PageHandle, viewport: Viewport) -> EngineResult<()> {
396        self.dispatch(move |e| e.set_viewport(page, viewport))
397    }
398
399    pub fn save_auth(&self, page: PageHandle) -> EngineResult<AuthBlob> {
400        self.dispatch(move |e| e.save_auth(page))
401    }
402
403    pub fn load_auth(&self, page: PageHandle, blob: AuthBlob) -> EngineResult<()> {
404        self.dispatch(move |e| e.load_auth(page, &blob))
405    }
406
407    pub fn console_entries(
408        &self,
409        page: PageHandle,
410    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
411        self.dispatch(move |e| e.console_entries(page))
412    }
413
414    pub fn network_entries(
415        &self,
416        page: PageHandle,
417    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
418        self.dispatch(move |e| e.network_entries(page))
419    }
420
421    pub fn request_detail(
422        &self,
423        page: PageHandle,
424        seq: u64,
425    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
426        self.dispatch(move |e| e.request_detail(page, seq))
427    }
428
429    pub fn eval_js(
430        &self,
431        page: PageHandle,
432        expr: &str,
433    ) -> EngineResult<crate::inspector::EvalResult> {
434        let expr = expr.to_string();
435        self.dispatch(move |e| e.eval_js(page, &expr))
436    }
437
438    pub fn eval_js_in_frame(
439        &self,
440        page: PageHandle,
441        frame: &str,
442        expr: &str,
443    ) -> EngineResult<crate::inspector::EvalResult> {
444        let (frame, expr) = (frame.to_string(), expr.to_string());
445        self.dispatch(move |e| e.eval_js_in_frame(page, &frame, &expr))
446    }
447
448    pub fn storage(
449        &self,
450        page: PageHandle,
451        scope: crate::inspector::StorageScope,
452    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
453        self.dispatch(move |e| e.storage(page, scope))
454    }
455
456    pub fn cookie_events(
457        &self,
458        page: PageHandle,
459    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
460        self.dispatch(move |e| e.cookie_events(page))
461    }
462
463    pub fn type_text(
464        &self,
465        page: PageHandle,
466        text: &str,
467        mode: crate::engine::InputMode,
468    ) -> EngineResult<()> {
469        let text = text.to_string();
470        self.dispatch(move |e| e.type_text(page, &text, mode))
471    }
472
473    pub fn cursor_op(
474        &self,
475        page: PageHandle,
476        op: crate::engine::CursorOp,
477        mode: crate::engine::InputMode,
478    ) -> EngineResult<()> {
479        self.dispatch(move |e| e.cursor_op(page, op, mode))
480    }
481
482    pub fn scripts(&self, page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
483        self.dispatch(move |e| e.scripts(page))
484    }
485
486    pub fn script_source(
487        &self,
488        page: PageHandle,
489        seq: u64,
490    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
491        self.dispatch(move |e| e.script_source(page, seq))
492    }
493
494    pub fn dom(
495        &self,
496        page: PageHandle,
497        r: vs_protocol::Ref,
498        extra_props: Vec<String>,
499    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
500        self.dispatch(move |e| e.dom(page, r, &extra_props))
501    }
502
503    pub fn performance(
504        &self,
505        page: PageHandle,
506    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
507        self.dispatch(move |e| e.performance(page))
508    }
509
510    pub fn drop_data(
511        &self,
512        page: PageHandle,
513        x: f64,
514        y: f64,
515        data: crate::engine::DropData,
516    ) -> EngineResult<bool> {
517        self.dispatch(move |e| e.drop_data(page, x, y, &data))
518    }
519
520    pub fn crash(&self, page: PageHandle) -> EngineResult<()> {
521        self.dispatch(move |e| e.crash(page))
522    }
523
524    pub fn set_zoom(&self, page: PageHandle, zoom: f64) -> EngineResult<()> {
525        self.dispatch(move |e| e.set_zoom(page, zoom))
526    }
527
528    pub fn cookies(
529        &self,
530        page: PageHandle,
531        op: crate::engine::CookieOp,
532    ) -> EngineResult<Vec<crate::engine::CookieData>> {
533        self.dispatch(move |e| e.cookies(page, op))
534    }
535
536    pub fn main_response(
537        &self,
538        page: PageHandle,
539    ) -> EngineResult<Option<crate::inspector::MainResponse>> {
540        self.dispatch(move |e| e.main_response(page))
541    }
542
543    pub fn capabilities(&self) -> EngineResult<EngineCapabilities> {
544        self.dispatch(|e| Ok(e.capabilities()))
545    }
546
547    pub fn set_popups(&self, page: PageHandle, on: bool) -> EngineResult<()> {
548        self.dispatch(move |e| e.set_popups(page, on))
549    }
550
551    pub fn popup_feed(&self) -> EngineResult<Option<std::sync::Arc<crate::engine::PopupFeed>>> {
552        self.dispatch(|e| Ok(e.popup_feed()))
553    }
554}
555
556impl Drop for EngineRuntime {
557    fn drop(&mut self) {
558        self.shutdown();
559    }
560}
561
562/// Drives an engine that lives on the caller'\''s thread (typically the
563/// OS main thread on macOS, since `WKWebView` is pinned there). The
564/// driver owns the engine and a receiver for jobs sent by the runtime
565/// handle that the daemon holds.
566pub struct MainThreadDispatcher {
567    engine: Box<dyn Engine>,
568    rx: mpsc::Receiver<Job>,
569    waiters: Vec<Waiter>,
570}
571
572impl MainThreadDispatcher {
573    /// Look in on pending calls, then drain one job if available.
574    /// Returns `Ok(true)` if a job was executed, `Ok(false)` if the
575    /// queue is currently empty, `Err(())` if the channel is closed
576    /// (the runtime was dropped — the dispatcher should exit its loop).
577    /// A pending call finishes on a later tick, once the host loop has
578    /// run the engine's events.
579    pub fn tick(&mut self) -> Result<bool, ()> {
580        poll_waiters(self.engine.as_mut(), &mut self.waiters);
581        match self.rx.try_recv() {
582            Ok(job) => {
583                job(self.engine.as_mut(), &mut self.waiters);
584                Ok(true)
585            }
586            Err(mpsc::TryRecvError::Empty) => Ok(false),
587            Err(mpsc::TryRecvError::Disconnected) => Err(()),
588        }
589    }
590
591    /// Block until a job arrives or the channel is closed; execute one
592    /// job. Returns `Ok(true)` after running, `Err(())` on closed.
593    pub fn tick_blocking(&mut self) -> Result<bool, ()> {
594        poll_waiters(self.engine.as_mut(), &mut self.waiters);
595        match self.rx.recv() {
596            Ok(job) => {
597                job(self.engine.as_mut(), &mut self.waiters);
598                Ok(true)
599            }
600            Err(_) => Err(()),
601        }
602    }
603}
604
605#[cfg(test)]
606mod tests {
607    use std::path::PathBuf;
608    use std::time::Duration;
609
610    use vs_protocol::{Node, Ref, Role, Tree};
611
612    use super::*;
613    use crate::engine::{
614        ActTarget, Action, AuthBlob, CaptureScope, EngineCapabilities, LayoutBox, Viewport,
615        WaitCondition,
616    };
617
618    /// Minimal in-process `Engine` impl used only to exercise the
619    /// runtime's spawn / dispatch / shutdown plumbing. Lives in the
620    /// same `cfg(test)` block as the tests so it can never be reached
621    /// from production code.
622    #[derive(Default)]
623    struct TestEngine {
624        next_handle: u64,
625        last_url: String,
626        /// When set, opens stay pending until the flag turns true.
627        slow_open: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
628    }
629
630    impl Engine for TestEngine {
631        fn open(&mut self, url: &str, _store: &DataStore) -> EngineResult<PageHandle> {
632            self.next_handle += 1;
633            self.last_url = url.to_string();
634            Ok(PageHandle(self.next_handle))
635        }
636        fn open_start(&mut self, url: &str, store: &DataStore) -> EngineResult<OpenStart> {
637            if self.slow_open.is_some() {
638                return Ok(OpenStart::Pending(1));
639            }
640            self.open(url, store).map(OpenStart::Done)
641        }
642        fn open_poll(&mut self, _ticket: u64) -> Option<EngineResult<PageHandle>> {
643            let done = self.slow_open.as_ref()?;
644            done.load(std::sync::atomic::Ordering::SeqCst)
645                .then_some(Ok(PageHandle(7)))
646        }
647        fn navigate(&mut self, _page: PageHandle, url: &str) -> EngineResult<()> {
648            self.last_url = url.to_string();
649            Ok(())
650        }
651        fn enable_webauthn(&mut self, _page: PageHandle) -> EngineResult<()> {
652            Ok(())
653        }
654        fn add_init_script(&mut self, _page: PageHandle, _source: &str) -> EngineResult<()> {
655            Ok(())
656        }
657        fn close(&mut self, _page: PageHandle) -> EngineResult<()> {
658            Ok(())
659        }
660        fn snapshot(&mut self, _page: PageHandle) -> EngineResult<Tree> {
661            Ok(Tree::from_root(Node::leaf(
662                Ref(1),
663                Role::Doc,
664                &self.last_url,
665            )))
666        }
667        fn act(
668            &mut self,
669            _: PageHandle,
670            _: ActTarget,
671            _: Action,
672            _: crate::engine::InputMode,
673        ) -> EngineResult<()> {
674            Ok(())
675        }
676        fn wait(&mut self, _: PageHandle, _: WaitCondition, _: Duration) -> EngineResult<()> {
677            Ok(())
678        }
679        fn capture(&mut self, _: PageHandle, _: CaptureScope) -> EngineResult<PathBuf> {
680            Ok(PathBuf::from("/tmp/test.png"))
681        }
682        fn layout(&mut self, _: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>> {
683            Ok(refs
684                .iter()
685                .map(|r| LayoutBox {
686                    r: *r,
687                    x: 0.0,
688                    y: 0.0,
689                    width: 1.0,
690                    height: 1.0,
691                    visible: true,
692                    z_index: 0,
693                })
694                .collect())
695        }
696        fn set_viewport(&mut self, _: PageHandle, _: Viewport) -> EngineResult<()> {
697            Ok(())
698        }
699        fn save_auth(&mut self, _: PageHandle) -> EngineResult<AuthBlob> {
700            Ok(AuthBlob {
701                bytes: self.last_url.as_bytes().to_vec(),
702            })
703        }
704        fn load_auth(&mut self, _: PageHandle, _: &AuthBlob) -> EngineResult<()> {
705            Ok(())
706        }
707        fn capabilities(&self) -> EngineCapabilities {
708            EngineCapabilities {
709                renders: false,
710                honors_viewport: false,
711                measures_layout: false,
712                persists_auth: false,
713                inspector_console: false,
714                inspector_network: false,
715                inspector_cookie_events: false,
716                name: "test",
717                version: "runtime-tests",
718            }
719        }
720    }
721
722    fn spawn_test_runtime() -> EngineRuntime {
723        EngineRuntime::spawn(|| Ok(Box::new(TestEngine::default()) as Box<dyn Engine>))
724            .expect("spawn")
725    }
726
727    #[test]
728    fn spawn_and_shutdown_cleanly() {
729        let mut rt = spawn_test_runtime();
730        rt.shutdown();
731        rt.shutdown();
732    }
733
734    /// An open whose load is still running does not hold up other
735    /// calls, and its caller gets the page once the load ends.
736    #[test]
737    fn a_pending_open_does_not_hold_up_other_calls() {
738        use std::sync::atomic::{AtomicBool, Ordering};
739        use std::sync::Arc;
740        let loaded = Arc::new(AtomicBool::new(false));
741        let engine = TestEngine {
742            slow_open: Some(loaded.clone()),
743            ..TestEngine::default()
744        };
745        let (rt, mut driver) = EngineRuntime::dispatcher(Box::new(engine));
746        let rt = Arc::new(rt);
747        let deadline = std::time::Instant::now() + Duration::from_secs(5);
748        let mut drive_until = |done: &dyn Fn() -> bool| {
749            while !done() && std::time::Instant::now() < deadline {
750                let _ = driver.tick();
751                std::thread::yield_now();
752            }
753        };
754
755        let r = rt.clone();
756        let opener = std::thread::spawn(move || r.open("about:blank", &DataStore::Shared));
757        let r = rt.clone();
758        let other = std::thread::spawn(move || r.capabilities());
759        drive_until(&|| other.is_finished());
760        assert!(other.join().unwrap().is_ok(), "served while the open waits");
761        assert!(!opener.is_finished(), "the open waits for its load");
762
763        loaded.store(true, Ordering::SeqCst);
764        drive_until(&|| opener.is_finished());
765        assert_eq!(opener.join().unwrap().unwrap(), PageHandle(7));
766    }
767
768    #[test]
769    fn dispatch_blocks_until_reply() {
770        let rt = spawn_test_runtime();
771        let caps = rt.capabilities().unwrap();
772        assert_eq!(caps.name, "test");
773    }
774
775    #[test]
776    fn engine_construction_failure_reported() {
777        let err =
778            EngineRuntime::spawn(|| Err::<Box<dyn Engine>, _>(EngineError::Other("nope".into())))
779                .unwrap_err();
780        assert!(matches!(err, EngineError::Other(_)));
781    }
782
783    #[test]
784    fn calls_after_drop_error_with_closed() {
785        let mut rt = spawn_test_runtime();
786        rt.shutdown();
787        let err = rt.capabilities().unwrap_err();
788        assert!(matches!(err, EngineError::Closed));
789    }
790
791    /// Cover the round-trip path that used to live in
792    /// `tests/runtime_round_trip.rs`. The Engine impl is intentionally
793    /// trivial — this test verifies the dispatch channel, not engine
794    /// behavior.
795    #[test]
796    fn full_primitive_sequence_via_runtime() {
797        let rt = spawn_test_runtime();
798        let page = rt
799            .open("https://example.com/login", &DataStore::Shared)
800            .unwrap();
801        rt.wait(page, WaitCondition::Stable, Duration::from_millis(0))
802            .unwrap();
803        let tree = rt.snapshot(page).unwrap();
804        assert!(tree.roots[0].label.contains("https://example.com/login"));
805        rt.act(
806            page,
807            ActTarget::Ref(Ref(3)),
808            Action::Fill { value: "x".into() },
809            crate::engine::InputMode::Careful,
810        )
811        .unwrap();
812        let auth = rt.save_auth(page).unwrap();
813        rt.load_auth(page, auth).unwrap();
814        rt.close(page).unwrap();
815        rt.close(page).unwrap();
816    }
817
818    #[test]
819    fn dispatch_serializes_calls() {
820        let rt = spawn_test_runtime();
821        let mut handles = Vec::new();
822        for i in 0..32 {
823            handles.push(
824                rt.open(&format!("https://example.com/{i}"), &DataStore::Shared)
825                    .unwrap(),
826            );
827        }
828        let mut sorted = handles.clone();
829        sorted.sort();
830        sorted.dedup();
831        assert_eq!(sorted.len(), handles.len());
832    }
833}