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