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, Download, DownloadEntry, DownloadSource, Engine,
26    EngineCapabilities, EngineError, EngineResult, LayoutBox, PageHandle, Viewport, WaitCondition,
27};
28
29/// One unit of work for the engine thread.
30type Job = Box<dyn FnOnce(&mut dyn Engine) + Send>;
31
32/// Extract a human-readable message from a `catch_unwind` payload.
33fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
34    let detail = payload
35        .downcast_ref::<&str>()
36        .map(|s| (*s).to_string())
37        .or_else(|| payload.downcast_ref::<String>().cloned())
38        .unwrap_or_else(|| "unknown panic".to_string());
39    format!("engine panicked: {detail}")
40}
41
42/// Owns the engine thread and exposes a synchronous facade.
43///
44/// Drop semantics: dropping the runtime closes the command channel,
45/// which causes the engine thread to exit its loop and drop the
46/// engine. The destructor joins the thread.
47/// Called after a job is queued, to nudge a host loop that is asleep.
48///
49/// An `mpsc` send is invisible to a platform run loop, so a
50/// [`MainThreadDispatcher`] host cannot block waiting for work — it has
51/// to wake periodically and poll, trading idle CPU against how long a
52/// queued job sits. With a waker installed the host can sleep properly
53/// and be woken the moment a job lands, which removes both costs.
54///
55/// Must be safe to call from any thread.
56pub type Waker = Box<dyn Fn() + Send + Sync>;
57
58pub struct EngineRuntime {
59    sender: Option<mpsc::Sender<Job>>,
60    handle: Option<JoinHandle<()>>,
61    waker: Option<Waker>,
62}
63
64impl std::fmt::Debug for EngineRuntime {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        f.debug_struct("EngineRuntime")
67            .field("running", &self.sender.is_some())
68            .finish_non_exhaustive()
69    }
70}
71
72impl EngineRuntime {
73    /// Spawn the engine thread and construct the engine *on that thread*
74    /// via `make`. This is the only correct construction point: the
75    /// platform run loop must be initialized on the same thread that
76    /// later drives WebKit.
77    ///
78    /// Returns once the engine thread has signaled it is ready.
79    pub fn spawn<F>(make: F) -> EngineResult<Self>
80    where
81        F: FnOnce() -> EngineResult<Box<dyn Engine>> + Send + 'static,
82    {
83        let (tx, rx) = mpsc::channel::<Job>();
84        let (ready_tx, ready_rx) = mpsc::sync_channel::<EngineResult<()>>(1);
85
86        let handle = thread::Builder::new()
87            .name("vibesurfer-engine".into())
88            .spawn(move || {
89                let mut engine = match make() {
90                    Ok(e) => {
91                        let _ = ready_tx.send(Ok(()));
92                        e
93                    }
94                    Err(e) => {
95                        let _ = ready_tx.send(Err(e));
96                        return;
97                    }
98                };
99
100                while let Ok(job) = rx.recv() {
101                    job(engine.as_mut());
102                }
103                // Channel closed: drop the engine on this thread and exit.
104                drop(engine);
105            })
106            .map_err(|e| EngineError::Other(format!("spawn engine thread: {e}")))?;
107
108        match ready_rx.recv() {
109            Ok(Ok(())) => {}
110            Ok(Err(e)) => {
111                let _ = handle.join();
112                return Err(e);
113            }
114            Err(_) => {
115                let _ = handle.join();
116                return Err(EngineError::Crashed);
117            }
118        }
119
120        Ok(Self {
121            sender: Some(tx),
122            handle: Some(handle),
123            // The spawned-thread runtime blocks on `rx.recv()`, so it is
124            // already woken by the send itself.
125            waker: None,
126        })
127    }
128
129    /// Construct a runtime whose engine runs on the *caller'\''s* thread.
130    /// No internal thread is spawned. The returned [`MainThreadDispatcher`]
131    /// drives the engine: call [`MainThreadDispatcher::tick`] in the
132    /// caller'\''s loop to drain one queued job, or [`MainThreadDispatcher::run_until`]
133    /// to block until a stop flag fires.
134    ///
135    /// Use this when the engine is bound to a specific OS thread (e.g.
136    /// the macOS Cocoa main thread, where `WKWebView` must run).
137    pub fn dispatcher(engine: Box<dyn Engine>) -> (Self, MainThreadDispatcher) {
138        let (tx, rx) = mpsc::channel::<Job>();
139        let runtime = Self {
140            sender: Some(tx),
141            handle: None,
142            waker: None,
143        };
144        let dispatcher = MainThreadDispatcher { engine, rx };
145        (runtime, dispatcher)
146    }
147
148    /// Install the [`Waker`] the host loop is woken by.
149    ///
150    /// Call before the runtime is shared. Without one the host must
151    /// poll; with one it can sleep until there is actually work.
152    #[must_use]
153    pub fn with_waker(mut self, waker: Waker) -> Self {
154        self.waker = Some(waker);
155        self
156    }
157
158    /// Cleanly shut down: close the channel and join the thread.
159    /// Idempotent — calling shutdown twice is a no-op.
160    pub fn shutdown(&mut self) {
161        drop(self.sender.take());
162        if let Some(handle) = self.handle.take() {
163            let _ = handle.join();
164        }
165    }
166
167    fn dispatch<R, F>(&self, f: F) -> EngineResult<R>
168    where
169        F: FnOnce(&mut dyn Engine) -> EngineResult<R> + Send + 'static,
170        R: Send + 'static,
171    {
172        let sender = self.sender.as_ref().ok_or(EngineError::Closed)?;
173        let (reply_tx, reply_rx) = mpsc::sync_channel::<EngineResult<R>>(1);
174        let job: Job = Box::new(move |engine| {
175            // Isolate a panicking engine op: on macOS the job runs on
176            // the Cocoa main thread inside an Obj-C run-loop frame, so an
177            // unwinding panic is undefined behavior that can take the
178            // whole daemon down ("could not connect to the server" on the
179            // next request). Catch it here and hand back a clean, message-
180            // bearing error instead — far better than the bare
181            // `ENGINE_CRASH` (empty-args) the dropped reply channel would
182            // otherwise produce.
183            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(engine)))
184                .unwrap_or_else(|payload| Err(EngineError::Other(panic_message(&payload))));
185            let _ = reply_tx.send(result);
186        });
187        sender.send(job).map_err(|_| EngineError::Closed)?;
188        // Wake the host loop *after* the job is queued, so it cannot
189        // wake, find nothing, and go back to sleep past this job.
190        if let Some(waker) = &self.waker {
191            waker();
192        }
193        reply_rx.recv().map_err(|_| EngineError::Crashed)?
194    }
195
196    // -----------------------------------------------------------------
197    // Synchronous facade for every Engine method.
198    // -----------------------------------------------------------------
199
200    pub fn open(&self, url: &str) -> EngineResult<PageHandle> {
201        let url = url.to_string();
202        self.dispatch(move |e| e.open(&url))
203    }
204
205    pub fn navigate(&self, page: PageHandle, url: &str) -> EngineResult<()> {
206        let url = url.to_string();
207        self.dispatch(move |e| e.navigate(page, &url))
208    }
209
210    pub fn close(&self, page: PageHandle) -> EngineResult<()> {
211        self.dispatch(move |e| e.close(page))
212    }
213
214    pub fn enable_webauthn(&self, page: PageHandle) -> EngineResult<()> {
215        self.dispatch(move |e| e.enable_webauthn(page))
216    }
217
218    pub fn snapshot(&self, page: PageHandle) -> EngineResult<Tree> {
219        self.dispatch(move |e| e.snapshot(page))
220    }
221
222    /// Snapshot the tree and read the console buffer in a single
223    /// main-thread hop. `vs_view` needs both (the tree, plus the
224    /// console entries behind its `? console_error` warning); folding
225    /// the cheap native console read into the snapshot dispatch avoids
226    /// a second round trip on every view. The console read is a buffer
227    /// borrow, so it adds no measurable cost.
228    pub fn snapshot_with_console(
229        &self,
230        page: PageHandle,
231    ) -> EngineResult<(Tree, Vec<crate::inspector::ConsoleEntry>)> {
232        self.dispatch(move |e| {
233            let tree = e.snapshot(page)?;
234            let console = e.console_entries(page)?;
235            Ok((tree, console))
236        })
237    }
238
239    pub fn act(
240        &self,
241        page: PageHandle,
242        target: ActTarget,
243        action: Action,
244        mode: crate::engine::InputMode,
245    ) -> EngineResult<()> {
246        self.dispatch(move |e| e.act(page, target, action, mode))
247    }
248
249    /// Perform an action and snapshot the resulting tree in a single
250    /// main-thread hop. `vs_act` always snapshots right after acting, so
251    /// folding the two into one dispatch removes a full engine round
252    /// trip (~10ms) from every action. The backend's `act` already
253    /// settles input + flushes rAF before returning, so the snapshot
254    /// sees the post-action DOM exactly as the two-call form did.
255    pub fn act_and_snapshot(
256        &self,
257        page: PageHandle,
258        target: ActTarget,
259        action: Action,
260        mode: crate::engine::InputMode,
261    ) -> EngineResult<Tree> {
262        self.dispatch(move |e| {
263            e.act(page, target, action, mode)?;
264            e.snapshot(page)
265        })
266    }
267
268    pub fn wait(
269        &self,
270        page: PageHandle,
271        cond: WaitCondition,
272        budget: Duration,
273    ) -> EngineResult<()> {
274        self.dispatch(move |e| e.wait(page, cond, budget))
275    }
276
277    pub fn capture(&self, page: PageHandle, scope: CaptureScope) -> EngineResult<PathBuf> {
278        self.dispatch(move |e| e.capture(page, scope))
279    }
280
281    pub fn capture_live(&self, page: PageHandle, max_width: u32) -> EngineResult<PathBuf> {
282        self.dispatch(move |e| e.capture_live(page, max_width))
283    }
284
285    pub fn record_begin(
286        &self,
287        page: PageHandle,
288        tx: std::sync::mpsc::Sender<crate::engine::RecFrame>,
289        fps: u32,
290        max_width: u32,
291    ) -> EngineResult<()> {
292        self.dispatch(move |e| e.record_begin(page, tx, fps, max_width))
293    }
294
295    pub fn record_end(&self, page: PageHandle) -> EngineResult<()> {
296        self.dispatch(move |e| e.record_end(page))
297    }
298
299    pub fn layout(&self, page: PageHandle, refs: Vec<Ref>) -> EngineResult<Vec<LayoutBox>> {
300        self.dispatch(move |e| e.layout(page, &refs))
301    }
302
303    pub fn download(
304        &self,
305        page: PageHandle,
306        source: DownloadSource,
307        budget: Duration,
308    ) -> EngineResult<Download> {
309        self.dispatch(move |e| e.download(page, source, budget))
310    }
311
312    pub fn download_list(&self, page: PageHandle) -> EngineResult<Vec<DownloadEntry>> {
313        self.dispatch(move |e| e.download_list(page))
314    }
315
316    pub fn set_viewport(&self, page: PageHandle, viewport: Viewport) -> EngineResult<()> {
317        self.dispatch(move |e| e.set_viewport(page, viewport))
318    }
319
320    pub fn save_auth(&self, page: PageHandle) -> EngineResult<AuthBlob> {
321        self.dispatch(move |e| e.save_auth(page))
322    }
323
324    pub fn load_auth(&self, page: PageHandle, blob: AuthBlob) -> EngineResult<()> {
325        self.dispatch(move |e| e.load_auth(page, &blob))
326    }
327
328    pub fn console_entries(
329        &self,
330        page: PageHandle,
331    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
332        self.dispatch(move |e| e.console_entries(page))
333    }
334
335    pub fn network_entries(
336        &self,
337        page: PageHandle,
338    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
339        self.dispatch(move |e| e.network_entries(page))
340    }
341
342    pub fn request_detail(
343        &self,
344        page: PageHandle,
345        seq: u64,
346    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
347        self.dispatch(move |e| e.request_detail(page, seq))
348    }
349
350    pub fn eval_js(
351        &self,
352        page: PageHandle,
353        expr: &str,
354    ) -> EngineResult<crate::inspector::EvalResult> {
355        let expr = expr.to_string();
356        self.dispatch(move |e| e.eval_js(page, &expr))
357    }
358
359    pub fn storage(
360        &self,
361        page: PageHandle,
362        scope: crate::inspector::StorageScope,
363    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
364        self.dispatch(move |e| e.storage(page, scope))
365    }
366
367    pub fn cookie_events(
368        &self,
369        page: PageHandle,
370    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
371        self.dispatch(move |e| e.cookie_events(page))
372    }
373
374    pub fn type_text(
375        &self,
376        page: PageHandle,
377        text: &str,
378        mode: crate::engine::InputMode,
379    ) -> EngineResult<()> {
380        let text = text.to_string();
381        self.dispatch(move |e| e.type_text(page, &text, mode))
382    }
383
384    pub fn cursor_op(
385        &self,
386        page: PageHandle,
387        op: crate::engine::CursorOp,
388        mode: crate::engine::InputMode,
389    ) -> EngineResult<()> {
390        self.dispatch(move |e| e.cursor_op(page, op, mode))
391    }
392
393    pub fn scripts(&self, page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
394        self.dispatch(move |e| e.scripts(page))
395    }
396
397    pub fn script_source(
398        &self,
399        page: PageHandle,
400        seq: u64,
401    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
402        self.dispatch(move |e| e.script_source(page, seq))
403    }
404
405    pub fn dom(
406        &self,
407        page: PageHandle,
408        r: vs_protocol::Ref,
409        extra_props: Vec<String>,
410    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
411        self.dispatch(move |e| e.dom(page, r, &extra_props))
412    }
413
414    pub fn performance(
415        &self,
416        page: PageHandle,
417    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
418        self.dispatch(move |e| e.performance(page))
419    }
420
421    pub fn capabilities(&self) -> EngineResult<EngineCapabilities> {
422        self.dispatch(|e| Ok(e.capabilities()))
423    }
424}
425
426impl Drop for EngineRuntime {
427    fn drop(&mut self) {
428        self.shutdown();
429    }
430}
431
432/// Drives an engine that lives on the caller'\''s thread (typically the
433/// OS main thread on macOS, since `WKWebView` is pinned there). The
434/// driver owns the engine and a receiver for jobs sent by the runtime
435/// handle that the daemon holds.
436pub struct MainThreadDispatcher {
437    engine: Box<dyn Engine>,
438    rx: mpsc::Receiver<Job>,
439}
440
441impl MainThreadDispatcher {
442    /// Drain one job if available. Returns `Ok(true)` if a job was
443    /// executed, `Ok(false)` if the queue is currently empty,
444    /// `Err(())` if the channel is closed (the runtime was dropped —
445    /// the dispatcher should exit its loop).
446    pub fn tick(&mut self) -> Result<bool, ()> {
447        match self.rx.try_recv() {
448            Ok(job) => {
449                job(self.engine.as_mut());
450                Ok(true)
451            }
452            Err(mpsc::TryRecvError::Empty) => Ok(false),
453            Err(mpsc::TryRecvError::Disconnected) => Err(()),
454        }
455    }
456
457    /// Block until a job arrives or the channel is closed; execute one
458    /// job. Returns `Ok(true)` after running, `Err(())` on closed.
459    pub fn tick_blocking(&mut self) -> Result<bool, ()> {
460        match self.rx.recv() {
461            Ok(job) => {
462                job(self.engine.as_mut());
463                Ok(true)
464            }
465            Err(_) => Err(()),
466        }
467    }
468}
469
470#[cfg(test)]
471mod tests {
472    use std::path::PathBuf;
473    use std::time::Duration;
474
475    use vs_protocol::{Node, Ref, Role, Tree};
476
477    use super::*;
478    use crate::engine::{
479        ActTarget, Action, AuthBlob, CaptureScope, EngineCapabilities, LayoutBox, Viewport,
480        WaitCondition,
481    };
482
483    /// Minimal in-process `Engine` impl used only to exercise the
484    /// runtime's spawn / dispatch / shutdown plumbing. Lives in the
485    /// same `cfg(test)` block as the tests so it can never be reached
486    /// from production code.
487    #[derive(Default)]
488    struct TestEngine {
489        next_handle: u64,
490        last_url: String,
491    }
492
493    impl Engine for TestEngine {
494        fn open(&mut self, url: &str) -> EngineResult<PageHandle> {
495            self.next_handle += 1;
496            self.last_url = url.to_string();
497            Ok(PageHandle(self.next_handle))
498        }
499        fn navigate(&mut self, _page: PageHandle, url: &str) -> EngineResult<()> {
500            self.last_url = url.to_string();
501            Ok(())
502        }
503        fn enable_webauthn(&mut self, _page: PageHandle) -> EngineResult<()> {
504            Ok(())
505        }
506        fn close(&mut self, _page: PageHandle) -> EngineResult<()> {
507            Ok(())
508        }
509        fn snapshot(&mut self, _page: PageHandle) -> EngineResult<Tree> {
510            Ok(Tree::from_root(Node::leaf(
511                Ref(1),
512                Role::Doc,
513                &self.last_url,
514            )))
515        }
516        fn act(
517            &mut self,
518            _: PageHandle,
519            _: ActTarget,
520            _: Action,
521            _: crate::engine::InputMode,
522        ) -> EngineResult<()> {
523            Ok(())
524        }
525        fn wait(&mut self, _: PageHandle, _: WaitCondition, _: Duration) -> EngineResult<()> {
526            Ok(())
527        }
528        fn capture(&mut self, _: PageHandle, _: CaptureScope) -> EngineResult<PathBuf> {
529            Ok(PathBuf::from("/tmp/test.png"))
530        }
531        fn layout(&mut self, _: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>> {
532            Ok(refs
533                .iter()
534                .map(|r| LayoutBox {
535                    r: *r,
536                    x: 0.0,
537                    y: 0.0,
538                    width: 1.0,
539                    height: 1.0,
540                    visible: true,
541                    z_index: 0,
542                })
543                .collect())
544        }
545        fn set_viewport(&mut self, _: PageHandle, _: Viewport) -> EngineResult<()> {
546            Ok(())
547        }
548        fn save_auth(&mut self, _: PageHandle) -> EngineResult<AuthBlob> {
549            Ok(AuthBlob {
550                bytes: self.last_url.as_bytes().to_vec(),
551            })
552        }
553        fn load_auth(&mut self, _: PageHandle, _: &AuthBlob) -> EngineResult<()> {
554            Ok(())
555        }
556        fn capabilities(&self) -> EngineCapabilities {
557            EngineCapabilities {
558                renders: false,
559                honors_viewport: false,
560                measures_layout: false,
561                persists_auth: false,
562                inspector_console: false,
563                inspector_network: false,
564                inspector_cookie_events: false,
565                name: "test",
566                version: "runtime-tests",
567            }
568        }
569    }
570
571    fn spawn_test_runtime() -> EngineRuntime {
572        EngineRuntime::spawn(|| Ok(Box::new(TestEngine::default()) as Box<dyn Engine>))
573            .expect("spawn")
574    }
575
576    #[test]
577    fn spawn_and_shutdown_cleanly() {
578        let mut rt = spawn_test_runtime();
579        rt.shutdown();
580        rt.shutdown();
581    }
582
583    #[test]
584    fn dispatch_blocks_until_reply() {
585        let rt = spawn_test_runtime();
586        let caps = rt.capabilities().unwrap();
587        assert_eq!(caps.name, "test");
588    }
589
590    #[test]
591    fn engine_construction_failure_reported() {
592        let err =
593            EngineRuntime::spawn(|| Err::<Box<dyn Engine>, _>(EngineError::Other("nope".into())))
594                .unwrap_err();
595        assert!(matches!(err, EngineError::Other(_)));
596    }
597
598    #[test]
599    fn calls_after_drop_error_with_closed() {
600        let mut rt = spawn_test_runtime();
601        rt.shutdown();
602        let err = rt.capabilities().unwrap_err();
603        assert!(matches!(err, EngineError::Closed));
604    }
605
606    /// Cover the round-trip path that used to live in
607    /// `tests/runtime_round_trip.rs`. The Engine impl is intentionally
608    /// trivial — this test verifies the dispatch channel, not engine
609    /// behavior.
610    #[test]
611    fn full_primitive_sequence_via_runtime() {
612        let rt = spawn_test_runtime();
613        let page = rt.open("https://example.com/login").unwrap();
614        rt.wait(page, WaitCondition::Stable, Duration::from_millis(0))
615            .unwrap();
616        let tree = rt.snapshot(page).unwrap();
617        assert!(tree.roots[0].label.contains("https://example.com/login"));
618        rt.act(
619            page,
620            ActTarget::Ref(Ref(3)),
621            Action::Fill { value: "x".into() },
622            crate::engine::InputMode::Careful,
623        )
624        .unwrap();
625        let auth = rt.save_auth(page).unwrap();
626        rt.load_auth(page, auth).unwrap();
627        rt.close(page).unwrap();
628        rt.close(page).unwrap();
629    }
630
631    #[test]
632    fn dispatch_serializes_calls() {
633        let rt = spawn_test_runtime();
634        let mut handles = Vec::new();
635        for i in 0..32 {
636            handles.push(rt.open(&format!("https://example.com/{i}")).unwrap());
637        }
638        let mut sorted = handles.clone();
639        sorted.sort();
640        sorted.dedup();
641        assert_eq!(sorted.len(), handles.len());
642    }
643}