Skip to main content

llm_browser_testkit/
scenario.rs

1//! Scenario types for human-readable browser test case definitions.
2//!
3//! Scenarios are written in [TOML](https://toml.io) and describe groups of
4//! browser interaction tests with reusable assertion definitions and
5//! configurable test-level overrides.
6//!
7//! # Structure
8//!
9//! ```toml
10//! [config]                         # Global defaults
11//! start_url = "/dashboard"
12//!
13//! [[definitions]]                  # Reusable assertion definitions
14//! name = "no_errors"
15//! preset = "no_error_on_page"
16//!
17//! [[test]]                         # Test group
18//! name = "Dashboard Smoke"
19//! start_url = "/dashboard"         # Override global start_url (optional)
20//!
21//! [[test.steps]]                   # Ordered steps — the `kind` field
22//! kind = "navigate"                # determines which other fields apply
23//! url = "/dashboard"
24//!
25//! [[test.steps]]
26//! kind = "click"
27//! target = "the Login button"      # Natural language — LLM resolves to selector
28//!
29//! [[test.steps]]
30//! kind = "assert"
31//! definition = "no_errors"
32//! ```
33//!
34//! ## Step Kinds
35//!
36//! | `kind`        | Required fields  | Optional fields                          |
37//! |---------------|-----------------|------------------------------------------|
38//! | `navigate`    | `url`           | `wait_after_ms`                          |
39//! | `click`       | `target`        | `selector`, `wait_after_ms`              |
40//! | `type`        | `target`, `text`| `selector`, `wait_after_ms`              |
41//! | `wait`        | `target`        | `selector`, `timeout_ms`                 |
42//! | `assert`      | *one of below*  | —                                        |
43//! | `screenshot`  | —               | `path`                                   |
44//! | `agent`       | `agent`, `task` | —                                        |
45//! | `mcp`         | `server`, `tool`| `args`                                   |
46//!
47//! Assert steps require one of: `definition` (references a named
48//! `[[definitions]]` entry), `preset` (built-in preset name), or `prompt`
49//! (custom LLM evaluation prompt).
50
51use std::collections::HashMap;
52
53use serde::Deserialize;
54use serde_json::Value;
55
56/// Top-level scenario file, deserialized from TOML.
57#[derive(Debug, Deserialize)]
58pub struct Scenario {
59    /// Global configuration (overridable per test).
60    #[serde(default)]
61    pub config: ScenarioConfig,
62
63    /// Reusable assertion definitions referenced by name in `assert` steps.
64    #[serde(default)]
65    pub definitions: Vec<AssertDefinition>,
66
67    /// Ordered test groups to execute.
68    #[serde(default)]
69    pub test: Vec<TestGroup>,
70}
71
72/// Global scenario configuration with per-test overridable fields.
73#[derive(Debug, Deserialize, Default, Clone)]
74pub struct ScenarioConfig {
75    /// Base URL for relative navigation.
76    #[serde(default)]
77    pub base_url: Option<String>,
78    /// LLM server base URL (deprecated; prefer `[config.endpoints]`).
79    #[serde(default)]
80    pub llm_url: Option<String>,
81    /// LLM model name (deprecated; prefer `[config.endpoints]`).
82    #[serde(default)]
83    pub llm_model: Option<String>,
84    /// LLM API key (Bearer token).
85    #[serde(default)]
86    pub llm_api_key: Option<String>,
87    /// Custom HTTP headers as JSON key-value pairs.
88    #[serde(default, deserialize_with = "deserialize_headers")]
89    pub llm_headers: HashMap<String, String>,
90    /// Run browser in headless mode.
91    #[serde(default)]
92    pub browser_headless: Option<bool>,
93    /// HTTP / browser action timeout in seconds.
94    #[serde(default)]
95    pub timeout_secs: Option<u64>,
96    /// Browser viewport width.
97    #[serde(default)]
98    pub viewport_width: Option<u32>,
99    /// Browser viewport height.
100    #[serde(default)]
101    pub viewport_height: Option<u32>,
102    /// Default URL every test auto-navigates to before running its steps.
103    #[serde(default)]
104    pub start_url: Option<String>,
105    /// Whether to auto-navigate to `start_url` before test steps.
106    ///
107    /// Disable when a test starts with click-based navigation.
108    #[serde(default = "default_auto_navigate")]
109    pub auto_navigate: bool,
110    /// LLM temperature (0.0–1.0). Lower = more deterministic.
111    #[serde(default = "default_temperature")]
112    pub temperature: f64,
113    /// Enable thinking/reasoning tokens. `None` means the provider default
114    /// is used (no `thinking` key is sent). Set to `true`/`false` to
115    /// explicitly enable or disable.
116    #[serde(default)]
117    pub thinking: Option<bool>,
118    /// Provider-specific model parameters merged into the chat completion
119    /// request body (e.g. `effort = "high"` for Anthropic).
120    #[serde(default, deserialize_with = "deserialize_model_params")]
121    pub model_params: HashMap<String, Value>,
122    /// Named endpoints (LLM, MCP, A2A agents) with pricing.
123    #[serde(default)]
124    pub endpoints: HashMap<String, EndpointConfig>,
125    /// Global and per-test budgets for cost/token/call limits.
126    #[serde(default)]
127    pub budgets: BudgetsConfig,
128    /// MCP server exposure configuration.
129    #[serde(default)]
130    pub mcp_server: Option<McpServerConfig>,
131    /// A2A agent server exposure configuration.
132    #[serde(default)]
133    pub a2a_server: Option<A2aServerConfig>,
134    /// Whether to continue running the remaining steps of a test after a
135    /// step fails. Default `false` = fail fast: the first failed step ends
136    /// the test and the rest are reported as skipped. Set to `true` to run
137    /// every step (more diagnostics, more LLM cost on broken apps).
138    #[serde(default)]
139    pub continue_on_failure: bool,
140    /// Longest edge (px) of screenshots attached to `screenshot = true`
141    /// assert steps, before they are JPEG-encoded and sent to the vision
142    /// endpoint. Downscaling keeps vision token cost/quality sane.
143    /// Default: 1400.
144    #[serde(default)]
145    pub screenshot_max_dimension: Option<u32>,
146    /// Height cap (px) of page coverage for screenshots attached to
147    /// `screenshot = true` assert steps. The full scrollable page is
148    /// captured, then split into viewport-tall tiles (each sent as its own
149    /// image part, ordered from the top) covering at most this many pixels
150    /// — below-the-fold content stays visible to the vision model at 1:1
151    /// detail while token cost stays bounded. Accepts an absolute pixel
152    /// count (`2880`) or a viewport multiple (`"20x"` = twenty times the
153    /// currently applied viewport height, which follows viewport-matrix
154    /// and per-test overrides). A value below the viewport height is
155    /// raised to it, so the visible viewport is always fully included
156    /// (`0` / `"0x"` therefore means "viewport only", the pre-full-page
157    /// behavior). Default: `"20x"`.
158    #[serde(default, deserialize_with = "deserialize_screenshot_max_height")]
159    pub screenshot_max_height: Option<ScreenshotHeight>,
160    /// Directory for failure artifacts (screenshots, page snapshots).
161    /// Defaults to `artifacts`.
162    #[serde(default)]
163    pub artifacts_dir: Option<String>,
164    /// Optional viewport matrix: when set, every test in the scenario is
165    /// expanded into one variant per viewport (e.g. mobile/tablet/desktop).
166    /// Each variant overrides the test's viewport and gets a ` — <name>`
167    /// suffix on the test name. Per-test budgets apply per variant.
168    #[serde(default)]
169    pub viewport_matrix: Option<ViewportMatrix>,
170    /// Class-name prefixes the `layout_no_issues` scan skips: elements
171    /// whose class matches any prefix are ignored by the fixed-element,
172    /// text-clipped, and overlap checks. Defaults cover the Angular CDK
173    /// screen-reader helpers (`cdk-visually-hidden`,
174    /// `cdk-describedby-message-container`, `cdk-overlay-container`),
175    /// which are intentionally 1x1 / off-screen.
176    #[serde(default = "default_layout_ignore_classes")]
177    pub layout_ignore_classes: Vec<String>,
178}
179
180/// A list of named viewports a scenario is expanded across.
181#[derive(Debug, Deserialize, Clone, Default)]
182pub struct ViewportMatrix {
183    /// The viewport variants (`{name, width, height}`).
184    #[serde(default)]
185    pub viewports: Vec<ViewportDef>,
186}
187
188/// Height cap for screenshots attached to `screenshot = true` assert
189/// steps: either an absolute pixel count or a multiple of the currently
190/// applied viewport height.
191#[derive(Debug, Clone, PartialEq)]
192pub enum ScreenshotHeight {
193    /// Absolute height in pixels.
194    Pixels(u32),
195    /// Multiple of the active viewport height (e.g. `2x` = twice the
196    /// current viewport's pixel height).
197    ViewportTimes(f64),
198}
199
200/// Ceiling (px) applied when resolving screenshot height specs, so an
201/// absurdly large multiplier can never overflow or produce an unusable
202/// capture.
203const MAX_SCREENSHOT_HEIGHT: u32 = 4_000_000;
204
205impl ScreenshotHeight {
206    /// Resolves this height spec to a pixel value for the given viewport
207    /// height. Multipliers are rounded and clamped to
208    /// [`MAX_SCREENSHOT_HEIGHT`].
209    #[must_use]
210    pub fn to_px(&self, viewport_height: u32) -> u32 {
211        match self {
212            Self::Pixels(px) => *px,
213            Self::ViewportTimes(mult) => {
214                let scaled = f64::from(viewport_height) * mult;
215                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
216                let px = scaled
217                    .round()
218                    .max(1.0)
219                    .min(f64::from(MAX_SCREENSHOT_HEIGHT)) as u32;
220                px
221            }
222        }
223    }
224}
225
226/// One named viewport size in a matrix.
227#[derive(Debug, Deserialize, Clone)]
228pub struct ViewportDef {
229    /// Human-readable variant name (appended to test names, e.g.
230    /// `— mobile`).
231    pub name: String,
232    /// Browser viewport width in pixels.
233    pub width: u32,
234    /// Browser viewport height in pixels.
235    pub height: u32,
236}
237
238/// A named endpoint definition with pricing.
239#[derive(Debug, Deserialize, Clone, Default)]
240pub struct EndpointConfig {
241    /// Endpoint type: `llm`, `mcp`, or `a2a`.
242    #[serde(rename = "type")]
243    pub endpoint_type: EndpointType,
244    /// Base URL for the endpoint.
245    #[serde(default)]
246    pub url: Option<String>,
247    /// Model name (LLM endpoints only).
248    #[serde(default)]
249    pub model: Option<String>,
250    /// API key / bearer token.
251    #[serde(default)]
252    pub api_key: Option<String>,
253    /// Custom HTTP headers as JSON key-value pairs.
254    #[serde(default, deserialize_with = "deserialize_headers")]
255    pub headers: HashMap<String, String>,
256    /// Pricing configuration.
257    #[serde(default)]
258    pub pricing: Option<PricingConfig>,
259    /// Task types this endpoint serves by default
260    /// (e.g. `["targeting", "assertion"]`).
261    #[serde(default)]
262    pub default_for: Vec<String>,
263    /// Command to launch an MCP server subprocess (stdio transport).
264    #[serde(default)]
265    pub command: Option<String>,
266    /// Arguments for the MCP server command.
267    #[serde(default)]
268    pub args: Vec<String>,
269    /// Whether this LLM endpoint accepts image parts (vision) in addition
270    /// to text. `assert` steps with `screenshot = true` require a vision
271    /// endpoint.
272    #[serde(default)]
273    pub vision: bool,
274    /// How often a single chat completion against this endpoint is retried
275    /// on transient failures (HTTP 429/5xx, empty 200 bodies, network
276    /// errors) before the fallback chain is tried. Default: 3 (override
277    /// globally with `HARNESS_LLM_CALL_ATTEMPTS`).
278    #[serde(default)]
279    pub max_attempts: Option<u32>,
280    /// Ordered names of other endpoints to try when this endpoint exhausts
281    /// its attempts. Only LLM endpoints are eligible. Useful for pairing a
282    /// cheap primary model with a more powerful/expensive fallback.
283    #[serde(default)]
284    pub fallbacks: Vec<String>,
285    /// LLM provider protocol: `openai` (default, OpenAI-compatible chat
286    /// completions), `azure` (`Azure` `OpenAI`), or `bedrock` (AWS Bedrock
287    /// Converse API; requires the `aws` cargo feature).
288    #[serde(default)]
289    pub provider: Provider,
290    /// `Azure` `OpenAI` deployment name (`provider = "azure"`). Defaults to
291    /// `model` when unset.
292    #[serde(default)]
293    pub deployment: Option<String>,
294    /// `Azure` `OpenAI` API version (`provider = "azure"`). Defaults to
295    /// `2024-10-21`.
296    #[serde(default)]
297    pub api_version: Option<String>,
298    /// Authentication configuration for LLM endpoints (API key, token
299    /// command, Entra ID client credentials / managed identity).
300    #[serde(default)]
301    pub auth: AuthConfig,
302    /// Extra HTTP headers produced by running a command per call, keyed by
303    /// header name. The command's stdout (first line) becomes the header
304    /// value. Provider-agnostic — applies to every LLM provider.
305    #[serde(default, deserialize_with = "deserialize_headers")]
306    pub header_commands: HashMap<String, String>,
307    /// AWS credential settings (`provider = "bedrock"`).
308    #[serde(default)]
309    pub aws: AwsConfig,
310}
311
312/// Type discriminator for endpoint configuration.
313#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Default)]
314#[serde(rename_all = "lowercase")]
315pub enum EndpointType {
316    /// OpenAI-compatible LLM API.
317    #[default]
318    Llm,
319    /// Model Context Protocol server.
320    Mcp,
321    /// Agent-to-Agent protocol agent.
322    A2a,
323}
324
325/// LLM provider protocol used by an LLM endpoint.
326#[derive(Debug, Deserialize, Clone, Copy, PartialEq, Eq, Default)]
327#[serde(rename_all = "lowercase")]
328pub enum Provider {
329    /// OpenAI-compatible Chat Completions API
330    /// (`POST <url>/v1/chat/completions`).
331    #[default]
332    Openai,
333    /// `Azure` `OpenAI`
334    /// (`POST <url>/openai/deployments/<deployment>/chat/completions`).
335    Azure,
336    /// AWS Bedrock Converse API (`POST https://bedrock-runtime.<region>
337    /// .amazonaws.com/model/<model>/converse`). Requires the `aws` cargo
338    /// feature; uses the standard AWS credential chain unless overridden.
339    Bedrock,
340}
341
342/// Authentication mode for an LLM endpoint.
343#[derive(Debug, Deserialize, Clone, Copy, PartialEq, Eq, Default)]
344#[serde(rename_all = "kebab-case")]
345pub enum AuthMode {
346    /// Static API key. Sent as `Authorization: Bearer <key>` by default;
347    /// set [`AuthConfig::api_key_header`] (or use the `azure` provider)
348    /// to send it in a different header.
349    #[default]
350    ApiKey,
351    /// Execute a command and use its stdout (first line) as the bearer
352    /// token. Uses the `token_command` field. Provider-agnostic escape
353    /// hatch — e.g. `az account get-access-token …`.
354    TokenCommand,
355    /// Entra ID (`Azure` AD) OAuth 2.0 client-credentials grant: exchanges
356    /// `client_id` + `client_secret` in `tenant_id` for a bearer token.
357    EntraClientCredentials,
358    /// Entra ID managed identity: fetches a bearer token from the IMDS
359    /// endpoint (works on `Azure` VMs / App Service / ACI with a
360    /// system-assigned identity; zero credentials in the config).
361    EntraManagedIdentity,
362}
363
364/// Authentication settings for an LLM endpoint.
365#[derive(Debug, Deserialize, Clone, Default)]
366pub struct AuthConfig {
367    /// Which authentication mode to use. Default: `api-key`.
368    #[serde(default)]
369    pub mode: AuthMode,
370    /// Header name that receives the API key instead of
371    /// `Authorization: Bearer` (`mode = "api-key"`). For example the `Azure`
372    /// `OpenAI` `api-key` header.
373    #[serde(default)]
374    pub api_key_header: Option<String>,
375    /// Command whose stdout (first line) is used as the bearer token
376    /// (`mode = "token-command"`).
377    #[serde(default)]
378    pub token_command: Option<String>,
379    /// Entra tenant id (`mode = "entra-client-credentials"`,
380    /// `"entra-managed-identity"`).
381    #[serde(default)]
382    pub tenant_id: Option<String>,
383    /// Entra client id (`mode = "entra-client-credentials"`).
384    #[serde(default)]
385    pub client_id: Option<String>,
386    /// Entra client secret (`mode = "entra-client-credentials"`).
387    #[serde(default)]
388    pub client_secret: Option<String>,
389    /// Entra token scope. Defaults to
390    /// `https://cognitiveservices.azure.com/.default`.
391    #[serde(default)]
392    pub scope: Option<String>,
393    /// Override for the Entra token endpoint
394    /// (`mode = "entra-client-credentials"`), default
395    /// `https://login.microsoftonline.com`. Also used as the IMDS identity
396    /// endpoint base for `"entra-managed-identity"` (default
397    /// `http://169.254.169.254`). Mainly useful for tests and proxies.
398    #[serde(default)]
399    pub token_url: Option<String>,
400    /// Seconds to reuse a fetched (non-API-key) token before refetching.
401    /// For Entra modes the server-issued expiry is used when available;
402    /// this caps the reuse window. Default 300.
403    #[serde(default)]
404    pub cache_ttl_secs: Option<u64>,
405}
406
407/// AWS credential and region settings for a `bedrock` provider endpoint.
408///
409/// When no explicit access key is given, the standard AWS credential chain
410/// is used (env vars, shared config `~/.aws/config` + `~/.aws/credentials`,
411/// SSO, ECS/IMDS) — the same behavior as the AWS CLI. `profile` selects a
412/// named profile from the shared config, and `region` overrides the chain
413/// default.
414#[derive(Debug, Deserialize, Clone, Default)]
415pub struct AwsConfig {
416    /// Named profile from `~/.aws/config` / `~/.aws/credentials` to use
417    /// (default: the AWS CLI default selection via `AWS_PROFILE` or
418    /// `default`).
419    #[serde(default)]
420    pub profile: Option<String>,
421    /// AWS region (default: `AWS_REGION` env or the profile's region;
422    /// required if neither is set).
423    #[serde(default)]
424    pub region: Option<String>,
425    /// Explicit access key id (bypasses the credential chain).
426    #[serde(default)]
427    pub access_key_id: Option<String>,
428    /// Explicit secret access key (with `access_key_id`).
429    #[serde(default)]
430    pub secret_access_key: Option<String>,
431    /// Optional session token for explicit temporary credentials.
432    #[serde(default)]
433    pub session_token: Option<String>,
434}
435
436/// Pricing configuration for an endpoint.
437#[derive(Debug, Deserialize, Clone, Default)]
438pub struct PricingConfig {
439    /// Cost per 1M input tokens (USD).
440    #[serde(default)]
441    pub input_per_1m_tokens: f64,
442    /// Cost per 1M output tokens (USD).
443    #[serde(default)]
444    pub output_per_1m_tokens: f64,
445    /// Flat cost per call (USD), used for MCP/agent endpoints.
446    #[serde(default)]
447    pub per_call: f64,
448}
449
450/// Budget limits for test execution.
451#[derive(Debug, Deserialize, Clone, Default)]
452pub struct BudgetsConfig {
453    /// Global budget across all tests in the scenario.
454    #[serde(default)]
455    pub global: Option<BudgetDef>,
456    /// Default per-test budget. Individual tests can override.
457    #[serde(default)]
458    pub per_test_default: Option<BudgetDef>,
459}
460
461/// A budget definition with limits and enforcement mode.
462#[derive(Debug, Deserialize, Clone)]
463pub struct BudgetDef {
464    /// Maximum cost in USD.
465    #[serde(default)]
466    pub max_cost: Option<f64>,
467    /// Maximum total tokens (input + output).
468    #[serde(default)]
469    pub max_tokens: Option<u64>,
470    /// Maximum number of calls (LLM, MCP, agent combined).
471    #[serde(default)]
472    pub max_calls: Option<u64>,
473    /// Enforcement mode: `hard` (abort) or `soft` (warn and continue).
474    #[serde(default)]
475    pub enforcement: Option<BudgetEnforcement>,
476}
477
478/// Budget enforcement strategy.
479#[derive(Debug, Deserialize, Clone, PartialEq, Eq)]
480#[serde(rename_all = "lowercase")]
481pub enum BudgetEnforcement {
482    /// Abort the test or run when budget is exceeded.
483    Hard,
484    /// Log a warning but continue execution.
485    Soft,
486}
487
488/// MCP server exposure configuration.
489#[derive(Debug, Deserialize, Clone)]
490pub struct McpServerConfig {
491    /// Whether to enable the embedded MCP server.
492    #[serde(default)]
493    pub enabled: bool,
494    /// Port to listen on.
495    #[serde(default = "default_mcp_port")]
496    pub port: u16,
497}
498
499const fn default_mcp_port() -> u16 {
500    3000
501}
502
503/// A2A agent server exposure configuration.
504#[derive(Debug, Deserialize, Clone)]
505pub struct A2aServerConfig {
506    /// Whether to enable the embedded A2A agent server.
507    #[serde(default)]
508    pub enabled: bool,
509    /// Port to listen on.
510    #[serde(default = "default_a2a_port")]
511    pub port: u16,
512}
513
514const fn default_a2a_port() -> u16 {
515    3100
516}
517
518fn deserialize_headers<'de, D>(deserializer: D) -> Result<HashMap<String, String>, D::Error>
519where
520    D: serde::Deserializer<'de>,
521{
522    let raw: Option<serde_json::Value> = Option::deserialize(deserializer)?;
523    let Some(json) = raw else {
524        return Ok(HashMap::new());
525    };
526    let serde_json::Value::Object(obj) = json else {
527        return Ok(HashMap::new());
528    };
529    Ok(obj
530        .into_iter()
531        .filter_map(|(k, v)| v.as_str().map(|s| (k, s.to_owned())))
532        .collect())
533}
534
535const fn default_auto_navigate() -> bool {
536    true
537}
538
539fn default_layout_ignore_classes() -> Vec<String> {
540    vec![
541        "cdk-visually-hidden".to_owned(),
542        "cdk-describedby-message-container".to_owned(),
543        "cdk-overlay-container".to_owned(),
544    ]
545}
546
547const fn default_temperature() -> f64 {
548    0.0
549}
550
551fn deserialize_model_params<'de, D>(deserializer: D) -> Result<HashMap<String, Value>, D::Error>
552where
553    D: serde::Deserializer<'de>,
554{
555    #[derive(Deserialize)]
556    #[serde(untagged)]
557    enum Raw {
558        Map(HashMap<String, Value>),
559        Table(HashMap<String, Value>),
560    }
561    let raw: Option<Raw> = Option::deserialize(deserializer)?;
562    Ok(match raw {
563        Some(Raw::Map(m) | Raw::Table(m)) => m,
564        None => HashMap::new(),
565    })
566}
567
568fn deserialize_screenshot_max_height<'de, D>(
569    deserializer: D,
570) -> Result<Option<ScreenshotHeight>, D::Error>
571where
572    D: serde::Deserializer<'de>,
573{
574    let raw: Option<serde_json::Value> = Option::deserialize(deserializer)?;
575    match raw {
576        None => Ok(None),
577        Some(value) => match value.as_u64() {
578            // Integer: absolute pixel count.
579            Some(px) if px <= u64::from(MAX_SCREENSHOT_HEIGHT) => {
580                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
581                Ok(Some(ScreenshotHeight::Pixels(px as u32)))
582            }
583            // String: viewport multiple like "2x" or "1.5x".
584            None => match value.as_str() {
585                Some(s) => {
586                    let lower = s.trim().to_lowercase();
587                    if lower.ends_with('x') {
588                        let num = lower.strip_suffix("x");
589                        if let Some(num) = num {
590                            if let Ok(m) = num.parse::<f64>() {
591                                if m > 0.0 {
592                                    return Ok(Some(ScreenshotHeight::ViewportTimes(m)));
593                                }
594                            }
595                        }
596                    }
597                    Err(serde::de::Error::custom(format_args!(
598                        "screenshot_max_height must be a pixel count (e.g. 2880) or a viewport multiple like \"2x\", found {s:?}"
599                    )))
600                }
601                None => Err(serde::de::Error::custom(format_args!(
602                    "screenshot_max_height must be a pixel count (e.g. 2880) or a viewport multiple like \"2x\", found {value:?}"
603                ))),
604            },
605            Some(_) => Err(serde::de::Error::custom(format_args!(
606                "screenshot_max_height value too large (max {MAX_SCREENSHOT_HEIGHT} px)"
607            ))),
608        },
609    }
610}
611
612/// Reusable assertion definition referenced by name from `assert` steps.
613///
614/// Definitions can either reference a built-in preset via `preset`, supply a
615/// custom LLM `prompt`, or define a **custom preset** by providing both
616/// `system` and `user_template`. Custom presets support the same template
617/// variables as built-in presets: `{url}`, `{title}`, `{content}`,
618/// `{expected_text}`, `{description}`.
619#[derive(Debug, Deserialize, Clone)]
620pub struct AssertDefinition {
621    /// Unique name used to reference this definition from steps.
622    pub name: String,
623    /// Predefined assertion preset name
624    /// (e.g. `no_error_on_page`, `text_visible`).
625    #[serde(default)]
626    pub preset: Option<String>,
627    /// Custom LLM prompt for assertion evaluation.
628    #[serde(default)]
629    pub prompt: Option<String>,
630    /// System prompt for a custom preset.
631    #[serde(default)]
632    pub system: Option<String>,
633    /// User template (with `{placeholders}`) for a custom preset.
634    #[serde(default)]
635    pub user_template: Option<String>,
636    /// Text that the `text_visible` preset checks for, or the
637    /// `{expected_text}` placeholder value for custom presets.
638    #[serde(default)]
639    pub assert_text: Option<String>,
640    /// Agent endpoint to call for this assertion.
641    #[serde(default)]
642    pub agent: Option<String>,
643    /// Agent task template for this assertion.
644    #[serde(default)]
645    pub task_template: Option<String>,
646}
647
648/// A group of steps that form a single test scenario.
649#[derive(Debug, Deserialize, Clone)]
650pub struct TestGroup {
651    /// Human-readable test name.
652    pub name: String,
653    /// Override the global `start_url` for this test.
654    #[serde(default)]
655    pub start_url: Option<String>,
656    /// Override the global `auto_navigate` for this test.
657    #[serde(default)]
658    pub auto_navigate: Option<bool>,
659    /// Override the global `base_url` for this test.
660    #[serde(default)]
661    pub base_url: Option<String>,
662    /// Override the global `timeout_secs` for this test.
663    #[serde(default)]
664    pub timeout_secs: Option<u64>,
665    /// Override the global `browser_headless` for this test.
666    #[serde(default)]
667    pub browser_headless: Option<bool>,
668    /// Override the global viewport width for this test (applied via CDP
669    /// `Emulation.setDeviceMetricsOverride` before the test runs).
670    #[serde(default)]
671    pub viewport_width: Option<u32>,
672    /// Override the global viewport height for this test.
673    #[serde(default)]
674    pub viewport_height: Option<u32>,
675    /// Per-test budget override.
676    #[serde(default)]
677    pub budget: Option<BudgetDef>,
678    /// Endpoint to use for all steps in this test (can be overridden
679    /// per-step).
680    #[serde(default)]
681    pub endpoint: Option<String>,
682    /// Ordered steps to execute.
683    #[serde(default)]
684    pub steps: Vec<TestStep>,
685}
686
687/// A single step in a test. The `kind` field determines which variant is
688/// deserialized and which field constraints apply.
689#[derive(Debug, Deserialize, Clone)]
690#[serde(tag = "kind")]
691pub enum TestStep {
692    /// Navigate the browser to a URL.
693    #[serde(rename = "navigate")]
694    Navigate {
695        /// URL to navigate to (absolute, or relative to the test's
696        /// base URL).
697        url: String,
698        /// Milliseconds to wait after navigation completes.
699        #[serde(default)]
700        wait_after_ms: Option<u64>,
701    },
702
703    /// Click an element described in natural language.
704    #[serde(rename = "click")]
705    Click {
706        /// Natural language description of the element. The LLM resolves
707        /// this to a CSS selector at runtime.
708        target: String,
709        /// Explicit CSS selector override (bypasses LLM resolution).
710        #[serde(default)]
711        selector: Option<String>,
712        /// Milliseconds to wait after the click.
713        #[serde(default)]
714        wait_after_ms: Option<u64>,
715        /// Endpoint to use for LLM element targeting.
716        #[serde(default)]
717        endpoint: Option<String>,
718        /// Idempotent: when the target element is absent the step is
719        /// reported skipped instead of failed (the action was already
720        /// done / not applicable).
721        #[serde(default)]
722        idempotent: bool,
723    },
724
725    /// Type text into an input element.
726    #[serde(rename = "type")]
727    Type {
728        /// Natural language description of the target input element.
729        target: String,
730        /// Text to type into the element.
731        text: String,
732        /// Explicit CSS selector override (bypasses LLM resolution).
733        #[serde(default)]
734        selector: Option<String>,
735        /// Milliseconds to wait after typing.
736        #[serde(default)]
737        wait_after_ms: Option<u64>,
738        /// Endpoint to use for LLM element targeting.
739        #[serde(default)]
740        endpoint: Option<String>,
741        /// Idempotent: when the target element is absent the step is
742        /// reported skipped instead of failed (the action was already
743        /// done / not applicable).
744        #[serde(default)]
745        idempotent: bool,
746    },
747
748    /// Wait for an element to appear on the page.
749    #[serde(rename = "wait")]
750    Wait {
751        /// Natural language description of the element to wait for.
752        target: String,
753        /// Explicit CSS selector override (bypasses LLM resolution).
754        #[serde(default)]
755        selector: Option<String>,
756        /// Wait until the page's visible text contains this substring
757        /// (alternative to `selector`; either or both may be set — both are
758        /// required to hold when both are set).
759        #[serde(default)]
760        text: Option<String>,
761        /// Maximum milliseconds to wait (default: 10000).
762        #[serde(default)]
763        timeout_ms: Option<u64>,
764        /// Endpoint to use for LLM element targeting.
765        #[serde(default)]
766        endpoint: Option<String>,
767        /// Idempotent: when the condition never becomes true within the
768        /// timeout the step is reported skipped instead of failed (the
769        /// condition was not applicable, e.g. already-authenticated
770        /// pages in a viewport matrix).
771        #[serde(default)]
772        idempotent: bool,
773    },
774
775    /// Evaluate an assertion against the current page content.
776    #[serde(rename = "assert")]
777    Assert {
778        /// Reference to a named `[[definitions]]` entry.
779        #[serde(default)]
780        definition: Option<String>,
781        /// Inline predefined assertion preset (e.g. `no_error_on_page`).
782        #[serde(default)]
783        preset: Option<String>,
784        /// Inline custom LLM prompt for assertion evaluation.
785        #[serde(default)]
786        prompt: Option<String>,
787        /// Text that the `text_visible` preset checks for.
788        #[serde(default)]
789        assert_text: Option<String>,
790        /// Endpoint to use for this assertion's LLM call.
791        #[serde(default)]
792        endpoint: Option<String>,
793        /// Attach a screenshot of the current viewport to the assertion so
794        /// the LLM can evaluate visuals (overlaps, clipping, layout).
795        /// Requires the resolved endpoint to declare `vision = true`.
796        #[serde(default)]
797        screenshot: bool,
798    },
799
800    /// Take a screenshot of the current page.
801    #[serde(rename = "screenshot")]
802    Screenshot {
803        /// File path to save the screenshot (default: `screenshot.png`).
804        #[serde(default)]
805        path: Option<String>,
806    },
807
808    /// Call an A2A agent with a task.
809    #[serde(rename = "agent")]
810    Agent {
811        /// Name of the agent endpoint to call.
812        agent: String,
813        /// Task description / prompt for the agent.
814        task: String,
815        /// Optional definition name with a task template.
816        #[serde(default)]
817        definition: Option<String>,
818    },
819
820    /// Call an MCP server tool.
821    #[serde(rename = "mcp")]
822    Mcp {
823        /// Name of the MCP server endpoint.
824        server: String,
825        /// Tool name to invoke on the server.
826        tool: String,
827        /// Tool arguments as JSON.
828        #[serde(default)]
829        args: Option<serde_json::Value>,
830    },
831}