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