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 if let Some(ref token) = token_for_file {
162 write_token_file(token);
163 }
164
165 tracing::info!("Victauri MCP server listening on 127.0.0.1:{actual_port}");
166
167 let drain_state = state.clone();
168 let drain_bridge = bridge;
169 let drain_shutdown = state.shutdown_tx.subscribe();
170 let drain_finished = state.task_tracker.track("event_drain_loop");
171 tokio::spawn(async move {
172 event_drain_loop(drain_state, drain_bridge, drain_shutdown).await;
173 drain_finished.store(true, std::sync::atomic::Ordering::Relaxed);
174 });
175
176 let mut shutdown_rx2 = shutdown_rx.clone();
177 let server = axum::serve(listener, app).with_graceful_shutdown(async move {
178 let _ = shutdown_rx.wait_for(|&v| v).await;
179 remove_port_file();
180 tracing::info!("Victauri MCP server shutting down gracefully");
181 });
182
183 tokio::select! {
184 result = server => {
185 if let Err(e) = result {
186 tracing::error!("Victauri MCP server error: {e}");
187 }
188 }
189 _ = async {
190 let _ = shutdown_rx2.wait_for(|&v| v).await;
191 tokio::time::sleep(std::time::Duration::from_secs(5)).await;
192 } => {
193 tracing::warn!("Victauri MCP server shutdown timeout — forcing exit");
194 }
195 }
196 Ok(())
197}
198
199async fn try_bind(preferred: u16) -> anyhow::Result<(tokio::net::TcpListener, u16)> {
200 if let Ok(listener) = tokio::net::TcpListener::bind(format!("127.0.0.1:{preferred}")).await {
201 return Ok((listener, preferred));
202 }
203
204 for offset in 1..=PORT_FALLBACK_RANGE {
205 let port = preferred + offset;
206 if let Ok(listener) = tokio::net::TcpListener::bind(format!("127.0.0.1:{port}")).await {
207 return Ok((listener, port));
208 }
209 }
210
211 anyhow::bail!(
212 "could not bind to any port in range {preferred}-{}",
213 preferred + PORT_FALLBACK_RANGE
214 )
215}
216
217fn discovery_dir() -> std::path::PathBuf {
218 std::env::temp_dir()
219 .join("victauri")
220 .join(std::process::id().to_string())
221}
222
223fn write_port_file(port: u16) {
224 let dir = discovery_dir();
225 let _ = std::fs::create_dir_all(&dir);
226 #[cfg(unix)]
227 {
228 use std::os::unix::fs::PermissionsExt;
229 let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
230 }
231 let port_path = dir.join("port");
232 if let Err(e) = std::fs::write(&port_path, port.to_string()) {
233 tracing::debug!("could not write port file: {e}");
234 }
235 #[cfg(unix)]
236 {
237 use std::os::unix::fs::PermissionsExt;
238 let _ = std::fs::set_permissions(&port_path, std::fs::Permissions::from_mode(0o600));
239 }
240 let metadata = serde_json::json!({
242 "pid": std::process::id(),
243 "port": port,
244 "started_at": chrono::Utc::now().to_rfc3339(),
245 "version": env!("CARGO_PKG_VERSION"),
246 });
247 let meta_path = dir.join("metadata.json");
248 let _ = std::fs::write(&meta_path, metadata.to_string());
249 #[cfg(unix)]
250 {
251 use std::os::unix::fs::PermissionsExt;
252 let _ = std::fs::set_permissions(&meta_path, std::fs::Permissions::from_mode(0o600));
253 }
254}
255
256fn write_token_file(token: &str) {
257 let dir = discovery_dir();
258 let _ = std::fs::create_dir_all(&dir);
259 #[cfg(unix)]
260 {
261 use std::os::unix::fs::PermissionsExt;
262 let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
263 }
264 let token_path = dir.join("token");
265 if let Err(e) = std::fs::write(&token_path, token) {
266 tracing::debug!("could not write token file: {e}");
267 }
268 #[cfg(unix)]
269 {
270 use std::os::unix::fs::PermissionsExt;
271 let _ = std::fs::set_permissions(&token_path, std::fs::Permissions::from_mode(0o600));
272 }
273}
274
275fn remove_port_file() {
276 let _ = std::fs::remove_dir_all(discovery_dir());
277}
278
279#[must_use]
283pub fn parse_bridge_event(ev: &serde_json::Value) -> Option<victauri_core::AppEvent> {
284 use chrono::Utc;
285 use victauri_core::AppEvent;
286
287 let event_type = ev.get("type").and_then(|t| t.as_str()).unwrap_or("");
288 let now = Utc::now();
289
290 let app_event = match event_type {
291 "console" => AppEvent::StateChange {
292 key: format!(
293 "console.{}",
294 ev.get("level").and_then(|l| l.as_str()).unwrap_or("log")
295 ),
296 timestamp: now,
297 caused_by: ev
298 .get("message")
299 .and_then(|m| m.as_str())
300 .map(std::string::ToString::to_string),
301 },
302 "dom_mutation" => AppEvent::DomMutation {
303 webview_label: DEFAULT_WEBVIEW_LABEL.to_string(),
304 timestamp: now,
305 mutation_count: ev
306 .get("count")
307 .and_then(serde_json::Value::as_u64)
308 .unwrap_or(0) as u32,
309 },
310 "ipc" => {
311 let cmd = ev
312 .get("command")
313 .and_then(|c| c.as_str())
314 .unwrap_or("unknown");
315 AppEvent::Ipc(victauri_core::IpcCall {
316 id: uuid::Uuid::new_v4().to_string(),
317 command: cmd.to_string(),
318 timestamp: now,
319 result: match ev.get("status").and_then(|s| s.as_str()) {
320 Some("ok") => victauri_core::IpcResult::Ok(serde_json::Value::Null),
321 Some("error") => victauri_core::IpcResult::Err("error".to_string()),
322 _ => victauri_core::IpcResult::Pending,
323 },
324 duration_ms: ev
325 .get("duration_ms")
326 .and_then(serde_json::Value::as_f64)
327 .map(|d| d as u64),
328 arg_size_bytes: 0,
329 webview_label: DEFAULT_WEBVIEW_LABEL.to_string(),
330 })
331 }
332 "network" => AppEvent::StateChange {
333 key: format!(
334 "network.{}",
335 ev.get("method").and_then(|m| m.as_str()).unwrap_or("GET")
336 ),
337 timestamp: now,
338 caused_by: ev
339 .get("url")
340 .and_then(|u| u.as_str())
341 .map(std::string::ToString::to_string),
342 },
343 "navigation" => AppEvent::WindowEvent {
344 label: DEFAULT_WEBVIEW_LABEL.to_string(),
345 event: format!(
346 "navigation.{}",
347 ev.get("nav_type")
348 .and_then(|n| n.as_str())
349 .unwrap_or("unknown")
350 ),
351 timestamp: now,
352 },
353 "dom_interaction" => {
354 let action_str = ev.get("action").and_then(|a| a.as_str()).unwrap_or("click");
355 let action = match action_str {
356 "click" => victauri_core::InteractionKind::Click,
357 "double_click" => victauri_core::InteractionKind::DoubleClick,
358 "fill" => victauri_core::InteractionKind::Fill,
359 "key_press" => victauri_core::InteractionKind::KeyPress,
360 "select" => victauri_core::InteractionKind::Select,
361 "navigate" => victauri_core::InteractionKind::Navigate,
362 "scroll" => victauri_core::InteractionKind::Scroll,
363 _ => victauri_core::InteractionKind::Click,
364 };
365 AppEvent::DomInteraction {
366 action,
367 selector: ev
368 .get("selector")
369 .and_then(|s| s.as_str())
370 .unwrap_or("body")
371 .to_string(),
372 value: ev
373 .get("value")
374 .and_then(|v| v.as_str())
375 .map(std::string::ToString::to_string),
376 timestamp: now,
377 webview_label: DEFAULT_WEBVIEW_LABEL.to_string(),
378 }
379 }
380 _ => return None,
381 };
382
383 Some(app_event)
384}
385
386async fn event_drain_loop(
387 state: Arc<VictauriState>,
388 bridge: Arc<dyn WebviewBridge>,
389 mut shutdown: tokio::sync::watch::Receiver<bool>,
390) {
391 let mut last_drain_ts: f64 = 0.0;
392
393 loop {
394 tokio::select! {
395 _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {}
396 _ = shutdown.changed() => break,
397 }
398
399 let code = format!("return window.__VICTAURI__?.getEventStream({last_drain_ts})");
400 let id = uuid::Uuid::new_v4().to_string();
401 let (tx, rx) = tokio::sync::oneshot::channel();
402
403 {
404 let mut pending = state.pending_evals.lock().await;
405 if pending.len() >= MAX_PENDING_EVALS {
406 continue;
407 }
408 pending.insert(id.clone(), tx);
409 }
410
411 let inject = format!(
412 r"
413 (async () => {{
414 try {{
415 const __result = await (async () => {{ {code} }})();
416 await window.__TAURI_INTERNALS__.invoke('plugin:victauri|victauri_eval_callback', {{
417 id: '{id}',
418 result: JSON.stringify(__result)
419 }});
420 }} catch (e) {{
421 await window.__TAURI_INTERNALS__.invoke('plugin:victauri|victauri_eval_callback', {{
422 id: '{id}',
423 result: JSON.stringify({{ __error: e.message }})
424 }});
425 }}
426 }})();
427 "
428 );
429
430 if bridge.eval_webview(None, &inject).is_err() {
431 state.pending_evals.lock().await.remove(&id);
432 continue;
433 }
434
435 let Ok(Ok(result)) = tokio::time::timeout(std::time::Duration::from_secs(5), rx).await
436 else {
437 state.pending_evals.lock().await.remove(&id);
438 continue;
439 };
440
441 let events: Vec<serde_json::Value> = match serde_json::from_str(&result) {
442 Ok(v) => v,
443 Err(_) => continue,
444 };
445
446 for ev in &events {
447 let ts = ev
448 .get("timestamp")
449 .and_then(serde_json::Value::as_f64)
450 .unwrap_or(0.0);
451 if ts > last_drain_ts {
452 last_drain_ts = ts;
453 }
454
455 if let Some(app_event) = parse_bridge_event(ev) {
456 state.event_log.push(app_event.clone());
457 if state.recorder.is_recording() {
458 state.recorder.record_event(app_event);
459 }
460 }
461 }
462 }
463}
464
465#[cfg(test)]
466mod tests {
467 use super::*;
468 use victauri_core::{AppEvent, InteractionKind, IpcResult};
469
470 #[tokio::test]
471 async fn try_bind_preferred_port_available() {
472 let (listener, port) = try_bind(0).await.unwrap();
473 let addr = listener.local_addr().unwrap();
474 assert_eq!(port, 0);
475 assert_ne!(addr.port(), 0); }
477
478 #[tokio::test]
479 async fn try_bind_falls_back_when_taken() {
480 let blocker = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
481 let blocked_port = blocker.local_addr().unwrap().port();
482
483 let (_, actual) = try_bind(blocked_port).await.unwrap();
484 assert_ne!(actual, blocked_port);
485 assert!(actual > blocked_port);
486 assert!(actual <= blocked_port + PORT_FALLBACK_RANGE);
487 }
488
489 #[test]
490 fn port_file_roundtrip() {
491 write_port_file(7777);
492 let dir = discovery_dir();
493 let content = std::fs::read_to_string(dir.join("port")).unwrap();
494 assert_eq!(content, "7777");
495 let meta: serde_json::Value =
497 serde_json::from_str(&std::fs::read_to_string(dir.join("metadata.json")).unwrap())
498 .unwrap();
499 assert_eq!(meta["port"], 7777);
500 assert_eq!(meta["pid"], std::process::id());
501 remove_port_file();
502 assert!(!dir.exists());
503 }
504
505 #[test]
508 fn parse_dom_interaction_click() {
509 let ev = serde_json::json!({
510 "type": "dom_interaction",
511 "action": "click",
512 "selector": "#submit-btn",
513 });
514 let result = parse_bridge_event(&ev).expect("should produce an event");
515 match result {
516 AppEvent::DomInteraction {
517 action,
518 selector,
519 value,
520 webview_label,
521 ..
522 } => {
523 assert_eq!(action, InteractionKind::Click);
524 assert_eq!(selector, "#submit-btn");
525 assert!(value.is_none());
526 assert_eq!(webview_label, "main");
527 }
528 other => panic!("expected DomInteraction, got {other:?}"),
529 }
530 }
531
532 #[test]
533 fn parse_dom_interaction_fill_with_value() {
534 let ev = serde_json::json!({
535 "type": "dom_interaction",
536 "action": "fill",
537 "selector": "input[name=email]",
538 "value": "test@example.com",
539 });
540 let result = parse_bridge_event(&ev).expect("should produce an event");
541 match result {
542 AppEvent::DomInteraction {
543 action,
544 selector,
545 value,
546 ..
547 } => {
548 assert_eq!(action, InteractionKind::Fill);
549 assert_eq!(selector, "input[name=email]");
550 assert_eq!(value.as_deref(), Some("test@example.com"));
551 }
552 other => panic!("expected DomInteraction, got {other:?}"),
553 }
554 }
555
556 #[test]
557 fn parse_dom_interaction_key_press() {
558 let ev = serde_json::json!({
559 "type": "dom_interaction",
560 "action": "key_press",
561 "selector": "body",
562 "value": "Enter",
563 });
564 let result = parse_bridge_event(&ev).expect("should produce an event");
565 match result {
566 AppEvent::DomInteraction { action, value, .. } => {
567 assert_eq!(action, InteractionKind::KeyPress);
568 assert_eq!(value.as_deref(), Some("Enter"));
569 }
570 other => panic!("expected DomInteraction, got {other:?}"),
571 }
572 }
573
574 #[test]
575 fn parse_dom_interaction_unknown_action_defaults_to_click() {
576 let ev = serde_json::json!({
577 "type": "dom_interaction",
578 "action": "swipe_left",
579 "selector": ".card",
580 });
581 let result = parse_bridge_event(&ev).expect("should produce an event");
582 match result {
583 AppEvent::DomInteraction { action, .. } => {
584 assert_eq!(action, InteractionKind::Click);
585 }
586 other => panic!("expected DomInteraction, got {other:?}"),
587 }
588 }
589
590 #[test]
591 fn parse_dom_interaction_missing_action_defaults_to_click() {
592 let ev = serde_json::json!({
593 "type": "dom_interaction",
594 "selector": "button",
595 });
596 let result = parse_bridge_event(&ev).expect("should produce an event");
597 match result {
598 AppEvent::DomInteraction { action, .. } => {
599 assert_eq!(action, InteractionKind::Click);
600 }
601 other => panic!("expected DomInteraction, got {other:?}"),
602 }
603 }
604
605 #[test]
606 fn parse_dom_interaction_missing_selector_defaults_to_body() {
607 let ev = serde_json::json!({
608 "type": "dom_interaction",
609 "action": "scroll",
610 });
611 let result = parse_bridge_event(&ev).expect("should produce an event");
612 match result {
613 AppEvent::DomInteraction {
614 action, selector, ..
615 } => {
616 assert_eq!(action, InteractionKind::Scroll);
617 assert_eq!(selector, "body");
618 }
619 other => panic!("expected DomInteraction, got {other:?}"),
620 }
621 }
622
623 #[test]
624 fn parse_dom_interaction_all_action_kinds() {
625 let cases = [
626 ("click", InteractionKind::Click),
627 ("double_click", InteractionKind::DoubleClick),
628 ("fill", InteractionKind::Fill),
629 ("key_press", InteractionKind::KeyPress),
630 ("select", InteractionKind::Select),
631 ("navigate", InteractionKind::Navigate),
632 ("scroll", InteractionKind::Scroll),
633 ];
634 for (action_str, expected_kind) in cases {
635 let ev = serde_json::json!({
636 "type": "dom_interaction",
637 "action": action_str,
638 "selector": "body",
639 });
640 let result = parse_bridge_event(&ev)
641 .unwrap_or_else(|| panic!("should produce event for action {action_str}"));
642 match result {
643 AppEvent::DomInteraction { action, .. } => {
644 assert_eq!(action, expected_kind, "mismatch for action {action_str}");
645 }
646 other => panic!("expected DomInteraction for {action_str}, got {other:?}"),
647 }
648 }
649 }
650
651 #[test]
654 fn parse_ipc_status_ok() {
655 let ev = serde_json::json!({
656 "type": "ipc",
657 "command": "greet",
658 "status": "ok",
659 "duration_ms": 42.0,
660 });
661 let result = parse_bridge_event(&ev).expect("should produce an event");
662 match result {
663 AppEvent::Ipc(call) => {
664 assert_eq!(call.command, "greet");
665 assert_eq!(call.result, IpcResult::Ok(serde_json::Value::Null));
666 assert_eq!(call.duration_ms, Some(42));
667 assert_eq!(call.webview_label, "main");
668 }
669 other => panic!("expected Ipc, got {other:?}"),
670 }
671 }
672
673 #[test]
674 fn parse_ipc_status_error() {
675 let ev = serde_json::json!({
676 "type": "ipc",
677 "command": "save_file",
678 "status": "error",
679 });
680 let result = parse_bridge_event(&ev).expect("should produce an event");
681 match result {
682 AppEvent::Ipc(call) => {
683 assert_eq!(call.command, "save_file");
684 assert_eq!(call.result, IpcResult::Err("error".to_string()));
685 }
686 other => panic!("expected Ipc, got {other:?}"),
687 }
688 }
689
690 #[test]
691 fn parse_ipc_status_pending() {
692 let ev = serde_json::json!({
693 "type": "ipc",
694 "command": "long_task",
695 });
696 let result = parse_bridge_event(&ev).expect("should produce an event");
697 match result {
698 AppEvent::Ipc(call) => {
699 assert_eq!(call.result, IpcResult::Pending);
700 assert!(call.duration_ms.is_none());
701 }
702 other => panic!("expected Ipc, got {other:?}"),
703 }
704 }
705
706 #[test]
709 fn parse_console_event() {
710 let ev = serde_json::json!({
711 "type": "console",
712 "level": "warn",
713 "message": "deprecated API usage",
714 });
715 let result = parse_bridge_event(&ev).expect("should produce an event");
716 match result {
717 AppEvent::StateChange { key, caused_by, .. } => {
718 assert_eq!(key, "console.warn");
719 assert_eq!(caused_by.as_deref(), Some("deprecated API usage"));
720 }
721 other => panic!("expected StateChange, got {other:?}"),
722 }
723 }
724
725 #[test]
726 fn parse_console_default_level() {
727 let ev = serde_json::json!({
728 "type": "console",
729 "message": "hello",
730 });
731 let result = parse_bridge_event(&ev).expect("should produce an event");
732 match result {
733 AppEvent::StateChange { key, .. } => {
734 assert_eq!(key, "console.log");
735 }
736 other => panic!("expected StateChange, got {other:?}"),
737 }
738 }
739
740 #[test]
743 fn parse_navigation_event() {
744 let ev = serde_json::json!({
745 "type": "navigation",
746 "nav_type": "push",
747 });
748 let result = parse_bridge_event(&ev).expect("should produce an event");
749 match result {
750 AppEvent::WindowEvent { label, event, .. } => {
751 assert_eq!(label, "main");
752 assert_eq!(event, "navigation.push");
753 }
754 other => panic!("expected WindowEvent, got {other:?}"),
755 }
756 }
757
758 #[test]
759 fn parse_navigation_default_nav_type() {
760 let ev = serde_json::json!({ "type": "navigation" });
761 let result = parse_bridge_event(&ev).expect("should produce an event");
762 match result {
763 AppEvent::WindowEvent { event, .. } => {
764 assert_eq!(event, "navigation.unknown");
765 }
766 other => panic!("expected WindowEvent, got {other:?}"),
767 }
768 }
769
770 #[test]
773 fn parse_dom_mutation_event() {
774 let ev = serde_json::json!({
775 "type": "dom_mutation",
776 "count": 15,
777 });
778 let result = parse_bridge_event(&ev).expect("should produce an event");
779 match result {
780 AppEvent::DomMutation {
781 webview_label,
782 mutation_count,
783 ..
784 } => {
785 assert_eq!(webview_label, "main");
786 assert_eq!(mutation_count, 15);
787 }
788 other => panic!("expected DomMutation, got {other:?}"),
789 }
790 }
791
792 #[test]
795 fn parse_network_event() {
796 let ev = serde_json::json!({
797 "type": "network",
798 "method": "POST",
799 "url": "https://api.example.com/data",
800 });
801 let result = parse_bridge_event(&ev).expect("should produce an event");
802 match result {
803 AppEvent::StateChange { key, caused_by, .. } => {
804 assert_eq!(key, "network.POST");
805 assert_eq!(caused_by.as_deref(), Some("https://api.example.com/data"));
806 }
807 other => panic!("expected StateChange, got {other:?}"),
808 }
809 }
810
811 #[test]
814 fn parse_unknown_type_returns_none() {
815 let ev = serde_json::json!({
816 "type": "custom_telemetry",
817 "payload": 42,
818 });
819 assert!(parse_bridge_event(&ev).is_none());
820 }
821
822 #[test]
823 fn parse_missing_type_field_returns_none() {
824 let ev = serde_json::json!({ "data": "no type here" });
825 assert!(parse_bridge_event(&ev).is_none());
826 }
827
828 #[test]
829 fn parse_empty_object_returns_none() {
830 let ev = serde_json::json!({});
831 assert!(parse_bridge_event(&ev).is_none());
832 }
833}