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 add_init_script(&self, page: PageHandle, source: &str) -> EngineResult<()> {
219        let source = source.to_string();
220        self.dispatch(move |e| e.add_init_script(page, &source))
221    }
222
223    pub fn snapshot(&self, page: PageHandle) -> EngineResult<Tree> {
224        self.dispatch(move |e| e.snapshot(page))
225    }
226
227    /// Snapshot the tree and read the console buffer in a single
228    /// main-thread hop. `vs_view` needs both (the tree, plus the
229    /// console entries behind its `? console_error` warning); folding
230    /// the cheap native console read into the snapshot dispatch avoids
231    /// a second round trip on every view. The console read is a buffer
232    /// borrow, so it adds no measurable cost.
233    pub fn snapshot_with_console(
234        &self,
235        page: PageHandle,
236    ) -> EngineResult<(Tree, Vec<crate::inspector::ConsoleEntry>)> {
237        self.dispatch(move |e| {
238            let tree = e.snapshot(page)?;
239            let console = e.console_entries(page)?;
240            Ok((tree, console))
241        })
242    }
243
244    pub fn act(
245        &self,
246        page: PageHandle,
247        target: ActTarget,
248        action: Action,
249        mode: crate::engine::InputMode,
250    ) -> EngineResult<()> {
251        self.dispatch(move |e| e.act(page, target, action, mode))
252    }
253
254    /// Perform an action and snapshot the resulting tree in a single
255    /// main-thread hop. `vs_act` always snapshots right after acting, so
256    /// folding the two into one dispatch removes a full engine round
257    /// trip (~10ms) from every action. The backend's `act` already
258    /// settles input + flushes rAF before returning, so the snapshot
259    /// sees the post-action DOM exactly as the two-call form did.
260    pub fn act_and_snapshot(
261        &self,
262        page: PageHandle,
263        target: ActTarget,
264        action: Action,
265        mode: crate::engine::InputMode,
266    ) -> EngineResult<Tree> {
267        self.dispatch(move |e| {
268            e.act(page, target, action, mode)?;
269            e.snapshot(page)
270        })
271    }
272
273    pub fn wait(
274        &self,
275        page: PageHandle,
276        cond: WaitCondition,
277        budget: Duration,
278    ) -> EngineResult<()> {
279        self.dispatch(move |e| e.wait(page, cond, budget))
280    }
281
282    pub fn capture(&self, page: PageHandle, scope: CaptureScope) -> EngineResult<PathBuf> {
283        self.dispatch(move |e| e.capture(page, scope))
284    }
285
286    pub fn capture_live(&self, page: PageHandle, max_width: u32) -> EngineResult<PathBuf> {
287        self.dispatch(move |e| e.capture_live(page, max_width))
288    }
289
290    pub fn record_begin(
291        &self,
292        page: PageHandle,
293        tx: std::sync::mpsc::Sender<crate::engine::RecFrame>,
294        fps: u32,
295        max_width: u32,
296    ) -> EngineResult<()> {
297        self.dispatch(move |e| e.record_begin(page, tx, fps, max_width))
298    }
299
300    pub fn record_end(&self, page: PageHandle) -> EngineResult<()> {
301        self.dispatch(move |e| e.record_end(page))
302    }
303
304    pub fn layout(&self, page: PageHandle, refs: Vec<Ref>) -> EngineResult<Vec<LayoutBox>> {
305        self.dispatch(move |e| e.layout(page, &refs))
306    }
307
308    pub fn download(
309        &self,
310        page: PageHandle,
311        source: DownloadSource,
312        budget: Duration,
313    ) -> EngineResult<Download> {
314        self.dispatch(move |e| e.download(page, source, budget))
315    }
316
317    pub fn download_list(&self, page: PageHandle) -> EngineResult<Vec<DownloadEntry>> {
318        self.dispatch(move |e| e.download_list(page))
319    }
320
321    pub fn set_viewport(&self, page: PageHandle, viewport: Viewport) -> EngineResult<()> {
322        self.dispatch(move |e| e.set_viewport(page, viewport))
323    }
324
325    pub fn save_auth(&self, page: PageHandle) -> EngineResult<AuthBlob> {
326        self.dispatch(move |e| e.save_auth(page))
327    }
328
329    pub fn load_auth(&self, page: PageHandle, blob: AuthBlob) -> EngineResult<()> {
330        self.dispatch(move |e| e.load_auth(page, &blob))
331    }
332
333    pub fn console_entries(
334        &self,
335        page: PageHandle,
336    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
337        self.dispatch(move |e| e.console_entries(page))
338    }
339
340    pub fn network_entries(
341        &self,
342        page: PageHandle,
343    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
344        self.dispatch(move |e| e.network_entries(page))
345    }
346
347    pub fn request_detail(
348        &self,
349        page: PageHandle,
350        seq: u64,
351    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
352        self.dispatch(move |e| e.request_detail(page, seq))
353    }
354
355    pub fn eval_js(
356        &self,
357        page: PageHandle,
358        expr: &str,
359    ) -> EngineResult<crate::inspector::EvalResult> {
360        let expr = expr.to_string();
361        self.dispatch(move |e| e.eval_js(page, &expr))
362    }
363
364    pub fn storage(
365        &self,
366        page: PageHandle,
367        scope: crate::inspector::StorageScope,
368    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
369        self.dispatch(move |e| e.storage(page, scope))
370    }
371
372    pub fn cookie_events(
373        &self,
374        page: PageHandle,
375    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
376        self.dispatch(move |e| e.cookie_events(page))
377    }
378
379    pub fn type_text(
380        &self,
381        page: PageHandle,
382        text: &str,
383        mode: crate::engine::InputMode,
384    ) -> EngineResult<()> {
385        let text = text.to_string();
386        self.dispatch(move |e| e.type_text(page, &text, mode))
387    }
388
389    pub fn cursor_op(
390        &self,
391        page: PageHandle,
392        op: crate::engine::CursorOp,
393        mode: crate::engine::InputMode,
394    ) -> EngineResult<()> {
395        self.dispatch(move |e| e.cursor_op(page, op, mode))
396    }
397
398    pub fn scripts(&self, page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
399        self.dispatch(move |e| e.scripts(page))
400    }
401
402    pub fn script_source(
403        &self,
404        page: PageHandle,
405        seq: u64,
406    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
407        self.dispatch(move |e| e.script_source(page, seq))
408    }
409
410    pub fn dom(
411        &self,
412        page: PageHandle,
413        r: vs_protocol::Ref,
414        extra_props: Vec<String>,
415    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
416        self.dispatch(move |e| e.dom(page, r, &extra_props))
417    }
418
419    pub fn performance(
420        &self,
421        page: PageHandle,
422    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
423        self.dispatch(move |e| e.performance(page))
424    }
425
426    pub fn capabilities(&self) -> EngineResult<EngineCapabilities> {
427        self.dispatch(|e| Ok(e.capabilities()))
428    }
429}
430
431impl Drop for EngineRuntime {
432    fn drop(&mut self) {
433        self.shutdown();
434    }
435}
436
437/// Drives an engine that lives on the caller'\''s thread (typically the
438/// OS main thread on macOS, since `WKWebView` is pinned there). The
439/// driver owns the engine and a receiver for jobs sent by the runtime
440/// handle that the daemon holds.
441pub struct MainThreadDispatcher {
442    engine: Box<dyn Engine>,
443    rx: mpsc::Receiver<Job>,
444}
445
446impl MainThreadDispatcher {
447    /// Drain one job if available. Returns `Ok(true)` if a job was
448    /// executed, `Ok(false)` if the queue is currently empty,
449    /// `Err(())` if the channel is closed (the runtime was dropped —
450    /// the dispatcher should exit its loop).
451    pub fn tick(&mut self) -> Result<bool, ()> {
452        match self.rx.try_recv() {
453            Ok(job) => {
454                job(self.engine.as_mut());
455                Ok(true)
456            }
457            Err(mpsc::TryRecvError::Empty) => Ok(false),
458            Err(mpsc::TryRecvError::Disconnected) => Err(()),
459        }
460    }
461
462    /// Block until a job arrives or the channel is closed; execute one
463    /// job. Returns `Ok(true)` after running, `Err(())` on closed.
464    pub fn tick_blocking(&mut self) -> Result<bool, ()> {
465        match self.rx.recv() {
466            Ok(job) => {
467                job(self.engine.as_mut());
468                Ok(true)
469            }
470            Err(_) => Err(()),
471        }
472    }
473}
474
475#[cfg(test)]
476mod tests {
477    use std::path::PathBuf;
478    use std::time::Duration;
479
480    use vs_protocol::{Node, Ref, Role, Tree};
481
482    use super::*;
483    use crate::engine::{
484        ActTarget, Action, AuthBlob, CaptureScope, EngineCapabilities, LayoutBox, Viewport,
485        WaitCondition,
486    };
487
488    /// Minimal in-process `Engine` impl used only to exercise the
489    /// runtime's spawn / dispatch / shutdown plumbing. Lives in the
490    /// same `cfg(test)` block as the tests so it can never be reached
491    /// from production code.
492    #[derive(Default)]
493    struct TestEngine {
494        next_handle: u64,
495        last_url: String,
496    }
497
498    impl Engine for TestEngine {
499        fn open(&mut self, url: &str) -> EngineResult<PageHandle> {
500            self.next_handle += 1;
501            self.last_url = url.to_string();
502            Ok(PageHandle(self.next_handle))
503        }
504        fn navigate(&mut self, _page: PageHandle, url: &str) -> EngineResult<()> {
505            self.last_url = url.to_string();
506            Ok(())
507        }
508        fn enable_webauthn(&mut self, _page: PageHandle) -> EngineResult<()> {
509            Ok(())
510        }
511        fn add_init_script(&mut self, _page: PageHandle, _source: &str) -> EngineResult<()> {
512            Ok(())
513        }
514        fn close(&mut self, _page: PageHandle) -> EngineResult<()> {
515            Ok(())
516        }
517        fn snapshot(&mut self, _page: PageHandle) -> EngineResult<Tree> {
518            Ok(Tree::from_root(Node::leaf(
519                Ref(1),
520                Role::Doc,
521                &self.last_url,
522            )))
523        }
524        fn act(
525            &mut self,
526            _: PageHandle,
527            _: ActTarget,
528            _: Action,
529            _: crate::engine::InputMode,
530        ) -> EngineResult<()> {
531            Ok(())
532        }
533        fn wait(&mut self, _: PageHandle, _: WaitCondition, _: Duration) -> EngineResult<()> {
534            Ok(())
535        }
536        fn capture(&mut self, _: PageHandle, _: CaptureScope) -> EngineResult<PathBuf> {
537            Ok(PathBuf::from("/tmp/test.png"))
538        }
539        fn layout(&mut self, _: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>> {
540            Ok(refs
541                .iter()
542                .map(|r| LayoutBox {
543                    r: *r,
544                    x: 0.0,
545                    y: 0.0,
546                    width: 1.0,
547                    height: 1.0,
548                    visible: true,
549                    z_index: 0,
550                })
551                .collect())
552        }
553        fn set_viewport(&mut self, _: PageHandle, _: Viewport) -> EngineResult<()> {
554            Ok(())
555        }
556        fn save_auth(&mut self, _: PageHandle) -> EngineResult<AuthBlob> {
557            Ok(AuthBlob {
558                bytes: self.last_url.as_bytes().to_vec(),
559            })
560        }
561        fn load_auth(&mut self, _: PageHandle, _: &AuthBlob) -> EngineResult<()> {
562            Ok(())
563        }
564        fn capabilities(&self) -> EngineCapabilities {
565            EngineCapabilities {
566                renders: false,
567                honors_viewport: false,
568                measures_layout: false,
569                persists_auth: false,
570                inspector_console: false,
571                inspector_network: false,
572                inspector_cookie_events: false,
573                name: "test",
574                version: "runtime-tests",
575            }
576        }
577    }
578
579    fn spawn_test_runtime() -> EngineRuntime {
580        EngineRuntime::spawn(|| Ok(Box::new(TestEngine::default()) as Box<dyn Engine>))
581            .expect("spawn")
582    }
583
584    #[test]
585    fn spawn_and_shutdown_cleanly() {
586        let mut rt = spawn_test_runtime();
587        rt.shutdown();
588        rt.shutdown();
589    }
590
591    #[test]
592    fn dispatch_blocks_until_reply() {
593        let rt = spawn_test_runtime();
594        let caps = rt.capabilities().unwrap();
595        assert_eq!(caps.name, "test");
596    }
597
598    #[test]
599    fn engine_construction_failure_reported() {
600        let err =
601            EngineRuntime::spawn(|| Err::<Box<dyn Engine>, _>(EngineError::Other("nope".into())))
602                .unwrap_err();
603        assert!(matches!(err, EngineError::Other(_)));
604    }
605
606    #[test]
607    fn calls_after_drop_error_with_closed() {
608        let mut rt = spawn_test_runtime();
609        rt.shutdown();
610        let err = rt.capabilities().unwrap_err();
611        assert!(matches!(err, EngineError::Closed));
612    }
613
614    /// Cover the round-trip path that used to live in
615    /// `tests/runtime_round_trip.rs`. The Engine impl is intentionally
616    /// trivial — this test verifies the dispatch channel, not engine
617    /// behavior.
618    #[test]
619    fn full_primitive_sequence_via_runtime() {
620        let rt = spawn_test_runtime();
621        let page = rt.open("https://example.com/login").unwrap();
622        rt.wait(page, WaitCondition::Stable, Duration::from_millis(0))
623            .unwrap();
624        let tree = rt.snapshot(page).unwrap();
625        assert!(tree.roots[0].label.contains("https://example.com/login"));
626        rt.act(
627            page,
628            ActTarget::Ref(Ref(3)),
629            Action::Fill { value: "x".into() },
630            crate::engine::InputMode::Careful,
631        )
632        .unwrap();
633        let auth = rt.save_auth(page).unwrap();
634        rt.load_auth(page, auth).unwrap();
635        rt.close(page).unwrap();
636        rt.close(page).unwrap();
637    }
638
639    #[test]
640    fn dispatch_serializes_calls() {
641        let rt = spawn_test_runtime();
642        let mut handles = Vec::new();
643        for i in 0..32 {
644            handles.push(rt.open(&format!("https://example.com/{i}")).unwrap());
645        }
646        let mut sorted = handles.clone();
647        sorted.sort();
648        sorted.dedup();
649        assert_eq!(sorted.len(), handles.len());
650    }
651}