Skip to main content

day_script_protocol/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Dayscript's shared wire protocol and on-disk format.
5//!
6//! This leaf crate depends only on serde, JSON and YAML. The CLI and embedded engine share
7//! request/reply types and document validation without linking any UI, localization or transport.
8
9use serde::{Deserialize, Serialize};
10use std::collections::BTreeMap;
11
12pub mod format;
13pub mod ids;
14pub use ids::{EvidenceClass, IdCatalog, IdDeclaration, IdEvidence};
15mod memory;
16pub use format::{FailurePolicy, FormatError, Script, ScriptStep, steps_from_yaml, steps_to_yaml};
17pub use memory::MemorySize;
18
19/// Default implicit-wait budget, in seconds.
20pub const DEFAULT_TIMEOUT_SECS: f64 = 5.0;
21
22/// Which captures a run keeps.
23#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "kebab-case")]
25pub enum ShotPolicy {
26    Never,
27    #[default]
28    OnFailure,
29    Always,
30}
31
32#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
33pub struct Request {
34    pub token: String,
35    pub step: Step,
36}
37
38/// Native UI integration or deterministic Day request/response testing.
39#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
40#[serde(rename_all = "snake_case")]
41pub enum DialogMode {
42    Native,
43    Scripted,
44}
45
46#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
47#[serde(tag = "op", rename_all = "snake_case")]
48pub enum Step {
49    /// Compiled declaration registry, independent of the mounted tree.
50    IdCatalog,
51    /// Cumulative mounted families, diagnostic only.
52    IdMounted,
53    WaitFor {
54        id: String,
55        /// Upper bound in seconds for the implicit retry wait (§14.3), for elements that
56        /// appear only after slow work (a login round-trip, a first sync). Defaults to the
57        /// shared step timeout.
58        #[serde(default)]
59        timeout_secs: Option<f64>,
60    },
61    WaitIdle,
62    /// Sample current process memory once. Exceeding the optional byte limit is a
63    /// non-retryable failure. Host `only_on`/`skip_on` gates allow per-target budgets.
64    MemoryUsage {
65        #[serde(default)]
66        fail_if_above: Option<MemorySize>,
67    },
68    /// Transport control for background reporting. Zero stops the stream; otherwise
69    /// sample every 100..=60000 ms. Samples are unsolicited replies, not script steps.
70    MemoryWatch {
71        interval_ms: u64,
72    },
73    /// Programmatic scroll (docs/scroll.md §dayscript). With `edge`/`x`+`y`, `id` must name a
74    /// `scroll` piece; with neither, `id` names any element and its nearest enclosing scroll
75    /// reveals it. Unanimated, so the next step sees the settled position.
76    /// Native navigation menus also accept `top`/`bottom` on UIKit and Material.
77    ScrollTo {
78        id: String,
79        /// `"top"` | `"bottom"` | `"leading"` | `"trailing"`.
80        #[serde(default)]
81        edge: Option<String>,
82        #[serde(default)]
83        x: Option<f64>,
84        #[serde(default)]
85        y: Option<f64>,
86    },
87    Tap {
88        id: String,
89        /// Skip an absent element after UI transitions settle. Intended for idempotent
90        /// fixture cleanup; existing elements still pass the visibility/enabled gates.
91        #[serde(default)]
92        if_present: bool,
93        #[serde(default)]
94        repeat: Option<u32>,
95        /// Tap at this point in the element's coordinate space instead of its center, which is
96        /// what canvas hit-testing needs (`- tap: { id: canvas, at: [40, 60] }`).
97        #[serde(default)]
98        at: Option<[f64; 2]>,
99        /// Modifier keys "held" for the tap (`modifiers: [shift]` / `[primary]` / `[alt]`):
100        /// the executor stands them in through `day::modifiers()` while dispatching, so
101        /// modifier-dependent taps (shift-click multi-select) are drivable synthetically.
102        #[serde(default)]
103        modifiers: Vec<String>,
104    },
105    /// A non-text key press, delivered the way the platform delivers one: to whatever holds
106    /// focus (`- focus: { id: canvas }` then `- key: { key: ArrowRight, modifiers: [shift] }`,
107    /// docs/menus.md). Names follow the web `KeyboardEvent.key` vocabulary.
108    Key {
109        key: String,
110        /// The piece to deliver to. Omit to send it wherever focus is, which is what a real
111        /// key press does (docs/menus.md); pair it with a `focus:` step to drive the whole
112        /// route. Name an `id` to address one piece's handler regardless of focus.
113        #[serde(default)]
114        id: Option<String>,
115        #[serde(default)]
116        modifiers: Vec<String>,
117    },
118    /// A synthetic pointer drag over one element, in its own coordinate space: `Began` at
119    /// `from`, a few `Changed` samples along the segment, `Ended` at `to`, the same
120    /// `Event::Drag` stream a native recognizer delivers, so `.on_drag` state machines
121    /// (canvas move/resize) run their whole preview→commit path. Injected, like every
122    /// dayscript step: green here says the app logic holds, not that the platform recognizer
123    /// fires; verify that with real input (docs/agent.md).
124    Drag {
125        id: String,
126        from: [f64; 2],
127        to: [f64; 2],
128        /// Intermediate `Changed` samples between the endpoints (default 4).
129        #[serde(default)]
130        steps: Option<u32>,
131        /// Modifier keys "held" for the whole drag, named as in [`Step::Tap`], for gestures
132        /// whose meaning they change (a shift-drag that adds to a selection rather than
133        /// replacing it). They stand in for every phase, press through release, because that
134        /// is how a real drag reads them: once, when it starts.
135        #[serde(default)]
136        modifiers: Vec<String>,
137    },
138    /// A synthetic pointer hover over one element (`.on_hover`, docs/canvas.md "Interaction"):
139    /// the pointer enters at `at` (element coordinates; the center when omitted), or, with
140    /// `leave: true`, leaves. Injected, like [`Step::Drag`].
141    Hover {
142        id: String,
143        #[serde(default)]
144        at: Option<[f64; 2]>,
145        #[serde(default)]
146        leave: bool,
147    },
148    /// A synthetic two-finger pan over one element (`.on_pan`, docs/shapes.md): `Began`, a few
149    /// `Changed` samples whose deltas add up to `by`, `Ended`. Injected, like [`Step::Drag`].
150    Pan {
151        id: String,
152        by: [f64; 2],
153        /// `Changed` samples (default 4).
154        #[serde(default)]
155        steps: Option<u32>,
156    },
157    /// A synthetic pinch over one element (`.on_pinch`, docs/shapes.md): `Began` at scale 1,
158    /// `Changed` samples toward `scale`, `Ended` at `scale` (cumulative, as the platforms
159    /// report it), centered on the element. Injected, like [`Step::Drag`].
160    Pinch {
161        id: String,
162        scale: f64,
163        /// `Changed` samples (default 4).
164        #[serde(default)]
165        steps: Option<u32>,
166    },
167    /// Deliver `Event::Submitted` to the element: the scripted stand-in for the platform's
168    /// submit gesture (Enter in a `text_area` with `.on_submit`, a field's return key).
169    Submit {
170        id: String,
171    },
172    Input {
173        id: String,
174        #[serde(default)]
175        text: Option<String>,
176        /// Localized alternative to `text`: resolve this Fluent key (with `args`) in the run's
177        /// locale and type the result, for locale-portable queries (e.g. a localized fruit name).
178        #[serde(default)]
179        key: Option<String>,
180        #[serde(default)]
181        args: Option<BTreeMap<String, serde_json::Value>>,
182    },
183    SetValue {
184        id: String,
185        value: f64,
186    },
187    Toggle {
188        id: String,
189        #[serde(default)]
190        value: Option<bool>,
191    },
192    /// Invoke a list row without changing selection. Out-of-range indices are ignored.
193    Activate {
194        id: String,
195        index: usize,
196    },
197    Select {
198        id: String,
199        index: i64,
200        /// Skip an absent element after UI transitions settle, as `tap`'s does. For a
201        /// control that only some layouts have: the pane switcher a phone shows where a wide
202        /// window shows both panes.
203        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
204        if_present: bool,
205    },
206    /// Drag-reorder a list row programmatically: row `from` drops at row `to` through the same
207    /// guard → commit path a native drag takes (docs/list.md); the app's `reorder_guard` may
208    /// deny or retarget it. Fails (non-retryably) when the list isn't `.reorderable()` or the
209    /// guard denies the move.
210    Reorder {
211        id: String,
212        from: usize,
213        to: usize,
214    },
215    /// Undo one unit of the app's history, through the installed undo bridge, the same
216    /// handler ⌘Z and the Edit menu reach (docs/model.md). Portable: it needs no undo
217    /// button and no scriptable menu item on the target. Fails (non-retryably) when the
218    /// app never installed an undo stack.
219    Undo,
220    /// Redo one unit, [`Step::Undo`]'s mirror.
221    Redo,
222    /// Disclose or collapse a tree row programmatically (docs/tree.md). The row is resolved
223    /// by its `.row_id` string; the step emits the same `Event::TreeExpanded` a native
224    /// disclosure does, so the piece's expansion signal (and through it the native row)
225    /// follows. Retryable while the row id is unknown (a pending reload may still produce it).
226    Expand {
227        id: String,
228        row: String,
229        #[serde(default = "default_true")]
230        expanded: bool,
231    },
232    /// Move a tree row programmatically: `row` lands under `parent` (absent = the root) at
233    /// `index` (absent = dropped onto the parent, i.e. append), through the same guard → commit
234    /// path a native drag takes (docs/tree.md). Fails (non-retryably) when the tree isn't
235    /// `.movable()` or a guard (structural or the app's) denies the move.
236    TreeMove {
237        id: String,
238        row: String,
239        #[serde(default)]
240        parent: Option<String>,
241        #[serde(default)]
242        index: Option<usize>,
243    },
244    /// Delete a list row programmatically: row `row` goes through the same guard → commit path
245    /// a native swipe takes (docs/list.md); the app's `delete_guard` may refuse it. Fails
246    /// (non-retryably) when the list isn't `.deletable()` or the guard refuses.
247    ///
248    /// This is how a walkthrough asserts deletion on every target, including the desktops whose
249    /// toolkits answer `Cap::ListDelete = Unsupported` and have no gesture to simulate: the step
250    /// drives the guard → commit path, not the platform's gesture recognizer.
251    DeleteRow {
252        id: String,
253        row: usize,
254    },
255    /// Activate a list row's swipe action programmatically: pull row `row`'s offer for `edge`
256    /// (`trailing`, the default, or `leading`) and run action `action` (an index into the
257    /// offer, default 0, the one a native full swipe activates), through the same
258    /// offer → commit path a native gesture takes (docs/list.md). `label:` (literal) or
259    /// `key:` (a Fluent key resolved in the run's locale) pins which button may be pressed.
260    /// Offers are state-dependent ("Mark as Read" vs "Mark as Unread"), and the pin is
261    /// checked before the press: a mismatched offer refuses the activation and fails the
262    /// step with the row's state untouched, so a stale pin (leftover state from an aborted
263    /// earlier run) fails once instead of flipping state and poisoning every later run.
264    /// Fails (non-retryably) when the list offers no swipe actions or the row's offer has
265    /// no such action.
266    ///
267    /// This is how a walkthrough exercises swipe actions on every target, including the
268    /// toolkits that answer `Cap::ListSwipeActions = Unsupported` and show no affordance:
269    /// the step drives the offer → commit path, not the platform's gesture recognizer.
270    SwipeRow {
271        id: String,
272        row: usize,
273        #[serde(default)]
274        edge: Option<String>,
275        #[serde(default)]
276        action: usize,
277        #[serde(default)]
278        label: Option<String>,
279        #[serde(default)]
280        key: Option<String>,
281    },
282    /// Evaluate JavaScript in a web view node and assert on the result
283    /// (docs/webview-eval.md), the step that proves a page rendered, where
284    /// `assert_visible` only proves the native view exists. `script` runs in the page;
285    /// its value (a string compares as itself, anything else as its JSON) must contain
286    /// `contains:` and/or equal `text:`; with neither, a successful evaluation alone
287    /// passes. Retryable while the reply is pending, the script throws, or the assertion
288    /// mismatches (a page mid-load settles within the wait); fails non-retryably when the
289    /// id names no web view or no webview piece is linked. Only meaningful where the
290    /// backend's eval arm exists (`eval_support()`; docs/webview-eval.md keeps the list);
291    /// elsewhere the step fails after the wait, so gate it with `only_on:`.
292    WebEval {
293        id: String,
294        script: String,
295        #[serde(default)]
296        contains: Option<String>,
297        #[serde(default)]
298        text: Option<String>,
299        /// Override the shared wait for a cold browser engine or a slow page load.
300        #[serde(default)]
301        timeout_secs: Option<f64>,
302    },
303    /// Invoke an app-menu item programmatically (docs/menus.md): match a unique `Action`
304    /// leaf in the installed app-menu model by exact `item` label, or by `key`, a Fluent
305    /// key resolved in the run's locale (locale-portable; a standard-role item also
306    /// matches its role's core-catalog key, so the auto Preferences item is
307    /// `key: day_preferences`). `path` disambiguates with ancestor submenu labels (suffix
308    /// match). Items that run a native selector instead of a day action (role items with
309    /// id 0) are not invokable this way.
310    /// Choose an item from an element's context menu (`.context_menu`, `.context_menu_fn`;
311    /// docs/menus.md), as a right click or long press followed by a choice would. `id` names the
312    /// element; the item is addressed as [`Step::Menu`] addresses one: `item_id:` (the name the
313    /// app gave it), `item:` (the literal label) or `key:`, with `path` for submenus. A
314    /// provider menu is asked at the element's origin.
315    ContextMenu {
316        id: String,
317        /// Skip an absent element after UI transitions settle, as `tap` does: for idempotent
318        /// fixture cleanup through a row's menu.
319        #[serde(default)]
320        if_present: bool,
321        #[serde(default)]
322        item_id: Option<String>,
323        #[serde(default)]
324        item: Option<String>,
325        #[serde(default)]
326        key: Option<String>,
327        #[serde(default)]
328        path: Option<Vec<String>>,
329    },
330    /// Choose an app-menu item. Address it by `id:` (the name the app gave it with
331    /// `MenuEntry::id`) in preference to anything else: a label is localized, and an item that
332    /// shows a check mark rewrites its label as the state moves, so neither is a stable
333    /// address. `item:` matches the literal label, `key:` a built-in role key (`day_copy`) or a
334    /// Fluent key resolved in the run's locale.
335    Menu {
336        #[serde(default)]
337        id: Option<String>,
338        #[serde(default)]
339        item: Option<String>,
340        #[serde(default)]
341        key: Option<String>,
342        #[serde(default)]
343        path: Option<Vec<String>>,
344    },
345    /// Drive a window-toolbar item by its id (docs/toolbars.md). With neither `text:` nor
346    /// `on:` this runs a button's command; `text:` types into a search item; `on:` sets a
347    /// toggle. Each goes through the same dispatch the native control fires, so it exercises
348    /// the app's wiring; it does not prove the native widget drew (a screenshot does). With
349    /// `submit: true` a search item's text is then submitted, as its Return or Search key does.
350    Toolbar {
351        item: String,
352        #[serde(default)]
353        text: Option<String>,
354        /// Localized alternative to `text`, exactly as [`Step::Input`] takes one: resolve this
355        /// Fluent key (with `args`) in the run's locale and type the result. A toolbar search
356        /// field that filters on localized text needs this: a literal query written in English
357        /// matches nothing once the run switches locale.
358        #[serde(default)]
359        key: Option<String>,
360        #[serde(default)]
361        args: Option<BTreeMap<String, serde_json::Value>>,
362        #[serde(default)]
363        on: Option<bool>,
364        /// A segmented item's choice, by index (docs/toolbars.md). The step fails rather than
365        /// guessing if the item is not segmented or the index is out of range.
366        #[serde(default)]
367        index: Option<usize>,
368        /// Submit a search item's `text` (or `key`) after typing it (docs/search.md).
369        #[serde(default)]
370        submit: bool,
371    },
372    AssertVisible {
373        id: String,
374    },
375    /// Fail if the id is in the tree: the assertion for a subtree a `when` has not mounted
376    /// (a property row that does not apply, a page's absent chrome). `assert_visible` cannot
377    /// say this: a missing id is an error there, and an error is not a pass.
378    AssertMissing {
379        id: String,
380    },
381    /// Fail if the element is on screen: pass when it is missing, has an empty frame, or its
382    /// native widget reports itself hidden. For what a toolkit hides rather than removes (a
383    /// collapsed pane, a closed popover), where `assert_missing` would see it present.
384    AssertHidden {
385        id: String,
386    },
387    AssertText {
388        id: String,
389        #[serde(default)]
390        text: Option<String>,
391        #[serde(default)]
392        key: Option<String>,
393        #[serde(default)]
394        args: Option<BTreeMap<String, serde_json::Value>>,
395        /// Upper bound in seconds for the implicit retry wait (§14.3), for text that changes only
396        /// after slow work (a download finishing, an upload's receipt). Defaults to the shared
397        /// step timeout.
398        #[serde(default)]
399        timeout_secs: Option<f64>,
400    },
401    AssertValue {
402        id: String,
403        value: serde_json::Value,
404    },
405    /// Check an element's frame (docs/testing.md): its size, and its origin relative to
406    /// `relative_to`'s (or to the window content when absent), in points, within `tolerance`
407    /// (default 1). Day's layout must match, and so must the native widget's frame where the
408    /// toolkit reads it back; where it cannot, the reply's `data` lists the frame as unread.
409    AssertFrame {
410        id: String,
411        #[serde(default)]
412        width: Option<f64>,
413        #[serde(default)]
414        height: Option<f64>,
415        #[serde(default)]
416        x: Option<f64>,
417        #[serde(default)]
418        y: Option<f64>,
419        #[serde(default)]
420        relative_to: Option<String>,
421        #[serde(default)]
422        tolerance: Option<f64>,
423    },
424    /// Check the color of one point of an element in an in-process capture (docs/testing.md).
425    /// `x` and `y` are fractions of the element's frame (0.5, 0.5 is its center); `color` is
426    /// `#rrggbb`, matched per channel within `tolerance` (default 64 of 255, which absorbs color
427    /// management, such as a Display P3 capture reading sRGB red as `#ea3323`, and antialiasing,
428    /// but not a different color). A toolkit with no capture
429    /// (`Cap::Snapshot` unsupported) passes it as unread.
430    SamplePixel {
431        id: String,
432        x: f64,
433        y: f64,
434        color: String,
435        #[serde(default)]
436        tolerance: Option<u8>,
437    },
438    /// Check that the app asked to open `url` during this test run (docs/testing.md). While
439    /// `run_tests` runs, `open_url` records instead of opening anything.
440    AssertOpenedUrl {
441        url: String,
442    },
443    /// Check that the app announced `text` to the screen reader during this test run
444    /// (`day::announce`, docs/accessibility.md). The announcement still reaches the toolkit.
445    AssertAnnounced {
446        text: String,
447    },
448    /// Compare the NATIVE widget with what is expected (docs/testing.md): the state the
449    /// platform reports through `Toolkit::read_native`, not Day's tree. Only the fields given
450    /// are checked. A field the toolkit cannot read passes and is listed as unread in the
451    /// reply's `data`, so a gap is recorded rather than hidden. `enabled` is also checked
452    /// against Day's own state, so a disagreement between the two fails either way.
453    AssertNative {
454        id: String,
455        #[serde(default)]
456        text: Option<String>,
457        #[serde(default)]
458        number: Option<f64>,
459        #[serde(default)]
460        checked: Option<bool>,
461        #[serde(default)]
462        enabled: Option<bool>,
463        #[serde(default)]
464        visible: Option<bool>,
465    },
466    /// Fail if any piece kind rendered a `⟨kind⟩` placeholder, i.e. the backend had no renderer
467    /// for it. Placeholders are invisible to every other assertion (the app still renders, the
468    /// screenshot still looks plausible), so this is the only step that catches a missing or
469    /// silently-dropped renderer. `allow` lists the kinds a target is expected to lack, which
470    /// makes the script itself the per-target gap ledger; anything outside it is a failure.
471    AssertNoPlaceholders {
472        #[serde(default)]
473        allow: Vec<String>,
474    },
475    /// Close the secondary window opened under `window` (`day::open_window`'s key;
476    /// the preferences window is `day.preferences`), through the same async confirm →
477    /// teardown path a title-bar close takes (docs/windows.md; on the cover-fallback tier
478    /// this dismisses the cover). An already-closed window is a success (closing is
479    /// idempotent). With no `window`, the app's initial window, whose close ends the app
480    /// (docs/windows.md close policy), so follow it with `expect_exit`. GTK routes that close
481    /// through the title bar's path today; the other desktop toolkits' `close_window` duties
482    /// still look only at secondary windows, so there the step is a no-op and `expect_exit`
483    /// times out.
484    CloseWindow {
485        #[serde(default)]
486        window: Option<String>,
487    },
488    Screenshot {
489        name: String,
490        /// Capture the secondary window opened under this key (`day::open_window`'s `key`)
491        /// instead of the primary (docs/windows.md). On the cover-fallback tier the key
492        /// resolves to the primary window, whose fullscreen cover is the content: the same
493        /// pixels, no special case. A missing key fails retryably (the window may still be
494        /// opening).
495        #[serde(default)]
496        window: Option<String>,
497        /// Whether the reply carries the engine's capture (`png_base64`).
498        ///
499        /// On a device target the runner captures through `simctl`/`adb` and that image
500        /// (whole screen, system chrome and all) is what the gallery publishes, so a payload
501        /// rendered here would be encoded, shipped over the socket and dropped on the floor.
502        /// Measured at 819ms per shot on the iOS simulator (33.6s across one walkthrough
503        /// variant, ~4.5 minutes across a CI job's eight), so the runner asks for it only
504        /// where it will be used, and re-asks with this set if the device capture fails.
505        ///
506        /// Defaults to `true`: an older runner, `day drive`, or a hand-written step says
507        /// nothing and still gets the image. The idle wait above happens either way; it is
508        /// what makes a capture land on a settled frame, not an artifact of the encoding.
509        #[serde(default = "default_true")]
510        in_process: bool,
511    },
512    Pause {
513        secs: f64,
514    },
515    /// Deliver a deep-link URL in-process (docs/deep-links.md): the URL maps to its route
516    /// through the same `day_spec::route_of_url` every platform intake uses, then navigates,
517    /// identical to a warm OS delivery. Proves routing, params, and back-stack seeding on
518    /// every backend, including mock; OS registration and intake are the runner tier's job.
519    DeepLink {
520        url: String,
521    },
522    /// Deliver an original external URL to on_open_url (with normal routing fallback).
523    OpenUrl {
524        url: String,
525    },
526    /// Navigate to a registered route (reset-to semantics; "" = root). docs/navigation.md.
527    Navigate {
528        route: String,
529    },
530    /// Pop one navigation level. Bare, it is Day's own rail (`day_core::nav_back`), which pops
531    /// the model and lets the backend follow. `native: true` presses the platform's back
532    /// affordance instead (`Toolkit::native_back`): the bar's `shouldPop`, the dispatcher's
533    /// callbacks, the native pop, then the backend's report of it to Day as a user back, which
534    /// is the code a real tap runs and the bare step never reaches (docs/navigation.md).
535    NavBack {
536        // Skipped when false so a recorded bare back still writes as `- nav_back:`.
537        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
538        native: bool,
539    },
540    /// Assert the current route path ("" = root).
541    AssertRoute {
542        route: String,
543    },
544    /// Select presentation behavior for subsequent Day dialogs and file pickers.
545    /// Existing requests must be answered before switching.
546    DialogMode {
547        mode: DialogMode,
548    },
549    /// Assert that no Day presentation requests remain unanswered.
550    AssertNotPresented,
551    /// Assert a presentation is pending (native or scripted), optionally checking its title.
552    AssertPresented {
553        #[serde(default)]
554        title: Option<String>,
555    },
556    /// Answer the open modal: a button `index`, a prompt `text`, a file `path` (open/save
557    /// pickers; relative paths resolve against the app temp dir, writable on every target), or
558    /// `dismiss`.
559    Respond {
560        #[serde(default)]
561        button: Option<i64>,
562        #[serde(default)]
563        text: Option<String>,
564        #[serde(default)]
565        path: Option<String>,
566        #[serde(default)]
567        dismiss: bool,
568    },
569    /// Diff the native accessibility tree against Day's expectations (role/label/value/identifier)
570    /// for every id'd node, or just `id` (§13, §14.2). Backends that can't read their native tree
571    /// (`found = false`) are skipped; role is only compared when both sides map to a known `Role`.
572    A11yAudit {
573        #[serde(default)]
574        id: Option<String>,
575    },
576    /// List the `#[day::test]` cases the binary registers (docs/testing.md); the reply's
577    /// `data` is the listing.
578    Tests,
579    /// Run the registered tests whose names match `filter` (globs; empty = all), keeping
580    /// captures per `shots`. Retryable while the run is in progress, so the runner's wait loop
581    /// polls it; `timeout_secs` bounds the whole run, `case_timeout_secs` each case. The
582    /// reply's `data` is the report.
583    RunTests {
584        #[serde(default)]
585        filter: Vec<String>,
586        #[serde(default)]
587        shots: ShotPolicy,
588        #[serde(default)]
589        timeout_secs: Option<f64>,
590        /// Each case's time limit where the case sets none (default 30 s); `0` turns every
591        /// limit off, for a run held at a debugger's breakpoint.
592        #[serde(default)]
593        case_timeout_secs: Option<f64>,
594    },
595    /// Move native focus to the control: the real Toolkit duty, not a synthetic event, so
596    /// keyboards and end-editing flows engage (docs/focus.md). `focused: false` resigns it.
597    Focus {
598        id: String,
599        #[serde(default)]
600        focused: Option<bool>,
601    },
602    /// Assert the control's focus state as Day resolved it (`NodeProbe.focused`; retryable, since
603    /// focus lands a turn after the request). `focused` defaults to `true`.
604    AssertFocused {
605        id: String,
606        #[serde(default)]
607        focused: Option<bool>,
608    },
609    /// Expect the app to terminate: the only step that tolerates the app dying (docs/break.md's
610    /// crash-reporting flow, docs/agent.md). Must be the last step: a preceding step triggered an
611    /// exit or crash, and `expect_exit` treats the connection dropping within `within`
612    /// seconds (default 15) as success; the app surviving the window is the failure. Handled
613    /// runner-side (`day-cli`), so the in-app engine never executes it; this arm is defensive.
614    ExpectExit {
615        #[serde(default)]
616        within: Option<f64>,
617    },
618    /// Force the window's size class (docs/size-classes.md) without resizing anything: the
619    /// cheap way to drive a responsive layout on a backend whose window cannot be resized from a
620    /// script (the phones, an emulator). `width` is `compact` | `medium` | `expanded` | `large` |
621    /// `extra-large`; `height` is `compact` | `medium` | `expanded` and defaults to `expanded`.
622    ///
623    /// This reports a class the way a backend would, so everything downstream (an automatic
624    /// nav host re-presenting, a piece that lays out from `day::size_class()`) runs its real
625    /// path. What it does not do is change the window's actual pixels: a screenshot after this
626    /// step shows the new layout at the old size. Drive a real resize from the runner instead
627    /// (Playwright's `setViewportSize` on web, the simulator's rotation on iOS) when the
628    /// geometry itself is what's under test.
629    /// `width: auto` releases the override and restores the class the window itself reports, so
630    /// the steps after an adaptive sweep run at the device's real geometry again. A script that
631    /// forces `expanded` and never lets go leaves a phone laying out a split whose detail pane
632    /// falls off the screen: the layout is correct, the window just isn't that wide.
633    SizeClass {
634        width: String,
635        #[serde(default)]
636        height: Option<String>,
637    },
638    /// Change the window's actual geometry, and wait until the app has reported the new size
639    /// (docs/size-classes.md). The runner performs the resize (a device's window belongs to the
640    /// system, not to the app) and this half is the barrier: without it the next step races the
641    /// platform's resize animation.
642    ///
643    /// `size_class:`'s complement, and the difference matters: that step reports a class the
644    /// window is not actually at, so a screenshot after it shows the new layout at the old size.
645    /// This one moves the pixels.
646    Resize {
647        #[serde(default)]
648        width: Option<f64>,
649        #[serde(default)]
650        height: Option<f64>,
651        /// `resize: auto`: back to the device's geometry.
652        #[serde(default)]
653        restore: bool,
654    },
655}
656
657impl Step {
658    /// The implicit-wait budget for this step, seconds: its own `timeout_secs` when declared
659    /// (and positive), else the shared [`DEFAULT_TIMEOUT_SECS`].
660    pub fn wait_budget_secs(&self) -> f64 {
661        match self {
662            Step::WaitFor {
663                timeout_secs: Some(t),
664                ..
665            }
666            | Step::AssertText {
667                timeout_secs: Some(t),
668                ..
669            }
670            | Step::WebEval {
671                timeout_secs: Some(t),
672                ..
673            }
674            | Step::RunTests {
675                timeout_secs: Some(t),
676                ..
677            } if *t > 0.0 => *t,
678            _ => DEFAULT_TIMEOUT_SECS,
679        }
680    }
681}
682
683impl Step {
684    /// The stable snake-case operation name used on the wire and in script files.
685    pub const fn op(&self) -> &'static str {
686        match self {
687            Self::WaitFor { .. } => "wait_for",
688            Self::WaitIdle => "wait_idle",
689            Self::MemoryUsage { .. } => "memory_usage",
690            Self::MemoryWatch { .. } => "memory_watch",
691            Self::IdCatalog => "id_catalog",
692            Self::IdMounted => "id_mounted",
693            Self::ScrollTo { .. } => "scroll_to",
694            Self::Tap { .. } => "tap",
695            Self::Key { .. } => "key",
696            Self::Drag { .. } => "drag",
697            Self::Hover { .. } => "hover",
698            Self::Pan { .. } => "pan",
699            Self::Pinch { .. } => "pinch",
700            Self::Submit { .. } => "submit",
701            Self::Input { .. } => "input",
702            Self::SetValue { .. } => "set_value",
703            Self::Toggle { .. } => "toggle",
704            Self::Activate { .. } => "activate",
705            Self::Select { .. } => "select",
706            Self::Reorder { .. } => "reorder",
707            Self::Undo => "undo",
708            Self::Redo => "redo",
709            Self::Expand { .. } => "expand",
710            Self::TreeMove { .. } => "tree_move",
711            Self::DeleteRow { .. } => "delete_row",
712            Self::SwipeRow { .. } => "swipe_row",
713            Self::WebEval { .. } => "web_eval",
714            Self::ContextMenu { .. } => "context_menu",
715            Self::Menu { .. } => "menu",
716            Self::Toolbar { .. } => "toolbar",
717            Self::AssertVisible { .. } => "assert_visible",
718            Self::AssertMissing { .. } => "assert_missing",
719            Self::AssertHidden { .. } => "assert_hidden",
720            Self::AssertText { .. } => "assert_text",
721            Self::AssertValue { .. } => "assert_value",
722            Self::AssertFrame { .. } => "assert_frame",
723            Self::SamplePixel { .. } => "sample_pixel",
724            Self::AssertOpenedUrl { .. } => "assert_opened_url",
725            Self::AssertAnnounced { .. } => "assert_announced",
726            Self::AssertNative { .. } => "assert_native",
727            Self::AssertNoPlaceholders { .. } => "assert_no_placeholders",
728            Self::CloseWindow { .. } => "close_window",
729            Self::Screenshot { .. } => "screenshot",
730            Self::Pause { .. } => "pause",
731            Self::DeepLink { .. } => "deep_link",
732            Self::OpenUrl { .. } => "open_url",
733            Self::Navigate { .. } => "navigate",
734            Self::NavBack { .. } => "nav_back",
735            Self::AssertRoute { .. } => "assert_route",
736            Self::DialogMode { .. } => "dialog_mode",
737            Self::AssertNotPresented => "assert_not_presented",
738            Self::AssertPresented { .. } => "assert_presented",
739            Self::Respond { .. } => "respond",
740            Self::A11yAudit { .. } => "a11y_audit",
741            Self::Tests => "tests",
742            Self::RunTests { .. } => "run_tests",
743            Self::Focus { .. } => "focus",
744            Self::AssertFocused { .. } => "assert_focused",
745            Self::ExpectExit { .. } => "expect_exit",
746            Self::SizeClass { .. } => "size_class",
747            Self::Resize { .. } => "resize",
748        }
749    }
750}
751
752/// Defaults to on for fields introduced after the first protocol version.
753fn default_true() -> bool {
754    true
755}
756
757#[derive(Serialize, Deserialize, Debug, Default, PartialEq)]
758pub struct Reply {
759    #[serde(default, skip_serializing_if = "<[IdEvidence]>::is_empty")]
760    pub id_evidence: Box<[IdEvidence]>,
761    pub ok: bool,
762    #[serde(default, skip_serializing_if = "Option::is_none")]
763    pub error: Option<String>,
764    /// Set on failures that may succeed after a wait (element not found yet, assert pending).
765    #[serde(default)]
766    pub retryable: bool,
767    #[serde(default, skip_serializing_if = "Option::is_none")]
768    pub png_base64: Option<String>,
769    #[serde(default)]
770    pub screenshot_unsupported: bool,
771    /// Acknowledged render checkpoint. Absent when talking to an older app or when
772    /// freshness can only be established by an in-process snapshot.
773    #[serde(default, skip_serializing_if = "Option::is_none")]
774    pub capture_revision: Option<u32>,
775    /// App-side policy acknowledgment. Older apps omit it; runners must retain
776    /// animation pauses until the app confirms that fast motion is active.
777    #[serde(default, skip_serializing_if = "Option::is_none")]
778    pub fast_animations: Option<bool>,
779    /// Internal retry cadence: frame checkpoints can complete on the next display tick.
780    #[serde(skip)]
781    pub capture_pending: bool,
782    /// A step's structured answer (`tests`, `run_tests`, `memory_usage`).
783    #[serde(default, skip_serializing_if = "Option::is_none")]
784    pub data: Option<serde_json::Value>,
785    /// Unsolicited telemetry on a connection that explicitly enabled `memory_watch`.
786    #[serde(default, skip_serializing_if = "Option::is_none")]
787    pub memory_sample: Option<Box<MemorySample>>,
788    /// The step never ran: the app's main thread did not pick it up within the engine's
789    /// budget. Every later step would wait the full budget and fail the same way, so a runner
790    /// abandons the flow on this rather than on the error text. Older apps omit it.
791    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
792    pub main_thread_stalled: bool,
793}
794
795#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
796pub struct MemorySample {
797    pub bytes: Option<u64>,
798    pub metric: String,
799}
800
801impl Reply {
802    pub fn ok() -> Self {
803        Reply {
804            ok: true,
805            ..Default::default()
806        }
807    }
808    pub fn fail(msg: impl Into<String>, retryable: bool) -> Self {
809        Reply {
810            ok: false,
811            error: Some(msg.into()),
812            retryable,
813            ..Default::default()
814        }
815    }
816}
817
818#[cfg(test)]
819mod close_window_tests {
820    use super::*;
821
822    /// `close_window: {}` is the initial window; a key still names a secondary one.
823    #[test]
824    fn close_window_defaults_to_the_initial_window() {
825        let step: Step = serde_json::from_str(r#"{"op":"close_window"}"#).expect("parse");
826        assert_eq!(step, Step::CloseWindow { window: None });
827        let step: Step =
828            serde_json::from_str(r#"{"op":"close_window","window":"day.preferences"}"#)
829                .expect("parse");
830        assert_eq!(
831            step,
832            Step::CloseWindow {
833                window: Some("day.preferences".into())
834            }
835        );
836    }
837}