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 main_response(
511        &self,
512        page: PageHandle,
513    ) -> EngineResult<Option<crate::inspector::MainResponse>> {
514        self.dispatch(move |e| e.main_response(page))
515    }
516
517    pub fn capabilities(&self) -> EngineResult<EngineCapabilities> {
518        self.dispatch(|e| Ok(e.capabilities()))
519    }
520
521    pub fn set_popups(&self, page: PageHandle, on: bool) -> EngineResult<()> {
522        self.dispatch(move |e| e.set_popups(page, on))
523    }
524
525    pub fn popup_feed(&self) -> EngineResult<Option<std::sync::Arc<crate::engine::PopupFeed>>> {
526        self.dispatch(|e| Ok(e.popup_feed()))
527    }
528}
529
530impl Drop for EngineRuntime {
531    fn drop(&mut self) {
532        self.shutdown();
533    }
534}
535
536/// Drives an engine that lives on the caller'\''s thread (typically the
537/// OS main thread on macOS, since `WKWebView` is pinned there). The
538/// driver owns the engine and a receiver for jobs sent by the runtime
539/// handle that the daemon holds.
540pub struct MainThreadDispatcher {
541    engine: Box<dyn Engine>,
542    rx: mpsc::Receiver<Job>,
543    waiters: Vec<Waiter>,
544}
545
546impl MainThreadDispatcher {
547    /// Look in on pending calls, then drain one job if available.
548    /// Returns `Ok(true)` if a job was executed, `Ok(false)` if the
549    /// queue is currently empty, `Err(())` if the channel is closed
550    /// (the runtime was dropped — the dispatcher should exit its loop).
551    /// A pending call finishes on a later tick, once the host loop has
552    /// run the engine's events.
553    pub fn tick(&mut self) -> Result<bool, ()> {
554        poll_waiters(self.engine.as_mut(), &mut self.waiters);
555        match self.rx.try_recv() {
556            Ok(job) => {
557                job(self.engine.as_mut(), &mut self.waiters);
558                Ok(true)
559            }
560            Err(mpsc::TryRecvError::Empty) => Ok(false),
561            Err(mpsc::TryRecvError::Disconnected) => Err(()),
562        }
563    }
564
565    /// Block until a job arrives or the channel is closed; execute one
566    /// job. Returns `Ok(true)` after running, `Err(())` on closed.
567    pub fn tick_blocking(&mut self) -> Result<bool, ()> {
568        poll_waiters(self.engine.as_mut(), &mut self.waiters);
569        match self.rx.recv() {
570            Ok(job) => {
571                job(self.engine.as_mut(), &mut self.waiters);
572                Ok(true)
573            }
574            Err(_) => Err(()),
575        }
576    }
577}
578
579#[cfg(test)]
580mod tests {
581    use std::path::PathBuf;
582    use std::time::Duration;
583
584    use vs_protocol::{Node, Ref, Role, Tree};
585
586    use super::*;
587    use crate::engine::{
588        ActTarget, Action, AuthBlob, CaptureScope, EngineCapabilities, LayoutBox, Viewport,
589        WaitCondition,
590    };
591
592    /// Minimal in-process `Engine` impl used only to exercise the
593    /// runtime's spawn / dispatch / shutdown plumbing. Lives in the
594    /// same `cfg(test)` block as the tests so it can never be reached
595    /// from production code.
596    #[derive(Default)]
597    struct TestEngine {
598        next_handle: u64,
599        last_url: String,
600        /// When set, opens stay pending until the flag turns true.
601        slow_open: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
602    }
603
604    impl Engine for TestEngine {
605        fn open(&mut self, url: &str, _store: &DataStore) -> EngineResult<PageHandle> {
606            self.next_handle += 1;
607            self.last_url = url.to_string();
608            Ok(PageHandle(self.next_handle))
609        }
610        fn open_start(&mut self, url: &str, store: &DataStore) -> EngineResult<OpenStart> {
611            if self.slow_open.is_some() {
612                return Ok(OpenStart::Pending(1));
613            }
614            self.open(url, store).map(OpenStart::Done)
615        }
616        fn open_poll(&mut self, _ticket: u64) -> Option<EngineResult<PageHandle>> {
617            let done = self.slow_open.as_ref()?;
618            done.load(std::sync::atomic::Ordering::SeqCst)
619                .then_some(Ok(PageHandle(7)))
620        }
621        fn navigate(&mut self, _page: PageHandle, url: &str) -> EngineResult<()> {
622            self.last_url = url.to_string();
623            Ok(())
624        }
625        fn enable_webauthn(&mut self, _page: PageHandle) -> EngineResult<()> {
626            Ok(())
627        }
628        fn add_init_script(&mut self, _page: PageHandle, _source: &str) -> EngineResult<()> {
629            Ok(())
630        }
631        fn close(&mut self, _page: PageHandle) -> EngineResult<()> {
632            Ok(())
633        }
634        fn snapshot(&mut self, _page: PageHandle) -> EngineResult<Tree> {
635            Ok(Tree::from_root(Node::leaf(
636                Ref(1),
637                Role::Doc,
638                &self.last_url,
639            )))
640        }
641        fn act(
642            &mut self,
643            _: PageHandle,
644            _: ActTarget,
645            _: Action,
646            _: crate::engine::InputMode,
647        ) -> EngineResult<()> {
648            Ok(())
649        }
650        fn wait(&mut self, _: PageHandle, _: WaitCondition, _: Duration) -> EngineResult<()> {
651            Ok(())
652        }
653        fn capture(&mut self, _: PageHandle, _: CaptureScope) -> EngineResult<PathBuf> {
654            Ok(PathBuf::from("/tmp/test.png"))
655        }
656        fn layout(&mut self, _: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>> {
657            Ok(refs
658                .iter()
659                .map(|r| LayoutBox {
660                    r: *r,
661                    x: 0.0,
662                    y: 0.0,
663                    width: 1.0,
664                    height: 1.0,
665                    visible: true,
666                    z_index: 0,
667                })
668                .collect())
669        }
670        fn set_viewport(&mut self, _: PageHandle, _: Viewport) -> EngineResult<()> {
671            Ok(())
672        }
673        fn save_auth(&mut self, _: PageHandle) -> EngineResult<AuthBlob> {
674            Ok(AuthBlob {
675                bytes: self.last_url.as_bytes().to_vec(),
676            })
677        }
678        fn load_auth(&mut self, _: PageHandle, _: &AuthBlob) -> EngineResult<()> {
679            Ok(())
680        }
681        fn capabilities(&self) -> EngineCapabilities {
682            EngineCapabilities {
683                renders: false,
684                honors_viewport: false,
685                measures_layout: false,
686                persists_auth: false,
687                inspector_console: false,
688                inspector_network: false,
689                inspector_cookie_events: false,
690                name: "test",
691                version: "runtime-tests",
692            }
693        }
694    }
695
696    fn spawn_test_runtime() -> EngineRuntime {
697        EngineRuntime::spawn(|| Ok(Box::new(TestEngine::default()) as Box<dyn Engine>))
698            .expect("spawn")
699    }
700
701    #[test]
702    fn spawn_and_shutdown_cleanly() {
703        let mut rt = spawn_test_runtime();
704        rt.shutdown();
705        rt.shutdown();
706    }
707
708    /// An open whose load is still running does not hold up other
709    /// calls, and its caller gets the page once the load ends.
710    #[test]
711    fn a_pending_open_does_not_hold_up_other_calls() {
712        use std::sync::atomic::{AtomicBool, Ordering};
713        use std::sync::Arc;
714        let loaded = Arc::new(AtomicBool::new(false));
715        let engine = TestEngine {
716            slow_open: Some(loaded.clone()),
717            ..TestEngine::default()
718        };
719        let (rt, mut driver) = EngineRuntime::dispatcher(Box::new(engine));
720        let rt = Arc::new(rt);
721        let deadline = std::time::Instant::now() + Duration::from_secs(5);
722        let mut drive_until = |done: &dyn Fn() -> bool| {
723            while !done() && std::time::Instant::now() < deadline {
724                let _ = driver.tick();
725                std::thread::yield_now();
726            }
727        };
728
729        let r = rt.clone();
730        let opener = std::thread::spawn(move || r.open("about:blank", &DataStore::Shared));
731        let r = rt.clone();
732        let other = std::thread::spawn(move || r.capabilities());
733        drive_until(&|| other.is_finished());
734        assert!(other.join().unwrap().is_ok(), "served while the open waits");
735        assert!(!opener.is_finished(), "the open waits for its load");
736
737        loaded.store(true, Ordering::SeqCst);
738        drive_until(&|| opener.is_finished());
739        assert_eq!(opener.join().unwrap().unwrap(), PageHandle(7));
740    }
741
742    #[test]
743    fn dispatch_blocks_until_reply() {
744        let rt = spawn_test_runtime();
745        let caps = rt.capabilities().unwrap();
746        assert_eq!(caps.name, "test");
747    }
748
749    #[test]
750    fn engine_construction_failure_reported() {
751        let err =
752            EngineRuntime::spawn(|| Err::<Box<dyn Engine>, _>(EngineError::Other("nope".into())))
753                .unwrap_err();
754        assert!(matches!(err, EngineError::Other(_)));
755    }
756
757    #[test]
758    fn calls_after_drop_error_with_closed() {
759        let mut rt = spawn_test_runtime();
760        rt.shutdown();
761        let err = rt.capabilities().unwrap_err();
762        assert!(matches!(err, EngineError::Closed));
763    }
764
765    /// Cover the round-trip path that used to live in
766    /// `tests/runtime_round_trip.rs`. The Engine impl is intentionally
767    /// trivial — this test verifies the dispatch channel, not engine
768    /// behavior.
769    #[test]
770    fn full_primitive_sequence_via_runtime() {
771        let rt = spawn_test_runtime();
772        let page = rt
773            .open("https://example.com/login", &DataStore::Shared)
774            .unwrap();
775        rt.wait(page, WaitCondition::Stable, Duration::from_millis(0))
776            .unwrap();
777        let tree = rt.snapshot(page).unwrap();
778        assert!(tree.roots[0].label.contains("https://example.com/login"));
779        rt.act(
780            page,
781            ActTarget::Ref(Ref(3)),
782            Action::Fill { value: "x".into() },
783            crate::engine::InputMode::Careful,
784        )
785        .unwrap();
786        let auth = rt.save_auth(page).unwrap();
787        rt.load_auth(page, auth).unwrap();
788        rt.close(page).unwrap();
789        rt.close(page).unwrap();
790    }
791
792    #[test]
793    fn dispatch_serializes_calls() {
794        let rt = spawn_test_runtime();
795        let mut handles = Vec::new();
796        for i in 0..32 {
797            handles.push(
798                rt.open(&format!("https://example.com/{i}"), &DataStore::Shared)
799                    .unwrap(),
800            );
801        }
802        let mut sorted = handles.clone();
803        sorted.sort();
804        sorted.dedup();
805        assert_eq!(sorted.len(), handles.len());
806    }
807}