1use std::sync::Arc;
2use std::sync::atomic::Ordering;
3
4use axum::extract::DefaultBodyLimit;
5use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
6use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
7use tauri::Runtime;
8use tower::limit::ConcurrencyLimitLayer;
9
10use crate::VictauriState;
11use crate::bridge::WebviewBridge;
12
13use super::{MAX_PENDING_EVALS, VictauriMcpHandler};
14
15const DEFAULT_WEBVIEW_LABEL: &str = "main";
16
17pub fn build_app(state: Arc<VictauriState>, bridge: Arc<dyn WebviewBridge>) -> axum::Router {
21 build_app_with_options(state, bridge, None)
22}
23
24pub fn build_app_with_options(
26 state: Arc<VictauriState>,
27 bridge: Arc<dyn WebviewBridge>,
28 auth_token: Option<String>,
29) -> axum::Router {
30 build_app_full(state, bridge, auth_token, None)
31}
32
33pub fn build_app_full(
35 state: Arc<VictauriState>,
36 bridge: Arc<dyn WebviewBridge>,
37 auth_token: Option<String>,
38 rate_limiter: Option<Arc<crate::auth::RateLimiterState>>,
39) -> axum::Router {
40 let handler = VictauriMcpHandler::new(state.clone(), bridge);
41 let rest = super::rest::router(handler.clone());
42
43 let mcp_service = StreamableHttpService::new(
44 move || Ok(handler.clone()),
45 Arc::new(LocalSessionManager::default()),
46 StreamableHttpServerConfig::default(),
47 );
48
49 let auth_state = Arc::new(crate::auth::AuthState {
50 token: auth_token.clone(),
51 });
52 let info_state = state.clone();
53 let info_auth = auth_token.is_some();
54
55 let privacy_enabled = !state.privacy.disabled_tools.is_empty()
56 || state.privacy.command_allowlist.is_some()
57 || !state.privacy.command_blocklist.is_empty()
58 || state.privacy.redaction_enabled;
59
60 let mut router = axum::Router::new()
61 .route_service("/mcp", mcp_service)
62 .nest("/api/tools", rest)
63 .route(
64 "/info",
65 axum::routing::get(move || {
66 let s = info_state.clone();
67 async move {
68 axum::Json(serde_json::json!({
69 "name": "victauri",
70 "description": "Full-stack Tauri app inspection: webview + IPC + Rust backend + SQLite",
71 "version": env!("CARGO_PKG_VERSION"),
72 "protocol": "mcp",
73 "capabilities": ["webview", "ipc", "backend", "database", "filesystem"],
74 "commands_registered": s.registry.count(),
75 "events_captured": s.event_log.len(),
76 "port": s.port.load(Ordering::Relaxed),
77 "auth_required": info_auth,
78 "privacy_mode": privacy_enabled,
79 }))
80 }
81 }),
82 );
83
84 if auth_token.is_some() {
85 router = router.layer(axum::middleware::from_fn_with_state(
86 auth_state,
87 crate::auth::require_auth,
88 ));
89 }
90
91 let limiter = rate_limiter.unwrap_or_else(crate::auth::default_rate_limiter);
92 router = router.layer(axum::middleware::from_fn_with_state(
93 limiter,
94 crate::auth::rate_limit,
95 ));
96
97 router
98 .route(
99 "/health",
100 axum::routing::get(|| async { axum::Json(serde_json::json!({"status": "ok"})) }),
101 )
102 .layer(DefaultBodyLimit::max(2 * 1024 * 1024))
103 .layer(ConcurrencyLimitLayer::new(64))
104 .layer(axum::middleware::from_fn(crate::auth::security_headers))
105 .layer(axum::middleware::from_fn(crate::auth::origin_guard))
106 .layer(axum::middleware::from_fn(crate::auth::dns_rebinding_guard))
107}
108
109#[doc(hidden)]
110#[allow(dead_code)]
111pub mod tests_support {
112 #[must_use]
114 pub fn get_memory_stats() -> serde_json::Value {
115 crate::memory::current_stats()
116 }
117}
118
119const PORT_FALLBACK_RANGE: u16 = 10;
120
121pub async fn start_server<R: Runtime>(
128 app_handle: tauri::AppHandle<R>,
129 state: Arc<VictauriState>,
130 port: u16,
131 shutdown_rx: tokio::sync::watch::Receiver<bool>,
132) -> anyhow::Result<()> {
133 start_server_with_options(app_handle, state, port, None, shutdown_rx).await
134}
135
136pub async fn start_server_with_options<R: Runtime>(
143 app_handle: tauri::AppHandle<R>,
144 state: Arc<VictauriState>,
145 port: u16,
146 auth_token: Option<String>,
147 mut shutdown_rx: tokio::sync::watch::Receiver<bool>,
148) -> anyhow::Result<()> {
149 let bridge: Arc<dyn WebviewBridge> = Arc::new(app_handle);
150 let token_for_file = auth_token.clone();
151 let app = build_app_with_options(state.clone(), bridge.clone(), auth_token);
152
153 let (listener, actual_port) = try_bind(port).await?;
154
155 if actual_port != port {
156 tracing::warn!("Victauri: port {port} in use, fell back to {actual_port}");
157 }
158
159 state.port.store(actual_port, Ordering::Relaxed);
160 write_port_file(actual_port);
161 let discovery_token = token_for_file
168 .as_deref()
169 .map_or_else(crate::auth::generate_token, String::from);
170 write_token_file(&discovery_token);
171
172 tracing::info!("Victauri MCP server listening on 127.0.0.1:{actual_port}");
173
174 let drain_state = state.clone();
175 let drain_bridge = bridge;
176 let drain_shutdown = state.shutdown_tx.subscribe();
177 let drain_finished = state.task_tracker.track("event_drain_loop");
178 tokio::spawn(async move {
179 event_drain_loop(drain_state, drain_bridge, drain_shutdown).await;
180 drain_finished.store(true, std::sync::atomic::Ordering::Relaxed);
181 });
182
183 let mut shutdown_rx2 = shutdown_rx.clone();
184 let server = axum::serve(listener, app).with_graceful_shutdown(async move {
185 let _ = shutdown_rx.wait_for(|&v| v).await;
186 remove_port_file();
187 tracing::info!("Victauri MCP server shutting down gracefully");
188 });
189
190 tokio::select! {
191 result = server => {
192 if let Err(e) = result {
193 tracing::error!("Victauri MCP server error: {e}");
194 }
195 }
196 _ = async {
197 let _ = shutdown_rx2.wait_for(|&v| v).await;
198 tokio::time::sleep(std::time::Duration::from_secs(5)).await;
199 } => {
200 tracing::warn!("Victauri MCP server shutdown timeout — forcing exit");
201 }
202 }
203 Ok(())
204}
205
206async fn try_bind(preferred: u16) -> anyhow::Result<(tokio::net::TcpListener, u16)> {
207 if let Ok(listener) = tokio::net::TcpListener::bind(format!("127.0.0.1:{preferred}")).await {
208 return Ok((listener, preferred));
209 }
210
211 for offset in 1..=PORT_FALLBACK_RANGE {
212 let port = preferred + offset;
213 if let Ok(listener) = tokio::net::TcpListener::bind(format!("127.0.0.1:{port}")).await {
214 return Ok((listener, port));
215 }
216 }
217
218 anyhow::bail!(
219 "could not bind to any port in range {preferred}-{}",
220 preferred + PORT_FALLBACK_RANGE
221 )
222}
223
224fn discovery_dir() -> std::path::PathBuf {
225 std::env::temp_dir()
226 .join("victauri")
227 .join(std::process::id().to_string())
228}
229
230fn write_port_file(port: u16) {
231 let dir = discovery_dir();
232 let _ = std::fs::create_dir_all(&dir);
233 #[cfg(unix)]
234 {
235 use std::os::unix::fs::PermissionsExt;
236 let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
237 }
238 let port_path = dir.join("port");
239 if let Err(e) = std::fs::write(&port_path, port.to_string()) {
240 tracing::debug!("could not write port file: {e}");
241 }
242 #[cfg(unix)]
243 {
244 use std::os::unix::fs::PermissionsExt;
245 let _ = std::fs::set_permissions(&port_path, std::fs::Permissions::from_mode(0o600));
246 }
247 let metadata = serde_json::json!({
249 "pid": std::process::id(),
250 "port": port,
251 "started_at": chrono::Utc::now().to_rfc3339(),
252 "version": env!("CARGO_PKG_VERSION"),
253 });
254 let meta_path = dir.join("metadata.json");
255 let _ = std::fs::write(&meta_path, metadata.to_string());
256 #[cfg(unix)]
257 {
258 use std::os::unix::fs::PermissionsExt;
259 let _ = std::fs::set_permissions(&meta_path, std::fs::Permissions::from_mode(0o600));
260 }
261}
262
263fn write_token_file(token: &str) {
264 let dir = discovery_dir();
265 let _ = std::fs::create_dir_all(&dir);
266 #[cfg(unix)]
267 {
268 use std::os::unix::fs::PermissionsExt;
269 let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
270 }
271 let token_path = dir.join("token");
272 if let Err(e) = std::fs::write(&token_path, token) {
273 tracing::debug!("could not write token file: {e}");
274 }
275 #[cfg(unix)]
276 {
277 use std::os::unix::fs::PermissionsExt;
278 let _ = std::fs::set_permissions(&token_path, std::fs::Permissions::from_mode(0o600));
279 }
280}
281
282fn remove_port_file() {
283 let _ = std::fs::remove_dir_all(discovery_dir());
284}
285
286#[must_use]
290pub fn parse_bridge_event(ev: &serde_json::Value) -> Option<victauri_core::AppEvent> {
291 use chrono::Utc;
292 use victauri_core::AppEvent;
293
294 let event_type = ev.get("type").and_then(|t| t.as_str()).unwrap_or("");
295 let now = Utc::now();
296
297 let app_event = match event_type {
298 "console" => AppEvent::Console {
299 level: ev
300 .get("level")
301 .and_then(|l| l.as_str())
302 .unwrap_or("log")
303 .to_string(),
304 message: ev
305 .get("message")
306 .and_then(|m| m.as_str())
307 .unwrap_or("")
308 .to_string(),
309 timestamp: now,
310 },
311 "dom_mutation" => AppEvent::DomMutation {
312 webview_label: DEFAULT_WEBVIEW_LABEL.to_string(),
313 timestamp: now,
314 mutation_count: ev
315 .get("count")
316 .and_then(serde_json::Value::as_u64)
317 .unwrap_or(0) as u32,
318 },
319 "ipc" => {
320 let cmd = ev
321 .get("command")
322 .and_then(|c| c.as_str())
323 .unwrap_or("unknown");
324 AppEvent::Ipc(victauri_core::IpcCall {
325 id: uuid::Uuid::new_v4().to_string(),
326 command: cmd.to_string(),
327 timestamp: now,
328 result: match ev.get("status").and_then(|s| s.as_str()) {
329 Some("ok") => victauri_core::IpcResult::Ok(serde_json::Value::Null),
330 Some("error") => victauri_core::IpcResult::Err("error".to_string()),
331 _ => victauri_core::IpcResult::Pending,
332 },
333 duration_ms: ev
334 .get("duration_ms")
335 .and_then(serde_json::Value::as_f64)
336 .map(|d| d as u64),
337 arg_size_bytes: 0,
338 webview_label: DEFAULT_WEBVIEW_LABEL.to_string(),
339 })
340 }
341 "network" => AppEvent::StateChange {
342 key: format!(
343 "network.{}",
344 ev.get("method").and_then(|m| m.as_str()).unwrap_or("GET")
345 ),
346 timestamp: now,
347 caused_by: ev
348 .get("url")
349 .and_then(|u| u.as_str())
350 .map(std::string::ToString::to_string),
351 },
352 "navigation" => AppEvent::WindowEvent {
353 label: DEFAULT_WEBVIEW_LABEL.to_string(),
354 event: format!(
355 "navigation.{}",
356 ev.get("nav_type")
357 .and_then(|n| n.as_str())
358 .unwrap_or("unknown")
359 ),
360 timestamp: now,
361 },
362 "dom_interaction" => {
363 let action_str = ev.get("action").and_then(|a| a.as_str()).unwrap_or("click");
364 let action = match action_str {
365 "click" => victauri_core::InteractionKind::Click,
366 "double_click" => victauri_core::InteractionKind::DoubleClick,
367 "fill" => victauri_core::InteractionKind::Fill,
368 "key_press" => victauri_core::InteractionKind::KeyPress,
369 "select" => victauri_core::InteractionKind::Select,
370 "navigate" => victauri_core::InteractionKind::Navigate,
371 "scroll" => victauri_core::InteractionKind::Scroll,
372 _ => victauri_core::InteractionKind::Click,
373 };
374 AppEvent::DomInteraction {
375 action,
376 selector: ev
377 .get("selector")
378 .and_then(|s| s.as_str())
379 .unwrap_or("body")
380 .to_string(),
381 value: ev
382 .get("value")
383 .and_then(|v| v.as_str())
384 .map(std::string::ToString::to_string),
385 timestamp: now,
386 webview_label: DEFAULT_WEBVIEW_LABEL.to_string(),
387 }
388 }
389 _ => return None,
390 };
391
392 Some(app_event)
393}
394
395async fn event_drain_loop(
396 state: Arc<VictauriState>,
397 bridge: Arc<dyn WebviewBridge>,
398 mut shutdown: tokio::sync::watch::Receiver<bool>,
399) {
400 let mut last_drain_ts: f64 = 0.0;
401
402 loop {
403 tokio::select! {
404 _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {}
405 _ = shutdown.changed() => break,
406 }
407
408 let code = format!("return window.__VICTAURI__?.getEventStream({last_drain_ts})");
409 let id = uuid::Uuid::new_v4().to_string();
410 let (tx, rx) = tokio::sync::oneshot::channel();
411
412 {
413 let mut pending = state.pending_evals.lock().await;
414 if pending.len() >= MAX_PENDING_EVALS {
415 continue;
416 }
417 pending.insert(id.clone(), tx);
418 }
419
420 let id_js = super::helpers::js_string(&id);
421 let inject = format!(
422 r"
423 (async () => {{
424 try {{
425 const __result = await (async () => {{ {code} }})();
426 await window.__TAURI_INTERNALS__.invoke('plugin:victauri|victauri_eval_callback', {{
427 id: {id_js},
428 result: JSON.stringify(__result)
429 }});
430 }} catch (e) {{
431 await window.__TAURI_INTERNALS__.invoke('plugin:victauri|victauri_eval_callback', {{
432 id: {id_js},
433 result: JSON.stringify({{ __error: e.message }})
434 }});
435 }}
436 }})();
437 "
438 );
439
440 if bridge.eval_webview(None, &inject).is_err() {
441 state.pending_evals.lock().await.remove(&id);
442 continue;
443 }
444
445 let Ok(Ok(result)) = tokio::time::timeout(std::time::Duration::from_secs(5), rx).await
446 else {
447 state.pending_evals.lock().await.remove(&id);
448 continue;
449 };
450
451 let events: Vec<serde_json::Value> = match serde_json::from_str(&result) {
452 Ok(v) => v,
453 Err(_) => continue,
454 };
455
456 for ev in &events {
457 let ts = ev
458 .get("timestamp")
459 .and_then(serde_json::Value::as_f64)
460 .unwrap_or(0.0);
461 if ts > last_drain_ts {
462 last_drain_ts = ts;
463 }
464
465 if let Some(app_event) = parse_bridge_event(ev) {
466 state.event_log.push(app_event.clone());
467 if state.recorder.is_recording() {
468 state.recorder.record_event(app_event);
469 }
470 }
471 }
472 }
473}
474
475#[cfg(test)]
476mod tests {
477 use super::*;
478 use victauri_core::{AppEvent, InteractionKind, IpcResult};
479
480 #[tokio::test]
481 async fn try_bind_preferred_port_available() {
482 let (listener, port) = try_bind(0).await.unwrap();
483 let addr = listener.local_addr().unwrap();
484 assert_eq!(port, 0);
485 assert_ne!(addr.port(), 0); }
487
488 #[tokio::test]
489 async fn try_bind_falls_back_when_taken() {
490 let blocker = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
491 let blocked_port = blocker.local_addr().unwrap().port();
492
493 let (_, actual) = try_bind(blocked_port).await.unwrap();
494 assert_ne!(actual, blocked_port);
495 assert!(actual > blocked_port);
496 assert!(actual <= blocked_port + PORT_FALLBACK_RANGE);
497 }
498
499 #[test]
500 fn port_file_roundtrip() {
501 write_port_file(7777);
502 let dir = discovery_dir();
503 let content = std::fs::read_to_string(dir.join("port")).unwrap();
504 assert_eq!(content, "7777");
505 let meta: serde_json::Value =
507 serde_json::from_str(&std::fs::read_to_string(dir.join("metadata.json")).unwrap())
508 .unwrap();
509 assert_eq!(meta["port"], 7777);
510 assert_eq!(meta["pid"], std::process::id());
511 remove_port_file();
512 assert!(!dir.exists());
513 }
514
515 #[test]
518 fn parse_dom_interaction_click() {
519 let ev = serde_json::json!({
520 "type": "dom_interaction",
521 "action": "click",
522 "selector": "#submit-btn",
523 });
524 let result = parse_bridge_event(&ev).expect("should produce an event");
525 match result {
526 AppEvent::DomInteraction {
527 action,
528 selector,
529 value,
530 webview_label,
531 ..
532 } => {
533 assert_eq!(action, InteractionKind::Click);
534 assert_eq!(selector, "#submit-btn");
535 assert!(value.is_none());
536 assert_eq!(webview_label, "main");
537 }
538 other => panic!("expected DomInteraction, got {other:?}"),
539 }
540 }
541
542 #[test]
543 fn parse_dom_interaction_fill_with_value() {
544 let ev = serde_json::json!({
545 "type": "dom_interaction",
546 "action": "fill",
547 "selector": "input[name=email]",
548 "value": "test@example.com",
549 });
550 let result = parse_bridge_event(&ev).expect("should produce an event");
551 match result {
552 AppEvent::DomInteraction {
553 action,
554 selector,
555 value,
556 ..
557 } => {
558 assert_eq!(action, InteractionKind::Fill);
559 assert_eq!(selector, "input[name=email]");
560 assert_eq!(value.as_deref(), Some("test@example.com"));
561 }
562 other => panic!("expected DomInteraction, got {other:?}"),
563 }
564 }
565
566 #[test]
567 fn parse_dom_interaction_key_press() {
568 let ev = serde_json::json!({
569 "type": "dom_interaction",
570 "action": "key_press",
571 "selector": "body",
572 "value": "Enter",
573 });
574 let result = parse_bridge_event(&ev).expect("should produce an event");
575 match result {
576 AppEvent::DomInteraction { action, value, .. } => {
577 assert_eq!(action, InteractionKind::KeyPress);
578 assert_eq!(value.as_deref(), Some("Enter"));
579 }
580 other => panic!("expected DomInteraction, got {other:?}"),
581 }
582 }
583
584 #[test]
585 fn parse_dom_interaction_unknown_action_defaults_to_click() {
586 let ev = serde_json::json!({
587 "type": "dom_interaction",
588 "action": "swipe_left",
589 "selector": ".card",
590 });
591 let result = parse_bridge_event(&ev).expect("should produce an event");
592 match result {
593 AppEvent::DomInteraction { action, .. } => {
594 assert_eq!(action, InteractionKind::Click);
595 }
596 other => panic!("expected DomInteraction, got {other:?}"),
597 }
598 }
599
600 #[test]
601 fn parse_dom_interaction_missing_action_defaults_to_click() {
602 let ev = serde_json::json!({
603 "type": "dom_interaction",
604 "selector": "button",
605 });
606 let result = parse_bridge_event(&ev).expect("should produce an event");
607 match result {
608 AppEvent::DomInteraction { action, .. } => {
609 assert_eq!(action, InteractionKind::Click);
610 }
611 other => panic!("expected DomInteraction, got {other:?}"),
612 }
613 }
614
615 #[test]
616 fn parse_dom_interaction_missing_selector_defaults_to_body() {
617 let ev = serde_json::json!({
618 "type": "dom_interaction",
619 "action": "scroll",
620 });
621 let result = parse_bridge_event(&ev).expect("should produce an event");
622 match result {
623 AppEvent::DomInteraction {
624 action, selector, ..
625 } => {
626 assert_eq!(action, InteractionKind::Scroll);
627 assert_eq!(selector, "body");
628 }
629 other => panic!("expected DomInteraction, got {other:?}"),
630 }
631 }
632
633 #[test]
634 fn parse_dom_interaction_all_action_kinds() {
635 let cases = [
636 ("click", InteractionKind::Click),
637 ("double_click", InteractionKind::DoubleClick),
638 ("fill", InteractionKind::Fill),
639 ("key_press", InteractionKind::KeyPress),
640 ("select", InteractionKind::Select),
641 ("navigate", InteractionKind::Navigate),
642 ("scroll", InteractionKind::Scroll),
643 ];
644 for (action_str, expected_kind) in cases {
645 let ev = serde_json::json!({
646 "type": "dom_interaction",
647 "action": action_str,
648 "selector": "body",
649 });
650 let result = parse_bridge_event(&ev)
651 .unwrap_or_else(|| panic!("should produce event for action {action_str}"));
652 match result {
653 AppEvent::DomInteraction { action, .. } => {
654 assert_eq!(action, expected_kind, "mismatch for action {action_str}");
655 }
656 other => panic!("expected DomInteraction for {action_str}, got {other:?}"),
657 }
658 }
659 }
660
661 #[test]
664 fn parse_ipc_status_ok() {
665 let ev = serde_json::json!({
666 "type": "ipc",
667 "command": "greet",
668 "status": "ok",
669 "duration_ms": 42.0,
670 });
671 let result = parse_bridge_event(&ev).expect("should produce an event");
672 match result {
673 AppEvent::Ipc(call) => {
674 assert_eq!(call.command, "greet");
675 assert_eq!(call.result, IpcResult::Ok(serde_json::Value::Null));
676 assert_eq!(call.duration_ms, Some(42));
677 assert_eq!(call.webview_label, "main");
678 }
679 other => panic!("expected Ipc, got {other:?}"),
680 }
681 }
682
683 #[test]
684 fn parse_ipc_status_error() {
685 let ev = serde_json::json!({
686 "type": "ipc",
687 "command": "save_file",
688 "status": "error",
689 });
690 let result = parse_bridge_event(&ev).expect("should produce an event");
691 match result {
692 AppEvent::Ipc(call) => {
693 assert_eq!(call.command, "save_file");
694 assert_eq!(call.result, IpcResult::Err("error".to_string()));
695 }
696 other => panic!("expected Ipc, got {other:?}"),
697 }
698 }
699
700 #[test]
701 fn parse_ipc_status_pending() {
702 let ev = serde_json::json!({
703 "type": "ipc",
704 "command": "long_task",
705 });
706 let result = parse_bridge_event(&ev).expect("should produce an event");
707 match result {
708 AppEvent::Ipc(call) => {
709 assert_eq!(call.result, IpcResult::Pending);
710 assert!(call.duration_ms.is_none());
711 }
712 other => panic!("expected Ipc, got {other:?}"),
713 }
714 }
715
716 #[test]
719 fn parse_console_event() {
720 let ev = serde_json::json!({
721 "type": "console",
722 "level": "warn",
723 "message": "deprecated API usage",
724 });
725 let result = parse_bridge_event(&ev).expect("should produce an event");
726 match result {
727 AppEvent::Console { level, message, .. } => {
728 assert_eq!(level, "warn");
729 assert_eq!(message, "deprecated API usage");
730 }
731 other => panic!("expected Console, got {other:?}"),
732 }
733 }
734
735 #[test]
736 fn parse_console_default_level() {
737 let ev = serde_json::json!({
738 "type": "console",
739 "message": "hello",
740 });
741 let result = parse_bridge_event(&ev).expect("should produce an event");
742 match result {
743 AppEvent::Console { level, message, .. } => {
744 assert_eq!(level, "log");
745 assert_eq!(message, "hello");
746 }
747 other => panic!("expected Console, got {other:?}"),
748 }
749 }
750
751 #[test]
754 fn parse_navigation_event() {
755 let ev = serde_json::json!({
756 "type": "navigation",
757 "nav_type": "push",
758 });
759 let result = parse_bridge_event(&ev).expect("should produce an event");
760 match result {
761 AppEvent::WindowEvent { label, event, .. } => {
762 assert_eq!(label, "main");
763 assert_eq!(event, "navigation.push");
764 }
765 other => panic!("expected WindowEvent, got {other:?}"),
766 }
767 }
768
769 #[test]
770 fn parse_navigation_default_nav_type() {
771 let ev = serde_json::json!({ "type": "navigation" });
772 let result = parse_bridge_event(&ev).expect("should produce an event");
773 match result {
774 AppEvent::WindowEvent { event, .. } => {
775 assert_eq!(event, "navigation.unknown");
776 }
777 other => panic!("expected WindowEvent, got {other:?}"),
778 }
779 }
780
781 #[test]
784 fn parse_dom_mutation_event() {
785 let ev = serde_json::json!({
786 "type": "dom_mutation",
787 "count": 15,
788 });
789 let result = parse_bridge_event(&ev).expect("should produce an event");
790 match result {
791 AppEvent::DomMutation {
792 webview_label,
793 mutation_count,
794 ..
795 } => {
796 assert_eq!(webview_label, "main");
797 assert_eq!(mutation_count, 15);
798 }
799 other => panic!("expected DomMutation, got {other:?}"),
800 }
801 }
802
803 #[test]
806 fn parse_network_event() {
807 let ev = serde_json::json!({
808 "type": "network",
809 "method": "POST",
810 "url": "https://api.example.com/data",
811 });
812 let result = parse_bridge_event(&ev).expect("should produce an event");
813 match result {
814 AppEvent::StateChange { key, caused_by, .. } => {
815 assert_eq!(key, "network.POST");
816 assert_eq!(caused_by.as_deref(), Some("https://api.example.com/data"));
817 }
818 other => panic!("expected StateChange, got {other:?}"),
819 }
820 }
821
822 #[test]
825 fn parse_unknown_type_returns_none() {
826 let ev = serde_json::json!({
827 "type": "custom_telemetry",
828 "payload": 42,
829 });
830 assert!(parse_bridge_event(&ev).is_none());
831 }
832
833 #[test]
834 fn parse_missing_type_field_returns_none() {
835 let ev = serde_json::json!({ "data": "no type here" });
836 assert!(parse_bridge_event(&ev).is_none());
837 }
838
839 #[test]
840 fn parse_empty_object_returns_none() {
841 let ev = serde_json::json!({});
842 assert!(parse_bridge_event(&ev).is_none());
843 }
844}