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