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 /// Directory for failure artifacts (screenshots, page snapshots).
147 /// Defaults to `artifacts`.
148 #[serde(default)]
149 pub artifacts_dir: Option<String>,
150 /// Optional viewport matrix: when set, every test in the scenario is
151 /// expanded into one variant per viewport (e.g. mobile/tablet/desktop).
152 /// Each variant overrides the test's viewport and gets a ` — <name>`
153 /// suffix on the test name. Per-test budgets apply per variant.
154 #[serde(default)]
155 pub viewport_matrix: Option<ViewportMatrix>,
156 /// Class-name prefixes the `layout_no_issues` scan skips: elements
157 /// whose class matches any prefix are ignored by the fixed-element,
158 /// text-clipped, and overlap checks. Defaults cover the Angular CDK
159 /// screen-reader helpers (`cdk-visually-hidden`,
160 /// `cdk-describedby-message-container`, `cdk-overlay-container`),
161 /// which are intentionally 1x1 / off-screen.
162 #[serde(default = "default_layout_ignore_classes")]
163 pub layout_ignore_classes: Vec<String>,
164}
165
166/// A list of named viewports a scenario is expanded across.
167#[derive(Debug, Deserialize, Clone, Default)]
168pub struct ViewportMatrix {
169 /// The viewport variants (`{name, width, height}`).
170 #[serde(default)]
171 pub viewports: Vec<ViewportDef>,
172}
173
174/// One named viewport size in a matrix.
175#[derive(Debug, Deserialize, Clone)]
176pub struct ViewportDef {
177 /// Human-readable variant name (appended to test names, e.g.
178 /// `— mobile`).
179 pub name: String,
180 /// Browser viewport width in pixels.
181 pub width: u32,
182 /// Browser viewport height in pixels.
183 pub height: u32,
184}
185
186/// A named endpoint definition with pricing.
187#[derive(Debug, Deserialize, Clone, Default)]
188pub struct EndpointConfig {
189 /// Endpoint type: `llm`, `mcp`, or `a2a`.
190 #[serde(rename = "type")]
191 pub endpoint_type: EndpointType,
192 /// Base URL for the endpoint.
193 #[serde(default)]
194 pub url: Option<String>,
195 /// Model name (LLM endpoints only).
196 #[serde(default)]
197 pub model: Option<String>,
198 /// API key / bearer token.
199 #[serde(default)]
200 pub api_key: Option<String>,
201 /// Custom HTTP headers as JSON key-value pairs.
202 #[serde(default, deserialize_with = "deserialize_headers")]
203 pub headers: HashMap<String, String>,
204 /// Pricing configuration.
205 #[serde(default)]
206 pub pricing: Option<PricingConfig>,
207 /// Task types this endpoint serves by default
208 /// (e.g. `["targeting", "assertion"]`).
209 #[serde(default)]
210 pub default_for: Vec<String>,
211 /// Command to launch an MCP server subprocess (stdio transport).
212 #[serde(default)]
213 pub command: Option<String>,
214 /// Arguments for the MCP server command.
215 #[serde(default)]
216 pub args: Vec<String>,
217 /// Whether this LLM endpoint accepts image parts (vision) in addition
218 /// to text. `assert` steps with `screenshot = true` require a vision
219 /// endpoint.
220 #[serde(default)]
221 pub vision: bool,
222}
223
224/// Type discriminator for endpoint configuration.
225#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Default)]
226#[serde(rename_all = "lowercase")]
227pub enum EndpointType {
228 /// OpenAI-compatible LLM API.
229 #[default]
230 Llm,
231 /// Model Context Protocol server.
232 Mcp,
233 /// Agent-to-Agent protocol agent.
234 A2a,
235}
236
237/// Pricing configuration for an endpoint.
238#[derive(Debug, Deserialize, Clone, Default)]
239pub struct PricingConfig {
240 /// Cost per 1M input tokens (USD).
241 #[serde(default)]
242 pub input_per_1m_tokens: f64,
243 /// Cost per 1M output tokens (USD).
244 #[serde(default)]
245 pub output_per_1m_tokens: f64,
246 /// Flat cost per call (USD), used for MCP/agent endpoints.
247 #[serde(default)]
248 pub per_call: f64,
249}
250
251/// Budget limits for test execution.
252#[derive(Debug, Deserialize, Clone, Default)]
253pub struct BudgetsConfig {
254 /// Global budget across all tests in the scenario.
255 #[serde(default)]
256 pub global: Option<BudgetDef>,
257 /// Default per-test budget. Individual tests can override.
258 #[serde(default)]
259 pub per_test_default: Option<BudgetDef>,
260}
261
262/// A budget definition with limits and enforcement mode.
263#[derive(Debug, Deserialize, Clone)]
264pub struct BudgetDef {
265 /// Maximum cost in USD.
266 #[serde(default)]
267 pub max_cost: Option<f64>,
268 /// Maximum total tokens (input + output).
269 #[serde(default)]
270 pub max_tokens: Option<u64>,
271 /// Maximum number of calls (LLM, MCP, agent combined).
272 #[serde(default)]
273 pub max_calls: Option<u64>,
274 /// Enforcement mode: `hard` (abort) or `soft` (warn and continue).
275 #[serde(default)]
276 pub enforcement: Option<BudgetEnforcement>,
277}
278
279/// Budget enforcement strategy.
280#[derive(Debug, Deserialize, Clone, PartialEq, Eq)]
281#[serde(rename_all = "lowercase")]
282pub enum BudgetEnforcement {
283 /// Abort the test or run when budget is exceeded.
284 Hard,
285 /// Log a warning but continue execution.
286 Soft,
287}
288
289/// MCP server exposure configuration.
290#[derive(Debug, Deserialize, Clone)]
291pub struct McpServerConfig {
292 /// Whether to enable the embedded MCP server.
293 #[serde(default)]
294 pub enabled: bool,
295 /// Port to listen on.
296 #[serde(default = "default_mcp_port")]
297 pub port: u16,
298}
299
300const fn default_mcp_port() -> u16 {
301 3000
302}
303
304/// A2A agent server exposure configuration.
305#[derive(Debug, Deserialize, Clone)]
306pub struct A2aServerConfig {
307 /// Whether to enable the embedded A2A agent server.
308 #[serde(default)]
309 pub enabled: bool,
310 /// Port to listen on.
311 #[serde(default = "default_a2a_port")]
312 pub port: u16,
313}
314
315const fn default_a2a_port() -> u16 {
316 3100
317}
318
319fn deserialize_headers<'de, D>(deserializer: D) -> Result<HashMap<String, String>, D::Error>
320where
321 D: serde::Deserializer<'de>,
322{
323 let raw: Option<serde_json::Value> = Option::deserialize(deserializer)?;
324 let Some(json) = raw else {
325 return Ok(HashMap::new());
326 };
327 let serde_json::Value::Object(obj) = json else {
328 return Ok(HashMap::new());
329 };
330 Ok(obj
331 .into_iter()
332 .filter_map(|(k, v)| v.as_str().map(|s| (k, s.to_owned())))
333 .collect())
334}
335
336const fn default_auto_navigate() -> bool {
337 true
338}
339
340fn default_layout_ignore_classes() -> Vec<String> {
341 vec![
342 "cdk-visually-hidden".to_owned(),
343 "cdk-describedby-message-container".to_owned(),
344 "cdk-overlay-container".to_owned(),
345 ]
346}
347
348const fn default_temperature() -> f64 {
349 0.0
350}
351
352fn deserialize_model_params<'de, D>(deserializer: D) -> Result<HashMap<String, Value>, D::Error>
353where
354 D: serde::Deserializer<'de>,
355{
356 #[derive(Deserialize)]
357 #[serde(untagged)]
358 enum Raw {
359 Map(HashMap<String, Value>),
360 Table(HashMap<String, Value>),
361 }
362 let raw: Option<Raw> = Option::deserialize(deserializer)?;
363 Ok(match raw {
364 Some(Raw::Map(m) | Raw::Table(m)) => m,
365 None => HashMap::new(),
366 })
367}
368
369/// Reusable assertion definition referenced by name from `assert` steps.
370///
371/// Definitions can either reference a built-in preset via `preset`, supply a
372/// custom LLM `prompt`, or define a **custom preset** by providing both
373/// `system` and `user_template`. Custom presets support the same template
374/// variables as built-in presets: `{url}`, `{title}`, `{content}`,
375/// `{expected_text}`, `{description}`.
376#[derive(Debug, Deserialize, Clone)]
377pub struct AssertDefinition {
378 /// Unique name used to reference this definition from steps.
379 pub name: String,
380 /// Predefined assertion preset name
381 /// (e.g. `no_error_on_page`, `text_visible`).
382 #[serde(default)]
383 pub preset: Option<String>,
384 /// Custom LLM prompt for assertion evaluation.
385 #[serde(default)]
386 pub prompt: Option<String>,
387 /// System prompt for a custom preset.
388 #[serde(default)]
389 pub system: Option<String>,
390 /// User template (with `{placeholders}`) for a custom preset.
391 #[serde(default)]
392 pub user_template: Option<String>,
393 /// Text that the `text_visible` preset checks for, or the
394 /// `{expected_text}` placeholder value for custom presets.
395 #[serde(default)]
396 pub assert_text: Option<String>,
397 /// Agent endpoint to call for this assertion.
398 #[serde(default)]
399 pub agent: Option<String>,
400 /// Agent task template for this assertion.
401 #[serde(default)]
402 pub task_template: Option<String>,
403}
404
405/// A group of steps that form a single test scenario.
406#[derive(Debug, Deserialize, Clone)]
407pub struct TestGroup {
408 /// Human-readable test name.
409 pub name: String,
410 /// Override the global `start_url` for this test.
411 #[serde(default)]
412 pub start_url: Option<String>,
413 /// Override the global `auto_navigate` for this test.
414 #[serde(default)]
415 pub auto_navigate: Option<bool>,
416 /// Override the global `base_url` for this test.
417 #[serde(default)]
418 pub base_url: Option<String>,
419 /// Override the global `timeout_secs` for this test.
420 #[serde(default)]
421 pub timeout_secs: Option<u64>,
422 /// Override the global `browser_headless` for this test.
423 #[serde(default)]
424 pub browser_headless: Option<bool>,
425 /// Override the global viewport width for this test (applied via CDP
426 /// `Emulation.setDeviceMetricsOverride` before the test runs).
427 #[serde(default)]
428 pub viewport_width: Option<u32>,
429 /// Override the global viewport height for this test.
430 #[serde(default)]
431 pub viewport_height: Option<u32>,
432 /// Per-test budget override.
433 #[serde(default)]
434 pub budget: Option<BudgetDef>,
435 /// Endpoint to use for all steps in this test (can be overridden
436 /// per-step).
437 #[serde(default)]
438 pub endpoint: Option<String>,
439 /// Ordered steps to execute.
440 #[serde(default)]
441 pub steps: Vec<TestStep>,
442}
443
444/// A single step in a test. The `kind` field determines which variant is
445/// deserialized and which field constraints apply.
446#[derive(Debug, Deserialize, Clone)]
447#[serde(tag = "kind")]
448pub enum TestStep {
449 /// Navigate the browser to a URL.
450 #[serde(rename = "navigate")]
451 Navigate {
452 /// URL to navigate to (absolute, or relative to the test's
453 /// base URL).
454 url: String,
455 /// Milliseconds to wait after navigation completes.
456 #[serde(default)]
457 wait_after_ms: Option<u64>,
458 },
459
460 /// Click an element described in natural language.
461 #[serde(rename = "click")]
462 Click {
463 /// Natural language description of the element. The LLM resolves
464 /// this to a CSS selector at runtime.
465 target: String,
466 /// Explicit CSS selector override (bypasses LLM resolution).
467 #[serde(default)]
468 selector: Option<String>,
469 /// Milliseconds to wait after the click.
470 #[serde(default)]
471 wait_after_ms: Option<u64>,
472 /// Endpoint to use for LLM element targeting.
473 #[serde(default)]
474 endpoint: Option<String>,
475 /// Idempotent: when the target element is absent the step is
476 /// reported skipped instead of failed (the action was already
477 /// done / not applicable).
478 #[serde(default)]
479 idempotent: bool,
480 },
481
482 /// Type text into an input element.
483 #[serde(rename = "type")]
484 Type {
485 /// Natural language description of the target input element.
486 target: String,
487 /// Text to type into the element.
488 text: String,
489 /// Explicit CSS selector override (bypasses LLM resolution).
490 #[serde(default)]
491 selector: Option<String>,
492 /// Milliseconds to wait after typing.
493 #[serde(default)]
494 wait_after_ms: Option<u64>,
495 /// Endpoint to use for LLM element targeting.
496 #[serde(default)]
497 endpoint: Option<String>,
498 /// Idempotent: when the target element is absent the step is
499 /// reported skipped instead of failed (the action was already
500 /// done / not applicable).
501 #[serde(default)]
502 idempotent: bool,
503 },
504
505 /// Wait for an element to appear on the page.
506 #[serde(rename = "wait")]
507 Wait {
508 /// Natural language description of the element to wait for.
509 target: String,
510 /// Explicit CSS selector override (bypasses LLM resolution).
511 #[serde(default)]
512 selector: Option<String>,
513 /// Wait until the page's visible text contains this substring
514 /// (alternative to `selector`; either or both may be set — both are
515 /// required to hold when both are set).
516 #[serde(default)]
517 text: Option<String>,
518 /// Maximum milliseconds to wait (default: 10000).
519 #[serde(default)]
520 timeout_ms: Option<u64>,
521 /// Endpoint to use for LLM element targeting.
522 #[serde(default)]
523 endpoint: Option<String>,
524 /// Idempotent: when the condition never becomes true within the
525 /// timeout the step is reported skipped instead of failed (the
526 /// condition was not applicable, e.g. already-authenticated
527 /// pages in a viewport matrix).
528 #[serde(default)]
529 idempotent: bool,
530 },
531
532 /// Evaluate an assertion against the current page content.
533 #[serde(rename = "assert")]
534 Assert {
535 /// Reference to a named `[[definitions]]` entry.
536 #[serde(default)]
537 definition: Option<String>,
538 /// Inline predefined assertion preset (e.g. `no_error_on_page`).
539 #[serde(default)]
540 preset: Option<String>,
541 /// Inline custom LLM prompt for assertion evaluation.
542 #[serde(default)]
543 prompt: Option<String>,
544 /// Text that the `text_visible` preset checks for.
545 #[serde(default)]
546 assert_text: Option<String>,
547 /// Endpoint to use for this assertion's LLM call.
548 #[serde(default)]
549 endpoint: Option<String>,
550 /// Attach a screenshot of the current viewport to the assertion so
551 /// the LLM can evaluate visuals (overlaps, clipping, layout).
552 /// Requires the resolved endpoint to declare `vision = true`.
553 #[serde(default)]
554 screenshot: bool,
555 },
556
557 /// Take a screenshot of the current page.
558 #[serde(rename = "screenshot")]
559 Screenshot {
560 /// File path to save the screenshot (default: `screenshot.png`).
561 #[serde(default)]
562 path: Option<String>,
563 },
564
565 /// Call an A2A agent with a task.
566 #[serde(rename = "agent")]
567 Agent {
568 /// Name of the agent endpoint to call.
569 agent: String,
570 /// Task description / prompt for the agent.
571 task: String,
572 /// Optional definition name with a task template.
573 #[serde(default)]
574 definition: Option<String>,
575 },
576
577 /// Call an MCP server tool.
578 #[serde(rename = "mcp")]
579 Mcp {
580 /// Name of the MCP server endpoint.
581 server: String,
582 /// Tool name to invoke on the server.
583 tool: String,
584 /// Tool arguments as JSON.
585 #[serde(default)]
586 args: Option<serde_json::Value>,
587 },
588}