1#![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, PageHandle, Viewport,
27 WaitCondition,
28};
29
30type Job = Box<dyn FnOnce(&mut dyn Engine) + Send>;
32
33fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
35 let detail = payload
36 .downcast_ref::<&str>()
37 .map(|s| (*s).to_string())
38 .or_else(|| payload.downcast_ref::<String>().cloned())
39 .unwrap_or_else(|| "unknown panic".to_string());
40 format!("engine panicked: {detail}")
41}
42
43pub type Waker = Box<dyn Fn() + Send + Sync>;
58
59pub struct EngineRuntime {
60 sender: Option<mpsc::Sender<Job>>,
61 handle: Option<JoinHandle<()>>,
62 waker: Option<Waker>,
63}
64
65impl std::fmt::Debug for EngineRuntime {
66 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67 f.debug_struct("EngineRuntime")
68 .field("running", &self.sender.is_some())
69 .finish_non_exhaustive()
70 }
71}
72
73impl EngineRuntime {
74 pub fn spawn<F>(make: F) -> EngineResult<Self>
81 where
82 F: FnOnce() -> EngineResult<Box<dyn Engine>> + Send + 'static,
83 {
84 let (tx, rx) = mpsc::channel::<Job>();
85 let (ready_tx, ready_rx) = mpsc::sync_channel::<EngineResult<()>>(1);
86
87 let handle = thread::Builder::new()
88 .name("vibesurfer-engine".into())
89 .spawn(move || {
90 let mut engine = match make() {
91 Ok(e) => {
92 let _ = ready_tx.send(Ok(()));
93 e
94 }
95 Err(e) => {
96 let _ = ready_tx.send(Err(e));
97 return;
98 }
99 };
100
101 while let Ok(job) = rx.recv() {
102 job(engine.as_mut());
103 }
104 drop(engine);
106 })
107 .map_err(|e| EngineError::Other(format!("spawn engine thread: {e}")))?;
108
109 match ready_rx.recv() {
110 Ok(Ok(())) => {}
111 Ok(Err(e)) => {
112 let _ = handle.join();
113 return Err(e);
114 }
115 Err(_) => {
116 let _ = handle.join();
117 return Err(EngineError::Crashed);
118 }
119 }
120
121 Ok(Self {
122 sender: Some(tx),
123 handle: Some(handle),
124 waker: None,
127 })
128 }
129
130 pub fn dispatcher(engine: Box<dyn Engine>) -> (Self, MainThreadDispatcher) {
139 let (tx, rx) = mpsc::channel::<Job>();
140 let runtime = Self {
141 sender: Some(tx),
142 handle: None,
143 waker: None,
144 };
145 let dispatcher = MainThreadDispatcher { engine, rx };
146 (runtime, dispatcher)
147 }
148
149 #[must_use]
154 pub fn with_waker(mut self, waker: Waker) -> Self {
155 self.waker = Some(waker);
156 self
157 }
158
159 pub fn shutdown(&mut self) {
162 drop(self.sender.take());
163 if let Some(handle) = self.handle.take() {
164 let _ = handle.join();
165 }
166 }
167
168 fn dispatch<R, F>(&self, f: F) -> EngineResult<R>
169 where
170 F: FnOnce(&mut dyn Engine) -> EngineResult<R> + Send + 'static,
171 R: Send + 'static,
172 {
173 let sender = self.sender.as_ref().ok_or(EngineError::Closed)?;
174 let (reply_tx, reply_rx) = mpsc::sync_channel::<EngineResult<R>>(1);
175 let job: Job = Box::new(move |engine| {
176 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(engine)))
185 .unwrap_or_else(|payload| Err(EngineError::Other(panic_message(&payload))));
186 let _ = reply_tx.send(result);
187 });
188 sender.send(job).map_err(|_| EngineError::Closed)?;
189 if let Some(waker) = &self.waker {
192 waker();
193 }
194 reply_rx.recv().map_err(|_| EngineError::Crashed)?
195 }
196
197 pub fn open(&self, url: &str, store: &DataStore) -> EngineResult<PageHandle> {
202 let url = url.to_string();
203 let store = store.clone();
204 self.dispatch(move |e| e.open(&url, &store))
205 }
206
207 pub fn drop_store(&self, key: &str) -> EngineResult<()> {
208 let key = key.to_string();
209 self.dispatch(move |e| e.drop_store(&key))
210 }
211
212 pub fn navigate(&self, page: PageHandle, url: &str) -> EngineResult<()> {
213 let url = url.to_string();
214 self.dispatch(move |e| e.navigate(page, &url))
215 }
216
217 pub fn load_html(&self, page: PageHandle, url: &str, html: &str) -> EngineResult<()> {
218 let url = url.to_string();
219 let html = html.to_string();
220 self.dispatch(move |e| e.load_html(page, &url, &html))
221 }
222
223 pub fn close(&self, page: PageHandle) -> EngineResult<()> {
224 self.dispatch(move |e| e.close(page))
225 }
226
227 pub fn enable_webauthn(&self, page: PageHandle) -> EngineResult<()> {
228 self.dispatch(move |e| e.enable_webauthn(page))
229 }
230
231 pub fn add_init_script(&self, page: PageHandle, source: &str) -> EngineResult<()> {
232 let source = source.to_string();
233 self.dispatch(move |e| e.add_init_script(page, &source))
234 }
235
236 pub fn snapshot(&self, page: PageHandle) -> EngineResult<Tree> {
237 self.dispatch(move |e| e.snapshot(page))
238 }
239
240 pub fn snapshot_with_console(
247 &self,
248 page: PageHandle,
249 ) -> EngineResult<(Tree, Vec<crate::inspector::ConsoleEntry>)> {
250 self.dispatch(move |e| {
251 let tree = e.snapshot(page)?;
252 let console = e.console_entries(page)?;
253 Ok((tree, console))
254 })
255 }
256
257 pub fn act(
258 &self,
259 page: PageHandle,
260 target: ActTarget,
261 action: Action,
262 mode: crate::engine::InputMode,
263 ) -> EngineResult<()> {
264 self.dispatch(move |e| e.act(page, target, action, mode))
265 }
266
267 pub fn act_and_snapshot(
274 &self,
275 page: PageHandle,
276 target: ActTarget,
277 action: Action,
278 mode: crate::engine::InputMode,
279 ) -> EngineResult<Tree> {
280 self.dispatch(move |e| {
281 e.act(page, target, action, mode)?;
282 e.snapshot(page)
283 })
284 }
285
286 pub fn wait(
287 &self,
288 page: PageHandle,
289 cond: WaitCondition,
290 budget: Duration,
291 ) -> EngineResult<()> {
292 self.dispatch(move |e| e.wait(page, cond, budget))
293 }
294
295 pub fn capture(&self, page: PageHandle, scope: CaptureScope) -> EngineResult<PathBuf> {
296 self.dispatch(move |e| e.capture(page, scope))
297 }
298
299 pub fn capture_live(&self, page: PageHandle, max_width: u32) -> EngineResult<PathBuf> {
300 self.dispatch(move |e| e.capture_live(page, max_width))
301 }
302
303 pub fn record_begin(
304 &self,
305 page: PageHandle,
306 tx: std::sync::mpsc::Sender<crate::engine::RecFrame>,
307 fps: u32,
308 max_width: u32,
309 ) -> EngineResult<()> {
310 self.dispatch(move |e| e.record_begin(page, tx, fps, max_width))
311 }
312
313 pub fn record_end(&self, page: PageHandle) -> EngineResult<()> {
314 self.dispatch(move |e| e.record_end(page))
315 }
316
317 pub fn layout(&self, page: PageHandle, refs: Vec<Ref>) -> EngineResult<Vec<LayoutBox>> {
318 self.dispatch(move |e| e.layout(page, &refs))
319 }
320
321 pub fn download(
322 &self,
323 page: PageHandle,
324 source: DownloadSource,
325 budget: Duration,
326 ) -> EngineResult<Download> {
327 self.dispatch(move |e| e.download(page, source, budget))
328 }
329
330 pub fn download_list(&self, page: PageHandle) -> EngineResult<Vec<DownloadEntry>> {
331 self.dispatch(move |e| e.download_list(page))
332 }
333
334 pub fn set_viewport(&self, page: PageHandle, viewport: Viewport) -> EngineResult<()> {
335 self.dispatch(move |e| e.set_viewport(page, viewport))
336 }
337
338 pub fn save_auth(&self, page: PageHandle) -> EngineResult<AuthBlob> {
339 self.dispatch(move |e| e.save_auth(page))
340 }
341
342 pub fn load_auth(&self, page: PageHandle, blob: AuthBlob) -> EngineResult<()> {
343 self.dispatch(move |e| e.load_auth(page, &blob))
344 }
345
346 pub fn console_entries(
347 &self,
348 page: PageHandle,
349 ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
350 self.dispatch(move |e| e.console_entries(page))
351 }
352
353 pub fn network_entries(
354 &self,
355 page: PageHandle,
356 ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
357 self.dispatch(move |e| e.network_entries(page))
358 }
359
360 pub fn request_detail(
361 &self,
362 page: PageHandle,
363 seq: u64,
364 ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
365 self.dispatch(move |e| e.request_detail(page, seq))
366 }
367
368 pub fn eval_js(
369 &self,
370 page: PageHandle,
371 expr: &str,
372 ) -> EngineResult<crate::inspector::EvalResult> {
373 let expr = expr.to_string();
374 self.dispatch(move |e| e.eval_js(page, &expr))
375 }
376
377 pub fn eval_js_in_frame(
378 &self,
379 page: PageHandle,
380 frame: &str,
381 expr: &str,
382 ) -> EngineResult<crate::inspector::EvalResult> {
383 let (frame, expr) = (frame.to_string(), expr.to_string());
384 self.dispatch(move |e| e.eval_js_in_frame(page, &frame, &expr))
385 }
386
387 pub fn storage(
388 &self,
389 page: PageHandle,
390 scope: crate::inspector::StorageScope,
391 ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
392 self.dispatch(move |e| e.storage(page, scope))
393 }
394
395 pub fn cookie_events(
396 &self,
397 page: PageHandle,
398 ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
399 self.dispatch(move |e| e.cookie_events(page))
400 }
401
402 pub fn type_text(
403 &self,
404 page: PageHandle,
405 text: &str,
406 mode: crate::engine::InputMode,
407 ) -> EngineResult<()> {
408 let text = text.to_string();
409 self.dispatch(move |e| e.type_text(page, &text, mode))
410 }
411
412 pub fn cursor_op(
413 &self,
414 page: PageHandle,
415 op: crate::engine::CursorOp,
416 mode: crate::engine::InputMode,
417 ) -> EngineResult<()> {
418 self.dispatch(move |e| e.cursor_op(page, op, mode))
419 }
420
421 pub fn scripts(&self, page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
422 self.dispatch(move |e| e.scripts(page))
423 }
424
425 pub fn script_source(
426 &self,
427 page: PageHandle,
428 seq: u64,
429 ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
430 self.dispatch(move |e| e.script_source(page, seq))
431 }
432
433 pub fn dom(
434 &self,
435 page: PageHandle,
436 r: vs_protocol::Ref,
437 extra_props: Vec<String>,
438 ) -> EngineResult<Option<crate::inspector::DomDetail>> {
439 self.dispatch(move |e| e.dom(page, r, &extra_props))
440 }
441
442 pub fn performance(
443 &self,
444 page: PageHandle,
445 ) -> EngineResult<crate::inspector::PerformanceMetrics> {
446 self.dispatch(move |e| e.performance(page))
447 }
448
449 pub fn main_response(
450 &self,
451 page: PageHandle,
452 ) -> EngineResult<Option<crate::inspector::MainResponse>> {
453 self.dispatch(move |e| e.main_response(page))
454 }
455
456 pub fn capabilities(&self) -> EngineResult<EngineCapabilities> {
457 self.dispatch(|e| Ok(e.capabilities()))
458 }
459
460 pub fn set_popups(&self, page: PageHandle, on: bool) -> EngineResult<()> {
461 self.dispatch(move |e| e.set_popups(page, on))
462 }
463
464 pub fn popup_feed(&self) -> EngineResult<Option<std::sync::Arc<crate::engine::PopupFeed>>> {
465 self.dispatch(|e| Ok(e.popup_feed()))
466 }
467}
468
469impl Drop for EngineRuntime {
470 fn drop(&mut self) {
471 self.shutdown();
472 }
473}
474
475pub struct MainThreadDispatcher {
480 engine: Box<dyn Engine>,
481 rx: mpsc::Receiver<Job>,
482}
483
484impl MainThreadDispatcher {
485 pub fn tick(&mut self) -> Result<bool, ()> {
490 match self.rx.try_recv() {
491 Ok(job) => {
492 job(self.engine.as_mut());
493 Ok(true)
494 }
495 Err(mpsc::TryRecvError::Empty) => Ok(false),
496 Err(mpsc::TryRecvError::Disconnected) => Err(()),
497 }
498 }
499
500 pub fn tick_blocking(&mut self) -> Result<bool, ()> {
503 match self.rx.recv() {
504 Ok(job) => {
505 job(self.engine.as_mut());
506 Ok(true)
507 }
508 Err(_) => Err(()),
509 }
510 }
511}
512
513#[cfg(test)]
514mod tests {
515 use std::path::PathBuf;
516 use std::time::Duration;
517
518 use vs_protocol::{Node, Ref, Role, Tree};
519
520 use super::*;
521 use crate::engine::{
522 ActTarget, Action, AuthBlob, CaptureScope, EngineCapabilities, LayoutBox, Viewport,
523 WaitCondition,
524 };
525
526 #[derive(Default)]
531 struct TestEngine {
532 next_handle: u64,
533 last_url: String,
534 }
535
536 impl Engine for TestEngine {
537 fn open(&mut self, url: &str, _store: &DataStore) -> EngineResult<PageHandle> {
538 self.next_handle += 1;
539 self.last_url = url.to_string();
540 Ok(PageHandle(self.next_handle))
541 }
542 fn navigate(&mut self, _page: PageHandle, url: &str) -> EngineResult<()> {
543 self.last_url = url.to_string();
544 Ok(())
545 }
546 fn enable_webauthn(&mut self, _page: PageHandle) -> EngineResult<()> {
547 Ok(())
548 }
549 fn add_init_script(&mut self, _page: PageHandle, _source: &str) -> EngineResult<()> {
550 Ok(())
551 }
552 fn close(&mut self, _page: PageHandle) -> EngineResult<()> {
553 Ok(())
554 }
555 fn snapshot(&mut self, _page: PageHandle) -> EngineResult<Tree> {
556 Ok(Tree::from_root(Node::leaf(
557 Ref(1),
558 Role::Doc,
559 &self.last_url,
560 )))
561 }
562 fn act(
563 &mut self,
564 _: PageHandle,
565 _: ActTarget,
566 _: Action,
567 _: crate::engine::InputMode,
568 ) -> EngineResult<()> {
569 Ok(())
570 }
571 fn wait(&mut self, _: PageHandle, _: WaitCondition, _: Duration) -> EngineResult<()> {
572 Ok(())
573 }
574 fn capture(&mut self, _: PageHandle, _: CaptureScope) -> EngineResult<PathBuf> {
575 Ok(PathBuf::from("/tmp/test.png"))
576 }
577 fn layout(&mut self, _: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>> {
578 Ok(refs
579 .iter()
580 .map(|r| LayoutBox {
581 r: *r,
582 x: 0.0,
583 y: 0.0,
584 width: 1.0,
585 height: 1.0,
586 visible: true,
587 z_index: 0,
588 })
589 .collect())
590 }
591 fn set_viewport(&mut self, _: PageHandle, _: Viewport) -> EngineResult<()> {
592 Ok(())
593 }
594 fn save_auth(&mut self, _: PageHandle) -> EngineResult<AuthBlob> {
595 Ok(AuthBlob {
596 bytes: self.last_url.as_bytes().to_vec(),
597 })
598 }
599 fn load_auth(&mut self, _: PageHandle, _: &AuthBlob) -> EngineResult<()> {
600 Ok(())
601 }
602 fn capabilities(&self) -> EngineCapabilities {
603 EngineCapabilities {
604 renders: false,
605 honors_viewport: false,
606 measures_layout: false,
607 persists_auth: false,
608 inspector_console: false,
609 inspector_network: false,
610 inspector_cookie_events: false,
611 name: "test",
612 version: "runtime-tests",
613 }
614 }
615 }
616
617 fn spawn_test_runtime() -> EngineRuntime {
618 EngineRuntime::spawn(|| Ok(Box::new(TestEngine::default()) as Box<dyn Engine>))
619 .expect("spawn")
620 }
621
622 #[test]
623 fn spawn_and_shutdown_cleanly() {
624 let mut rt = spawn_test_runtime();
625 rt.shutdown();
626 rt.shutdown();
627 }
628
629 #[test]
630 fn dispatch_blocks_until_reply() {
631 let rt = spawn_test_runtime();
632 let caps = rt.capabilities().unwrap();
633 assert_eq!(caps.name, "test");
634 }
635
636 #[test]
637 fn engine_construction_failure_reported() {
638 let err =
639 EngineRuntime::spawn(|| Err::<Box<dyn Engine>, _>(EngineError::Other("nope".into())))
640 .unwrap_err();
641 assert!(matches!(err, EngineError::Other(_)));
642 }
643
644 #[test]
645 fn calls_after_drop_error_with_closed() {
646 let mut rt = spawn_test_runtime();
647 rt.shutdown();
648 let err = rt.capabilities().unwrap_err();
649 assert!(matches!(err, EngineError::Closed));
650 }
651
652 #[test]
657 fn full_primitive_sequence_via_runtime() {
658 let rt = spawn_test_runtime();
659 let page = rt
660 .open("https://example.com/login", &DataStore::Shared)
661 .unwrap();
662 rt.wait(page, WaitCondition::Stable, Duration::from_millis(0))
663 .unwrap();
664 let tree = rt.snapshot(page).unwrap();
665 assert!(tree.roots[0].label.contains("https://example.com/login"));
666 rt.act(
667 page,
668 ActTarget::Ref(Ref(3)),
669 Action::Fill { value: "x".into() },
670 crate::engine::InputMode::Careful,
671 )
672 .unwrap();
673 let auth = rt.save_auth(page).unwrap();
674 rt.load_auth(page, auth).unwrap();
675 rt.close(page).unwrap();
676 rt.close(page).unwrap();
677 }
678
679 #[test]
680 fn dispatch_serializes_calls() {
681 let rt = spawn_test_runtime();
682 let mut handles = Vec::new();
683 for i in 0..32 {
684 handles.push(
685 rt.open(&format!("https://example.com/{i}"), &DataStore::Shared)
686 .unwrap(),
687 );
688 }
689 let mut sorted = handles.clone();
690 sorted.sort();
691 sorted.dedup();
692 assert_eq!(sorted.len(), handles.len());
693 }
694}