victauri_test/client.rs
1use serde::Deserialize;
2use serde_json::{Value, json};
3
4use crate::assertions::VerifyBuilder;
5use crate::discovery::{scan_discovery_dirs_for_port, scan_discovery_dirs_for_token};
6use crate::error::TestError;
7use crate::visual::{VisualDiff, VisualOptions};
8
9// ── Typed Response Structs (Phase 4E) ───────────────────────────────────────
10
11/// Structured plugin information returned by [`VictauriClient::plugin_info`].
12///
13/// # Example
14///
15/// ```rust,ignore
16/// let info = client.plugin_info().await.unwrap();
17/// println!("v{} — {} tools, up {:.0}s", info.version, info.tools.total, info.uptime_secs);
18/// ```
19#[derive(Debug, Clone, Deserialize)]
20pub struct PluginInfo {
21 /// Plugin version string (e.g. `"0.2.0"`).
22 pub version: String,
23 /// Seconds since the plugin was initialized.
24 pub uptime_secs: f64,
25 /// Total number of tool invocations served.
26 pub tool_invocations: u64,
27 /// Tool details (nested object with `total`, `enabled`, etc.).
28 #[serde(default)]
29 pub tools: PluginToolInfo,
30 /// Number of tools — derived from `tools.total` if present, else top-level
31 /// `tool_count` for backwards compatibility.
32 #[serde(default)]
33 pub tool_count: usize,
34}
35
36/// Tool information nested inside [`PluginInfo`].
37#[derive(Debug, Clone, Default, Deserialize)]
38pub struct PluginToolInfo {
39 /// Total number of tools registered.
40 #[serde(default)]
41 pub total: usize,
42 /// Number of enabled tools.
43 #[serde(default)]
44 pub enabled: usize,
45}
46
47/// Structured process memory statistics returned by [`VictauriClient::memory_stats`].
48///
49/// # Example
50///
51/// ```rust,ignore
52/// let mem = client.memory_stats().await.unwrap();
53/// let mb = mem.working_set_bytes as f64 / 1_048_576.0;
54/// assert!(mb < 512.0, "memory usage too high: {mb:.1} MB");
55/// ```
56#[derive(Debug, Clone, Deserialize)]
57pub struct MemoryStats {
58 /// Current working set size in bytes.
59 pub working_set_bytes: u64,
60 /// Peak working set size in bytes, if available.
61 pub peak_working_set_bytes: Option<u64>,
62}
63
64// ── WaitForBuilder (Phase 4B) ───────────────────────────────────────────────
65
66/// Builder for configuring and executing a `wait_for` condition.
67///
68/// Created via [`VictauriClient::wait`]. Provides a fluent API as an
69/// alternative to the positional-argument [`VictauriClient::wait_for`] method.
70///
71/// # Examples
72///
73/// ```rust,ignore
74/// // Wait for text to appear with custom timeout
75/// client.wait("text")
76/// .value("Hello, World!")
77/// .timeout_ms(15_000)
78/// .run()
79/// .await
80/// .unwrap();
81///
82/// // Wait for network idle with fast polling
83/// client.wait("network_idle")
84/// .poll_ms(50)
85/// .run()
86/// .await
87/// .unwrap();
88/// ```
89pub struct WaitForBuilder<'a> {
90 client: &'a mut VictauriClient,
91 condition: String,
92 value: Option<String>,
93 timeout_ms: u64,
94 poll_ms: u64,
95}
96
97impl<'a> WaitForBuilder<'a> {
98 /// Set the value to match against (e.g. the text string for `"text"` condition).
99 #[must_use]
100 pub fn value(mut self, v: &str) -> Self {
101 self.value = Some(v.to_string());
102 self
103 }
104
105 /// Set the maximum time to wait in milliseconds (default: 10 000).
106 #[must_use]
107 pub fn timeout_ms(mut self, ms: u64) -> Self {
108 self.timeout_ms = ms;
109 self
110 }
111
112 /// Set the polling interval in milliseconds (default: 200).
113 #[must_use]
114 pub fn poll_ms(mut self, ms: u64) -> Self {
115 self.poll_ms = ms;
116 self
117 }
118
119 /// Execute the wait, polling until the condition is met or the timeout expires.
120 ///
121 /// # Errors
122 ///
123 /// Returns errors from [`VictauriClient::call_tool`].
124 pub async fn run(self) -> Result<Value, TestError> {
125 self.client
126 .wait_for(
127 &self.condition,
128 self.value.as_deref(),
129 Some(self.timeout_ms),
130 Some(self.poll_ms),
131 )
132 .await
133 }
134}
135
136/// Typed HTTP client for the Victauri MCP server.
137///
138/// Manages session lifecycle (initialize → tool calls → cleanup) and provides
139/// convenient methods for common test operations.
140///
141/// # Example
142///
143/// ```rust,ignore
144/// use victauri_test::VictauriClient;
145///
146/// let mut client = VictauriClient::connect(7373).await.unwrap();
147/// let title = client.eval_js("document.title").await.unwrap();
148/// client.click("e3").await.unwrap();
149/// let snapshot = client.dom_snapshot().await.unwrap();
150/// ```
151pub struct VictauriClient {
152 http: reqwest::Client,
153 base_url: String,
154 host: String,
155 port: u16,
156 session_id: String,
157 next_id: u64,
158 auth_token: Option<String>,
159}
160
161impl VictauriClient {
162 /// Connect to a Victauri MCP server on the given port.
163 /// Sends `initialize` and `notifications/initialized` automatically.
164 ///
165 /// # Errors
166 ///
167 /// Returns [`TestError::Connection`] if the server is unreachable or
168 /// returns a non-success status. Returns [`TestError::Request`] on
169 /// HTTP transport failures.
170 pub async fn connect(port: u16) -> Result<Self, TestError> {
171 Self::connect_with_token(port, None).await
172 }
173
174 /// Connect with an optional Bearer auth token.
175 ///
176 /// Retries up to 3 times with exponential backoff on 429 (rate limited).
177 ///
178 /// # Errors
179 ///
180 /// Returns [`TestError::Connection`] if the server is unreachable or
181 /// returns a non-success status. Returns [`TestError::Request`] on
182 /// HTTP transport failures.
183 pub async fn connect_with_token(port: u16, token: Option<&str>) -> Result<Self, TestError> {
184 let host = "127.0.0.1";
185 let base_url = format!("http://{host}:{port}");
186 let http = reqwest::Client::builder()
187 .timeout(std::time::Duration::from_secs(60))
188 .connect_timeout(std::time::Duration::from_secs(10))
189 .build()
190 .map_err(|e| TestError::Connection {
191 host: host.to_string(),
192 port,
193 reason: e.to_string(),
194 })?;
195
196 let session_id = Self::perform_handshake(&http, &base_url, host, port, token).await?;
197
198 Ok(Self {
199 http,
200 base_url,
201 host: host.to_string(),
202 port,
203 session_id,
204 next_id: 10,
205 auth_token: token.map(String::from),
206 })
207 }
208
209 /// Run the MCP `initialize` + `notifications/initialized` handshake and return the
210 /// minted session id. Shared by [`Self::connect_with_token`] and [`Self::reinitialize`]
211 /// so a fresh session can be established without rebuilding the whole client.
212 async fn perform_handshake(
213 http: &reqwest::Client,
214 base_url: &str,
215 host: &str,
216 port: u16,
217 token: Option<&str>,
218 ) -> Result<String, TestError> {
219 let init_body = json!({
220 "jsonrpc": "2.0",
221 "id": 1,
222 "method": "initialize",
223 "params": {
224 "protocolVersion": "2025-03-26",
225 "capabilities": {},
226 "clientInfo": {"name": "victauri-test", "version": env!("CARGO_PKG_VERSION")}
227 }
228 });
229
230 let mut init_resp = None;
231 for attempt in 0..4 {
232 let mut req = http
233 .post(format!("{base_url}/mcp"))
234 .header("Content-Type", "application/json")
235 .header("Accept", "application/json, text/event-stream")
236 .json(&init_body);
237 if let Some(t) = token {
238 req = req.header("Authorization", format!("Bearer {t}"));
239 }
240
241 let resp = req.send().await.map_err(|e| TestError::Connection {
242 host: host.to_string(),
243 port,
244 reason: e.to_string(),
245 })?;
246
247 if resp.status() == 429 && attempt < 3 {
248 let delay = std::time::Duration::from_millis(100 * (1 << attempt));
249 tokio::time::sleep(delay).await;
250 continue;
251 }
252
253 init_resp = Some(resp);
254 break;
255 }
256
257 let init_resp = init_resp.ok_or_else(|| TestError::Connection {
258 host: host.to_string(),
259 port,
260 reason: "initialize failed after retries".into(),
261 })?;
262
263 if !init_resp.status().is_success() {
264 return Err(TestError::Connection {
265 host: host.to_string(),
266 port,
267 reason: format!("initialize returned {}", init_resp.status()),
268 });
269 }
270
271 let session_id = init_resp
272 .headers()
273 .get("mcp-session-id")
274 .and_then(|v| v.to_str().ok())
275 .ok_or_else(|| TestError::Connection {
276 host: host.to_string(),
277 port,
278 reason: "no mcp-session-id header".into(),
279 })?
280 .to_string();
281
282 let mut notify_req = http
283 .post(format!("{base_url}/mcp"))
284 .header("Content-Type", "application/json")
285 .header("mcp-session-id", &session_id)
286 .json(&json!({
287 "jsonrpc": "2.0",
288 "method": "notifications/initialized"
289 }));
290
291 if let Some(t) = token {
292 notify_req = notify_req.header("Authorization", format!("Bearer {t}"));
293 }
294
295 notify_req.send().await?;
296
297 Ok(session_id)
298 }
299
300 /// Re-run the MCP handshake to mint a fresh session, replacing the stale one.
301 ///
302 /// Called automatically by [`Self::call_tool`] when a tool call returns HTTP 422
303 /// "expected initialized request" — the session went stale because the in-app server
304 /// restarted, the client reconnected, or the `notifications/initialized` was missed.
305 async fn reinitialize(&mut self) -> Result<(), TestError> {
306 let token = self.auth_token.clone();
307 let session_id = Self::perform_handshake(
308 &self.http,
309 &self.base_url,
310 &self.host,
311 self.port,
312 token.as_deref(),
313 )
314 .await?;
315 self.session_id = session_id;
316 Ok(())
317 }
318
319 /// Auto-discover a running Victauri server via temp files.
320 ///
321 /// Discovery priority:
322 /// 1. `VICTAURI_PORT` / `VICTAURI_AUTH_TOKEN` env vars (explicit override)
323 /// 2. Per-process discovery directory: `<temp>/victauri/<pid>/port`
324 /// 3. Default: port 7373, no auth
325 ///
326 /// # Errors
327 ///
328 /// Returns [`TestError::Connection`] if the server is unreachable or
329 /// returns a non-success status. Returns [`TestError::Request`] on
330 /// HTTP transport failures.
331 pub async fn discover() -> Result<Self, TestError> {
332 // Classify the discovery directory BEFORE `discover_port` runs — that path
333 // deletes stale (unreachable) discovery dirs as a side effect, so the
334 // diagnosis must be captured first to explain a subsequent failure.
335 let diagnosis = crate::discovery::diagnose_discovery();
336 let port = Self::discover_port();
337 let token = Self::discover_token();
338 match Self::connect_with_token(port, token.as_deref()).await {
339 Ok(client) => Ok(client),
340 Err(TestError::Connection { host, port, reason }) => {
341 let reason = match diagnosis.hint() {
342 Some(hint) => format!("{reason}\n\n Discovery diagnosis: {hint}"),
343 None => reason,
344 };
345 Err(TestError::Connection { host, port, reason })
346 }
347 Err(other) => Err(other),
348 }
349 }
350
351 fn discover_port() -> u16 {
352 if let Ok(p) = std::env::var("VICTAURI_PORT")
353 && let Ok(port) = p.parse::<u16>()
354 {
355 return port;
356 }
357 // Scan per-process discovery directories for live servers
358 if let Some(port) = scan_discovery_dirs_for_port() {
359 return port;
360 }
361 7373
362 }
363
364 fn discover_token() -> Option<String> {
365 if let Ok(token) = std::env::var("VICTAURI_AUTH_TOKEN") {
366 return Some(token);
367 }
368 // Scan per-process discovery directories
369 if let Some(token) = scan_discovery_dirs_for_token() {
370 return Some(token);
371 }
372 None
373 }
374
375 /// Check whether the server is still reachable.
376 ///
377 /// Sends a GET to `/health` and returns `true` if the response is 200 OK.
378 #[must_use]
379 pub async fn is_alive(&self) -> bool {
380 self.http
381 .get(format!("{}/health", self.base_url))
382 .send()
383 .await
384 .is_ok_and(|r| r.status().is_success())
385 }
386
387 /// Re-establish an MCP session after the app restarts.
388 ///
389 /// Polls `/health` up to `max_wait` and then re-runs the
390 /// initialize/initialized handshake. The returned client has a fresh
391 /// session ID; the old client should be dropped.
392 ///
393 /// # Errors
394 ///
395 /// Returns [`TestError::Connection`] if the server doesn't come back
396 /// within `max_wait`.
397 pub async fn reconnect(&self, max_wait: std::time::Duration) -> Result<Self, TestError> {
398 let start = std::time::Instant::now();
399 loop {
400 if self.is_alive().await {
401 return Self::connect_with_token(self.port, self.auth_token.as_deref()).await;
402 }
403 if start.elapsed() > max_wait {
404 return Err(TestError::Connection {
405 host: self.host.clone(),
406 port: self.port,
407 reason: format!("server did not recover within {}s", max_wait.as_secs()),
408 });
409 }
410 tokio::time::sleep(std::time::Duration::from_millis(250)).await;
411 }
412 }
413
414 /// Call an MCP tool by name and return the result content as JSON.
415 ///
416 /// Retries up to 3 times with exponential backoff on 429 (rate limited). On a 422
417 /// "expected initialized request" (the MCP session went stale after an app/server
418 /// restart) it re-runs the handshake once and retries transparently; if the session is
419 /// still stale, the error names the cause and the sessionless REST fallback.
420 ///
421 /// # Errors
422 ///
423 /// Returns [`TestError::Connection`] if the request fails after retries (including an
424 /// unrecoverable stale session). Returns [`TestError::Request`] on HTTP transport
425 /// errors. Returns [`TestError::Mcp`] if the server returns a JSON-RPC error.
426 pub async fn call_tool(&mut self, name: &str, arguments: Value) -> Result<Value, TestError> {
427 let id = self.next_id;
428 self.next_id += 1;
429
430 let call_body = json!({
431 "jsonrpc": "2.0",
432 "id": id,
433 "method": "tools/call",
434 "params": {
435 "name": name,
436 "arguments": arguments
437 }
438 });
439
440 let mut resp = None;
441 let mut reinitialized = false;
442 for attempt in 0..4 {
443 let mut req = self
444 .http
445 .post(format!("{}/mcp", self.base_url))
446 .header("Content-Type", "application/json")
447 .header("Accept", "application/json, text/event-stream")
448 .header("mcp-session-id", &self.session_id)
449 .json(&call_body);
450 if let Some(ref t) = self.auth_token {
451 req = req.header("Authorization", format!("Bearer {t}"));
452 }
453 let r = req.send().await?;
454 let status = r.status();
455
456 if status == 429 && attempt < 3 {
457 let delay = std::time::Duration::from_millis(100 * (1 << attempt));
458 tokio::time::sleep(delay).await;
459 continue;
460 }
461 // HTTP 422 "expected initialized request": the MCP session went stale (the
462 // in-app server restarted, the client reconnected, or notifications/initialized
463 // was missed). Re-handshake ONCE to mint a fresh session and retry transparently.
464 // Bounded by `reinitialized` so a persistently-stale server cannot loop.
465 if status == 422 && !reinitialized && attempt < 3 {
466 drop(r);
467 reinitialized = true;
468 self.reinitialize().await?;
469 continue;
470 }
471 resp = Some(r);
472 break;
473 }
474
475 let resp = resp.ok_or_else(|| TestError::Connection {
476 host: self.host.clone(),
477 port: self.port,
478 reason: "tool call failed after retries".into(),
479 })?;
480
481 // Still stale after a re-handshake: surface a clear, actionable error pointing at
482 // the sessionless REST endpoint, which never hits this failure class.
483 if resp.status() == 422 {
484 return Err(TestError::Connection {
485 host: self.host.clone(),
486 port: self.port,
487 reason: format!(
488 "MCP session is stale (HTTP 422 'expected initialized request') and \
489 re-initialization did not recover — the server likely restarted \
490 mid-session. Use the sessionless REST API instead: \
491 POST http://{}:{}/api/tools/{name} (same Bearer auth, no session \
492 handshake).",
493 self.host, self.port
494 ),
495 });
496 }
497 let body = Self::parse_response(resp, &self.host, self.port).await?;
498
499 if let Some(error) = body.get("error") {
500 return Err(TestError::Mcp {
501 code: error["code"].as_i64().unwrap_or(-1),
502 message: error["message"].as_str().map_or_else(
503 || {
504 format!(
505 "unknown error (raw: {})",
506 serde_json::to_string(error).unwrap_or_else(|_| "<unparseable>".into())
507 )
508 },
509 String::from,
510 ),
511 });
512 }
513
514 let result = &body["result"];
515 let content = &result["content"];
516
517 // Honor MCP tool-level errors: a tool that sets `isError: true` returns its
518 // failure message in the content text. Without this check the SDK would
519 // report a failed eval / invalid selector / tool_error as a successful
520 // `Ok(...)`, hiding real failures from callers (red-team P1).
521 let is_tool_error = result.get("isError").and_then(Value::as_bool) == Some(true);
522
523 if let Some(arr) = content.as_array()
524 && let Some(first) = arr.first()
525 {
526 if let Some(text) = first["text"].as_str() {
527 if is_tool_error {
528 return Err(TestError::ToolError(text.to_string()));
529 }
530 if let Ok(parsed) = serde_json::from_str::<Value>(text) {
531 return Ok(parsed);
532 }
533 return Ok(Value::String(text.to_string()));
534 }
535 if first.get("type").and_then(Value::as_str) == Some("image") {
536 return Ok(first.clone());
537 }
538 }
539
540 if is_tool_error {
541 return Err(TestError::ToolError(format!(
542 "tool '{name}' returned an error result: {result}"
543 )));
544 }
545
546 Ok(body)
547 }
548
549 /// Parse a response that may be JSON or SSE (text/event-stream).
550 ///
551 /// rmcp's Streamable HTTP transport always returns SSE format with the
552 /// JSON-RPC payload in a `data:` line. This method handles both formats.
553 async fn parse_response(
554 resp: reqwest::Response,
555 host: &str,
556 port: u16,
557 ) -> Result<Value, TestError> {
558 let content_type = resp
559 .headers()
560 .get("content-type")
561 .and_then(|v| v.to_str().ok())
562 .unwrap_or("")
563 .to_string();
564
565 let text = resp.text().await?;
566
567 if content_type.contains("text/event-stream") {
568 for line in text.lines() {
569 let data = line
570 .strip_prefix("data: ")
571 .or_else(|| line.strip_prefix("data:"));
572 let Some(data) = data else { continue };
573 let trimmed = data.trim();
574 if trimmed.is_empty() {
575 continue;
576 }
577 if let Ok(parsed) = serde_json::from_str::<Value>(trimmed) {
578 return Ok(parsed);
579 }
580 }
581 Err(TestError::Connection {
582 host: host.to_string(),
583 port,
584 reason: "SSE stream contained no JSON-RPC data".into(),
585 })
586 } else {
587 serde_json::from_str(&text).map_err(|e| TestError::Connection {
588 host: host.to_string(),
589 port,
590 reason: format!(
591 "JSON parse error: {e}, body: {}",
592 &text[..200.min(text.len())]
593 ),
594 })
595 }
596 }
597
598 /// Evaluate JavaScript in the webview and return the result.
599 ///
600 /// # Errors
601 ///
602 /// Returns errors from [`VictauriClient::call_tool`].
603 pub async fn eval_js(&mut self, code: &str) -> Result<Value, TestError> {
604 self.call_tool("eval_js", json!({"code": code})).await
605 }
606
607 /// Get a DOM snapshot of the current page.
608 ///
609 /// # Errors
610 ///
611 /// Returns errors from [`VictauriClient::call_tool`].
612 pub async fn dom_snapshot(&mut self) -> Result<Value, TestError> {
613 self.call_tool("dom_snapshot", json!({})).await
614 }
615
616 /// Get a DOM snapshot of a specific webview by label.
617 ///
618 /// # Errors
619 ///
620 /// Returns errors from [`VictauriClient::call_tool`].
621 pub async fn dom_snapshot_for(&mut self, label: &str) -> Result<Value, TestError> {
622 self.call_tool("dom_snapshot", json!({"webview_label": label}))
623 .await
624 }
625
626 /// Capture a screenshot of a specific webview by label.
627 ///
628 /// # Errors
629 ///
630 /// Returns errors from [`VictauriClient::call_tool`].
631 pub async fn screenshot_for(&mut self, label: &str) -> Result<Value, TestError> {
632 self.call_tool("screenshot", json!({"window_label": label}))
633 .await
634 }
635
636 /// List running CSS animations/transitions (timing, easing, keyframes,
637 /// target). Pass `selector` to scope, or `None` for all running animations.
638 ///
639 /// # Errors
640 ///
641 /// Returns errors from [`VictauriClient::call_tool`].
642 pub async fn animation_list(&mut self, selector: Option<&str>) -> Result<Value, TestError> {
643 let mut args = json!({ "action": "list" });
644 if let Some(s) = selector {
645 args["selector"] = json!(s);
646 }
647 self.call_tool("animation", args).await
648 }
649
650 /// Deterministically scrub the target's animation to `points` evenly-spaced
651 /// steps, returning the geometry curve (and a filmstrip when `capture`).
652 ///
653 /// # Errors
654 ///
655 /// Returns errors from [`VictauriClient::call_tool`].
656 pub async fn animation_scrub(
657 &mut self,
658 selector: Option<&str>,
659 points: usize,
660 capture: bool,
661 ) -> Result<Value, TestError> {
662 let mut args = json!({ "action": "scrub", "points": points, "capture": capture });
663 if let Some(s) = selector {
664 args["selector"] = json!(s);
665 }
666 self.call_tool("animation", args).await
667 }
668
669 /// Arm the real-time motion recorder. Trigger the animation, then call
670 /// [`VictauriClient::animation_sample_read`] to read the measured curve.
671 ///
672 /// # Errors
673 ///
674 /// Returns errors from [`VictauriClient::call_tool`].
675 pub async fn animation_sample_arm(
676 &mut self,
677 selector: Option<&str>,
678 ) -> Result<Value, TestError> {
679 let mut args = json!({ "action": "sample", "record": true });
680 if let Some(s) = selector {
681 args["selector"] = json!(s);
682 }
683 self.call_tool("animation", args).await
684 }
685
686 /// Read back recorded motion sessions (per-frame curve + jank stats). Pass
687 /// `clear` to reset sessions afterwards.
688 ///
689 /// # Errors
690 ///
691 /// Returns errors from [`VictauriClient::call_tool`].
692 pub async fn animation_sample_read(&mut self, clear: bool) -> Result<Value, TestError> {
693 self.call_tool(
694 "animation",
695 json!({ "action": "sample", "record": false, "clear": clear }),
696 )
697 .await
698 }
699
700 /// Click an element by ref handle ID.
701 ///
702 /// # Errors
703 ///
704 /// Returns errors from [`VictauriClient::call_tool`].
705 pub async fn click(&mut self, ref_id: &str) -> Result<Value, TestError> {
706 self.call_tool("interact", json!({"action": "click", "ref_id": ref_id}))
707 .await
708 }
709
710 /// Fill an input element with a value.
711 ///
712 /// # Errors
713 ///
714 /// Returns errors from [`VictauriClient::call_tool`].
715 pub async fn fill(&mut self, ref_id: &str, value: &str) -> Result<Value, TestError> {
716 self.call_tool(
717 "input",
718 json!({"action": "fill", "ref_id": ref_id, "value": value}),
719 )
720 .await
721 }
722
723 /// Type text into an element character by character.
724 ///
725 /// # Errors
726 ///
727 /// Returns errors from [`VictauriClient::call_tool`].
728 pub async fn type_text(&mut self, ref_id: &str, text: &str) -> Result<Value, TestError> {
729 self.call_tool(
730 "input",
731 json!({"action": "type_text", "ref_id": ref_id, "text": text}),
732 )
733 .await
734 }
735
736 /// List all window labels.
737 ///
738 /// # Errors
739 ///
740 /// Returns errors from [`VictauriClient::call_tool`].
741 pub async fn list_windows(&mut self) -> Result<Value, TestError> {
742 self.call_tool("window", json!({"action": "list"})).await
743 }
744
745 /// Get the state of a specific window (or all windows).
746 ///
747 /// # Errors
748 ///
749 /// Returns errors from [`VictauriClient::call_tool`].
750 pub async fn get_window_state(&mut self, label: Option<&str>) -> Result<Value, TestError> {
751 let mut args = json!({"action": "get_state"});
752 if let Some(l) = label {
753 args["label"] = json!(l);
754 }
755 self.call_tool("window", args).await
756 }
757
758 /// Take a screenshot and return base64-encoded PNG.
759 ///
760 /// # Errors
761 ///
762 /// Returns errors from [`VictauriClient::call_tool`].
763 pub async fn screenshot(&mut self) -> Result<Value, TestError> {
764 self.call_tool("screenshot", json!({})).await
765 }
766
767 /// Take a screenshot and compare it against a stored baseline.
768 ///
769 /// Captures the current window, extracts the base64 PNG data, and passes
770 /// it to [`visual::compare_screenshot`](crate::visual::compare_screenshot).
771 /// On first run the screenshot is saved as the new baseline.
772 ///
773 /// # Errors
774 ///
775 /// Returns [`TestError::VisualRegression`] if the diff exceeds the
776 /// threshold, or [`TestError::Other`] if the screenshot result does not
777 /// contain recognizable image data.
778 pub async fn screenshot_visual(
779 &mut self,
780 name: &str,
781 options: &VisualOptions,
782 ) -> Result<VisualDiff, TestError> {
783 let result = self.screenshot().await?;
784 let base64_data = extract_screenshot_base64(&result)?;
785 crate::visual::compare_screenshot(name, &base64_data, options)
786 }
787
788 /// Invoke a Tauri command by name with optional arguments.
789 ///
790 /// # Errors
791 ///
792 /// Returns errors from [`VictauriClient::call_tool`].
793 pub async fn invoke_command(
794 &mut self,
795 command: &str,
796 args: Option<Value>,
797 ) -> Result<Value, TestError> {
798 let mut params = json!({"command": command});
799 if let Some(a) = args {
800 params["args"] = a;
801 }
802 self.call_tool("invoke_command", params).await
803 }
804
805 /// Get the IPC call log.
806 ///
807 /// # Errors
808 ///
809 /// Returns errors from [`VictauriClient::call_tool`].
810 pub async fn get_ipc_log(&mut self, limit: Option<usize>) -> Result<Value, TestError> {
811 let mut args = json!({"action": "ipc"});
812 if let Some(n) = limit {
813 args["limit"] = json!(n);
814 }
815 self.call_tool("logs", args).await
816 }
817
818 /// Verify frontend state against backend state.
819 ///
820 /// # Errors
821 ///
822 /// Returns errors from [`VictauriClient::call_tool`].
823 pub async fn verify_state(
824 &mut self,
825 frontend_expr: &str,
826 backend_state: Value,
827 ) -> Result<Value, TestError> {
828 self.call_tool(
829 "verify_state",
830 json!({
831 "frontend_expr": frontend_expr,
832 "backend_state": backend_state,
833 }),
834 )
835 .await
836 }
837
838 /// Detect ghost commands (registered but never called, or called but not registered).
839 ///
840 /// # Errors
841 ///
842 /// Returns errors from [`VictauriClient::call_tool`].
843 pub async fn detect_ghost_commands(&mut self) -> Result<Value, TestError> {
844 self.call_tool("detect_ghost_commands", json!({})).await
845 }
846
847 /// Check IPC call health (pending, stale, errored).
848 ///
849 /// # Errors
850 ///
851 /// Returns errors from [`VictauriClient::call_tool`].
852 pub async fn check_ipc_integrity(&mut self) -> Result<Value, TestError> {
853 self.call_tool("check_ipc_integrity", json!({})).await
854 }
855
856 /// Run a semantic assertion against a JS expression.
857 ///
858 /// # Errors
859 ///
860 /// Returns errors from [`VictauriClient::call_tool`].
861 pub async fn assert_semantic(
862 &mut self,
863 expression: &str,
864 label: &str,
865 condition: &str,
866 expected: Value,
867 ) -> Result<Value, TestError> {
868 self.call_tool(
869 "assert_semantic",
870 json!({
871 "expression": expression,
872 "label": label,
873 "condition": condition,
874 "expected": expected,
875 }),
876 )
877 .await
878 }
879
880 /// Run an accessibility audit.
881 ///
882 /// # Errors
883 ///
884 /// Returns errors from [`VictauriClient::call_tool`].
885 pub async fn audit_accessibility(&mut self) -> Result<Value, TestError> {
886 self.call_tool("inspect", json!({"action": "audit_accessibility"}))
887 .await
888 }
889
890 /// Get performance metrics (timing, heap, resources).
891 ///
892 /// # Errors
893 ///
894 /// Returns errors from [`VictauriClient::call_tool`].
895 pub async fn get_performance_metrics(&mut self) -> Result<Value, TestError> {
896 self.call_tool("inspect", json!({"action": "get_performance"}))
897 .await
898 }
899
900 /// Get the command registry.
901 ///
902 /// # Errors
903 ///
904 /// Returns errors from [`VictauriClient::call_tool`].
905 pub async fn get_registry(&mut self) -> Result<Value, TestError> {
906 self.call_tool("get_registry", json!({})).await
907 }
908
909 /// Get process memory statistics.
910 ///
911 /// # Errors
912 ///
913 /// Returns errors from [`VictauriClient::call_tool`].
914 pub async fn get_memory_stats(&mut self) -> Result<Value, TestError> {
915 self.call_tool("get_memory_stats", json!({})).await
916 }
917
918 /// Read plugin info (version, uptime, tool count).
919 ///
920 /// # Errors
921 ///
922 /// Returns errors from [`VictauriClient::call_tool`].
923 pub async fn get_plugin_info(&mut self) -> Result<Value, TestError> {
924 self.call_tool("get_plugin_info", json!({})).await
925 }
926
927 /// Run environment diagnostics to detect potential compatibility issues.
928 ///
929 /// Checks for service workers, closed shadow DOM, iframes, large DOM,
930 /// and CSP status. Returns warnings and environment info.
931 ///
932 /// # Errors
933 ///
934 /// Returns errors from [`VictauriClient::call_tool`].
935 pub async fn get_diagnostics(&mut self) -> Result<Value, TestError> {
936 self.call_tool("get_diagnostics", json!({})).await
937 }
938
939 // ── Backend Access ─────────────────────────────────────────────────────
940
941 /// Get app info: Tauri config, directory paths, env vars, discovered databases.
942 ///
943 /// # Errors
944 ///
945 /// Returns errors from [`VictauriClient::call_tool`].
946 pub async fn app_info(&mut self) -> Result<Value, TestError> {
947 self.call_tool("app_info", json!({})).await
948 }
949
950 /// List files in an app directory (data, config, log, or `local_data`).
951 ///
952 /// # Errors
953 ///
954 /// Returns errors from [`VictauriClient::call_tool`].
955 pub async fn list_app_dir(
956 &mut self,
957 directory: Option<&str>,
958 path: Option<&str>,
959 ) -> Result<Value, TestError> {
960 let mut args = json!({});
961 if let Some(d) = directory {
962 args["directory"] = json!(d);
963 }
964 if let Some(p) = path {
965 args["path"] = json!(p);
966 }
967 self.call_tool("list_app_dir", args).await
968 }
969
970 /// Read a file from an app directory.
971 ///
972 /// # Errors
973 ///
974 /// Returns errors from [`VictauriClient::call_tool`].
975 pub async fn read_app_file(
976 &mut self,
977 path: &str,
978 directory: Option<&str>,
979 ) -> Result<Value, TestError> {
980 let mut args = json!({"path": path});
981 if let Some(d) = directory {
982 args["directory"] = json!(d);
983 }
984 self.call_tool("read_app_file", args).await
985 }
986
987 /// Execute a read-only SQL query against a `SQLite` database in the app data directory.
988 ///
989 /// # Errors
990 ///
991 /// Returns errors from [`VictauriClient::call_tool`].
992 pub async fn query_db(
993 &mut self,
994 query: &str,
995 db_path: Option<&str>,
996 params: Option<Vec<Value>>,
997 ) -> Result<Value, TestError> {
998 let mut args = json!({"query": query});
999 if let Some(p) = db_path {
1000 args["path"] = json!(p);
1001 }
1002 if let Some(params) = params {
1003 args["params"] = json!(params);
1004 }
1005 self.call_tool("query_db", args).await
1006 }
1007
1008 /// Wait for a condition to be met, polling at an interval.
1009 ///
1010 /// Conditions: `text`, `text_gone`, `selector`, `selector_gone`, `url`,
1011 /// `ipc_idle`, `network_idle`.
1012 ///
1013 /// # Errors
1014 ///
1015 /// Returns errors from [`VictauriClient::call_tool`].
1016 pub async fn wait_for(
1017 &mut self,
1018 condition: &str,
1019 value: Option<&str>,
1020 timeout_ms: Option<u64>,
1021 poll_ms: Option<u64>,
1022 ) -> Result<Value, TestError> {
1023 let mut args = json!({"condition": condition});
1024 if let Some(v) = value {
1025 args["value"] = json!(v);
1026 }
1027 if let Some(t) = timeout_ms {
1028 args["timeout_ms"] = json!(t);
1029 }
1030 if let Some(p) = poll_ms {
1031 args["poll_ms"] = json!(p);
1032 }
1033 self.call_tool("wait_for", args).await
1034 }
1035
1036 /// Poll a JavaScript expression until it is truthy (or equals `expected`),
1037 /// awaited server-side. This is the level-triggered, race-free way to wait
1038 /// for a fire-and-forget backend command to finish: pass an expression that
1039 /// reads a pollable status (it may `await`).
1040 ///
1041 /// Returns `{ ok: true, value, elapsed_ms }` on success or
1042 /// `{ ok: false, error, last_value, last_error, elapsed_ms }` on timeout.
1043 ///
1044 /// # Errors
1045 ///
1046 /// Returns errors from [`VictauriClient::call_tool`].
1047 pub async fn wait_for_expression(
1048 &mut self,
1049 expression: &str,
1050 expected: Option<Value>,
1051 timeout_ms: Option<u64>,
1052 poll_ms: Option<u64>,
1053 ) -> Result<Value, TestError> {
1054 let mut args = json!({ "condition": "expression", "value": expression });
1055 if let Some(e) = expected {
1056 args["expected"] = e;
1057 }
1058 if let Some(t) = timeout_ms {
1059 args["timeout_ms"] = json!(t);
1060 }
1061 if let Some(p) = poll_ms {
1062 args["poll_ms"] = json!(p);
1063 }
1064 self.call_tool("wait_for", args).await
1065 }
1066
1067 /// Block until a named Tauri event fires on the app's event bus.
1068 ///
1069 /// Edge-triggered completion with a `since_ms` look-back (default 2000) so an
1070 /// event that fired between an `invoke_command` and this call is still caught.
1071 /// The app must emit the event and Victauri must capture it (custom events
1072 /// require `VictauriBuilder::listen_events`).
1073 ///
1074 /// Returns `{ ok: true, event: { name, payload, timestamp }, elapsed_ms }` on
1075 /// success or `{ ok: false, error, hint, elapsed_ms }` on timeout.
1076 ///
1077 /// # Errors
1078 ///
1079 /// Returns errors from [`VictauriClient::call_tool`].
1080 pub async fn wait_for_event(
1081 &mut self,
1082 event: &str,
1083 since_ms: Option<u64>,
1084 timeout_ms: Option<u64>,
1085 poll_ms: Option<u64>,
1086 ) -> Result<Value, TestError> {
1087 let mut args = json!({ "condition": "event", "value": event });
1088 if let Some(s) = since_ms {
1089 args["since_ms"] = json!(s);
1090 }
1091 if let Some(t) = timeout_ms {
1092 args["timeout_ms"] = json!(t);
1093 }
1094 if let Some(p) = poll_ms {
1095 args["poll_ms"] = json!(p);
1096 }
1097 self.call_tool("wait_for", args).await
1098 }
1099
1100 /// Read application-defined backend state via a registered probe.
1101 ///
1102 /// With `probe = None`, returns `{ "probes": [names...] }`. With a probe name,
1103 /// returns that probe's JSON snapshot. Probes are registered by the app via
1104 /// `VictauriBuilder::probe`.
1105 ///
1106 /// # Errors
1107 ///
1108 /// Returns errors from [`VictauriClient::call_tool`].
1109 pub async fn app_state(&mut self, probe: Option<&str>) -> Result<Value, TestError> {
1110 let args = match probe {
1111 Some(name) => json!({ "probe": name }),
1112 None => json!({}),
1113 };
1114 self.call_tool("app_state", args).await
1115 }
1116
1117 /// Start a time-travel recording session.
1118 ///
1119 /// # Errors
1120 ///
1121 /// Returns errors from [`VictauriClient::call_tool`].
1122 pub async fn start_recording(&mut self, session_id: Option<&str>) -> Result<Value, TestError> {
1123 let mut args = json!({"action": "start"});
1124 if let Some(id) = session_id {
1125 args["session_id"] = json!(id);
1126 }
1127 self.call_tool("recording", args).await
1128 }
1129
1130 /// Stop the recording and return the session.
1131 ///
1132 /// # Errors
1133 ///
1134 /// Returns errors from [`VictauriClient::call_tool`].
1135 pub async fn stop_recording(&mut self) -> Result<Value, TestError> {
1136 self.call_tool("recording", json!({"action": "stop"})).await
1137 }
1138
1139 /// Export the current recording session as JSON.
1140 ///
1141 /// # Errors
1142 ///
1143 /// Returns errors from [`VictauriClient::call_tool`].
1144 pub async fn export_session(&mut self) -> Result<Value, TestError> {
1145 self.call_tool("recording", json!({"action": "export"}))
1146 .await
1147 }
1148
1149 /// Search for elements by various criteria without a full snapshot.
1150 ///
1151 /// # Errors
1152 ///
1153 /// Returns errors from [`VictauriClient::call_tool`].
1154 pub async fn find_elements(&mut self, query: Value) -> Result<Value, TestError> {
1155 self.call_tool("find_elements", query).await
1156 }
1157
1158 /// Double-click an element by ref handle ID.
1159 ///
1160 /// # Errors
1161 ///
1162 /// Returns errors from [`VictauriClient::call_tool`].
1163 pub async fn double_click(&mut self, ref_id: &str) -> Result<Value, TestError> {
1164 self.call_tool(
1165 "interact",
1166 json!({"action": "double_click", "ref_id": ref_id}),
1167 )
1168 .await
1169 }
1170
1171 /// Hover over an element by ref handle.
1172 ///
1173 /// # Errors
1174 ///
1175 /// Returns errors from [`VictauriClient::call_tool`].
1176 pub async fn hover(&mut self, ref_id: &str) -> Result<Value, TestError> {
1177 self.call_tool("interact", json!({"action": "hover", "ref_id": ref_id}))
1178 .await
1179 }
1180
1181 /// Focus an element by ref handle.
1182 ///
1183 /// # Errors
1184 ///
1185 /// Returns errors from [`VictauriClient::call_tool`].
1186 pub async fn focus(&mut self, ref_id: &str) -> Result<Value, TestError> {
1187 self.call_tool("interact", json!({"action": "focus", "ref_id": ref_id}))
1188 .await
1189 }
1190
1191 /// Press a keyboard key.
1192 ///
1193 /// # Errors
1194 ///
1195 /// Returns errors from [`VictauriClient::call_tool`].
1196 pub async fn press_key(&mut self, key: &str) -> Result<Value, TestError> {
1197 self.call_tool("input", json!({"action": "press_key", "key": key}))
1198 .await
1199 }
1200
1201 /// Navigate to a URL.
1202 ///
1203 /// # Errors
1204 ///
1205 /// Returns errors from [`VictauriClient::call_tool`].
1206 pub async fn navigate(&mut self, url: &str) -> Result<Value, TestError> {
1207 self.call_tool("navigate", json!({"action": "go_to", "url": url}))
1208 .await
1209 }
1210
1211 /// Get logs by type (console, network, ipc, navigation, dialogs).
1212 ///
1213 /// # Errors
1214 ///
1215 /// Returns errors from [`VictauriClient::call_tool`].
1216 pub async fn logs(&mut self, action: &str, limit: Option<usize>) -> Result<Value, TestError> {
1217 self.call_tool("logs", json!({"action": action, "limit": limit}))
1218 .await
1219 }
1220
1221 /// Scroll an element into view by ref handle.
1222 ///
1223 /// # Errors
1224 ///
1225 /// Returns errors from [`VictauriClient::call_tool`].
1226 pub async fn scroll_to(&mut self, ref_id: &str) -> Result<Value, TestError> {
1227 self.call_tool(
1228 "interact",
1229 json!({"action": "scroll_into_view", "ref_id": ref_id}),
1230 )
1231 .await
1232 }
1233
1234 /// Select option(s) in a `<select>` element.
1235 ///
1236 /// # Errors
1237 ///
1238 /// Returns errors from [`VictauriClient::call_tool`].
1239 pub async fn select_option(
1240 &mut self,
1241 ref_id: &str,
1242 values: &[&str],
1243 ) -> Result<Value, TestError> {
1244 self.call_tool(
1245 "interact",
1246 json!({"action": "select_option", "ref_id": ref_id, "values": values}),
1247 )
1248 .await
1249 }
1250
1251 /// Get the server base URL.
1252 #[must_use]
1253 pub fn base_url(&self) -> &str {
1254 &self.base_url
1255 }
1256
1257 /// Get the host the client is connected to.
1258 #[must_use]
1259 pub fn host(&self) -> &str {
1260 &self.host
1261 }
1262
1263 /// Get the port the client is connected to.
1264 #[must_use]
1265 pub fn port(&self) -> u16 {
1266 self.port
1267 }
1268
1269 /// Get the MCP session ID.
1270 #[must_use]
1271 pub fn session_id(&self) -> &str {
1272 &self.session_id
1273 }
1274
1275 pub(crate) fn http_client(&self) -> &reqwest::Client {
1276 &self.http
1277 }
1278
1279 // ── IPC Log Helpers ───────────────────────────────────────────────────────
1280
1281 /// Get IPC calls filtered to a specific command.
1282 ///
1283 /// Returns a Vec of all IPC log entries matching the given command name.
1284 ///
1285 /// # Errors
1286 ///
1287 /// Returns errors from [`VictauriClient::call_tool`].
1288 #[deprecated(since = "0.2.0", note = "renamed to get_ipc_calls_for")]
1289 pub async fn get_ipc_calls(&mut self, command: &str) -> Result<Vec<Value>, TestError> {
1290 let log = self.get_ipc_log(None).await?;
1291 let entries = if let Some(arr) = log.as_array() {
1292 arr.clone()
1293 } else if let Some(entries) = log.get("entries").and_then(Value::as_array) {
1294 entries.clone()
1295 } else {
1296 return Ok(Vec::new());
1297 };
1298 Ok(entries
1299 .into_iter()
1300 .filter(|e| {
1301 e.get("command")
1302 .and_then(Value::as_str)
1303 .is_some_and(|c| c == command)
1304 })
1305 .collect())
1306 }
1307
1308 /// Get IPC calls made since a previous checkpoint.
1309 ///
1310 /// # Errors
1311 ///
1312 /// Returns errors from [`VictauriClient::call_tool`].
1313 #[deprecated(since = "0.2.0", note = "renamed to get_ipc_calls_since")]
1314 pub async fn ipc_calls_since(&mut self, checkpoint: usize) -> Result<Vec<Value>, TestError> {
1315 let log = self.get_ipc_log(None).await?;
1316 let entries = if let Some(arr) = log.as_array() {
1317 arr.clone()
1318 } else if let Some(entries) = log.get("entries").and_then(Value::as_array) {
1319 entries.clone()
1320 } else {
1321 return Ok(Vec::new());
1322 };
1323 Ok(entries.into_iter().skip(checkpoint).collect())
1324 }
1325
1326 /// Filter the IPC log for calls to a specific command.
1327 ///
1328 /// # Errors
1329 ///
1330 /// Returns errors from [`VictauriClient::call_tool`].
1331 pub async fn get_ipc_calls_for(&mut self, command: &str) -> Result<Vec<Value>, TestError> {
1332 #[allow(deprecated)]
1333 self.get_ipc_calls(command).await
1334 }
1335
1336 /// Get IPC calls made since a previous checkpoint.
1337 ///
1338 /// # Errors
1339 ///
1340 /// Returns errors from [`VictauriClient::call_tool`].
1341 pub async fn get_ipc_calls_since(
1342 &mut self,
1343 checkpoint: usize,
1344 ) -> Result<Vec<Value>, TestError> {
1345 #[allow(deprecated)]
1346 self.ipc_calls_since(checkpoint).await
1347 }
1348
1349 // ── Builder-Style Wait (Phase 4B) ──────────────────────────────────────────
1350
1351 /// Start a builder-style wait for a condition.
1352 ///
1353 /// This is a fluent alternative to [`VictauriClient::wait_for`] that avoids
1354 /// positional `Option` arguments.
1355 ///
1356 /// # Examples
1357 ///
1358 /// ```rust,ignore
1359 /// client.wait("text")
1360 /// .value("Welcome")
1361 /// .timeout_ms(5000)
1362 /// .run()
1363 /// .await
1364 /// .unwrap();
1365 /// ```
1366 pub fn wait(&mut self, condition: &str) -> WaitForBuilder<'_> {
1367 WaitForBuilder {
1368 client: self,
1369 condition: condition.to_string(),
1370 value: None,
1371 timeout_ms: 10_000,
1372 poll_ms: 200,
1373 }
1374 }
1375
1376 // ── Deprecated Aliases (Phase 4C) ────────────────────────────────────────
1377
1378 /// Snapshot the current IPC log length, for use with `ipc_calls_since`.
1379 ///
1380 /// Prefer [`VictauriClient::create_ipc_checkpoint`] — this alias exists
1381 /// for backwards compatibility.
1382 ///
1383 /// # Errors
1384 ///
1385 /// Returns errors from [`VictauriClient::call_tool`].
1386 #[deprecated(since = "0.2.0", note = "renamed to create_ipc_checkpoint")]
1387 pub async fn ipc_checkpoint(&mut self) -> Result<usize, TestError> {
1388 self.create_ipc_checkpoint().await
1389 }
1390
1391 /// Snapshot the current IPC log length, for use with `ipc_calls_since`.
1392 ///
1393 /// Returns the number of IPC calls recorded so far. Pass this value to
1394 /// [`VictauriClient::ipc_calls_since`] to get only the calls that occurred
1395 /// after the checkpoint.
1396 ///
1397 /// # Errors
1398 ///
1399 /// Returns errors from [`VictauriClient::call_tool`].
1400 pub async fn create_ipc_checkpoint(&mut self) -> Result<usize, TestError> {
1401 let log = self.get_ipc_log(None).await?;
1402 let len = if let Some(arr) = log.as_array() {
1403 arr.len()
1404 } else if let Some(entries) = log.get("entries").and_then(Value::as_array) {
1405 entries.len()
1406 } else {
1407 0
1408 };
1409 Ok(len)
1410 }
1411
1412 // ── Typed Response Methods (Phase 4E) ────────────────────────────────────
1413
1414 /// Read plugin info as a typed [`PluginInfo`] struct.
1415 ///
1416 /// This is a typed alternative to [`VictauriClient::get_plugin_info`] which
1417 /// returns raw JSON.
1418 ///
1419 /// # Errors
1420 ///
1421 /// Returns [`TestError::Other`] if the response cannot be deserialized.
1422 /// Returns other errors from [`VictauriClient::call_tool`].
1423 pub async fn plugin_info(&mut self) -> Result<PluginInfo, TestError> {
1424 let value = self.get_plugin_info().await?;
1425 serde_json::from_value(value)
1426 .map_err(|e| TestError::Other(format!("failed to deserialize PluginInfo: {e}")))
1427 }
1428
1429 /// Read process memory statistics as a typed [`MemoryStats`] struct.
1430 ///
1431 /// This is a typed alternative to [`VictauriClient::get_memory_stats`] which
1432 /// returns raw JSON.
1433 ///
1434 /// # Errors
1435 ///
1436 /// Returns [`TestError::Other`] if the response cannot be deserialized.
1437 /// Returns other errors from [`VictauriClient::call_tool`].
1438 pub async fn memory_stats(&mut self) -> Result<MemoryStats, TestError> {
1439 let value = self.get_memory_stats().await?;
1440 serde_json::from_value(value)
1441 .map_err(|e| TestError::Other(format!("failed to deserialize MemoryStats: {e}")))
1442 }
1443
1444 // ── Fluent Verification Builder ───────────────────────────────────────────
1445
1446 /// Start a fluent verification chain that checks multiple conditions at once.
1447 ///
1448 /// Unlike individual assertions that panic on failure, `verify()` collects
1449 /// all results and reports them together — making test failures more
1450 /// informative and reducing test reruns.
1451 ///
1452 /// # Examples
1453 ///
1454 /// ```rust,ignore
1455 /// let report = client.verify()
1456 /// .has_text("Welcome")
1457 /// .ipc_was_called("greet")
1458 /// .no_console_errors()
1459 /// .run()
1460 /// .await
1461 /// .unwrap();
1462 /// report.assert_all_passed();
1463 /// ```
1464 pub fn verify(&mut self) -> VerifyBuilder<'_> {
1465 VerifyBuilder::new(self)
1466 }
1467
1468 // ── High-Level Playwright-Style API ─────────────────────────────────────
1469
1470 /// Click the first element whose accessible text contains the given string.
1471 ///
1472 /// Takes a DOM snapshot, finds the element, and clicks it.
1473 ///
1474 /// # Errors
1475 ///
1476 /// Returns [`TestError::ElementNotFound`] if no matching element is found.
1477 /// Returns other errors from [`VictauriClient::call_tool`].
1478 pub async fn click_by_text(&mut self, text: &str) -> Result<Value, TestError> {
1479 let ref_id = self.find_ref_by_text(text).await?;
1480 self.click(&ref_id).await
1481 }
1482
1483 /// Click the element with the given HTML `id` attribute.
1484 ///
1485 /// # Errors
1486 ///
1487 /// Returns [`TestError::ElementNotFound`] if no element has the given id.
1488 /// Returns other errors from [`VictauriClient::call_tool`].
1489 pub async fn click_by_id(&mut self, id: &str) -> Result<Value, TestError> {
1490 let ref_id = self.find_ref_by_id(id).await?;
1491 self.click(&ref_id).await
1492 }
1493
1494 /// Double-click the first element whose accessible text contains the given string.
1495 ///
1496 /// # Errors
1497 ///
1498 /// Returns [`TestError::ElementNotFound`] if no matching element is found.
1499 /// Returns other errors from [`VictauriClient::call_tool`].
1500 pub async fn double_click_by_text(&mut self, text: &str) -> Result<Value, TestError> {
1501 let ref_id = self.find_ref_by_text(text).await?;
1502 self.double_click(&ref_id).await
1503 }
1504
1505 /// Double-click the element with the given HTML `id` attribute.
1506 ///
1507 /// # Errors
1508 ///
1509 /// Returns [`TestError::ElementNotFound`] if no element has the given id.
1510 /// Returns other errors from [`VictauriClient::call_tool`].
1511 pub async fn double_click_by_id(&mut self, id: &str) -> Result<Value, TestError> {
1512 let ref_id = self.find_ref_by_id(id).await?;
1513 self.double_click(&ref_id).await
1514 }
1515
1516 /// Double-click the first element matching a CSS selector.
1517 ///
1518 /// Resolves the selector via `find_elements`, then double-clicks the first match.
1519 ///
1520 /// # Errors
1521 ///
1522 /// Returns [`TestError::ElementNotFound`] if no element matches the selector.
1523 /// Returns other errors from [`VictauriClient::call_tool`].
1524 pub async fn double_click_by_selector(&mut self, selector: &str) -> Result<Value, TestError> {
1525 let ref_id = self.find_ref_by_selector(selector).await?;
1526 self.double_click(&ref_id).await
1527 }
1528
1529 /// Click the first element matching a CSS selector.
1530 ///
1531 /// Resolves the selector via `find_elements`, then clicks the first match.
1532 ///
1533 /// # Errors
1534 ///
1535 /// Returns [`TestError::ElementNotFound`] if no element matches the selector.
1536 /// Returns other errors from [`VictauriClient::call_tool`].
1537 pub async fn click_by_selector(&mut self, selector: &str) -> Result<Value, TestError> {
1538 let ref_id = self.find_ref_by_selector(selector).await?;
1539 self.click(&ref_id).await
1540 }
1541
1542 /// Fill an input identified by HTML `id` with the given value.
1543 ///
1544 /// # Errors
1545 ///
1546 /// Returns [`TestError::ElementNotFound`] if no element has the given id.
1547 /// Returns other errors from [`VictauriClient::call_tool`].
1548 pub async fn fill_by_id(&mut self, id: &str, value: &str) -> Result<Value, TestError> {
1549 let ref_id = self.find_ref_by_id(id).await?;
1550 self.fill(&ref_id, value).await
1551 }
1552
1553 /// Fill an input whose accessible text contains the given string.
1554 ///
1555 /// # Errors
1556 ///
1557 /// Returns [`TestError::ElementNotFound`] if no matching element is found.
1558 /// Returns other errors from [`VictauriClient::call_tool`].
1559 pub async fn fill_by_text(&mut self, text: &str, value: &str) -> Result<Value, TestError> {
1560 let ref_id = self.find_ref_by_text(text).await?;
1561 self.fill(&ref_id, value).await
1562 }
1563
1564 /// Fill an input matching a CSS selector with the given value.
1565 ///
1566 /// Resolves the selector via `find_elements`, then fills the first match.
1567 ///
1568 /// # Errors
1569 ///
1570 /// Returns [`TestError::ElementNotFound`] if no element matches the selector.
1571 /// Returns other errors from [`VictauriClient::call_tool`].
1572 pub async fn fill_by_selector(
1573 &mut self,
1574 selector: &str,
1575 value: &str,
1576 ) -> Result<Value, TestError> {
1577 let ref_id = self.find_ref_by_selector(selector).await?;
1578 self.fill(&ref_id, value).await
1579 }
1580
1581 /// Type text into an input identified by HTML `id`, character by character.
1582 ///
1583 /// # Errors
1584 ///
1585 /// Returns [`TestError::ElementNotFound`] if no element has the given id.
1586 /// Returns other errors from [`VictauriClient::call_tool`].
1587 pub async fn type_by_id(&mut self, id: &str, text: &str) -> Result<Value, TestError> {
1588 let ref_id = self.find_ref_by_id(id).await?;
1589 self.type_text(&ref_id, text).await
1590 }
1591
1592 /// Wait until the page contains the given text (polls DOM snapshots).
1593 ///
1594 /// Default timeout: 5000ms, poll interval: 200ms.
1595 ///
1596 /// # Errors
1597 ///
1598 /// Returns [`TestError::Timeout`] if the text doesn't appear within the timeout.
1599 /// Returns other errors from [`VictauriClient::call_tool`].
1600 pub async fn expect_text(&mut self, text: &str) -> Result<(), TestError> {
1601 self.expect_text_with_timeout(text, 5000).await
1602 }
1603
1604 /// Wait until the page contains the given text, with a custom timeout in ms.
1605 ///
1606 /// # Errors
1607 ///
1608 /// Returns [`TestError::Timeout`] if the text doesn't appear within the timeout.
1609 /// Returns other errors from [`VictauriClient::call_tool`].
1610 pub async fn expect_text_with_timeout(
1611 &mut self,
1612 text: &str,
1613 timeout_ms: u64,
1614 ) -> Result<(), TestError> {
1615 let result = self
1616 .wait_for("text", Some(text), Some(timeout_ms), Some(200))
1617 .await?;
1618 if result.get("ok").and_then(Value::as_bool) == Some(true) {
1619 Ok(())
1620 } else {
1621 Err(TestError::Timeout(format!(
1622 "text \"{text}\" did not appear within {timeout_ms}ms"
1623 )))
1624 }
1625 }
1626
1627 /// Wait until the page no longer contains the given text.
1628 ///
1629 /// Default timeout: 3000ms, poll interval: 200ms.
1630 ///
1631 /// # Errors
1632 ///
1633 /// Returns [`TestError::Timeout`] if the text is still present after the timeout.
1634 /// Returns other errors from [`VictauriClient::call_tool`].
1635 pub async fn expect_no_text(&mut self, text: &str) -> Result<(), TestError> {
1636 let result = self
1637 .wait_for("text_gone", Some(text), Some(3000), Some(200))
1638 .await?;
1639 if result.get("ok").and_then(Value::as_bool) == Some(true) {
1640 Ok(())
1641 } else {
1642 Err(TestError::Timeout(format!(
1643 "text \"{text}\" still present after 3000ms"
1644 )))
1645 }
1646 }
1647
1648 /// Select an option in a `<select>` element identified by HTML `id`.
1649 ///
1650 /// # Errors
1651 ///
1652 /// Returns [`TestError::ElementNotFound`] if no element has the given id.
1653 /// Returns other errors from [`VictauriClient::call_tool`].
1654 pub async fn select_by_id(&mut self, id: &str, value: &str) -> Result<Value, TestError> {
1655 let ref_id = self.find_ref_by_id(id).await?;
1656 self.select_option(&ref_id, &[value]).await
1657 }
1658
1659 /// Select option(s) in a `<select>` element identified by HTML `id`.
1660 ///
1661 /// Accepts multiple values for multi-select elements.
1662 ///
1663 /// # Errors
1664 ///
1665 /// Returns [`TestError::ElementNotFound`] if no element has the given id.
1666 /// Returns other errors from [`VictauriClient::call_tool`].
1667 pub async fn select_option_by_id(
1668 &mut self,
1669 id: &str,
1670 values: &[&str],
1671 ) -> Result<Value, TestError> {
1672 let ref_id = self.find_ref_by_id(id).await?;
1673 self.select_option(&ref_id, values).await
1674 }
1675
1676 /// Select option(s) in a `<select>` element whose accessible text contains
1677 /// the given string.
1678 ///
1679 /// # Errors
1680 ///
1681 /// Returns [`TestError::ElementNotFound`] if no matching element is found.
1682 /// Returns other errors from [`VictauriClient::call_tool`].
1683 pub async fn select_option_by_text(
1684 &mut self,
1685 text: &str,
1686 values: &[&str],
1687 ) -> Result<Value, TestError> {
1688 let ref_id = self.find_ref_by_text(text).await?;
1689 self.select_option(&ref_id, values).await
1690 }
1691
1692 /// Select option(s) in a `<select>` element matching a CSS selector.
1693 ///
1694 /// Resolves the selector via `find_elements`, then selects in the first match.
1695 ///
1696 /// # Errors
1697 ///
1698 /// Returns [`TestError::ElementNotFound`] if no element matches the selector.
1699 /// Returns other errors from [`VictauriClient::call_tool`].
1700 pub async fn select_option_by_selector(
1701 &mut self,
1702 selector: &str,
1703 values: &[&str],
1704 ) -> Result<Value, TestError> {
1705 let ref_id = self.find_ref_by_selector(selector).await?;
1706 self.select_option(&ref_id, values).await
1707 }
1708
1709 /// Scroll an element matching a CSS selector into view.
1710 ///
1711 /// Resolves the selector via `find_elements`, then scrolls the first match.
1712 ///
1713 /// # Errors
1714 ///
1715 /// Returns [`TestError::ElementNotFound`] if no element matches the selector.
1716 /// Returns other errors from [`VictauriClient::call_tool`].
1717 pub async fn scroll_to_by_selector(&mut self, selector: &str) -> Result<Value, TestError> {
1718 let ref_id = self.find_ref_by_selector(selector).await?;
1719 self.scroll_to(&ref_id).await
1720 }
1721
1722 /// Scroll an element with the given HTML `id` into view.
1723 ///
1724 /// # Errors
1725 ///
1726 /// Returns [`TestError::ElementNotFound`] if no element has the given id.
1727 /// Returns other errors from [`VictauriClient::call_tool`].
1728 pub async fn scroll_to_by_id(&mut self, id: &str) -> Result<Value, TestError> {
1729 let ref_id = self.find_ref_by_id(id).await?;
1730 self.scroll_to(&ref_id).await
1731 }
1732
1733 /// Get the text content of an element identified by HTML `id`.
1734 ///
1735 /// # Errors
1736 ///
1737 /// Returns [`TestError::ElementNotFound`] if no element has the given id.
1738 /// Returns other errors from [`VictauriClient::call_tool`].
1739 pub async fn text_by_id(&mut self, id: &str) -> Result<String, TestError> {
1740 let snap = self.snapshot_json().await?;
1741 let tree = &snap["tree"];
1742 find_text_by_attr_id(tree, id)
1743 .ok_or_else(|| TestError::ElementNotFound(format!("id=\"{id}\"")))
1744 }
1745
1746 // ── Internal helpers for high-level API ─────────────────────────────────
1747
1748 async fn snapshot_json(&mut self) -> Result<Value, TestError> {
1749 self.call_tool("dom_snapshot", json!({"format": "json"}))
1750 .await
1751 }
1752
1753 async fn find_ref_by_text(&mut self, text: &str) -> Result<String, TestError> {
1754 let snap = self.snapshot_json().await?;
1755 let tree = &snap["tree"];
1756 find_in_tree_by_text(tree, text)
1757 .ok_or_else(|| TestError::ElementNotFound(format!("text=\"{text}\"")))
1758 }
1759
1760 async fn find_ref_by_id(&mut self, id: &str) -> Result<String, TestError> {
1761 let snap = self.snapshot_json().await?;
1762 let tree = &snap["tree"];
1763 find_in_tree_by_attr_id(tree, id)
1764 .ok_or_else(|| TestError::ElementNotFound(format!("id=\"{id}\"")))
1765 }
1766
1767 async fn find_ref_by_selector(&mut self, selector: &str) -> Result<String, TestError> {
1768 let result = self.find_elements(json!({"selector": selector})).await?;
1769 // find_elements returns an array of matched elements with ref_id fields
1770 let elements = result
1771 .as_array()
1772 .or_else(|| result.get("elements").and_then(Value::as_array));
1773 if let Some(elems) = elements
1774 && let Some(first) = elems.first()
1775 && let Some(ref_id) = first.get("ref_id").and_then(Value::as_str)
1776 {
1777 return Ok(ref_id.to_string());
1778 }
1779 Err(TestError::ElementNotFound(format!(
1780 "selector=\"{selector}\""
1781 )))
1782 }
1783
1784 // ── Locator Factories ──────────────────────────────────────────────────
1785
1786 /// Create a [`Locator`](crate::Locator) matching elements by ARIA role.
1787 ///
1788 /// Equivalent to Playwright's `page.getByRole()`.
1789 #[must_use]
1790 pub fn get_by_role(&self, role: &str) -> crate::locator::Locator {
1791 crate::locator::Locator::role(role)
1792 }
1793
1794 /// Create a [`Locator`](crate::Locator) matching elements by visible text content.
1795 ///
1796 /// Equivalent to Playwright's `page.getByText()`.
1797 #[must_use]
1798 pub fn get_by_text(&self, text: &str) -> crate::locator::Locator {
1799 crate::locator::Locator::text(text)
1800 }
1801
1802 /// Create a [`Locator`](crate::Locator) matching elements by `data-testid` attribute.
1803 ///
1804 /// Equivalent to Playwright's `page.getByTestId()`.
1805 #[must_use]
1806 pub fn get_by_test_id(&self, id: &str) -> crate::locator::Locator {
1807 crate::locator::Locator::test_id(id)
1808 }
1809
1810 /// Create a [`Locator`](crate::Locator) matching form controls by associated label text.
1811 ///
1812 /// Equivalent to Playwright's `page.getByLabel()`.
1813 #[must_use]
1814 pub fn get_by_label(&self, text: &str) -> crate::locator::Locator {
1815 crate::locator::Locator::label(text)
1816 }
1817
1818 /// Create a [`Locator`](crate::Locator) matching elements by placeholder text.
1819 ///
1820 /// Equivalent to Playwright's `page.getByPlaceholder()`.
1821 #[must_use]
1822 pub fn get_by_placeholder(&self, text: &str) -> crate::locator::Locator {
1823 crate::locator::Locator::placeholder(text)
1824 }
1825
1826 /// Create a [`Locator`](crate::Locator) matching elements by CSS selector.
1827 ///
1828 /// Equivalent to Playwright's `page.locator()`.
1829 #[must_use]
1830 pub fn locator(&self, css: &str) -> crate::locator::Locator {
1831 crate::locator::Locator::css(css)
1832 }
1833
1834 /// Create a [`Locator`](crate::Locator) matching elements by alt text (images).
1835 ///
1836 /// Equivalent to Playwright's `page.getByAltText()`.
1837 #[must_use]
1838 pub fn get_by_alt_text(&self, alt: &str) -> crate::locator::Locator {
1839 crate::locator::Locator::alt_text(alt)
1840 }
1841
1842 /// Create a [`Locator`](crate::Locator) matching elements by title attribute.
1843 ///
1844 /// Equivalent to Playwright's `page.getByTitle()`.
1845 #[must_use]
1846 pub fn get_by_title(&self, title: &str) -> crate::locator::Locator {
1847 crate::locator::Locator::title(title)
1848 }
1849
1850 // ── Screenshot to File ─────────────────────────────────────────────────
1851
1852 /// Take a screenshot and save it to a file on disk.
1853 ///
1854 /// Captures the default window, decodes the base64 PNG, and writes it
1855 /// to the given path. Returns the canonical path of the saved file.
1856 ///
1857 /// # Errors
1858 ///
1859 /// Returns [`TestError::Other`] if the screenshot cannot be captured,
1860 /// decoded, or written to disk.
1861 pub async fn screenshot_to_file(
1862 &mut self,
1863 path: impl AsRef<std::path::Path>,
1864 ) -> Result<std::path::PathBuf, TestError> {
1865 let result = self.screenshot().await?;
1866 let base64_data = extract_screenshot_base64(&result)?;
1867 save_screenshot_to_file(&base64_data, path.as_ref())
1868 }
1869
1870 /// Take a screenshot of a specific window and save it to a file.
1871 ///
1872 /// # Errors
1873 ///
1874 /// Returns [`TestError::Other`] if the screenshot cannot be captured,
1875 /// decoded, or written to disk.
1876 pub async fn screenshot_to_file_for(
1877 &mut self,
1878 label: &str,
1879 path: impl AsRef<std::path::Path>,
1880 ) -> Result<std::path::PathBuf, TestError> {
1881 let result = self.screenshot_for(label).await?;
1882 let base64_data = extract_screenshot_base64(&result)?;
1883 save_screenshot_to_file(&base64_data, path.as_ref())
1884 }
1885}
1886
1887fn save_screenshot_to_file(
1888 base64_data: &str,
1889 path: &std::path::Path,
1890) -> Result<std::path::PathBuf, TestError> {
1891 use base64::Engine;
1892 let bytes = base64::engine::general_purpose::STANDARD
1893 .decode(base64_data)
1894 .map_err(|e| TestError::Other(format!("failed to decode screenshot base64: {e}")))?;
1895 if let Some(parent) = path.parent() {
1896 std::fs::create_dir_all(parent)
1897 .map_err(|e| TestError::Other(format!("failed to create directory: {e}")))?;
1898 }
1899 std::fs::write(path, &bytes)
1900 .map_err(|e| TestError::Other(format!("failed to write screenshot: {e}")))?;
1901 path.canonicalize()
1902 .or_else(|_| Ok(path.to_path_buf()))
1903 .map_err(|e: std::io::Error| TestError::Other(format!("path error: {e}")))
1904}
1905
1906fn extract_screenshot_base64(result: &Value) -> Result<String, TestError> {
1907 // Try various response shapes the plugin may return
1908 if let Some(data) = result.get("base64").and_then(Value::as_str) {
1909 return Ok(data.to_string());
1910 }
1911 if let Some(data) = result.get("data").and_then(Value::as_str) {
1912 return Ok(data.to_string());
1913 }
1914 if let Some(data) = result.get("image").and_then(Value::as_str) {
1915 return Ok(data.to_string());
1916 }
1917 if let Some(data) = result
1918 .pointer("/result/content/0/data")
1919 .and_then(Value::as_str)
1920 {
1921 return Ok(data.to_string());
1922 }
1923 Err(TestError::Other(
1924 "screenshot result does not contain recognizable base64 image data".to_string(),
1925 ))
1926}
1927
1928fn find_in_tree_by_text(node: &Value, text: &str) -> Option<String> {
1929 let node_text = node.get("text").and_then(Value::as_str).unwrap_or("");
1930 let node_name = node.get("name").and_then(Value::as_str).unwrap_or("");
1931 if (node_text.contains(text) || node_name.contains(text))
1932 && let Some(ref_id) = node.get("ref_id").and_then(Value::as_str)
1933 {
1934 return Some(ref_id.to_string());
1935 }
1936 if let Some(children) = node.get("children").and_then(Value::as_array) {
1937 for child in children {
1938 if let Some(found) = find_in_tree_by_text(child, text) {
1939 return Some(found);
1940 }
1941 }
1942 }
1943 None
1944}
1945
1946fn find_in_tree_by_attr_id(node: &Value, id: &str) -> Option<String> {
1947 if node
1948 .get("attributes")
1949 .and_then(|a| a.get("id"))
1950 .and_then(Value::as_str)
1951 == Some(id)
1952 && let Some(ref_id) = node.get("ref_id").and_then(Value::as_str)
1953 {
1954 return Some(ref_id.to_string());
1955 }
1956 if let Some(children) = node.get("children").and_then(Value::as_array) {
1957 for child in children {
1958 if let Some(found) = find_in_tree_by_attr_id(child, id) {
1959 return Some(found);
1960 }
1961 }
1962 }
1963 None
1964}
1965
1966fn find_text_by_attr_id(node: &Value, id: &str) -> Option<String> {
1967 if node
1968 .get("attributes")
1969 .and_then(|a| a.get("id"))
1970 .and_then(Value::as_str)
1971 == Some(id)
1972 {
1973 let text = node.get("text").and_then(Value::as_str).unwrap_or("");
1974 return Some(text.to_string());
1975 }
1976 if let Some(children) = node.get("children").and_then(Value::as_array) {
1977 for child in children {
1978 if let Some(found) = find_text_by_attr_id(child, id) {
1979 return Some(found);
1980 }
1981 }
1982 }
1983 None
1984}
1985
1986// ── Assertion Helpers ────────────────────────────────────────────────────────
1987
1988/// Assert that a JSON value at the given pointer equals the expected value.
1989///
1990/// # Panics
1991///
1992/// Panics if the value at `pointer` is missing or does not equal `expected`.
1993///
1994/// # Examples
1995///
1996/// ```
1997/// use serde_json::json;
1998///
1999/// let state = json!({"visible": true, "title": "My App"});
2000/// victauri_test::assert_json_eq(&state, "/visible", &json!(true));
2001/// victauri_test::assert_json_eq(&state, "/title", &json!("My App"));
2002/// ```
2003pub fn assert_json_eq(value: &Value, pointer: &str, expected: &Value) {
2004 let actual = value.pointer(pointer);
2005 assert!(
2006 actual == Some(expected),
2007 "JSON pointer {pointer}: expected {expected}, got {}",
2008 actual.map_or("missing".to_string(), std::string::ToString::to_string)
2009 );
2010}
2011
2012/// Assert that a JSON value at the given pointer is truthy (not null/false/0/"").
2013///
2014/// # Panics
2015///
2016/// Panics if the value at `pointer` is missing, null, false, zero, or empty.
2017///
2018/// # Examples
2019///
2020/// ```
2021/// use serde_json::json;
2022///
2023/// let value = json!({"active": true, "name": "test", "count": 42});
2024/// victauri_test::assert_json_truthy(&value, "/active");
2025/// victauri_test::assert_json_truthy(&value, "/name");
2026/// victauri_test::assert_json_truthy(&value, "/count");
2027/// ```
2028pub fn assert_json_truthy(value: &Value, pointer: &str) {
2029 let actual = value.pointer(pointer);
2030 let is_truthy = match actual {
2031 None | Some(Value::Null) => false,
2032 Some(Value::Bool(b)) => *b,
2033 Some(Value::Number(n)) => n.as_f64().unwrap_or(0.0) != 0.0,
2034 Some(Value::String(s)) => !s.is_empty(),
2035 Some(Value::Array(a)) => !a.is_empty(),
2036 Some(Value::Object(_)) => true,
2037 };
2038 assert!(
2039 is_truthy,
2040 "JSON pointer {pointer}: expected truthy, got {}",
2041 actual.map_or("missing".to_string(), std::string::ToString::to_string)
2042 );
2043}
2044
2045/// Assert that an accessibility audit has zero violations.
2046///
2047/// # Panics
2048///
2049/// Panics if the audit contains any violations.
2050///
2051/// # Examples
2052///
2053/// ```
2054/// use serde_json::json;
2055///
2056/// let audit = json!({"summary": {"violations": 0, "passes": 12}});
2057/// victauri_test::assert_no_a11y_violations(&audit);
2058/// ```
2059pub fn assert_no_a11y_violations(audit: &Value) {
2060 let violations = audit
2061 .pointer("/summary/violations")
2062 .and_then(serde_json::Value::as_u64)
2063 .unwrap_or(u64::MAX);
2064 assert_eq!(
2065 violations, 0,
2066 "expected 0 accessibility violations, got {violations}"
2067 );
2068}
2069
2070/// Assert that all performance metrics are within budget.
2071///
2072/// # Panics
2073///
2074/// Panics if load time exceeds `max_load_ms` or heap usage exceeds `max_heap_mb`.
2075///
2076/// # Examples
2077///
2078/// ```
2079/// use serde_json::json;
2080///
2081/// let metrics = json!({
2082/// "navigation": {"load_event_ms": 450.0},
2083/// "js_heap": {"used_mb": 12.5}
2084/// });
2085/// victauri_test::assert_performance_budget(&metrics, 1000.0, 50.0);
2086/// ```
2087pub fn assert_performance_budget(metrics: &Value, max_load_ms: f64, max_heap_mb: f64) {
2088 if let Some(load) = metrics
2089 .pointer("/navigation/load_event_ms")
2090 .and_then(serde_json::Value::as_f64)
2091 {
2092 assert!(
2093 load <= max_load_ms,
2094 "load event took {load}ms, budget is {max_load_ms}ms"
2095 );
2096 }
2097
2098 if let Some(heap) = metrics
2099 .pointer("/js_heap/used_mb")
2100 .and_then(serde_json::Value::as_f64)
2101 {
2102 assert!(
2103 heap <= max_heap_mb,
2104 "JS heap is {heap}MB, budget is {max_heap_mb}MB"
2105 );
2106 }
2107}
2108
2109/// Assert that IPC integrity is healthy (no stale or errored calls).
2110///
2111/// # Panics
2112///
2113/// Panics if the integrity check reports an unhealthy state.
2114///
2115/// # Examples
2116///
2117/// ```
2118/// use serde_json::json;
2119///
2120/// let integrity = json!({"healthy": true, "stale_calls": 0, "error_calls": 0});
2121/// victauri_test::assert_ipc_healthy(&integrity);
2122/// ```
2123pub fn assert_ipc_healthy(integrity: &Value) {
2124 let healthy = integrity
2125 .get("healthy")
2126 .and_then(serde_json::Value::as_bool)
2127 .unwrap_or(false);
2128 assert!(
2129 healthy,
2130 "IPC integrity check failed: {}",
2131 serde_json::to_string_pretty(integrity).unwrap_or_default()
2132 );
2133}
2134
2135/// Assert that state verification passed with no divergences.
2136///
2137/// # Panics
2138///
2139/// Panics if the verification reports any divergences.
2140///
2141/// # Examples
2142///
2143/// ```
2144/// use serde_json::json;
2145///
2146/// let verification = json!({"passed": true, "divergences": []});
2147/// victauri_test::assert_state_matches(&verification);
2148/// ```
2149pub fn assert_state_matches(verification: &Value) {
2150 let passed = verification
2151 .get("passed")
2152 .and_then(serde_json::Value::as_bool)
2153 .unwrap_or(false);
2154 assert!(
2155 passed,
2156 "state verification failed: {}",
2157 serde_json::to_string_pretty(verification).unwrap_or_default()
2158 );
2159}