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, Engine, EngineCapabilities, EngineError,
26 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 struct EngineRuntime {
48 sender: Option<mpsc::Sender<Job>>,
49 handle: Option<JoinHandle<()>>,
50}
51
52impl std::fmt::Debug for EngineRuntime {
53 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54 f.debug_struct("EngineRuntime")
55 .field("running", &self.sender.is_some())
56 .finish_non_exhaustive()
57 }
58}
59
60impl EngineRuntime {
61 pub fn spawn<F>(make: F) -> EngineResult<Self>
68 where
69 F: FnOnce() -> EngineResult<Box<dyn Engine>> + Send + 'static,
70 {
71 let (tx, rx) = mpsc::channel::<Job>();
72 let (ready_tx, ready_rx) = mpsc::sync_channel::<EngineResult<()>>(1);
73
74 let handle = thread::Builder::new()
75 .name("vibesurfer-engine".into())
76 .spawn(move || {
77 let mut engine = match make() {
78 Ok(e) => {
79 let _ = ready_tx.send(Ok(()));
80 e
81 }
82 Err(e) => {
83 let _ = ready_tx.send(Err(e));
84 return;
85 }
86 };
87
88 while let Ok(job) = rx.recv() {
89 job(engine.as_mut());
90 }
91 drop(engine);
93 })
94 .map_err(|e| EngineError::Other(format!("spawn engine thread: {e}")))?;
95
96 match ready_rx.recv() {
97 Ok(Ok(())) => {}
98 Ok(Err(e)) => {
99 let _ = handle.join();
100 return Err(e);
101 }
102 Err(_) => {
103 let _ = handle.join();
104 return Err(EngineError::Crashed);
105 }
106 }
107
108 Ok(Self {
109 sender: Some(tx),
110 handle: Some(handle),
111 })
112 }
113
114 pub fn dispatcher(engine: Box<dyn Engine>) -> (Self, MainThreadDispatcher) {
123 let (tx, rx) = mpsc::channel::<Job>();
124 let runtime = Self {
125 sender: Some(tx),
126 handle: None,
127 };
128 let dispatcher = MainThreadDispatcher { engine, rx };
129 (runtime, dispatcher)
130 }
131
132 pub fn shutdown(&mut self) {
135 drop(self.sender.take());
136 if let Some(handle) = self.handle.take() {
137 let _ = handle.join();
138 }
139 }
140
141 fn dispatch<R, F>(&self, f: F) -> EngineResult<R>
142 where
143 F: FnOnce(&mut dyn Engine) -> EngineResult<R> + Send + 'static,
144 R: Send + 'static,
145 {
146 let sender = self.sender.as_ref().ok_or(EngineError::Closed)?;
147 let (reply_tx, reply_rx) = mpsc::sync_channel::<EngineResult<R>>(1);
148 let job: Job = Box::new(move |engine| {
149 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(engine)))
158 .unwrap_or_else(|payload| Err(EngineError::Other(panic_message(&payload))));
159 let _ = reply_tx.send(result);
160 });
161 sender.send(job).map_err(|_| EngineError::Closed)?;
162 reply_rx.recv().map_err(|_| EngineError::Crashed)?
163 }
164
165 pub fn open(&self, url: &str) -> EngineResult<PageHandle> {
170 let url = url.to_string();
171 self.dispatch(move |e| e.open(&url))
172 }
173
174 pub fn navigate(&self, page: PageHandle, url: &str) -> EngineResult<()> {
175 let url = url.to_string();
176 self.dispatch(move |e| e.navigate(page, &url))
177 }
178
179 pub fn close(&self, page: PageHandle) -> EngineResult<()> {
180 self.dispatch(move |e| e.close(page))
181 }
182
183 pub fn enable_webauthn(&self, page: PageHandle) -> EngineResult<()> {
184 self.dispatch(move |e| e.enable_webauthn(page))
185 }
186
187 pub fn snapshot(&self, page: PageHandle) -> EngineResult<Tree> {
188 self.dispatch(move |e| e.snapshot(page))
189 }
190
191 pub fn snapshot_with_console(
198 &self,
199 page: PageHandle,
200 ) -> EngineResult<(Tree, Vec<crate::inspector::ConsoleEntry>)> {
201 self.dispatch(move |e| {
202 let tree = e.snapshot(page)?;
203 let console = e.console_entries(page)?;
204 Ok((tree, console))
205 })
206 }
207
208 pub fn act(
209 &self,
210 page: PageHandle,
211 target: ActTarget,
212 action: Action,
213 mode: crate::engine::InputMode,
214 ) -> EngineResult<()> {
215 self.dispatch(move |e| e.act(page, target, action, mode))
216 }
217
218 pub fn act_and_snapshot(
225 &self,
226 page: PageHandle,
227 target: ActTarget,
228 action: Action,
229 mode: crate::engine::InputMode,
230 ) -> EngineResult<Tree> {
231 self.dispatch(move |e| {
232 e.act(page, target, action, mode)?;
233 e.snapshot(page)
234 })
235 }
236
237 pub fn wait(
238 &self,
239 page: PageHandle,
240 cond: WaitCondition,
241 budget: Duration,
242 ) -> EngineResult<()> {
243 self.dispatch(move |e| e.wait(page, cond, budget))
244 }
245
246 pub fn capture(&self, page: PageHandle, scope: CaptureScope) -> EngineResult<PathBuf> {
247 self.dispatch(move |e| e.capture(page, scope))
248 }
249
250 pub fn capture_live(&self, page: PageHandle, max_width: u32) -> EngineResult<PathBuf> {
251 self.dispatch(move |e| e.capture_live(page, max_width))
252 }
253
254 pub fn record_begin(
255 &self,
256 page: PageHandle,
257 tx: std::sync::mpsc::Sender<crate::engine::RecFrame>,
258 fps: u32,
259 max_width: u32,
260 ) -> EngineResult<()> {
261 self.dispatch(move |e| e.record_begin(page, tx, fps, max_width))
262 }
263
264 pub fn record_end(&self, page: PageHandle) -> EngineResult<()> {
265 self.dispatch(move |e| e.record_end(page))
266 }
267
268 pub fn layout(&self, page: PageHandle, refs: Vec<Ref>) -> EngineResult<Vec<LayoutBox>> {
269 self.dispatch(move |e| e.layout(page, &refs))
270 }
271
272 pub fn set_viewport(&self, page: PageHandle, viewport: Viewport) -> EngineResult<()> {
273 self.dispatch(move |e| e.set_viewport(page, viewport))
274 }
275
276 pub fn save_auth(&self, page: PageHandle) -> EngineResult<AuthBlob> {
277 self.dispatch(move |e| e.save_auth(page))
278 }
279
280 pub fn load_auth(&self, page: PageHandle, blob: AuthBlob) -> EngineResult<()> {
281 self.dispatch(move |e| e.load_auth(page, &blob))
282 }
283
284 pub fn console_entries(
285 &self,
286 page: PageHandle,
287 ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
288 self.dispatch(move |e| e.console_entries(page))
289 }
290
291 pub fn network_entries(
292 &self,
293 page: PageHandle,
294 ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
295 self.dispatch(move |e| e.network_entries(page))
296 }
297
298 pub fn request_detail(
299 &self,
300 page: PageHandle,
301 seq: u64,
302 ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
303 self.dispatch(move |e| e.request_detail(page, seq))
304 }
305
306 pub fn eval_js(
307 &self,
308 page: PageHandle,
309 expr: &str,
310 ) -> EngineResult<crate::inspector::EvalResult> {
311 let expr = expr.to_string();
312 self.dispatch(move |e| e.eval_js(page, &expr))
313 }
314
315 pub fn storage(
316 &self,
317 page: PageHandle,
318 scope: crate::inspector::StorageScope,
319 ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
320 self.dispatch(move |e| e.storage(page, scope))
321 }
322
323 pub fn cookie_events(
324 &self,
325 page: PageHandle,
326 ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
327 self.dispatch(move |e| e.cookie_events(page))
328 }
329
330 pub fn type_text(
331 &self,
332 page: PageHandle,
333 text: &str,
334 mode: crate::engine::InputMode,
335 ) -> EngineResult<()> {
336 let text = text.to_string();
337 self.dispatch(move |e| e.type_text(page, &text, mode))
338 }
339
340 pub fn cursor_op(
341 &self,
342 page: PageHandle,
343 op: crate::engine::CursorOp,
344 mode: crate::engine::InputMode,
345 ) -> EngineResult<()> {
346 self.dispatch(move |e| e.cursor_op(page, op, mode))
347 }
348
349 pub fn scripts(&self, page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
350 self.dispatch(move |e| e.scripts(page))
351 }
352
353 pub fn script_source(
354 &self,
355 page: PageHandle,
356 seq: u64,
357 ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
358 self.dispatch(move |e| e.script_source(page, seq))
359 }
360
361 pub fn dom(
362 &self,
363 page: PageHandle,
364 r: vs_protocol::Ref,
365 extra_props: Vec<String>,
366 ) -> EngineResult<Option<crate::inspector::DomDetail>> {
367 self.dispatch(move |e| e.dom(page, r, &extra_props))
368 }
369
370 pub fn performance(
371 &self,
372 page: PageHandle,
373 ) -> EngineResult<crate::inspector::PerformanceMetrics> {
374 self.dispatch(move |e| e.performance(page))
375 }
376
377 pub fn capabilities(&self) -> EngineResult<EngineCapabilities> {
378 self.dispatch(|e| Ok(e.capabilities()))
379 }
380}
381
382impl Drop for EngineRuntime {
383 fn drop(&mut self) {
384 self.shutdown();
385 }
386}
387
388pub struct MainThreadDispatcher {
393 engine: Box<dyn Engine>,
394 rx: mpsc::Receiver<Job>,
395}
396
397impl MainThreadDispatcher {
398 pub fn tick(&mut self) -> Result<bool, ()> {
403 match self.rx.try_recv() {
404 Ok(job) => {
405 job(self.engine.as_mut());
406 Ok(true)
407 }
408 Err(mpsc::TryRecvError::Empty) => Ok(false),
409 Err(mpsc::TryRecvError::Disconnected) => Err(()),
410 }
411 }
412
413 pub fn tick_blocking(&mut self) -> Result<bool, ()> {
416 match self.rx.recv() {
417 Ok(job) => {
418 job(self.engine.as_mut());
419 Ok(true)
420 }
421 Err(_) => Err(()),
422 }
423 }
424}
425
426#[cfg(test)]
427mod tests {
428 use std::path::PathBuf;
429 use std::time::Duration;
430
431 use vs_protocol::{Node, Ref, Role, Tree};
432
433 use super::*;
434 use crate::engine::{
435 ActTarget, Action, AuthBlob, CaptureScope, EngineCapabilities, LayoutBox, Viewport,
436 WaitCondition,
437 };
438
439 #[derive(Default)]
444 struct TestEngine {
445 next_handle: u64,
446 last_url: String,
447 }
448
449 impl Engine for TestEngine {
450 fn open(&mut self, url: &str) -> EngineResult<PageHandle> {
451 self.next_handle += 1;
452 self.last_url = url.to_string();
453 Ok(PageHandle(self.next_handle))
454 }
455 fn navigate(&mut self, _page: PageHandle, url: &str) -> EngineResult<()> {
456 self.last_url = url.to_string();
457 Ok(())
458 }
459 fn enable_webauthn(&mut self, _page: PageHandle) -> EngineResult<()> {
460 Ok(())
461 }
462 fn close(&mut self, _page: PageHandle) -> EngineResult<()> {
463 Ok(())
464 }
465 fn snapshot(&mut self, _page: PageHandle) -> EngineResult<Tree> {
466 Ok(Tree::from_root(Node::leaf(
467 Ref(1),
468 Role::Doc,
469 &self.last_url,
470 )))
471 }
472 fn act(
473 &mut self,
474 _: PageHandle,
475 _: ActTarget,
476 _: Action,
477 _: crate::engine::InputMode,
478 ) -> EngineResult<()> {
479 Ok(())
480 }
481 fn wait(&mut self, _: PageHandle, _: WaitCondition, _: Duration) -> EngineResult<()> {
482 Ok(())
483 }
484 fn capture(&mut self, _: PageHandle, _: CaptureScope) -> EngineResult<PathBuf> {
485 Ok(PathBuf::from("/tmp/test.png"))
486 }
487 fn layout(&mut self, _: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>> {
488 Ok(refs
489 .iter()
490 .map(|r| LayoutBox {
491 r: *r,
492 x: 0.0,
493 y: 0.0,
494 width: 1.0,
495 height: 1.0,
496 visible: true,
497 z_index: 0,
498 })
499 .collect())
500 }
501 fn set_viewport(&mut self, _: PageHandle, _: Viewport) -> EngineResult<()> {
502 Ok(())
503 }
504 fn save_auth(&mut self, _: PageHandle) -> EngineResult<AuthBlob> {
505 Ok(AuthBlob {
506 bytes: self.last_url.as_bytes().to_vec(),
507 })
508 }
509 fn load_auth(&mut self, _: PageHandle, _: &AuthBlob) -> EngineResult<()> {
510 Ok(())
511 }
512 fn capabilities(&self) -> EngineCapabilities {
513 EngineCapabilities {
514 renders: false,
515 honors_viewport: false,
516 measures_layout: false,
517 persists_auth: false,
518 inspector_console: false,
519 inspector_network: false,
520 inspector_cookie_events: false,
521 name: "test",
522 version: "runtime-tests",
523 }
524 }
525 }
526
527 fn spawn_test_runtime() -> EngineRuntime {
528 EngineRuntime::spawn(|| Ok(Box::new(TestEngine::default()) as Box<dyn Engine>))
529 .expect("spawn")
530 }
531
532 #[test]
533 fn spawn_and_shutdown_cleanly() {
534 let mut rt = spawn_test_runtime();
535 rt.shutdown();
536 rt.shutdown();
537 }
538
539 #[test]
540 fn dispatch_blocks_until_reply() {
541 let rt = spawn_test_runtime();
542 let caps = rt.capabilities().unwrap();
543 assert_eq!(caps.name, "test");
544 }
545
546 #[test]
547 fn engine_construction_failure_reported() {
548 let err =
549 EngineRuntime::spawn(|| Err::<Box<dyn Engine>, _>(EngineError::Other("nope".into())))
550 .unwrap_err();
551 assert!(matches!(err, EngineError::Other(_)));
552 }
553
554 #[test]
555 fn calls_after_drop_error_with_closed() {
556 let mut rt = spawn_test_runtime();
557 rt.shutdown();
558 let err = rt.capabilities().unwrap_err();
559 assert!(matches!(err, EngineError::Closed));
560 }
561
562 #[test]
567 fn full_primitive_sequence_via_runtime() {
568 let rt = spawn_test_runtime();
569 let page = rt.open("https://example.com/login").unwrap();
570 rt.wait(page, WaitCondition::Stable, Duration::from_millis(0))
571 .unwrap();
572 let tree = rt.snapshot(page).unwrap();
573 assert!(tree.roots[0].label.contains("https://example.com/login"));
574 rt.act(
575 page,
576 ActTarget::Ref(Ref(3)),
577 Action::Fill { value: "x".into() },
578 crate::engine::InputMode::Careful,
579 )
580 .unwrap();
581 let auth = rt.save_auth(page).unwrap();
582 rt.load_auth(page, auth).unwrap();
583 rt.close(page).unwrap();
584 rt.close(page).unwrap();
585 }
586
587 #[test]
588 fn dispatch_serializes_calls() {
589 let rt = spawn_test_runtime();
590 let mut handles = Vec::new();
591 for i in 0..32 {
592 handles.push(rt.open(&format!("https://example.com/{i}")).unwrap());
593 }
594 let mut sorted = handles.clone();
595 sorted.sort();
596 sorted.dedup();
597 assert_eq!(sorted.len(), handles.len());
598 }
599}