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