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, Download, DownloadEntry, DownloadSource, Engine,
26 EngineCapabilities, EngineError, EngineResult, LayoutBox, PageHandle, Viewport, WaitCondition,
27};
28
29type Job = Box<dyn FnOnce(&mut dyn Engine) + Send>;
31
32fn 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
42pub 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 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 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 waker: None,
126 })
127 }
128
129 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 #[must_use]
153 pub fn with_waker(mut self, waker: Waker) -> Self {
154 self.waker = Some(waker);
155 self
156 }
157
158 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 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 if let Some(waker) = &self.waker {
191 waker();
192 }
193 reply_rx.recv().map_err(|_| EngineError::Crashed)?
194 }
195
196 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 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 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
432pub struct MainThreadDispatcher {
437 engine: Box<dyn Engine>,
438 rx: mpsc::Receiver<Job>,
439}
440
441impl MainThreadDispatcher {
442 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 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 #[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 #[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}