Skip to main content

day_script/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-script: the embedded dayscript engine (DESIGN.md §14). Bind-only-when-invited: the
5//! server starts only when `DAYSCRIPT_PORT` + `DAYSCRIPT_TOKEN` are present in the environment
6//! (never otherwise), listens on 127.0.0.1, and accepts only the step catalog. Steps execute
7//! as synthesized Day events on the main thread between flushes, deterministic and
8//! toolkit-uniform. Locator steps get an implicit bounded wait (default 5s).
9
10use std::collections::BTreeMap;
11use std::io::{BufRead, BufReader, Write};
12use std::net::{TcpListener, TcpStream};
13use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
14use std::sync::{Arc, mpsc};
15use std::time::{Duration, Instant};
16
17use day_core::{NodeProbe, rnode_to_id, with_tree};
18
19/// The dayscript **recorder** and in-process **playback** (§14.6): capture the events an app
20/// receives back into a replayable dayscript, and replay one against the live UI. See
21/// [`record::start`]/[`record::play`].
22pub mod record;
23pub use record::play;
24/// The in-app test runner behind `day test` (docs/testing.md).
25pub mod conformance;
26mod memory;
27mod memory_watch;
28/// The PNG reader behind `sample_pixel` (docs/testing.md).
29pub mod png;
30
31/// How long one dispatch may wait for the main thread before the step is failed.
32///
33/// This is not the step's implicit-wait budget ([`DEFAULT_TIMEOUT_SECS`], §14.3). That one governs
34/// re-asking a question whose answer may change ("is it visible yet?"). This one governs a main
35/// thread that has not answered *at all*: a CI runner compositing its first frame on a shared vCPU,
36/// a debug build faulting in pages, a compositor stall. Those are properties of the machine, not of
37/// the script, which is why `DAY_SCRIPT_MAIN_TIMEOUT_SECS` can raise it without editing a
38/// walkthrough. It was a flat 10s, and a single Windows runner hiccup mid-walkthrough was enough to
39/// fail an otherwise perfect 407-step run.
40pub const DEFAULT_MAIN_TIMEOUT_SECS: f64 = 30.0;
41
42// Preserve the embedded engine's public protocol API; the definitions live in the leaf crate.
43pub use day_script_protocol::{DEFAULT_TIMEOUT_SECS, DialogMode, Reply, Request, Step};
44
45/// `size_class:`'s `width:` spelling → the class. Kebab-case, matching how the docs name them.
46fn parse_width_class(s: &str) -> Option<day_spec::WidthClass> {
47    use day_spec::WidthClass as W;
48    match s {
49        "compact" => Some(W::Compact),
50        "medium" => Some(W::Medium),
51        "expanded" => Some(W::Expanded),
52        "large" => Some(W::Large),
53        "extra-large" => Some(W::ExtraLarge),
54        _ => None,
55    }
56}
57
58/// `size_class:`'s `height:` spelling → the class.
59fn parse_height_class(s: &str) -> Option<day_spec::HeightClass> {
60    use day_spec::HeightClass as H;
61    match s {
62        "compact" => Some(H::Compact),
63        "medium" => Some(H::Medium),
64        "expanded" => Some(H::Expanded),
65        _ => None,
66    }
67}
68
69/// The `undo:`/`redo:` steps' shared body: through the installed bridge, or a non-retryable
70/// failure when the app has no undo stack.
71fn drive_undo(redo: bool) -> Result<Reply, Reply> {
72    if day_core::invoke_undo(redo) {
73        day_reactive::flush_sync();
74        Ok(Reply::ok())
75    } else {
76        Err(Reply::fail("no undo stack installed".to_string(), false))
77    }
78}
79
80// ---------------------------------------------------------------------------
81// Engine activation + server
82// ---------------------------------------------------------------------------
83
84/// Start the engine iff invited via env (call before `launch_with`; inert otherwise).
85pub fn init() {
86    // Recording (§14.6) is independent of the socket engine: `DAY_RECORD=<path>` (from `day launch
87    // --record`, or set directly) starts a headless recorder that continuously flushes a replayable
88    // dayscript to that file for the app's lifetime; no port/token needed. Checked before the
89    // engine gate so `--record` works on an ordinary launch, and on every backend that calls
90    // `init()`.
91    if let Some(path) = std::env::var_os("DAY_RECORD").filter(|p| !p.is_empty()) {
92        record::start_to_file(path);
93    }
94    // `DAY_LOG_ACTIONS=1` narrates every action to stdout without recording anything (§14.6): the
95    // same lines a recording echoes. An app can also switch it on for itself with
96    // `day::record::log_actions(true)`; the env var is here so any app gets it without a rebuild.
97    if std::env::var("DAY_LOG_ACTIONS").is_ok_and(|v| v == "1") {
98        record::log_actions(true);
99    }
100    let (Ok(port), Ok(token)) = (
101        std::env::var("DAYSCRIPT_PORT"),
102        std::env::var("DAYSCRIPT_TOKEN"),
103    ) else {
104        return;
105    };
106    let Ok(port) = port.parse::<u16>() else {
107        return;
108    };
109    std::thread::spawn(move || serve(port, &token));
110}
111
112// ---------------------------------------------------------------------------
113// Web transport (docs/web.md): the host page pipes newline-JSON request lines from a
114// WebSocket into [`web_line`], and replies leave through the sender given to [`web_init`]
115// (the day-cli dev server bridges that WebSocket to the same TCP protocol the runner
116// already speaks, so `day drive`/`--script` are unchanged). Everything runs on the one
117// wasm thread: the implicit bounded wait reschedules through the delayed poster instead
118// of sleeping, and there is no `Instant` (it traps on wasm), so attempts are counted.
119// ---------------------------------------------------------------------------
120
121/// Retry cadence of the implicit bounded wait, shared by both transports.
122const RETRY_MS: u32 = 100;
123
124#[cfg(target_arch = "wasm32")]
125mod web {
126    use super::*;
127    use std::cell::RefCell;
128
129    /// One reply line out to the page (installed by [`web_init`]).
130    type WebSender = Box<dyn Fn(&str)>;
131
132    thread_local! {
133        /// (token, reply sender) once [`web_init`] ran; requests before/without it are dropped.
134        static WEB: RefCell<Option<(String, WebSender)>> = const { RefCell::new(None) };
135        static WATCH: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
136    }
137
138    /// Arm the web transport: `token` authenticates each request (the query-parameter
139    /// spelling of `DAYSCRIPT_TOKEN`), `send` carries one reply line back to the page.
140    pub fn web_init(token: String, send: impl Fn(&str) + 'static) {
141        WATCH.with(|w| w.set(w.get() + 1));
142        WEB.with(|w| *w.borrow_mut() = Some((token, Box::new(send))));
143    }
144
145    /// One request line from the page. Executes on the main thread now; a retryable failure
146    /// reschedules itself until the shared step timeout is spent, then the reply goes out
147    /// through the sender. Requests are answered in order because the runner awaits each
148    /// reply before sending the next step.
149    pub fn web_line(line: &str) {
150        let reply = match serde_json::from_str::<Request>(line.trim()) {
151            Ok(req) => {
152                let authed =
153                    WEB.with(|w| w.borrow().as_ref().is_some_and(|(t, _)| *t == req.token));
154                if authed {
155                    if let Step::MemoryWatch { interval_ms } = req.step {
156                        if !memory_watch::valid_interval(interval_ms) {
157                            send_reply(&Reply::fail(
158                                "memory_watch interval must be 0 or 100..60000 ms",
159                                false,
160                            ));
161                            return;
162                        }
163                        let generation = WATCH.with(|w| {
164                            w.set(w.get() + 1);
165                            w.get()
166                        });
167                        send_reply(&memory_watch::sample());
168                        if interval_ms > 0 {
169                            watch_tick(generation, interval_ms as u32);
170                        }
171                        send_reply(&Reply::ok());
172                        return;
173                    }
174                    let budget_ms = (req.step.wait_budget_secs() * 1000.0) as u32;
175                    attempt(req.step, budget_ms, next_capture_revision());
176                    return;
177                }
178                Reply::fail("bad token", false)
179            }
180            Err(e) => Reply::fail(format!("bad request: {e}"), false),
181        };
182        send_reply(&reply);
183    }
184
185    fn attempt(step: Step, remaining_ms: u32, revision: u32) {
186        let reply = exec(step.clone(), revision);
187        if reply.ok || !reply.retryable || remaining_ms == 0 {
188            send_reply(&reply);
189            return;
190        }
191        let interval = if reply.capture_pending { 16 } else { RETRY_MS };
192        let delay = interval.min(remaining_ms);
193        day_reactive::on_main_delayed(delay, move || attempt(step, remaining_ms - delay, revision));
194    }
195
196    fn watch_tick(generation: u64, interval: u32) {
197        day_reactive::on_main_delayed(interval, move || {
198            if WATCH.with(std::cell::Cell::get) == generation {
199                send_reply(&memory_watch::sample());
200                watch_tick(generation, interval);
201            }
202        });
203    }
204
205    fn send_reply(reply: &Reply) {
206        let mut out = serde_json::to_string(reply).unwrap_or_else(|_| "{\"ok\":false}".into());
207        out.push('\n');
208        WEB.with(|w| {
209            if let Some((_, send)) = w.borrow().as_ref() {
210                send(&out);
211            }
212        });
213    }
214}
215#[cfg(target_arch = "wasm32")]
216pub use web::{web_init, web_line};
217
218fn serve(port: u16, token: &str) {
219    // Give the app time to mount before binding traffic arrives.
220    std::thread::sleep(Duration::from_millis(300));
221    // Retry, because the port is a fixed per-target number and a capture sweep relaunches the
222    // app on it every variant: the previous instance can still be letting go of the socket when
223    // this one starts. Giving up on the first EADDRINUSE is what made that silent: the engine
224    // thread ended, the app carried on without one, and the runner then talked to
225    // whatever was still listening. That is the previous variant's app, which shares this run's
226    // token and answers every step, so a locale sweep re-photographs the earlier locale instead
227    // of failing.
228    let deadline = std::time::Instant::now() + Duration::from_secs(15);
229    let mut said = false;
230    let listener = loop {
231        match TcpListener::bind(("127.0.0.1", port)) {
232            Ok(l) => break l,
233            Err(e) if std::time::Instant::now() < deadline => {
234                // Once, not per attempt: a sweep that waits a second or two per variant would
235                // otherwise bury the run's own output.
236                if !said {
237                    said = true;
238                    log::warn!("day-script: 127.0.0.1:{port} still busy ({e}) — waiting for it");
239                }
240                std::thread::sleep(Duration::from_millis(250));
241            }
242            Err(e) => {
243                // Loud: an app with no engine looks exactly like a healthy one until a script
244                // drives the wrong process.
245                log::error!(
246                    "day-script: bind 127.0.0.1:{port} failed after 15s: {e} — this app has NO \
247                     dayscript engine; anything driving this port is reaching a DIFFERENT process"
248                );
249                return;
250            }
251        }
252    };
253    for stream in listener.incoming().flatten() {
254        handle_conn(stream, token);
255    }
256}
257
258fn handle_conn(stream: TcpStream, token: &str) {
259    let _ = stream.set_nodelay(true);
260    let _ = stream.set_write_timeout(Some(Duration::from_secs(15)));
261    let mut reader = BufReader::new(stream.try_clone().expect("clone stream"));
262    let writer = Arc::new(std::sync::Mutex::new(stream));
263    let mut watch = None;
264    let mut line = String::new();
265    loop {
266        line.clear();
267        match reader.read_line(&mut line) {
268            Ok(0) | Err(_) => return,
269            Ok(_) => {}
270        }
271        let reply = match serde_json::from_str::<Request>(line.trim()) {
272            Ok(req) if req.token == token => {
273                if let Step::MemoryWatch { interval_ms } = req.step {
274                    if memory_watch::valid_interval(interval_ms) {
275                        drop(watch.take());
276                        if interval_ms > 0 {
277                            watch = Some(memory_watch::Watch::start(writer.clone(), interval_ms));
278                        }
279                        Reply::ok()
280                    } else {
281                        Reply::fail("memory_watch interval must be 0 or 100..60000 ms", false)
282                    }
283                } else {
284                    run_step_with_wait(&req.step)
285                }
286            }
287            Ok(_) => Reply::fail("bad token", false),
288            Err(e) => Reply::fail(format!("bad request: {e}"), false),
289        };
290        let mut out = serde_json::to_string(&reply).unwrap_or_else(|_| "{\"ok\":false}".into());
291        out.push('\n');
292        if writer.lock().unwrap().write_all(out.as_bytes()).is_err() {
293            return;
294        }
295    }
296}
297
298/// How many times in a row a failed window snapshot is retried before the engine answers
299/// "unsupported" (the `screenshot` step): about three seconds at [`RETRY_MS`].
300const SNAPSHOT_RETRIES: u32 = 30;
301/// Consecutive failed snapshots of the current `screenshot` step.
302static SNAPSHOT_MISSES: AtomicU32 = AtomicU32::new(0);
303/// A snapshot has succeeded in this process, so a failure is a window not ready, not a backend
304/// that cannot capture.
305static SNAPSHOT_WORKS: AtomicBool = AtomicBool::new(false);
306/// The retries ran out before any snapshot ever succeeded: this backend does not capture, and
307/// later `screenshot` steps answer "unsupported" at once.
308static SNAPSHOT_NEVER: AtomicBool = AtomicBool::new(false);
309
310/// How many retries a `focus` step waits for the toolkit's focus report before passing
311/// without it: about a second at [`RETRY_MS`].
312const FOCUS_WAIT_POLLS: u32 = 10;
313/// Retries the current `focus` step has spent waiting for its focus report.
314static FOCUS_WAITS: AtomicU32 = AtomicU32::new(0);
315
316/// Implicit bounded wait (§14.3): retryable failures poll on the main thread until timeout
317/// (the shared default, or the step's `timeout_secs` where it declares one).
318static CAPTURE_REVISION: AtomicU32 = AtomicU32::new(1);
319fn next_capture_revision() -> u32 {
320    CAPTURE_REVISION.fetch_add(1, Ordering::Relaxed)
321}
322
323/// Run one step on the calling thread, which must be Day's UI thread with a tree installed:
324/// the entry a harness that already sits on that thread (the mock, `cargo test`) uses instead
325/// of the socket.
326#[must_use]
327pub fn step(step: Step) -> Reply {
328    exec(step, next_capture_revision())
329}
330
331fn run_step_with_wait(step: &Step) -> Reply {
332    let revision = next_capture_revision();
333    let budget = Duration::from_secs_f64(step.wait_budget_secs());
334    let deadline = Instant::now() + budget;
335    let main_budget = main_thread_budget(budget);
336    loop {
337        let reply = run_on_main(step.clone(), main_budget, revision);
338        if reply.ok || !reply.retryable || Instant::now() > deadline {
339            return reply;
340        }
341        let retry_ms = if reply.capture_pending { 16 } else { RETRY_MS };
342        std::thread::sleep(Duration::from_millis(u64::from(retry_ms)));
343    }
344}
345
346/// The main-thread budget for one dispatch: [`DEFAULT_MAIN_TIMEOUT_SECS`], overridable by
347/// `DAY_SCRIPT_MAIN_TIMEOUT_SECS`, and never shorter than the step's wait budget: a step that
348/// declares `timeout_secs: 60` is saying the app may legitimately take that long.
349fn main_thread_budget(step_budget: Duration) -> Duration {
350    let secs = std::env::var("DAY_SCRIPT_MAIN_TIMEOUT_SECS")
351        .ok()
352        .and_then(|v| v.parse::<f64>().ok())
353        .filter(|v| v.is_finite() && *v > 0.0)
354        .unwrap_or(DEFAULT_MAIN_TIMEOUT_SECS);
355    Duration::from_secs_f64(secs).max(step_budget)
356}
357
358fn run_on_main(step: Step, budget: Duration, revision: u32) -> Reply {
359    // The engine can take a step before the backend has started and installed its main-thread
360    // poster (a runner connecting during a slow launch). Nothing can reach the UI thread yet,
361    // so the step goes back to the bounded wait as "not there yet", the same answer as a tree
362    // that is not built.
363    if !day_reactive::has_main_poster() {
364        return Reply::fail(
365            "the app is still starting (its UI thread is not running yet)",
366            true,
367        );
368    }
369    let (tx, rx) = mpsc::sync_channel::<Reply>(1);
370    // A dispatch that times out leaves its closure queued on the main thread, where it would run
371    // later and apply a `navigate`/`tap` the runner has already given up on, moving the app to a
372    // state the rest of the script does not expect, so the real damage shows up as a later step
373    // failing for no visible reason. The flag makes an abandoned dispatch a no-op. (It is checked
374    // before `exec`, so a dispatch that starts in the instant before the timeout still runs; that
375    // window is inherent without cancelling work already on the main thread.)
376    let abandoned = Arc::new(AtomicBool::new(false));
377    let flag = Arc::clone(&abandoned);
378    day_reactive::on_main(move || {
379        if flag.load(Ordering::SeqCst) {
380            return;
381        }
382        // The engine listens from the moment `day_script::init` runs, which is before the
383        // backend has built the tree; a runner that connects during a slow startup (day-piece-crash-reporter
384        // reconciling a crash from the previous launch is the reliable way to be slow) can land
385        // a step in that window. Answering "retryable" hands it back to the bounded wait, which
386        // is exactly the "not there yet" case that machinery exists for; running it anyway would
387        // panic inside `with_tree`.
388        if !day_core::has_tree() {
389            let _ = tx.send(Reply::fail("the app is still starting", true));
390            return;
391        }
392        let _ = tx.send(exec(step, revision));
393    });
394    if let Ok(reply) = rx.recv_timeout(budget) {
395        reply
396    } else {
397        abandoned.store(true, Ordering::SeqCst);
398        Reply {
399            main_thread_stalled: true,
400            ..Reply::fail(
401                format!(
402                    "main thread did not respond within {:.0}s — raise \
403                     DAY_SCRIPT_MAIN_TIMEOUT_SECS if this machine is just slow",
404                    budget.as_secs_f64()
405                ),
406                false,
407            )
408        }
409    }
410}
411
412// ---------------------------------------------------------------------------
413// Step execution (main thread; events go through the normal Day path)
414// ---------------------------------------------------------------------------
415
416/// Resolve a Fluent key (+ JSON args) in the current locale: the shared engine for the
417/// `key:`-flavored script fields (`assert_text`, input).
418/// Walk the app-menu model for `Action` leaves matching the `menu:` step's target: by
419/// exact label, or (when the step used `key:`) by the role's core-catalog key (the
420/// injected Preferences item carries an empty label; its role is its identity). `path`
421/// filters by ancestor submenu labels (suffix match). Returns `(id, enabled, trail)`.
422/// `[shift, primary, alt]` (with `cmd`/`ctrl` accepted for `primary`) → the day mask.
423fn parse_modifiers(names: &[String]) -> day_spec::Modifiers {
424    use day_spec::Modifiers;
425    let mut m = Modifiers::NONE;
426    for n in names {
427        match n.to_ascii_lowercase().as_str() {
428            "shift" => m |= Modifiers::SHIFT,
429            "primary" | "cmd" | "ctrl" | "meta" => m |= Modifiers::PRIMARY,
430            "alt" | "option" => m |= Modifiers::ALT,
431            _ => {}
432        }
433    }
434    m
435}
436
437fn find_menu_actions(
438    items: &[day_spec::MenuItem],
439    target_label: &str,
440    target_key: Option<&str>,
441    target_id: Option<&str>,
442    path: &[(String, String)],
443) -> Vec<(u64, bool, Vec<String>)> {
444    // Mirrors day-pieces' role_catalog_key (docs/menus.md), the stable `day_*` key set.
445    fn role_key(role: day_spec::MenuRole) -> &'static str {
446        use day_spec::MenuRole as R;
447        match role {
448            R::Cut => "day_cut",
449            R::Copy => "day_copy",
450            R::Paste => "day_paste",
451            R::SelectAll => "day_select_all",
452            R::Undo => "day_undo",
453            R::Redo => "day_redo",
454            R::Delete => "day_delete",
455            R::About => "day_about",
456            R::Quit => "day_quit",
457            R::Preferences => "day_preferences",
458            R::Minimize => "day_minimize",
459            R::CloseWindow => "day_close",
460            R::Fullscreen => "day_fullscreen",
461            R::NewWindow => "day_new_window",
462            R::CheckForUpdates => "day_check_for_updates",
463        }
464    }
465    #[allow(clippy::too_many_arguments)]
466    fn walk(
467        items: &[day_spec::MenuItem],
468        trail: &mut Vec<String>,
469        target_label: &str,
470        target_key: Option<&str>,
471        target_id: Option<&str>,
472        path: &[(String, String)],
473        out: &mut Vec<(u64, bool, Vec<String>)>,
474    ) {
475        for it in items {
476            match it {
477                day_spec::MenuItem::Action {
478                    id,
479                    action,
480                    label,
481                    enabled,
482                    role,
483                    ..
484                } => {
485                    // An `id:` step is an exact address and nothing else may answer it: matching
486                    // the label too would let a step that named a missing id quietly hit some
487                    // other item whose title happened to read the same.
488                    let by_id = target_id.is_some_and(|w| id.as_deref() == Some(w));
489                    let by_label =
490                        target_id.is_none() && !label.is_empty() && label == target_label;
491                    let by_key = target_id.is_none()
492                        && target_key.is_some_and(|k| role.is_some_and(|r| role_key(r) == k));
493                    let path_ok = path.is_empty()
494                        || (path.len() <= trail.len()
495                            && trail[trail.len() - path.len()..]
496                                .iter()
497                                .zip(path)
498                                .all(|(seen, want)| seen == &want.0 || seen == &want.1));
499                    if (by_id || by_label || by_key) && path_ok {
500                        out.push((*action, *enabled, trail.clone()));
501                    }
502                }
503                day_spec::MenuItem::Submenu { label, items, .. } => {
504                    trail.push(label.clone());
505                    walk(items, trail, target_label, target_key, target_id, path, out);
506                    trail.pop();
507                }
508                day_spec::MenuItem::Separator => {}
509            }
510        }
511    }
512    let mut out = Vec::new();
513    walk(
514        items,
515        &mut Vec::new(),
516        target_label,
517        target_key,
518        target_id,
519        path,
520        &mut out,
521    );
522    out
523}
524
525fn format_key(key: &str, args: Option<BTreeMap<String, serde_json::Value>>) -> String {
526    let mut lt = day_localization_ui::tr(key);
527    for (name, v) in args.unwrap_or_default() {
528        lt = match v {
529            serde_json::Value::Number(n) => lt.arg(&name, n.as_f64().unwrap_or(0.0)),
530            serde_json::Value::String(s) => lt.arg(&name, s),
531            other => lt.arg(&name, other.to_string()),
532        };
533    }
534    lt.format()
535}
536
537fn find(id: &str) -> Result<day_core::RNode, Reply> {
538    with_tree(|t| t.find_by_id(id)).ok_or_else(|| Reply::fail(format!("no element {id:?}"), true))
539}
540
541fn probe(id: &str) -> Result<NodeProbe, Reply> {
542    let node = find(id)?;
543    with_tree(|t| t.node_probe(node)).ok_or_else(|| Reply::fail("element vanished", true))
544}
545
546/// `at` in the node's coordinates, or its center.
547fn point_in(node: day_core::RNode, at: Option<[f64; 2]>) -> day_spec::Point {
548    match at {
549        Some([x, y]) => day_spec::Point::new(x, y),
550        None => with_tree(|t| t.node_frame(node)).map_or(day_spec::Point::ZERO, |f| {
551            day_spec::Point::new(f.size.width / 2.0, f.size.height / 2.0)
552        }),
553    }
554}
555
556fn emit(id: &str, ev: day_spec::Event) -> Result<(), Reply> {
557    let node = find(id)?;
558    day_core::enqueue_event(rnode_to_id(node), ev);
559    day_reactive::flush_sync();
560    Ok(())
561}
562
563fn visible(id: &str) -> Result<(), Reply> {
564    let node = find(id)?;
565    let frame = with_tree(|t| t.node_frame(node));
566    match frame {
567        Some(f) if f.size.width > 0.0 && f.size.height > 0.0 => Ok(()),
568        _ => Err(Reply::fail(format!("{id:?} has no visible frame"), true)),
569    }
570}
571
572/// `#rrggbb` as its three channels.
573fn parse_hex_color(s: &str) -> Option<[u8; 3]> {
574    let hex = s.strip_prefix('#')?;
575    if hex.len() != 6 {
576        return None;
577    }
578    let channel = |i: usize| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok();
579    Some([channel(0)?, channel(2)?, channel(4)?])
580}
581
582fn norm(s: &str) -> String {
583    day_localization_ui::strip_isolates(s)
584}
585
586/// Hosts that present frames of their own (`day_spec::capture::register_hold`) must have them
587/// on screen before a capture checkpoint is requested: a frame that lands after the checkpoint
588/// commits is not in the capture, and the fence for this revision does not rearm.
589fn hosts_settled() -> Result<(), Reply> {
590    if day_spec::capture::holds_settled() {
591        Ok(())
592    } else {
593        Err(Reply {
594            capture_pending: true,
595            ..Reply::fail("waiting for a host's pending frame", true)
596        })
597    }
598}
599
600fn id_catalog() -> Result<&'static day_script_protocol::IdCatalog, String> {
601    static CATALOG: std::sync::OnceLock<Result<day_script_protocol::IdCatalog, String>> =
602        std::sync::OnceLock::new();
603    CATALOG
604        .get_or_init(|| {
605            Ok(day_script_protocol::IdCatalog {
606                schema_version: 1,
607                declarations: day_core::element_id::registry()?
608                    .iter()
609                    .cloned()
610                    .map(|d| day_script_protocol::IdDeclaration {
611                        family: d.family,
612                        keyed: d.keyed,
613                        package: d.package,
614                        version: d.version,
615                        locations: d.locations,
616                    })
617                    .collect(),
618            })
619        })
620        .as_ref()
621        .map_err(Clone::clone)
622}
623
624fn exec(step: Step, revision: u32) -> Reply {
625    use day_spec::Event;
626    use day_spec::present::PresentResult;
627    let evidence_class = step.evidence_class();
628    let evidence_id = step.element_references().into_iter().next();
629    // An optional absent action succeeds without an interaction. Capture presence before
630    // executing, since a successful button can remove itself or close its window.
631    let absent_optional_action = matches!(&step,
632        Step::Tap { id, if_present: true, .. }
633        | Step::Select { id, if_present: true, .. }
634        | Step::ContextMenu { id, if_present: true, .. } if find(id).is_err());
635
636    let result: Result<Reply, Reply> = (|| {
637        match step {
638            Step::IdMounted => Ok(Reply {
639                data: Some(serde_json::json!(with_tree(|t| t.mounted_id_families()))),
640                ..Reply::ok()
641            }),
642            Step::IdCatalog => {
643                let catalog = id_catalog().map_err(|e| Reply::fail(e, false))?;
644                Ok(Reply {
645                    data: Some(serde_json::to_value(catalog).unwrap()),
646                    ..Reply::ok()
647                })
648            }
649            Step::WaitFor { id, .. } | Step::AssertVisible { id } => {
650                visible(&id)?;
651                Ok(Reply::ok())
652            }
653            Step::WaitIdle => {
654                day_reactive::flush_sync();
655                if !with_tree(|t| t.ui_idle()) {
656                    return Err(Reply::fail("ui transitions still settling", true));
657                }
658                Ok(Reply::ok())
659            }
660            Step::MemoryUsage { fail_if_above } => Ok(memory::sample(fail_if_above)),
661            Step::MemoryWatch { .. } => Err(Reply::fail(
662                "memory_watch requires a transport connection",
663                false,
664            )),
665            Step::Tap {
666                id,
667                if_present,
668                repeat,
669                at,
670                modifiers,
671            } => {
672                // Finding a node is not proof that a user can activate it. In particular,
673                // Button's enabled gate silently ignores Pressed while an async operation
674                // is finishing. Retry BEFORE dispatch, never replay an accepted action.
675                day_reactive::flush_sync();
676                if !with_tree(|t| t.ui_idle()) {
677                    return Err(Reply::fail("ui transitions still settling", true));
678                }
679                if if_present && with_tree(|t| t.find_by_id(&id)).is_none() {
680                    return Ok(Reply::ok());
681                }
682                visible(&id)?;
683                if !probe(&id)?.enabled {
684                    return Err(Reply::fail(format!("{id:?} is disabled"), true));
685                }
686                // Deliver a button `Pressed` and a gesture `Tap` (at `at`, or the node's local
687                // center), so one step exercises buttons (which ignore `Tap`) and
688                // shape/`.on_tap` pieces (which ignore `Pressed`) alike; the native
689                // recognizers deliver the same `Tap`.
690                let node = find(&id)?;
691                let point = match at {
692                    Some([x, y]) => day_spec::Point::new(x, y),
693                    None => with_tree(|t| t.node_frame(node)).map_or(day_spec::Point::ZERO, |f| {
694                        day_spec::Point::new(f.size.width / 2.0, f.size.height / 2.0)
695                    }),
696                };
697                // Declared modifiers stand in for held keys while the tap dispatches
698                // (`day::modifiers()` answers them), then clear, since a synthetic tap cannot
699                // hold a real shift key.
700                if !modifiers.is_empty() {
701                    day_core::set_modifier_override(Some(parse_modifiers(&modifiers)));
702                }
703                for _ in 0..repeat.unwrap_or(1).max(1) {
704                    day_core::enqueue_event(rnode_to_id(node), Event::Pressed);
705                    day_core::enqueue_event(rnode_to_id(node), Event::Tap(point));
706                }
707                day_reactive::flush_sync();
708                day_core::set_modifier_override(None);
709                Ok(Reply::ok())
710            }
711            Step::Key {
712                key,
713                id,
714                modifiers,
715                phase,
716            } => {
717                use day_spec::{KeyEvent, KeyPhase, Modifiers};
718                // Keys follow focus, so a synthetic one lands where the platform would put it:
719                // on the named piece, else on whatever holds focus. With nothing focused there
720                // is no target and the step says so, rather than dropping the key silently the
721                // way delivering it to the window used to.
722                let target = match &id {
723                    Some(id) => rnode_to_id(find(id)?),
724                    None => match day_core::focused_node() {
725                        Some(n) => rnode_to_id(n),
726                        None => {
727                            return Err(Reply::fail(
728                                "nothing has focus — name an `id`, or `focus:` a piece first",
729                                true,
730                            ));
731                        }
732                    },
733                };
734                let phase = match phase.as_deref() {
735                    None | Some("down") => KeyPhase::Down,
736                    Some("repeat") => KeyPhase::Repeat,
737                    Some("up") => KeyPhase::Up,
738                    Some(other) => {
739                        return Err(Reply::fail(
740                            format!("unknown key phase {other:?} (down, repeat or up)"),
741                            false,
742                        ));
743                    }
744                };
745                let mut mods = parse_modifiers(&modifiers);
746                // The physical Control key (docs/menus.md "The full route") is a key-event
747                // modifier `day::modifiers()` does not answer, so it is read off the names.
748                if modifiers.iter().any(|n| n.eq_ignore_ascii_case("control")) {
749                    mods |= Modifiers::CONTROL;
750                }
751                // The step's `key:` is the web name; this is where it becomes a typed key.
752                // On the full route (docs/menus.md "The full route") a key that types does so
753                // here too: a name outside the vocabulary, pressed with nothing but Shift, is
754                // the text it types, so `key: a` reaches a terminal the way a real press does.
755                let chord = mods.primary() || mods.alt() || mods.control();
756                let event = if day_spec::keys::text(target)
757                    && !chord
758                    && !KeyEvent::NAMED.contains(&key.as_str())
759                {
760                    KeyEvent::typed_text(key, mods)
761                } else {
762                    KeyEvent::named(key, mods)
763                };
764                day_core::enqueue_event(target, Event::Key(event.with_phase(phase)));
765                day_reactive::flush_sync();
766                Ok(Reply::ok())
767            }
768            Step::Press { id, at, release } => {
769                let node = find(&id)?;
770                let location = point_in(node, at);
771                day_core::enqueue_event(
772                    rnode_to_id(node),
773                    Event::Press {
774                        pressed: !release,
775                        location,
776                    },
777                );
778                day_reactive::flush_sync();
779                Ok(Reply::ok())
780            }
781            Step::LongPress { id, at } => {
782                let node = find(&id)?;
783                day_core::enqueue_event(rnode_to_id(node), Event::LongPress(point_in(node, at)));
784                day_reactive::flush_sync();
785                Ok(Reply::ok())
786            }
787            Step::DoubleTap { id, at } => {
788                let node = find(&id)?;
789                day_core::enqueue_event(rnode_to_id(node), Event::DoubleTap(point_in(node, at)));
790                day_reactive::flush_sync();
791                Ok(Reply::ok())
792            }
793            Step::Touches { id, points, phase } => {
794                use day_spec::{Touch, TouchPhase};
795                let node = find(&id)?;
796                let phase = match phase.as_deref() {
797                    None | Some("began") => TouchPhase::Began,
798                    Some("moved") => TouchPhase::Moved,
799                    Some("ended") => TouchPhase::Ended,
800                    Some("cancelled") => TouchPhase::Cancelled,
801                    Some(other) => {
802                        return Err(Reply::fail(
803                            format!(
804                                "unknown touch phase {other:?} (began, moved, ended or cancelled)"
805                            ),
806                            false,
807                        ));
808                    }
809                };
810                let touches = points
811                    .iter()
812                    .zip(0u64..)
813                    .map(|(p, i)| Touch::new(i, phase, day_spec::Point::new(p[0], p[1])))
814                    .collect();
815                day_core::enqueue_event(rnode_to_id(node), Event::Touches(touches));
816                day_reactive::flush_sync();
817                Ok(Reply::ok())
818            }
819            Step::Pointer { kind } => {
820                let Some(kind) = day_spec::PointerKind::from_name(&kind) else {
821                    return Err(Reply::fail(
822                        format!("unknown pointer kind {kind:?} (touch, mouse or stylus)"),
823                        false,
824                    ));
825                };
826                day_core::enqueue_event(day_spec::WINDOW_NODE, Event::PointerKindChanged(kind));
827                day_reactive::flush_sync();
828                Ok(Reply::ok())
829            }
830            Step::Drop {
831                id,
832                files,
833                text,
834                at,
835                phase,
836            } => {
837                use day_spec::transfer::{Item, Location, Offer, Operation, Representation};
838                let node = find(&id)?;
839                // The target sits on the layer `.drop_target` wrapped the piece in: the node
840                // itself, or the nearest one above it.
841                let mut cur = Some(node);
842                let mut target = None;
843                while let Some(n) = cur {
844                    target = with_tree(|t| t.drop_target(n));
845                    if target.is_some() {
846                        break;
847                    }
848                    cur = with_tree(|t| t.parent_of(n));
849                }
850                let Some(target) = target else {
851                    return Err(Reply::fail(format!("{id:?} has no drop target"), true));
852                };
853                let mut representations = Vec::new();
854                if !files.is_empty() {
855                    let mut list = String::new();
856                    for file in &files {
857                        list.push_str("file://");
858                        list.push_str(file);
859                        list.push_str("\r\n");
860                    }
861                    representations.push(Representation::new("text/uri-list", list));
862                }
863                if let Some(text) = text {
864                    representations.push(Representation::new("text/plain", text));
865                }
866                let offer = Offer {
867                    items: vec![Item::new(representations)],
868                };
869                let location = Location {
870                    position: point_in(node, at),
871                    types: offer.types(),
872                    allowed: vec![Operation::Copy, Operation::Move, Operation::Link],
873                    local: false,
874                };
875                match phase.as_deref() {
876                    Some("enter") => {
877                        if target.proposal(&location) == Operation::None {
878                            return Err(Reply::fail(format!("{id:?} refuses this drag"), false));
879                        }
880                    }
881                    Some("leave") => target.leave(),
882                    None | Some("drop") => {
883                        if target.proposal(&location) == Operation::None
884                            || !target.deliver(location, offer)
885                        {
886                            return Err(Reply::fail(format!("{id:?} refused the drop"), false));
887                        }
888                    }
889                    Some(other) => {
890                        return Err(Reply::fail(
891                            format!("unknown drop phase {other:?} (enter, leave or drop)"),
892                            false,
893                        ));
894                    }
895                }
896                day_reactive::flush_sync();
897                Ok(Reply::ok())
898            }
899            Step::Drag {
900                id,
901                from,
902                to,
903                steps,
904                modifiers,
905                velocity,
906            } => {
907                let node = find(&id)?;
908                let (fx, fy) = (from[0], from[1]);
909                let (tx, ty) = (to[0], to[1]);
910                let n = steps.unwrap_or(4).max(1);
911                let emit_drag = |phase, x: f64, y: f64| {
912                    day_core::enqueue_event(
913                        rnode_to_id(node),
914                        Event::Drag {
915                            phase,
916                            location: day_spec::Point::new(x, y),
917                            translation: day_spec::Point::new(x - fx, y - fy),
918                        },
919                    );
920                };
921                // Held for the whole gesture rather than one phase: a drag that reads
922                // modifiers reads them at `Began`, and the override has to still be in place
923                // at `Ended` for a handler that re-reads them there.
924                if !modifiers.is_empty() {
925                    day_core::set_modifier_override(Some(parse_modifiers(&modifiers)));
926                }
927                emit_drag(day_spec::DragPhase::Began, fx, fy);
928                day_reactive::flush_sync();
929                for i in 1..=n {
930                    let f = f64::from(i) / f64::from(n);
931                    emit_drag(
932                        day_spec::DragPhase::Changed,
933                        fx + (tx - fx) * f,
934                        fy + (ty - fy) * f,
935                    );
936                    day_reactive::flush_sync();
937                }
938                if let Some([vx, vy]) = velocity {
939                    day_core::enqueue_event(
940                        rnode_to_id(node),
941                        Event::GestureVelocity {
942                            kind: day_spec::GestureKind::Drag,
943                            velocity: day_spec::Point::new(vx, vy),
944                        },
945                    );
946                }
947                emit_drag(day_spec::DragPhase::Ended, tx, ty);
948                day_reactive::flush_sync();
949                day_core::set_modifier_override(None);
950                Ok(Reply::ok())
951            }
952            Step::Hover { id, at, leave } => {
953                let node = find(&id)?;
954                let location = if let Some([x, y]) = at {
955                    day_spec::Point::new(x, y)
956                } else {
957                    let f = with_tree(|t| t.node_frame(node)).unwrap_or_default();
958                    day_spec::Point::new(f.size.width / 2.0, f.size.height / 2.0)
959                };
960                let phase = if leave {
961                    day_spec::DragPhase::Ended
962                } else {
963                    day_spec::DragPhase::Began
964                };
965                day_core::enqueue_event(rnode_to_id(node), Event::Hover { phase, location });
966                day_reactive::flush_sync();
967                Ok(Reply::ok())
968            }
969            Step::Pan { id, by, steps } => {
970                let node = find(&id)?;
971                let f = with_tree(|t| t.node_frame(node)).unwrap_or_default();
972                let location = day_spec::Point::new(f.size.width / 2.0, f.size.height / 2.0);
973                let n = steps.unwrap_or(4).max(1);
974                let emit_pan = |phase, dx: f64, dy: f64| {
975                    day_core::enqueue_event(
976                        rnode_to_id(node),
977                        Event::Pan {
978                            phase,
979                            delta: day_spec::Point::new(dx, dy),
980                            location,
981                        },
982                    );
983                    day_reactive::flush_sync();
984                };
985                emit_pan(day_spec::DragPhase::Began, 0.0, 0.0);
986                // Incremental deltas, as the platforms report them, adding up to `by`.
987                for _ in 0..n {
988                    emit_pan(
989                        day_spec::DragPhase::Changed,
990                        by[0] / f64::from(n),
991                        by[1] / f64::from(n),
992                    );
993                }
994                emit_pan(day_spec::DragPhase::Ended, 0.0, 0.0);
995                Ok(Reply::ok())
996            }
997            Step::Pinch { id, scale, steps } => {
998                let node = find(&id)?;
999                let f = with_tree(|t| t.node_frame(node)).unwrap_or_default();
1000                let location = day_spec::Point::new(f.size.width / 2.0, f.size.height / 2.0);
1001                let n = steps.unwrap_or(4).max(1);
1002                let emit_pinch = |phase, s: f64| {
1003                    day_core::enqueue_event(
1004                        rnode_to_id(node),
1005                        Event::Pinch {
1006                            phase,
1007                            scale: s,
1008                            location,
1009                        },
1010                    );
1011                    day_reactive::flush_sync();
1012                };
1013                emit_pinch(day_spec::DragPhase::Began, 1.0);
1014                // Cumulative since `Began`, as the platforms report it.
1015                for i in 1..=n {
1016                    emit_pinch(
1017                        day_spec::DragPhase::Changed,
1018                        1.0 + (scale - 1.0) * f64::from(i) / f64::from(n),
1019                    );
1020                }
1021                emit_pinch(day_spec::DragPhase::Ended, scale);
1022                Ok(Reply::ok())
1023            }
1024            Step::Rotate {
1025                id,
1026                rotation,
1027                steps,
1028            } => {
1029                let node = find(&id)?;
1030                let f = with_tree(|t| t.node_frame(node)).unwrap_or_default();
1031                let location = day_spec::Point::new(f.size.width / 2.0, f.size.height / 2.0);
1032                let n = steps.unwrap_or(4).max(1);
1033                let emit_rotate = |phase, r: f64| {
1034                    day_core::enqueue_event(
1035                        rnode_to_id(node),
1036                        Event::Rotate {
1037                            phase,
1038                            rotation: r,
1039                            location,
1040                        },
1041                    );
1042                    day_reactive::flush_sync();
1043                };
1044                emit_rotate(day_spec::DragPhase::Began, 0.0);
1045                // Cumulative since `Began`, as the platforms report it.
1046                for i in 1..=n {
1047                    emit_rotate(
1048                        day_spec::DragPhase::Changed,
1049                        rotation * f64::from(i) / f64::from(n),
1050                    );
1051                }
1052                emit_rotate(day_spec::DragPhase::Ended, rotation);
1053                Ok(Reply::ok())
1054            }
1055            Step::Submit { id } => emit(&id, Event::Submitted).map(|()| Reply::ok()),
1056            Step::Input {
1057                id,
1058                text,
1059                key,
1060                args,
1061            } => {
1062                let value = match key {
1063                    Some(k) => format_key(&k, args),
1064                    None => text.unwrap_or_default(),
1065                };
1066                // Paint-then-event via the shared synthesizer (day-core): the widget must
1067                // show the typed text, not only deliver it to the app's signal.
1068                let node = find(&id)?;
1069                day_core::synthesize_text(node, value);
1070                day_reactive::flush_sync();
1071                Ok(Reply::ok())
1072            }
1073            Step::SetValue { id, value } => {
1074                // Both, for the same reason `tap` sends `Pressed` and `Tap`: a binding follows
1075                // the live value and anything durable follows the committed one, and a replayed
1076                // `set_value` is a user who dragged and let go, so it has to look like one.
1077                emit(&id, Event::ValueChanged(value))?;
1078                emit(&id, Event::ValueCommitted(value))?;
1079                Ok(Reply::ok())
1080            }
1081            Step::Toggle { id, value } => {
1082                let target = match value {
1083                    Some(v) => v,
1084                    None => !probe(&id)?.flag,
1085                };
1086                emit(&id, Event::ToggleChanged(target))?;
1087                Ok(Reply::ok())
1088            }
1089            Step::Activate { id, index } => {
1090                emit(&id, Event::ListActivated(index))?;
1091                Ok(Reply::ok())
1092            }
1093            Step::Select {
1094                id,
1095                index,
1096                if_present,
1097            } => {
1098                if if_present {
1099                    // Absent only counts once the UI has settled: a control still being
1100                    // built is one to wait for, not one to skip (the same rule as `tap`).
1101                    day_reactive::flush_sync();
1102                    if !with_tree(|t| t.ui_idle()) {
1103                        return Err(Reply::fail("ui transitions still settling", true));
1104                    }
1105                    if with_tree(|t| t.find_by_id(&id)).is_none() {
1106                        return Ok(Reply::ok());
1107                    }
1108                }
1109                let node = find(&id)?;
1110                let state = probe(&id)?;
1111                if with_tree(|t| t.node_kind(node)) == Some(day_spec::kinds::PICKER)
1112                    && (index < 0 || index as usize >= state.options.len())
1113                {
1114                    return Err(Reply::fail(
1115                        format!(
1116                            "select {id:?}: index {index} is out of range for {} options",
1117                            state.options.len()
1118                        ),
1119                        false,
1120                    ));
1121                }
1122                emit(&id, Event::SelectionChanged(index))?;
1123                Ok(Reply::ok())
1124            }
1125            Step::Reorder { id, from, to } => {
1126                let node = find(&id)?;
1127                match day_core::list_try_reorder(node, from, to) {
1128                    Ok(_) => Ok(Reply::ok()),
1129                    // Not retryable: a guard denial or a non-reorderable list won't change by
1130                    // waiting; surface it to the runner immediately.
1131                    Err(e) => Err(Reply::fail(
1132                        format!("reorder {id:?} {from}->{to}: {e}"),
1133                        false,
1134                    )),
1135                }
1136            }
1137            Step::Undo => drive_undo(false),
1138            Step::Redo => drive_undo(true),
1139            Step::Expand { id, row, expanded } => {
1140                let node = find(&id)?;
1141                let driver = day_core::tree_driver(node).ok_or_else(|| {
1142                    Reply::fail(format!("expand {id:?}: no tree at this node"), false)
1143                })?;
1144                let token = (driver.resolve_row)(&row).ok_or_else(|| {
1145                    // Retryable: the row may appear after a pending reload (or the tree may
1146                    // not carry `.row_id`s at all, which the timeout will surface).
1147                    Reply::fail(format!("expand {id:?}: no row {row:?}"), true)
1148                })?;
1149                emit(&id, Event::TreeExpanded { token, expanded })?;
1150                Ok(Reply::ok())
1151            }
1152            Step::TreeMove {
1153                id,
1154                row,
1155                parent,
1156                index,
1157            } => {
1158                let node = find(&id)?;
1159                let driver = day_core::tree_driver(node).ok_or_else(|| {
1160                    Reply::fail(format!("tree_move {id:?}: no tree at this node"), false)
1161                })?;
1162                let token = (driver.resolve_row)(&row).ok_or_else(|| {
1163                    Reply::fail(format!("tree_move {id:?}: no row {row:?}"), true)
1164                })?;
1165                let parent_tok = match &parent {
1166                    Some(p) => Some((driver.resolve_row)(p).ok_or_else(|| {
1167                        Reply::fail(format!("tree_move {id:?}: no parent row {p:?}"), true)
1168                    })?),
1169                    None => None,
1170                };
1171                match day_core::tree_try_move(node, token, parent_tok, index) {
1172                    Ok(()) => Ok(Reply::ok()),
1173                    // Not retryable: a guard denial or an immovable tree won't change by waiting.
1174                    Err(e) => Err(Reply::fail(format!("tree_move {id:?} {row:?}: {e}"), false)),
1175                }
1176            }
1177            Step::DeleteRow { id, row } => {
1178                let node = find(&id)?;
1179                match day_core::list_try_delete(node, row) {
1180                    Ok(()) => Ok(Reply::ok()),
1181                    // Not retryable: a guard refusal or a non-deletable list won't change by
1182                    // waiting; surface it to the runner immediately.
1183                    Err(e) => Err(Reply::fail(format!("delete_row {id:?} {row}: {e}"), false)),
1184                }
1185            }
1186            Step::SwipeRow {
1187                id,
1188                row,
1189                edge,
1190                action,
1191                label,
1192                key,
1193            } => {
1194                let node = find(&id)?;
1195                let edge = match edge.as_deref() {
1196                    None | Some("trailing") => day_spec::SwipeEdge::Trailing,
1197                    Some("leading") => day_spec::SwipeEdge::Leading,
1198                    Some(other) => {
1199                        return Err(Reply::fail(
1200                            format!("swipe_row {id:?}: edge {other:?} (leading|trailing)"),
1201                            false,
1202                        ));
1203                    }
1204                };
1205                let expected = match (&label, &key) {
1206                    (Some(l), _) => Some(l.clone()),
1207                    (None, Some(k)) => Some(format_key(k, None)),
1208                    (None, None) => None,
1209                };
1210                // The pin is checked before the press (docs/list.md): a mismatched offer
1211                // refuses the activation rather than flipping state the script did not mean
1212                // to flip, which is how one aborted run would poison every later one.
1213                match day_core::list_try_swipe(node, row, edge, action, expected.as_deref()) {
1214                    Ok(_) => Ok(Reply::ok()),
1215                    // Not retryable: the offer was pulled live; a list without swipe offers, an
1216                    // out-of-offer action, or a different button at this position won't
1217                    // change by waiting. Surface it to the runner immediately.
1218                    Err(e) => Err(Reply::fail(format!("swipe_row {id:?} {row}: {e}"), false)),
1219                }
1220            }
1221            Step::WebEval {
1222                id,
1223                script,
1224                contains,
1225                text,
1226                ..
1227            } => {
1228                // The eval resolves at a later event drain, and a step handler cannot block
1229                // the pump it needs, so the step is a retryable poll: the first pass starts
1230                // the evaluation, retries within the runner's implicit wait collect it, and
1231                // an assertion mismatch discards the result so the retry re-evaluates (a page
1232                // mid-load settles into passing). Keyed by (id, script): the runner resends
1233                // the identical step on retry, and that pair is what identifies the request.
1234                use std::cell::RefCell;
1235                use std::rc::Rc;
1236                type EvalCell = Rc<RefCell<Option<Result<String, String>>>>;
1237                thread_local! {
1238                    static WEB_EVALS: RefCell<
1239                        std::collections::HashMap<(String, String), (u32, EvalCell)>,
1240                    > = RefCell::new(std::collections::HashMap::new());
1241                }
1242                let node = find(&id)?;
1243                let key = (id.clone(), script.clone());
1244                let pending = WEB_EVALS.with(|m| m.borrow().get(&key).map(|(_, c)| c.clone()));
1245                let Some(cell) = pending else {
1246                    let cell: EvalCell = Rc::new(RefCell::new(None));
1247                    let done = {
1248                        let cell = cell.clone();
1249                        Box::new(move |r: Result<String, String>| *cell.borrow_mut() = Some(r))
1250                    };
1251                    if !day_core::piece_operation(node, "day.webview.eval", &script, done) {
1252                        return Err(Reply::fail(
1253                            format!(
1254                                "web_eval {id:?}: not a web view (or no webview piece registered an evaluator)"
1255                            ),
1256                            false,
1257                        ));
1258                    }
1259                    WEB_EVALS.with(|m| m.borrow_mut().insert(key, (0, cell)));
1260                    return Err(Reply::fail(
1261                        format!("web_eval {id:?}: awaiting the engine"),
1262                        true,
1263                    ));
1264                };
1265                let Some(result) = cell.borrow_mut().take() else {
1266                    // Still pending. A reply that never comes (a torn-down view drops its
1267                    // callback) must not wedge every later identical step: after enough
1268                    // polls, forget the request so the next retry starts fresh.
1269                    let stale = WEB_EVALS.with(|m| {
1270                        let mut m = m.borrow_mut();
1271                        match m.get_mut(&key) {
1272                            Some((polls, _)) => {
1273                                *polls += 1;
1274                                *polls > 25
1275                            }
1276                            None => false,
1277                        }
1278                    });
1279                    if stale {
1280                        WEB_EVALS.with(|m| m.borrow_mut().remove(&key));
1281                    }
1282                    return Err(Reply::fail(
1283                        format!("web_eval {id:?}: awaiting the engine"),
1284                        true,
1285                    ));
1286                };
1287                WEB_EVALS.with(|m| m.borrow_mut().remove(&key));
1288                match result {
1289                    // Retryable: a throw from a page still loading (`document` half-built)
1290                    // resolves with time; a permanent error just spends the wait.
1291                    Err(e) => Err(Reply::fail(format!("web_eval {id:?}: {e}"), true)),
1292                    Ok(json) => {
1293                        // A string value compares as itself; anything else as its JSON text.
1294                        let value = serde_json::from_str::<serde_json::Value>(&json)
1295                            .ok()
1296                            .and_then(|v| v.as_str().map(str::to_string))
1297                            .unwrap_or(json);
1298                        let failed = match (&contains, &text) {
1299                            (Some(c), _) if !value.contains(c.as_str()) => {
1300                                Some(format!("result {value:?} does not contain {c:?}"))
1301                            }
1302                            (_, Some(t)) if value != *t => {
1303                                Some(format!("result {value:?}, expected {t:?}"))
1304                            }
1305                            _ => None,
1306                        };
1307                        match failed {
1308                            // Retryable: the page may still be settling; the retry
1309                            // re-evaluates against its current state.
1310                            Some(why) => Err(Reply::fail(format!("web_eval {id:?}: {why}"), true)),
1311                            None => Ok(Reply::ok()),
1312                        }
1313                    }
1314                }
1315            }
1316            Step::ContextMenu {
1317                id,
1318                if_present,
1319                item_id,
1320                item,
1321                key,
1322                path,
1323            } => {
1324                if if_present {
1325                    // The `tap` rule: absent counts only once the UI has settled.
1326                    day_reactive::flush_sync();
1327                    if !with_tree(|t| t.ui_idle()) {
1328                        return Err(Reply::fail("ui transitions still settling", true));
1329                    }
1330                    if with_tree(|t| t.find_by_id(&id)).is_none() {
1331                        return Ok(Reply::ok());
1332                    }
1333                }
1334                let node = find(&id)?;
1335                let menu = with_tree(|t| t.context_menu_of(node)).ok_or_else(|| {
1336                    Reply::fail(
1337                        format!("context_menu {id:?}: the element has no menu"),
1338                        true,
1339                    )
1340                })?;
1341                // Asked outside the tree borrow, at the origin, as a native summon asks it: a
1342                // provider may select what it was summoned over and flush.
1343                let items = menu(day_spec::Point::ZERO);
1344                let target_label = match (&item_id, &item, &key) {
1345                    (Some(_), _, _) => String::new(),
1346                    (None, Some(l), _) => l.clone(),
1347                    (None, None, Some(k)) => format_key(k, None),
1348                    (None, None, None) => {
1349                        return Err(Reply::fail(
1350                            "context_menu: needs `item_id:`, `item:` or `key:`",
1351                            false,
1352                        ));
1353                    }
1354                };
1355                let path: Vec<(String, String)> = path
1356                    .unwrap_or_default()
1357                    .into_iter()
1358                    .map(|p| {
1359                        let resolved = format_key(&p, None);
1360                        (p, resolved)
1361                    })
1362                    .collect();
1363                let matches = find_menu_actions(
1364                    &items,
1365                    &target_label,
1366                    key.as_deref(),
1367                    item_id.as_deref(),
1368                    &path,
1369                );
1370                let what = match &item_id {
1371                    Some(want) => format!("id {want:?}"),
1372                    None => format!("{target_label:?}"),
1373                };
1374                match matches.as_slice() {
1375                    [] => Err(Reply::fail(
1376                        format!("context_menu {id:?}: no item {what}"),
1377                        true,
1378                    )),
1379                    [(action, enabled, _)] => {
1380                        if *action == 0 {
1381                            Err(Reply::fail(
1382                                format!(
1383                                    "context_menu {id:?}: {what} runs a native command (no day \
1384                                     action)"
1385                                ),
1386                                false,
1387                            ))
1388                        } else if !enabled {
1389                            // Retryable, as a disabled `tap` target is: an item's enabled state
1390                            // follows app state that may still be arriving (a page's load).
1391                            Err(Reply::fail(
1392                                format!("context_menu {id:?}: {what} is disabled"),
1393                                true,
1394                            ))
1395                        } else {
1396                            day_core::dispatch_menu_action(*action);
1397                            day_reactive::flush_sync();
1398                            Ok(Reply::ok())
1399                        }
1400                    }
1401                    _ => Err(Reply::fail(
1402                        format!("context_menu {id:?}: {what} is ambiguous; add a path"),
1403                        false,
1404                    )),
1405                }
1406            }
1407            Step::Menu {
1408                id,
1409                item,
1410                key,
1411                path,
1412            } => {
1413                let target_label = match (&id, &item, &key) {
1414                    (Some(_), _, _) => String::new(),
1415                    (None, Some(l), _) => l.clone(),
1416                    (None, None, Some(k)) => format_key(k, None),
1417                    (None, None, None) => {
1418                        return Err(Reply::fail("menu: needs `id:`, `item:` or `key:`", false));
1419                    }
1420                };
1421                // Each `path:` entry matches an ancestor submenu by its literal label OR by
1422                // its Fluent key resolved in the run's locale, so `path: [menu_file]` works
1423                // wherever `key: menu_file` does.
1424                let path: Vec<(String, String)> = path
1425                    .unwrap_or_default()
1426                    .into_iter()
1427                    .map(|p| {
1428                        let resolved = format_key(&p, None);
1429                        (p, resolved)
1430                    })
1431                    .collect();
1432                let matches = find_menu_actions(
1433                    &day_core::menu::app_menu_model(),
1434                    &target_label,
1435                    key.as_deref(),
1436                    id.as_deref(),
1437                    &path,
1438                );
1439                // The auto items (docs/windows.md) exist even when the app never installed a
1440                // menu (the backend's default menu carries them): resolve their keys straight
1441                // to the registered dispatch actions when the model has no entry.
1442                let auto_id = match (matches.is_empty(), key.as_deref()) {
1443                    (true, Some("day_preferences")) => {
1444                        Some(day_core::windows::preferences_action_id())
1445                    }
1446                    (true, Some("day_new_window")) => {
1447                        Some(day_core::windows::new_window_action_id())
1448                    }
1449                    (true, Some("day_about")) => Some(day_core::windows::about_action_id()),
1450                    (true, Some("day_check_for_updates")) => {
1451                        Some(day_core::windows::check_for_updates_action_id())
1452                    }
1453                    _ => None,
1454                };
1455                if let Some(id) = auto_id
1456                    && id != 0
1457                {
1458                    day_core::dispatch_menu_action(id);
1459                    day_reactive::flush_sync();
1460                    return Ok(Reply::ok());
1461                }
1462                // Name the item back the way the step named it, so a failure says which spelling
1463                // it was actually asked to find.
1464                let what = match &id {
1465                    Some(want) => format!("id {want:?}"),
1466                    None => format!("{target_label:?}"),
1467                };
1468                match matches.as_slice() {
1469                    [] => Err(Reply::fail(
1470                        // Retryable: the (reactive) app menu may not have installed yet.
1471                        format!("menu: no item {what}"),
1472                        true,
1473                    )),
1474                    [(action, enabled, _)] => {
1475                        if *action == 0 {
1476                            Err(Reply::fail(
1477                                format!(
1478                                    "menu: {what} runs a native selector (no day action) — not \
1479                                     invokable from dayscript"
1480                                ),
1481                                false,
1482                            ))
1483                        } else if !enabled {
1484                            // Retryable, as a disabled `tap` target is: an item's enabled state
1485                            // follows app state that may still be arriving (a page's load).
1486                            Err(Reply::fail(format!("menu: {what} is disabled"), true))
1487                        } else {
1488                            day_core::dispatch_menu_action(*action);
1489                            day_reactive::flush_sync();
1490                            Ok(Reply::ok())
1491                        }
1492                    }
1493                    many => Err(Reply::fail(
1494                        format!(
1495                            "menu: {what} is ambiguous — disambiguate with path: {:?}",
1496                            many.iter()
1497                                .map(|(_, _, p)| p.join(" ▸ "))
1498                                .collect::<Vec<_>>()
1499                        ),
1500                        false,
1501                    )),
1502                }
1503            }
1504            Step::Toolbar {
1505                item,
1506                text,
1507                key,
1508                args,
1509                on,
1510                index,
1511                submit,
1512            } => {
1513                // `key` resolves through the run's locale, like `input`'s does; `text` stays a
1514                // literal. Resolved before the item lookup so a bad key fails as a bad key.
1515                let text = match key {
1516                    Some(k) => Some(format_key(&k, args)),
1517                    None => text,
1518                };
1519                // Every live chrome's items (docs/toolbars.md): the window's own, plus whichever
1520                // pages are showing. One bar per window at a time, so an id that appears twice is
1521                // an app bug rather than an ambiguity to resolve here.
1522                let model = day_core::toolbar::toolbar_model();
1523                let Some(found) = model.iter().find(|i| i.id == item) else {
1524                    // The reserved search id names one field wherever the platform put it
1525                    // (docs/search.md): on the bar it is the item found above; inline, on a
1526                    // phone's navigation surface, there is no item and the host answers for it.
1527                    // The text goes in as the native field would send it, so the same query and
1528                    // the same outbound patch (the field showing the text) follow on both.
1529                    if item == day_spec::SEARCH_ITEM_ID
1530                        && let Some(host) = day_core::inline_search_host()
1531                    {
1532                        let Some(t) = text else {
1533                            return Err(Reply::fail(
1534                                "toolbar: day::search rides the navigation surface here, which takes text (or key) only",
1535                                false,
1536                            ));
1537                        };
1538                        day_core::enqueue_event(rnode_to_id(host), Event::SearchChanged(t.clone()));
1539                        if submit {
1540                            day_core::enqueue_event(rnode_to_id(host), Event::SearchSubmitted(t));
1541                        }
1542                        day_reactive::flush_sync();
1543                        return Ok(Reply::ok());
1544                    }
1545                    // Retryable: a reactive toolbar may not have installed yet.
1546                    return Err(Reply::fail(format!("toolbar: no item {item:?}"), true));
1547                };
1548                if !found.enabled {
1549                    return Err(Reply::fail(format!("toolbar: {item:?} is disabled"), false));
1550                }
1551                // The sidebar affordance a host supplies for itself is an ordinary button
1552                // whose action carries its host, so it is pressed like any other: the same
1553                // path a click takes (docs/toolbars.md).
1554                if found.action == 0 {
1555                    return Err(Reply::fail(
1556                        format!("toolbar: {item:?} has no command"),
1557                        false,
1558                    ));
1559                }
1560                // A toggle's action lives in the value registry, not the menu-action one, so a
1561                // bare `toolbar: { item }` on one used to dispatch into the wrong registry and
1562                // do nothing at all: the step passed, the app did not move, and the script was
1563                // left asserting against a state it never reached. Say what is missing instead.
1564                // A segmented item takes an index; nothing else in the vocabulary does, and a
1565                // bare press on one would have no choice to make.
1566                if let day_spec::ToolbarItemKind::Segmented { segments, .. } = &found.kind {
1567                    let Some(i) = index else {
1568                        return Err(Reply::fail(
1569                            format!("toolbar: {item:?} is segmented — say `index: <n>`"),
1570                            false,
1571                        ));
1572                    };
1573                    if i >= segments.len() {
1574                        return Err(Reply::fail(
1575                            format!(
1576                                "toolbar: {item:?} has {} segments, asked for {i}",
1577                                segments.len()
1578                            ),
1579                            false,
1580                        ));
1581                    }
1582                    day_core::toolbar::dispatch_toolbar_value(
1583                        found.action,
1584                        &day_spec::ToolbarValue::Selected(i),
1585                    );
1586                    day_reactive::flush_sync();
1587                    return Ok(Reply::ok());
1588                }
1589                if matches!(found.kind, day_spec::ToolbarItemKind::Toggle { .. })
1590                    && on.is_none()
1591                    && text.is_none()
1592                {
1593                    return Err(Reply::fail(
1594                        format!("toolbar: {item:?} is a toggle — say `on: true` or `on: false`"),
1595                        false,
1596                    ));
1597                }
1598                if submit && text.is_none() {
1599                    return Err(Reply::fail(
1600                        format!("toolbar: submitting {item:?} needs `text:` (or `key:`)"),
1601                        false,
1602                    ));
1603                }
1604                match (text, on) {
1605                    (Some(t), _) => {
1606                        day_core::toolbar::synthesize_toolbar_value(
1607                            found.action,
1608                            &day_spec::ToolbarValue::Text(t.clone()),
1609                        );
1610                        if submit {
1611                            day_reactive::flush_sync();
1612                            day_core::toolbar::dispatch_toolbar_value(
1613                                found.action,
1614                                &day_spec::ToolbarValue::Submit(t),
1615                            );
1616                        }
1617                    }
1618                    (None, Some(v)) => day_core::toolbar::dispatch_toolbar_value(
1619                        found.action,
1620                        &day_spec::ToolbarValue::On(v),
1621                    ),
1622                    (None, None) => day_core::dispatch_menu_action(found.action),
1623                }
1624                day_reactive::flush_sync();
1625                Ok(Reply::ok())
1626            }
1627            Step::AssertHidden { id } => {
1628                let Some(node) = with_tree(|t| t.find_by_id(&id)) else {
1629                    return Ok(Reply::ok());
1630                };
1631                let empty = with_tree(|t| t.node_frame(node))
1632                    .is_none_or(|f| f.size.width <= 0.0 || f.size.height <= 0.0);
1633                let native = with_tree(|t| t.read_native(node)).unwrap_or_default();
1634                if empty || (native.found && native.visible == Some(false)) {
1635                    Ok(Reply::ok())
1636                } else {
1637                    Err(Reply::fail(format!("element {id:?} is shown"), true))
1638                }
1639            }
1640            Step::AssertMissing { id } => match with_tree(|t| t.find_by_id(&id)) {
1641                Some(_) => Err(Reply::fail(format!("element {id:?} is present"), true)),
1642                None => Ok(Reply::ok()),
1643            },
1644            Step::AssertText {
1645                id,
1646                text,
1647                key,
1648                args,
1649                ..
1650            } => {
1651                let actual = norm(&probe(&id)?.text);
1652                let expected = if let Some(k) = key {
1653                    norm(&format_key(&k, args))
1654                } else {
1655                    norm(&text.unwrap_or_default())
1656                };
1657                if actual == expected {
1658                    Ok(Reply::ok())
1659                } else {
1660                    Err(Reply::fail(
1661                        format!("{id:?}: expected {expected:?}, found {actual:?}"),
1662                        true,
1663                    ))
1664                }
1665            }
1666            Step::AssertNoPlaceholders { allow } => {
1667                let unexpected: Vec<&str> = day_spec::placeholder::seen()
1668                    .into_iter()
1669                    .filter(|k| !allow.iter().any(|a| a == k))
1670                    .collect();
1671                if unexpected.is_empty() {
1672                    Ok(Reply::ok())
1673                } else {
1674                    Err(Reply::fail(
1675                        format!(
1676                            "rendered a placeholder for {} — no renderer on this backend. Enable \
1677                             the piece's feature for this toolkit, or add the kind to `allow:` if \
1678                             the gap is intended.",
1679                            unexpected.join(", ")
1680                        ),
1681                        true,
1682                    ))
1683                }
1684            }
1685            Step::AssertValue { id, value } => {
1686                let p = probe(&id)?;
1687                let ok = match &value {
1688                    serde_json::Value::Bool(b) => p.flag == *b,
1689                    serde_json::Value::Number(n) => {
1690                        (p.value - n.as_f64().unwrap_or(f64::NAN)).abs() < 0.5
1691                    }
1692                    serde_json::Value::String(s) => norm(&p.text) == norm(s),
1693                    _ => false,
1694                };
1695                if ok {
1696                    Ok(Reply::ok())
1697                } else {
1698                    Err(Reply::fail(
1699                        format!(
1700                            "{id:?}: expected {value}, probe text={:?} value={} flag={}",
1701                            p.text, p.value, p.flag
1702                        ),
1703                        true,
1704                    ))
1705                }
1706            }
1707            Step::AssertAnnounced { text } => {
1708                let said = day_core::conformance::announcements();
1709                if said.iter().any(|s| norm(s) == norm(&text)) {
1710                    Ok(Reply::ok())
1711                } else {
1712                    Err(Reply::fail(
1713                        format!("{text:?} was not announced (announced: {said:?})"),
1714                        true,
1715                    ))
1716                }
1717            }
1718            Step::AssertOpenedUrl { url } => {
1719                let opened = day_core::conformance::opened_urls();
1720                if opened.contains(&url) {
1721                    Ok(Reply::ok())
1722                } else {
1723                    Err(Reply::fail(
1724                        format!("{url:?} was not opened (opened: {opened:?})"),
1725                        true,
1726                    ))
1727                }
1728            }
1729            Step::AssertFrame {
1730                id,
1731                width,
1732                height,
1733                x,
1734                y,
1735                relative_to,
1736                tolerance,
1737            } => {
1738                let tol = tolerance.unwrap_or(1.0);
1739                let node = find(&id)?;
1740                let day = with_tree(|t| t.node_frame(node))
1741                    .ok_or_else(|| Reply::fail(format!("{id:?} has no frame"), true))?;
1742                let native = with_tree(|t| t.read_native(node)).and_then(|n| n.frame);
1743                let (base_day, base_native) = match &relative_to {
1744                    Some(other) => {
1745                        let o = find(other)?;
1746                        let f = with_tree(|t| t.node_frame(o))
1747                            .ok_or_else(|| Reply::fail(format!("{other:?} has no frame"), true))?;
1748                        let n = with_tree(|t| t.read_native(o)).and_then(|n| n.frame);
1749                        (f.origin, n.map(|r| r.origin))
1750                    }
1751                    None => (day_spec::Point::ZERO, Some(day_spec::Point::ZERO)),
1752                };
1753                let mut fails = Vec::new();
1754                let mut check = |source: &str, f: day_spec::Rect, base: day_spec::Point| {
1755                    let got = [
1756                        ("width", f.size.width, width),
1757                        ("height", f.size.height, height),
1758                        ("x", f.origin.x - base.x, x),
1759                        ("y", f.origin.y - base.y, y),
1760                    ];
1761                    for (name, value, want) in got {
1762                        if let Some(w) = want
1763                            && (value - w).abs() > tol
1764                        {
1765                            fails.push(format!("{source} {name} {value:.1} ≠ {w}"));
1766                        }
1767                    }
1768                };
1769                check("Day", day, base_day);
1770                let unread = match (native, base_native) {
1771                    (Some(f), Some(base)) => {
1772                        check("native", f, base);
1773                        false
1774                    }
1775                    _ => true,
1776                };
1777                if !fails.is_empty() {
1778                    return Err(Reply::fail(format!("{id:?}: {}", fails.join("; ")), true));
1779                }
1780                Ok(Reply {
1781                    data: unread.then(|| serde_json::json!({ "unread": ["frame"] })),
1782                    ..Reply::ok()
1783                })
1784            }
1785            Step::AssertDisplayed {
1786                id,
1787                opacity,
1788                tx,
1789                ty,
1790                width,
1791                height,
1792                background,
1793                tolerance,
1794            } => {
1795                let want_color = match &background {
1796                    Some(c) => Some(parse_hex_color(c).ok_or_else(|| {
1797                        Reply::fail(format!("assert_displayed: {c:?} is not #rrggbb"), false)
1798                    })?),
1799                    None => None,
1800                };
1801                let node = find(&id)?;
1802                // A value in flight is only right at the moment it is asked for, so nothing
1803                // here is retried: flush what is pending, read once, answer.
1804                day_reactive::flush_sync();
1805                let shown = with_tree(|t| t.read_displayed(node)).unwrap_or_default();
1806                let unit = tolerance.unwrap_or(0.05);
1807                let points = tolerance.unwrap_or(1.0);
1808                let mut unread = Vec::new();
1809                let mut fails = Vec::new();
1810                let mut check = |field: &str, got: Option<f64>, want: Option<f64>, tol: f64| match (
1811                    got, want,
1812                ) {
1813                    (None, Some(_)) => {
1814                        if !unread.iter().any(|u| u == field) {
1815                            unread.push(field.to_owned());
1816                        }
1817                    }
1818                    (Some(g), Some(w)) if (g - w).abs() > tol => {
1819                        fails.push(format!("displayed {field} {g:.3} ≠ expected {w:.3} ±{tol}"));
1820                    }
1821                    _ => {}
1822                };
1823                check("opacity", shown.opacity, opacity, unit);
1824                check("translation", shown.translation.map(|t| t.x), tx, points);
1825                check("translation", shown.translation.map(|t| t.y), ty, points);
1826                check("frame", shown.frame.map(|f| f.size.width), width, points);
1827                check("frame", shown.frame.map(|f| f.size.height), height, points);
1828                if let Some(want) = want_color {
1829                    let got = shown.background.map(|c| [c.r, c.g, c.b]);
1830                    for (i, want) in want.into_iter().enumerate() {
1831                        check(
1832                            "background",
1833                            got.map(|g| g[i]),
1834                            Some(f64::from(want) / 255.0),
1835                            unit,
1836                        );
1837                    }
1838                }
1839                if !fails.is_empty() {
1840                    return Err(Reply::fail(format!("{id:?}: {}", fails.join("; ")), false));
1841                }
1842                Ok(Reply {
1843                    data: (!unread.is_empty()).then(|| serde_json::json!({ "unread": unread })),
1844                    ..Reply::ok()
1845                })
1846            }
1847            Step::SamplePixel {
1848                id,
1849                x,
1850                y,
1851                color,
1852                tolerance,
1853            } => {
1854                let want = parse_hex_color(&color).ok_or_else(|| {
1855                    Reply::fail(format!("sample_pixel: {color:?} is not #rrggbb"), false)
1856                })?;
1857                if day_core::capability(day_spec::Cap::Snapshot) == day_spec::Support::Unsupported {
1858                    return Ok(Reply {
1859                        data: Some(serde_json::json!({ "unread": ["pixel"] })),
1860                        ..Reply::ok()
1861                    });
1862                }
1863                day_reactive::flush_sync();
1864                if !with_tree(|t| t.ui_idle()) {
1865                    return Err(Reply::fail("ui transitions still settling", true));
1866                }
1867                hosts_settled()?;
1868                let readiness = with_tree(|t| t.prepare_snapshot(None, revision))
1869                    .map_err(|e| Reply::fail(format!("sample_pixel readiness: {e}"), false))?;
1870                if readiness == day_spec::capture::Readiness::Pending {
1871                    return Err(Reply {
1872                        capture_pending: true,
1873                        ..Reply::fail("waiting for a render checkpoint", true)
1874                    });
1875                }
1876                let node = find(&id)?;
1877                // A node's frame is relative to its nearest realized native ancestor (§7): add
1878                // the origins of the native ancestors below the window's root, so a node inside
1879                // a native container (a `.background`) is sampled where it is in the window.
1880                let frame = with_tree(|t| {
1881                    let mut f = t.node_frame(node)?;
1882                    let root = t.root_node();
1883                    let mut up = t.parent_of(node);
1884                    while let Some(a) = up.filter(|a| *a != root) {
1885                        if t.node_handle_any(a).is_some()
1886                            && let Some(p) = t.node_frame(a)
1887                        {
1888                            f.origin.x += p.origin.x;
1889                            f.origin.y += p.origin.y;
1890                        }
1891                        up = t.parent_of(a);
1892                    }
1893                    Some(f)
1894                })
1895                .ok_or_else(|| Reply::fail(format!("{id:?} has no frame"), true))?;
1896                let window = with_tree(|t| t.node_frame(t.root_node()))
1897                    .ok_or_else(|| Reply::fail("the window has no frame", true))?;
1898                let bytes = with_tree(|t| t.snapshot())
1899                    .map_err(|e| Reply::fail(format!("sample_pixel capture: {e}"), true))?;
1900                let origin = with_tree(|t| t.snapshot_origin());
1901                // A capture this reader cannot read (the mock's placeholder bytes) is a gap
1902                // to record, like a toolkit with no capture, not a wrong color.
1903                let unread = || Reply {
1904                    data: Some(serde_json::json!({ "unread": ["pixel"] })),
1905                    ..Reply::ok()
1906                };
1907                // Read as far as the header: only the sampled pixel's rows are decoded below.
1908                let Ok(img) = png::Png::read(&bytes) else {
1909                    return Ok(unread());
1910                };
1911                drop(bytes);
1912                // The capture is the window's content at the screen's scale. Where the toolkit
1913                // says where Day's root sits in it (Android's edge-to-edge content, with bars
1914                // above and below), that is the offset, and the scale comes from the screen
1915                // width the capture spans. Otherwise the capture is measured across Day's own
1916                // width, and rows beyond Day's content are window area above it (AppKit's
1917                // full-size content view under a transparent title bar).
1918                let (scale, left, above) = if let Some(o) = origin {
1919                    (
1920                        img.width as f64 / (window.size.width + 2.0 * o.x).max(1.0),
1921                        o.x,
1922                        o.y,
1923                    )
1924                } else {
1925                    let scale = img.width as f64 / window.size.width.max(1.0);
1926                    let above = (img.height as f64 / scale - window.size.height).max(0.0);
1927                    (scale, 0.0, above)
1928                };
1929                let px = ((left + frame.origin.x - window.origin.x + x * frame.size.width) * scale)
1930                    .floor()
1931                    .max(0.0) as usize;
1932                let py = ((above + frame.origin.y - window.origin.y + y * frame.size.height)
1933                    * scale)
1934                    .floor()
1935                    .max(0.0) as usize;
1936                let Ok(got) = img.pixel(px, py) else {
1937                    return Ok(unread());
1938                };
1939                let got = got.ok_or_else(|| {
1940                    Reply::fail(
1941                        format!("{id:?}: ({px}, {py}) is outside the capture"),
1942                        false,
1943                    )
1944                })?;
1945                let tol = tolerance.unwrap_or(64);
1946                let near = (0..3).all(|i| got[i].abs_diff(want[i]) <= tol);
1947                if near {
1948                    Ok(Reply::ok())
1949                } else {
1950                    Err(Reply::fail(
1951                        format!(
1952                            "{id:?} at ({x}, {y}): #{:02x}{:02x}{:02x} ≠ {color}",
1953                            got[0], got[1], got[2]
1954                        ),
1955                        true,
1956                    ))
1957                }
1958            }
1959            Step::AssertNative {
1960                id,
1961                text,
1962                number,
1963                checked,
1964                enabled,
1965                visible,
1966            } => {
1967                let node = find(&id)?;
1968                let native = with_tree(|t| t.read_native(node)).unwrap_or_default();
1969                if let Some(want) = enabled
1970                    && probe(&id)?.enabled != want
1971                {
1972                    return Err(Reply::fail(
1973                        format!("{id:?}: Day has enabled={}, expected {want}", !want),
1974                        true,
1975                    ));
1976                }
1977                let mut unread = Vec::new();
1978                let mut fails = Vec::new();
1979                let mut check = |field: &str,
1980                                 got: Option<String>,
1981                                 want: Option<String>,
1982                                 eq: bool| match (got, want) {
1983                    (None, Some(_)) => unread.push(field.to_owned()),
1984                    (Some(g), Some(w)) if !eq => {
1985                        fails.push(format!("native {field} {g} ≠ expected {w}"));
1986                    }
1987                    _ => {}
1988                };
1989                let text_eq =
1990                    matches!((&native.text, &text), (Some(g), Some(w)) if norm(g) == norm(w));
1991                check(
1992                    "text",
1993                    native.text.as_ref().map(|t| format!("{t:?}")),
1994                    text.as_ref().map(|t| format!("{t:?}")),
1995                    text_eq,
1996                );
1997                let number_eq = matches!((native.number, number), (Some(g), Some(w)) if (g - w).abs() <= 1e-3 * w.abs().max(1.0));
1998                check(
1999                    "number",
2000                    native.number.map(|n| n.to_string()),
2001                    number.map(|n| n.to_string()),
2002                    number_eq,
2003                );
2004                check(
2005                    "checked",
2006                    native.checked.map(|b| b.to_string()),
2007                    checked.map(|b| b.to_string()),
2008                    native.checked == checked,
2009                );
2010                check(
2011                    "enabled",
2012                    native.enabled.map(|b| b.to_string()),
2013                    enabled.map(|b| b.to_string()),
2014                    native.enabled == enabled,
2015                );
2016                check(
2017                    "visible",
2018                    native.visible.map(|b| b.to_string()),
2019                    visible.map(|b| b.to_string()),
2020                    native.visible == visible,
2021                );
2022                if !fails.is_empty() {
2023                    return Err(Reply::fail(format!("{id:?}: {}", fails.join("; ")), true));
2024                }
2025                Ok(Reply {
2026                    data: (!unread.is_empty()).then(|| serde_json::json!({ "unread": unread })),
2027                    ..Reply::ok()
2028                })
2029            }
2030            Step::ScrollTo { id, edge, x, y } => {
2031                let node = find(&id)?;
2032                let target = match (edge.as_deref(), x, y) {
2033                    (Some("top"), _, _) => day_core::ScrollTarget::Top,
2034                    (Some("bottom"), _, _) => day_core::ScrollTarget::Bottom,
2035                    (Some("leading"), _, _) => day_core::ScrollTarget::Leading,
2036                    (Some("trailing"), _, _) => day_core::ScrollTarget::Trailing,
2037                    (Some(other), _, _) => {
2038                        return Err(Reply::fail(
2039                            format!(
2040                                "scroll_to: unknown edge {other:?} (top|bottom|leading|trailing)"
2041                            ),
2042                            false,
2043                        ));
2044                    }
2045                    (None, None, None) => {
2046                        // Reveal the element in its nearest enclosing scroll.
2047                        let ok = with_tree(|t| t.scroll_reveal(node, false));
2048                        if !ok {
2049                            return Err(Reply::fail(
2050                                format!("scroll_to: {id:?} has no enclosing scroll"),
2051                                true,
2052                            ));
2053                        }
2054                        day_reactive::flush_sync();
2055                        return Ok(Reply::ok());
2056                    }
2057                    (None, x, y) => day_core::ScrollTarget::Offset(day_spec::Point::new(
2058                        x.unwrap_or(0.0),
2059                        y.unwrap_or(0.0),
2060                    )),
2061                };
2062                let ok = with_tree(|t| t.scroll_to_target(node, &target, false));
2063                if !ok {
2064                    return Err(Reply::fail(
2065                        format!("scroll_to: {id:?} does not support this scroll target"),
2066                        true,
2067                    ));
2068                }
2069                day_reactive::flush_sync();
2070                Ok(Reply::ok())
2071            }
2072            Step::Focus { id, focused } => {
2073                let want = focused.unwrap_or(true);
2074                let node = find(&id)?;
2075                with_tree(|t| t.focus_node(node, want));
2076                day_reactive::flush_sync();
2077                // Wait, briefly, for the toolkit to report the move. XAML raises GotFocus and
2078                // LostFocus as queued routed events, so on WinUI the report lands after this step
2079                // returns: the app's reaction to gaining focus (an address bar selecting its whole
2080                // address) then overwrote what a following `input` had typed. A control that never
2081                // reports focus still passes, after FOCUS_WAIT_POLLS retries.
2082                if probe(&id)?.focused != want
2083                    && FOCUS_WAITS.fetch_add(1, Ordering::Relaxed) < FOCUS_WAIT_POLLS
2084                {
2085                    return Err(Reply::fail(
2086                        format!("{id:?}: waiting for the toolkit to report focused={want}"),
2087                        true,
2088                    ));
2089                }
2090                FOCUS_WAITS.store(0, Ordering::Relaxed);
2091                Ok(Reply::ok())
2092            }
2093            Step::AssertFocused { id, focused } => {
2094                let want = focused.unwrap_or(true);
2095                let got = probe(&id)?.focused;
2096                if got == want {
2097                    Ok(Reply::ok())
2098                } else {
2099                    Err(Reply::fail(
2100                        format!("{id:?}: expected focused={want}, found focused={got}"),
2101                        true,
2102                    ))
2103                }
2104            }
2105            Step::CloseWindow { window } => {
2106                let handle = match &window {
2107                    Some(key) => day_core::window_by_key(key),
2108                    None => day_core::initial_window(),
2109                };
2110                if let Some(handle) = handle {
2111                    handle.close();
2112                }
2113                day_reactive::flush_sync();
2114                Ok(Reply::ok())
2115            }
2116            Step::Screenshot {
2117                window, in_process, ..
2118            } => {
2119                day_reactive::flush_sync();
2120                // Wait (retryable, bounded by the step timeout) for native transitions to
2121                // settle so the capture never shows a half-dismissed dialog or mid-push page.
2122                if !with_tree(|t| t.ui_idle()) {
2123                    return Err(Reply::fail("ui transitions still settling", true));
2124                }
2125                hosts_settled()?;
2126                let root = match window.as_deref() {
2127                    Some(key) => Some(
2128                        day_core::windows::window_root_by_key(key)
2129                            .ok_or_else(|| Reply::fail(format!("no window {key:?}"), true))?,
2130                    ),
2131                    None => None,
2132                };
2133                let readiness = with_tree(|t| t.prepare_snapshot(root, revision))
2134                    .map_err(|e| Reply::fail(format!("screenshot readiness: {e}"), false))?;
2135                if readiness == day_spec::capture::Readiness::Pending {
2136                    return Err(Reply {
2137                        capture_pending: true,
2138                        ..Reply::fail("waiting for screenshot render checkpoint", true)
2139                    });
2140                }
2141                let capture_revision =
2142                    (readiness == day_spec::capture::Readiness::Ready).then_some(revision);
2143                if !in_process {
2144                    return Ok(Reply {
2145                        capture_revision,
2146                        ..Reply::ok()
2147                    });
2148                }
2149                let png = match window.as_deref() {
2150                    Some(key) => match day_core::windows::window_root_by_key(key) {
2151                        Some(root) => with_tree(|t| t.snapshot_of(root)),
2152                        // Retryable: the window may still be opening (a Pending native
2153                        // creation, or the opening tap's turn not yet drained).
2154                        None => return Err(Reply::fail(format!("no window {key:?}"), true)),
2155                    },
2156                    None => with_tree(|t| t.snapshot()),
2157                };
2158                match png {
2159                    Ok(bytes) => {
2160                        SNAPSHOT_MISSES.store(0, Ordering::Relaxed);
2161                        SNAPSHOT_WORKS.store(true, Ordering::Relaxed);
2162                        Ok(Reply {
2163                            ok: true,
2164                            png_base64: Some(b64encode(&bytes)),
2165                            capture_revision: Some(revision),
2166                            ..Default::default()
2167                        })
2168                    }
2169                    // A backend also fails a snapshot it cannot take YET: a GTK window has no
2170                    // render node until its first frame, and a large window (the 1280x800
2171                    // capture size) is still laying out when a script's opening `screenshot`
2172                    // arrives. Answering "unsupported" there dropped a run's first capture, so
2173                    // the miss is retryable, a bounded number of times. A backend that has
2174                    // never produced a snapshot pays that wait once and is then believed.
2175                    Err(_)
2176                        if (SNAPSHOT_WORKS.load(Ordering::Relaxed)
2177                            || !SNAPSHOT_NEVER.load(Ordering::Relaxed))
2178                            && SNAPSHOT_MISSES.fetch_add(1, Ordering::Relaxed)
2179                                < SNAPSHOT_RETRIES =>
2180                    {
2181                        Err(Reply::fail("the window has nothing to capture yet", true))
2182                    }
2183                    Err(_) => {
2184                        SNAPSHOT_MISSES.store(0, Ordering::Relaxed);
2185                        if !SNAPSHOT_WORKS.load(Ordering::Relaxed) {
2186                            SNAPSHOT_NEVER.store(true, Ordering::Relaxed);
2187                        }
2188                        Ok(Reply {
2189                            ok: true,
2190                            screenshot_unsupported: true,
2191                            ..Default::default()
2192                        })
2193                    }
2194                }
2195            }
2196            Step::Pause { secs } => {
2197                // Pausing the main thread would freeze the UI; the runner sleeps instead.
2198                let _ = secs;
2199                Ok(Reply::ok())
2200            }
2201            Step::ExpectExit { within } => {
2202                // Runner-side (day-cli watches for the connection to drop); the engine only reaches
2203                // this arm if the step was somehow delivered; treat it as a no-op success.
2204                let _ = within;
2205                Ok(Reply::ok())
2206            }
2207            Step::SizeClass { width, height } => {
2208                if width == "auto" {
2209                    day_core::restore_reported_size_class();
2210                    day_reactive::flush_sync();
2211                    return Ok(Reply::ok());
2212                }
2213                let width = parse_width_class(&width).ok_or_else(|| {
2214                    Reply::fail(
2215                        format!(
2216                            "size_class: unknown width {width:?} \
2217                             (auto|compact|medium|expanded|large|extra-large)"
2218                        ),
2219                        false,
2220                    )
2221                })?;
2222                let height = match height.as_deref() {
2223                    None => day_spec::HeightClass::Expanded,
2224                    Some(h) => parse_height_class(h).ok_or_else(|| {
2225                        Reply::fail(
2226                            format!("size_class: unknown height {h:?} (compact|medium|expanded)"),
2227                            false,
2228                        )
2229                    })?,
2230                };
2231                day_core::override_size_class(day_spec::SizeClass { width, height });
2232                // Settle the re-present before the next step looks: the class write schedules a
2233                // binding, and the backend's re-home runs inside it.
2234                day_reactive::flush_sync();
2235                Ok(Reply::ok())
2236            }
2237            Step::Resize {
2238                width,
2239                height,
2240                restore,
2241            } => {
2242                // The runner has already asked the platform to resize; this half waits for the
2243                // app to have seen it. Everything downstream (the re-present, a piece rebuilding
2244                // off `size_class()`) rides the report, so acknowledging before it landed would
2245                // hand the next step the old layout.
2246                if !with_tree(|t| t.ui_idle()) {
2247                    return Err(Reply::fail("ui transitions still settling", true));
2248                }
2249                // Real geometry ends a class an earlier `size_class:` step forced.
2250                day_core::restore_reported_size_class();
2251                day_reactive::flush_sync();
2252                let (Some(w), Some(h)) = (width, height) else {
2253                    // `resize: auto`, or a resize with no dimensions to check against: the
2254                    // runner restored the device's own geometry and there is nothing to assert.
2255                    let _ = restore;
2256                    return Ok(Reply::ok());
2257                };
2258                // Compared as a width class, and only that.
2259                //
2260                // Two reasons, both learned from the first run of this step. What reaches day-core
2261                // is the safe-area-inset content size, not the window's: a window resized to 900dp
2262                // tall reports about 830 once the status bar, the navigation bar and the app bar
2263                // are taken out, so asserting the height class fails a resize that was letter
2264                // perfect. And width is what the step exists to control: every re-presentation
2265                // decision reads `SizeClass::width` (`prefers_split`, the Tabs/Rail/Split ladder),
2266                // while height enters into none of them. Top and bottom chrome is also exactly
2267                // where the insets are, so height is the axis the content size distorts most.
2268                let want = day_spec::SizeClass::from_size(w, h).width;
2269                let have = day_core::size_class();
2270                if have.map(|c| c.width) == Some(want) {
2271                    Ok(Reply::ok())
2272                } else {
2273                    // Retryable: a platform resize is animated, and the report lands when it ends.
2274                    Err(Reply::fail(
2275                        format!(
2276                            "resize to {w}x{h} wants width {want:?}, window reports {have:?} \
2277                             (a width within a few points of a breakpoint can fall the other \
2278                             side of it once safe-area insets come out — aim for mid-bucket)"
2279                        ),
2280                        true,
2281                    ))
2282                }
2283            }
2284            Step::OpenUrl { url } => {
2285                day_core::request_open_url(&url);
2286                Ok(Reply::ok())
2287            }
2288            Step::DeepLink { url } => {
2289                day_reactive::flush_sync();
2290                let route = day_spec::route_of_url(&url);
2291                if day_core::navigate(&route) {
2292                    day_reactive::flush_sync();
2293                    Ok(Reply::ok())
2294                } else {
2295                    // Retryable: the nav host may not have mounted yet.
2296                    Err(Reply::fail(format!("no route for {url:?}"), true))
2297                }
2298            }
2299            Step::Navigate { route } => {
2300                day_reactive::flush_sync();
2301                if day_core::navigate(&route) {
2302                    day_reactive::flush_sync();
2303                    Ok(Reply::ok())
2304                } else {
2305                    // Retryable: the nav host may not have mounted yet.
2306                    Err(Reply::fail(format!("no route {route:?}"), true))
2307                }
2308            }
2309            Step::NavBack { native } => {
2310                // `native`: the platform's own back affordance, so the backend's user-back
2311                // path (the bar's `shouldPop`, the pop, the report to Day) is what runs. The
2312                // pop animates and Day hears of it on completion, so nothing is flushed here;
2313                // the next `assert_route` waits for it like any assertion.
2314                // A native press must not race the transition before it: pressed during a
2315                // push still animating, the bar has nothing to pop yet, and a wide window
2316                // would then pass this step as "nothing was pushed" (below). Retryable, like
2317                // `screenshot`'s own settle.
2318                if native && !with_tree(|t| t.ui_idle()) {
2319                    return Err(Reply::fail("ui transitions still settling", true));
2320                }
2321                let popped = if native {
2322                    with_tree(|t| t.native_back())
2323                } else {
2324                    day_core::nav_back()
2325                };
2326                if popped {
2327                    if !native {
2328                        day_reactive::flush_sync();
2329                    }
2330                    Ok(Reply::ok())
2331                } else if day_core::size_class().is_some_and(day_spec::SizeClass::prefers_split) {
2332                    // Nothing to pop, and nothing should be: a window past the compact width keeps
2333                    // the detail beside the list instead of pushing it (docs/size-classes.md), so
2334                    // the script is already where `nav_back` would have taken it.
2335                    //
2336                    // Without this, one walkthrough could not describe both form factors of the
2337                    // same target. The step was gated `only_on: [uikit, material]`, a toolkit condition,
2338                    // which silently meant "phone" until ios-uikit started running on an iPad,
2339                    // where the presentation is expanded exactly like a desktop's. The toolkit was
2340                    // never the thing that decided; the width class is.
2341                    //
2342                    // Still a failure while compact, which is where a missing pop is a regression
2343                    // and where the guard in the scaffold's walkthrough does its job. Tolerating
2344                    // it everywhere would have made this step unable to fail.
2345                    Ok(Reply::ok())
2346                } else {
2347                    Err(Reply::fail("nothing to pop", true))
2348                }
2349            }
2350            Step::AssertRoute { route } => {
2351                let current = day_core::current_route();
2352                if current.as_deref() == Some(route.as_str()) {
2353                    Ok(Reply::ok())
2354                } else {
2355                    Err(Reply::fail(
2356                        format!("expected route {route:?}, current {current:?}"),
2357                        true,
2358                    ))
2359                }
2360            }
2361            Step::DialogMode { mode } => {
2362                let mode = match mode {
2363                    DialogMode::Native => day_core::PresentationMode::Native,
2364                    DialogMode::Scripted => day_core::PresentationMode::Scripted,
2365                };
2366                day_core::set_presentation_mode(mode).map_err(|why| Reply::fail(why, false))?;
2367                Ok(Reply::ok())
2368            }
2369            Step::AssertNotPresented => {
2370                if let Some((_, spec)) = day_core::pending_presentation() {
2371                    Err(Reply::fail(
2372                        format!("unanswered presentation: {:?}", spec.title()),
2373                        true,
2374                    ))
2375                } else {
2376                    Ok(Reply::ok())
2377                }
2378            }
2379            Step::AssertPresented { title } => match day_core::pending_presentation() {
2380                Some((_, spec)) => {
2381                    let actual = norm(spec.title());
2382                    match title {
2383                        Some(want) if norm(&want) != actual => Err(Reply::fail(
2384                            format!("modal title {actual:?} != expected {want:?}"),
2385                            true,
2386                        )),
2387                        _ => Ok(Reply::ok()),
2388                    }
2389                }
2390                None => Err(Reply::fail("no modal presented", true)),
2391            },
2392            Step::Respond {
2393                button,
2394                text,
2395                path,
2396                dismiss,
2397            } => {
2398                let Some((req, _)) = day_core::pending_presentation() else {
2399                    return Err(Reply::fail("no modal to respond to", true));
2400                };
2401                let result = if dismiss {
2402                    PresentResult::Dismissed
2403                } else if let Some(t) = text {
2404                    PresentResult::Text(t)
2405                } else if let Some(p) = path {
2406                    // Relative paths resolve against the app-writable temp dir so a scripted
2407                    // open/save round-trip works on desktop, iOS, and Android alike.
2408                    let pb = std::path::PathBuf::from(&p);
2409                    let full = if pb.is_absolute() {
2410                        pb
2411                    } else {
2412                        day_core::app_temp_dir().join(pb)
2413                    };
2414                    PresentResult::Files(vec![full.to_string_lossy().into_owned()])
2415                } else if let Some(i) = button {
2416                    PresentResult::Button(i)
2417                } else {
2418                    PresentResult::Dismissed
2419                };
2420                let _ = day_core::respond_presentation(req, result);
2421                day_reactive::flush_sync();
2422                Ok(Reply::ok())
2423            }
2424            Step::Tests => Ok(Reply {
2425                data: Some(conformance::listing().map_err(|e| Reply::fail(e, false))?),
2426                ..Reply::ok()
2427            }),
2428            Step::RunTests {
2429                filter,
2430                shots,
2431                case_timeout_secs,
2432                ..
2433            } => conformance::run_tests(&filter, shots, case_timeout_secs),
2434            Step::A11yAudit { id } => {
2435                let rows = with_tree(|t| t.a11y_nodes());
2436                let rows: Vec<_> = match &id {
2437                    Some(want) => rows.into_iter().filter(|(nid, ..)| nid == want).collect(),
2438                    None => rows,
2439                };
2440                if let Some(want) = &id
2441                    && rows.is_empty()
2442                {
2443                    return Err(Reply::fail(
2444                        format!("a11y_audit: no element {want:?}"),
2445                        true,
2446                    ));
2447                }
2448                let mut fails = Vec::new();
2449                for (nid, _kind, expected, actual) in &rows {
2450                    audit_a11y_node(nid, expected, actual, &mut fails);
2451                }
2452                if !fails.is_empty() {
2453                    return Err(Reply::fail(
2454                        format!("a11y_audit: {}", fails.join("; ")),
2455                        false,
2456                    ));
2457                }
2458                Ok(Reply::ok())
2459            }
2460        }
2461    })();
2462    let mut reply = result.unwrap_or_else(|r| r);
2463    if reply.ok
2464        && !absent_optional_action
2465        && let (Some(class), Some(id)) = (evidence_class, evidence_id)
2466        && let Ok(catalog) = id_catalog()
2467        && let Ok(d) = catalog.resolve(&id)
2468    {
2469        reply.id_evidence = Box::new([day_script_protocol::IdEvidence {
2470            family: d.family.clone(),
2471            class,
2472        }]);
2473    }
2474    reply.fast_animations = Some(day_core::testing::fast_animations());
2475    reply
2476}
2477
2478/// Compare readable, shown native accessibility nodes. Hidden navigation panes may retain
2479/// widgets whose platform accessibility nodes omit their metadata until shown again.
2480fn audit_a11y_node(
2481    nid: &str,
2482    expected: &day_spec::A11yProps,
2483    actual: &day_spec::NativeSnapshot,
2484    fails: &mut Vec<String>,
2485) {
2486    if !actual.found || actual.visible == Some(false) {
2487        return;
2488    }
2489    if actual.identifier.as_deref() != Some(nid) {
2490        fails.push(format!(
2491            "{nid}: native identifier {:?} ≠ {nid:?}",
2492            actual.identifier
2493        ));
2494    }
2495    // Role: audit only explicit (user-set) roles, the canvas/custom cases where
2496    // Day itself applies a role. Native controls own their roles (Day's job
2497    // is to not break them, §13), and those vary per platform, so we don't diff
2498    // the kind-default. Compare only when the native role also maps to a known Role.
2499    if expected.role != day_spec::Role::None
2500        && actual.role != day_spec::Role::None
2501        && !role_eq(expected.role, actual.role)
2502    {
2503        fails.push(format!(
2504            "{nid}: role {:?} ≠ expected {:?}",
2505            actual.role, expected.role
2506        ));
2507    }
2508    if let Some(lbl) = &expected.label
2509        && actual.label.as_deref() != Some(lbl.as_str())
2510    {
2511        fails.push(format!(
2512            "{nid}: label {:?} ≠ expected {lbl:?}",
2513            actual.label
2514        ));
2515    }
2516    if let Some(val) = &expected.value
2517        && actual.value.as_deref() != Some(val.as_str())
2518    {
2519        fails.push(format!(
2520            "{nid}: value {:?} ≠ expected {val:?}",
2521            actual.value
2522        ));
2523    }
2524}
2525
2526/// Two roles match for audit purposes; `Heading` levels are ignored (the native role carries
2527/// no level).
2528fn role_eq(a: day_spec::Role, b: day_spec::Role) -> bool {
2529    use day_spec::Role::Heading;
2530    matches!((a, b), (Heading(_), Heading(_))) || a == b
2531}
2532
2533// ---------------------------------------------------------------------------
2534// Minimal base64 (no dependency; screenshots cross as one JSON line)
2535// ---------------------------------------------------------------------------
2536
2537const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2538
2539#[must_use]
2540pub fn b64encode(data: &[u8]) -> String {
2541    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
2542    for chunk in data.chunks(3) {
2543        let b = [
2544            chunk[0],
2545            *chunk.get(1).unwrap_or(&0),
2546            *chunk.get(2).unwrap_or(&0),
2547        ];
2548        let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
2549        out.push(B64[(n >> 18) as usize & 63] as char);
2550        out.push(B64[(n >> 12) as usize & 63] as char);
2551        out.push(if chunk.len() > 1 {
2552            B64[(n >> 6) as usize & 63] as char
2553        } else {
2554            '='
2555        });
2556        out.push(if chunk.len() > 2 {
2557            B64[n as usize & 63] as char
2558        } else {
2559            '='
2560        });
2561    }
2562    out
2563}
2564
2565#[must_use]
2566pub fn b64decode(s: &str) -> Vec<u8> {
2567    let val = |c: u8| B64.iter().position(|&x| x == c).unwrap_or(0) as u32;
2568    let bytes: Vec<u8> = s.bytes().filter(|&c| c != b'\n' && c != b'\r').collect();
2569    let mut out = Vec::with_capacity(bytes.len() / 4 * 3);
2570    for chunk in bytes.chunks(4) {
2571        if chunk.len() < 4 {
2572            break;
2573        }
2574        #[expect(
2575            clippy::naive_bytecount,
2576            reason = "the chunk is four bytes; a byte-counting dependency would buy nothing"
2577        )]
2578        let pad = chunk.iter().filter(|&&c| c == b'=').count();
2579        let n = (val(chunk[0]) << 18)
2580            | (val(chunk[1]) << 12)
2581            | (val(if chunk[2] == b'=' { b'A' } else { chunk[2] }) << 6)
2582            | val(if chunk[3] == b'=' { b'A' } else { chunk[3] });
2583        out.push((n >> 16) as u8);
2584        if pad < 2 {
2585            out.push((n >> 8) as u8);
2586        }
2587        if pad < 1 {
2588            out.push(n as u8);
2589        }
2590    }
2591    out
2592}
2593
2594#[cfg(test)]
2595mod tests {
2596    use super::*;
2597
2598    #[test]
2599    fn a_step_before_the_backend_starts_waits_instead_of_panicking() {
2600        // The poster is process-wide and never removed: once another test in this binary has
2601        // launched a tree, there is no "before" left to test.
2602        if day_reactive::has_main_poster() {
2603            return;
2604        }
2605        let step: Step = serde_json::from_value(serde_json::json!({"op": "tap", "id": "anything"}))
2606            .expect("a tap step parses");
2607        let reply = run_on_main(step, Duration::from_millis(50), 1);
2608        assert!(!reply.ok, "{reply:?}");
2609        assert!(reply.retryable, "a starting app is retried: {reply:?}");
2610    }
2611
2612    #[test]
2613    fn a11y_audit_checks_metadata_when_visible_or_visibility_is_unknown() {
2614        // Synthetic snapshots model an Android list parked behind a compact detail pane.
2615        let expected = day_spec::A11yProps {
2616            label: Some("Fixture list".into()),
2617            ..Default::default()
2618        };
2619        let mut actual = day_spec::NativeSnapshot {
2620            found: true,
2621            identifier: Some("fixture-list".into()),
2622            visible: Some(false),
2623            ..Default::default()
2624        };
2625        let mut fails = Vec::new();
2626        audit_a11y_node("fixture-list", &expected, &actual, &mut fails);
2627        assert!(
2628            fails.is_empty(),
2629            "hidden panes need not expose their labels"
2630        );
2631
2632        for visible in [Some(true), None] {
2633            actual.visible = visible;
2634            fails.clear();
2635            audit_a11y_node("fixture-list", &expected, &actual, &mut fails);
2636            assert_eq!(
2637                fails.len(),
2638                1,
2639                "missing labels must still fail: {visible:?}"
2640            );
2641            assert!(fails[0].contains("label None"));
2642        }
2643
2644        actual.visible = Some(true);
2645        actual.label = expected.label.clone();
2646        fails.clear();
2647        audit_a11y_node("fixture-list", &expected, &actual, &mut fails);
2648        assert!(
2649            fails.is_empty(),
2650            "the list exposes its label when shown again"
2651        );
2652
2653        actual.label = None;
2654        actual.found = false;
2655        audit_a11y_node("fixture-list", &expected, &actual, &mut fails);
2656        assert!(
2657            fails.is_empty(),
2658            "unreadable accessibility nodes remain unsupported"
2659        );
2660    }
2661
2662    #[test]
2663    fn dialog_steps_hold_requests_until_an_explicit_response() {
2664        use day_spec::present::{PresentResult, PresentSpec};
2665        use std::future::Future;
2666        use std::task::{Context, Poll, Waker};
2667        assert!(serde_json::from_str::<Step>(r#"{"op":"dialog_mode","mode":"typo"}"#).is_err());
2668        let mode: Step = serde_json::from_str(r#"{"op":"dialog_mode","mode":"scripted"}"#).unwrap();
2669        assert!(exec(mode, 0).ok);
2670        assert!(exec(Step::AssertNotPresented, 0).ok);
2671        // No tree is installed: neither presenting nor answering may call a toolkit.
2672        let mut future = Box::pin(day_core::present(PresentSpec::OpenFile {
2673            title: "Choose file".into(),
2674            filters: vec![],
2675            multiple: false,
2676        }));
2677        let mut cx = Context::from_waker(Waker::noop());
2678        assert!(future.as_mut().poll(&mut cx).is_pending());
2679        assert!(
2680            exec(
2681                Step::AssertPresented {
2682                    title: Some("Choose file".into())
2683                },
2684                0
2685            )
2686            .ok
2687        );
2688        assert!(!exec(Step::AssertNotPresented, 0).ok);
2689        let refused = exec(
2690            Step::DialogMode {
2691                mode: DialogMode::Native,
2692            },
2693            0,
2694        );
2695        assert!(!refused.ok && !refused.retryable);
2696        assert!(
2697            exec(
2698                Step::Respond {
2699                    button: None,
2700                    text: None,
2701                    path: None,
2702                    dismiss: true
2703                },
2704                0
2705            )
2706            .ok
2707        );
2708        assert_eq!(
2709            future.as_mut().poll(&mut cx),
2710            Poll::Ready(PresentResult::Dismissed)
2711        );
2712        assert!(exec(Step::AssertNotPresented, 0).ok);
2713        assert!(
2714            exec(
2715                Step::DialogMode {
2716                    mode: DialogMode::Native
2717                },
2718                0
2719            )
2720            .ok
2721        );
2722    }
2723
2724    #[test]
2725    fn optional_tap_only_skips_absent_elements_after_transitions_settle() {
2726        use day_pieces::prelude::*;
2727        let _guard = ENV_LOCK
2728            .lock()
2729            .unwrap_or_else(std::sync::PoisonError::into_inner);
2730        day_core::uninstall_tree();
2731        let enabled = Signal::new(false);
2732        let presses = Signal::new(0);
2733        let (mock, probe) = day_mock::MockToolkit::new();
2734        day_core::launch_with(mock, day_spec::WindowOptions::default(), move || {
2735            button("Remove fixture")
2736                .enabled(move || enabled.get())
2737                .action(move || presses.update(|n| *n += 1))
2738                .id(day_core::id!(remove_fixture))
2739                .height(50.)
2740                .grow(Dimension::Width)
2741                .any()
2742        });
2743        let tap = |id, optional| {
2744            exec(
2745                serde_json::from_value(serde_json::json!({
2746                    "op": "tap", "id": id, "if_present": optional
2747                }))
2748                .unwrap(),
2749                1,
2750            )
2751        };
2752        assert!(!tap("missing", false).ok);
2753        let absent = tap("missing", true);
2754        assert!(absent.ok);
2755        assert!(absent.id_evidence.is_empty());
2756        probe.state.borrow_mut().ui_busy = true;
2757        assert!(!tap("missing", true).ok);
2758        probe.state.borrow_mut().ui_busy = false;
2759        let disabled = tap("remove_fixture", true);
2760        assert!(!disabled.ok && disabled.retryable);
2761        assert_eq!(presses.get(), 0);
2762        enabled.set(true);
2763        id_catalog().expect("the compiled test fixture registry is valid");
2764        let present = tap("remove_fixture", true);
2765        assert!(present.ok);
2766        assert_eq!(present.id_evidence.len(), 1);
2767        assert_eq!(present.id_evidence[0].family, "remove_fixture");
2768        assert_eq!(
2769            present.id_evidence[0].class,
2770            day_script_protocol::EvidenceClass::Interaction
2771        );
2772        assert_eq!(presses.get(), 1);
2773        day_core::uninstall_tree();
2774    }
2775
2776    /// Both forms of `nav_back` reach an app's `on_system_back` handler (docs/navigation.md
2777    /// "Handling the system Back"): Day's rail, and `native: true`, which presses the platform's
2778    /// back (the mock answers it in Android's order). Disabled, the handler takes neither, and a
2779    /// phone-width run fails the step as "nothing to pop".
2780    #[test]
2781    fn nav_back_steps_reach_the_system_back_handler() {
2782        use day_pieces::prelude::*;
2783        let _guard = ENV_LOCK
2784            .lock()
2785            .unwrap_or_else(std::sync::PoisonError::into_inner);
2786        day_core::uninstall_tree();
2787        let enabled = Signal::new(true);
2788        let backs = Signal::new(0);
2789        let (mock, probe) = day_mock::MockToolkit::new();
2790        day_core::launch_with(mock, day_spec::WindowOptions::default(), move || {
2791            label("Fixture page")
2792                .on_system_back(move || enabled.get(), move || backs.update(|n| *n += 1))
2793                .any()
2794        });
2795        let back = |native: bool| exec(Step::NavBack { native }, 1);
2796        assert!(back(false).ok);
2797        assert_eq!(backs.get(), 1);
2798        assert!(back(true).ok);
2799        assert_eq!(backs.get(), 2);
2800        enabled.set(false);
2801        day_reactive::flush_sync();
2802        assert!(!probe.system_back_armed());
2803        // Whether a missing pop fails depends on the width class; the handler must not run.
2804        let _ = back(false);
2805        let _ = back(true);
2806        assert_eq!(backs.get(), 2);
2807        day_core::uninstall_tree();
2808    }
2809
2810    #[test]
2811    fn tap_waits_for_navigation_and_enabled_state_before_dispatching_once() {
2812        use day_pieces::prelude::*;
2813        let _guard = ENV_LOCK
2814            .lock()
2815            .unwrap_or_else(std::sync::PoisonError::into_inner);
2816        day_core::uninstall_tree();
2817        let enabled = Signal::new(false);
2818        let presses = Signal::new(0);
2819        let (mock, probe) = day_mock::MockToolkit::new();
2820        day_core::launch_with(mock, day_spec::WindowOptions::default(), move || {
2821            button("Fixture download")
2822                .enabled(move || enabled.get())
2823                .action(move || presses.update(|n| *n += 1))
2824                .id(day_core::id!(fixture_download))
2825                .height(50.)
2826                .grow(Dimension::Width)
2827                .any()
2828        });
2829        let tap = || {
2830            exec(
2831                serde_json::from_value(serde_json::json!({
2832                    "op": "tap", "id": "fixture_download"
2833                }))
2834                .unwrap(),
2835                1,
2836            )
2837        };
2838        let reply = tap();
2839        assert!(!reply.ok && reply.retryable);
2840        assert!(reply.error.unwrap().contains("disabled"));
2841        assert_eq!(presses.get(), 0);
2842        enabled.set(true);
2843        probe.state.borrow_mut().ui_busy = true;
2844        assert!(!tap().ok);
2845        assert!(!exec(Step::WaitIdle, 1).ok);
2846        assert_eq!(presses.get(), 0);
2847        probe.state.borrow_mut().ui_busy = false;
2848        assert!(exec(Step::WaitIdle, 1).ok);
2849        assert!(tap().ok);
2850        assert_eq!(presses.get(), 1);
2851        day_core::uninstall_tree();
2852    }
2853
2854    #[test]
2855    fn capture_acknowledgments_are_optional_and_pending_stays_internal() {
2856        let old: Reply = serde_json::from_str(r#"{"ok":true}"#).unwrap();
2857        assert_eq!(old.capture_revision, None);
2858        assert_eq!(old.fast_animations, None);
2859        let reply = Reply {
2860            capture_revision: Some(73),
2861            fast_animations: Some(true),
2862            capture_pending: true,
2863            ..Reply::ok()
2864        };
2865        let json = serde_json::to_value(reply).unwrap();
2866        assert_eq!(json["capture_revision"], 73);
2867        assert!(json.get("capture_pending").is_none());
2868        let decoded: Reply = serde_json::from_value(json).unwrap();
2869        assert_eq!(decoded.capture_revision, Some(73));
2870        assert_eq!(decoded.fast_animations, Some(true));
2871    }
2872
2873    /// Serialize the env mutation below (`set_var` is unsafe under concurrency in edition 2024).
2874    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
2875
2876    /// The budget that decides whether a busy CI runner fails a walkthrough. One
2877    /// `main thread did not respond` was enough to fail an otherwise perfect 407-step run, so the
2878    /// default is generous, the environment can raise it, and a step that asks for longer gets it.
2879    #[test]
2880    fn the_main_thread_budget_is_generous_overridable_and_never_below_the_step() {
2881        let five = Duration::from_secs(5);
2882        let _guard = ENV_LOCK
2883            .lock()
2884            .unwrap_or_else(std::sync::PoisonError::into_inner);
2885        // SAFETY: the guard above serializes every mutation of this variable in this crate.
2886        unsafe { std::env::remove_var("DAY_SCRIPT_MAIN_TIMEOUT_SECS") };
2887        assert_eq!(
2888            main_thread_budget(five),
2889            Duration::from_secs_f64(DEFAULT_MAIN_TIMEOUT_SECS)
2890        );
2891        // A step declaring a longer wait is saying the app may legitimately take that long.
2892        assert_eq!(
2893            main_thread_budget(Duration::from_secs(120)),
2894            Duration::from_secs(120)
2895        );
2896        unsafe { std::env::set_var("DAY_SCRIPT_MAIN_TIMEOUT_SECS", "90") };
2897        assert_eq!(main_thread_budget(five), Duration::from_secs(90));
2898        // Nonsense is ignored rather than producing a zero budget that fails every step.
2899        for bad in ["0", "-3", "abc", ""] {
2900            unsafe { std::env::set_var("DAY_SCRIPT_MAIN_TIMEOUT_SECS", bad) };
2901            assert_eq!(
2902                main_thread_budget(five),
2903                Duration::from_secs_f64(DEFAULT_MAIN_TIMEOUT_SECS),
2904                "{bad:?} should fall back to the default"
2905            );
2906        }
2907        unsafe { std::env::remove_var("DAY_SCRIPT_MAIN_TIMEOUT_SECS") };
2908    }
2909
2910    /// A download finishing or an upload's receipt can take far longer than the shared wait, and
2911    /// a step's `timeout_secs` is how a script says so. An `assert_text` that dropped the field
2912    /// failed after five seconds while its script promised two minutes.
2913    #[test]
2914    fn assert_text_honors_its_own_timeout() {
2915        let step = |json: &str| serde_json::from_str::<Step>(json).expect("step");
2916        let slow = step(r#"{"op":"assert_text","id":"state","text":"done","timeout_secs":120}"#);
2917        assert_eq!(slow.wait_budget_secs(), 120.0);
2918        let plain = step(r#"{"op":"assert_text","id":"state","text":"done"}"#);
2919        assert_eq!(plain.wait_budget_secs(), DEFAULT_TIMEOUT_SECS);
2920        let waiting = step(r#"{"op":"wait_for","id":"state","timeout_secs":30}"#);
2921        assert_eq!(waiting.wait_budget_secs(), 30.0);
2922    }
2923
2924    /// A cold WebView2 engine can take longer than five seconds. The serialized step's
2925    /// budget must reach the engine poller, matching the CLI's socket timeout budget.
2926    #[test]
2927    fn web_eval_honors_its_own_timeout() {
2928        for (timeout, expected) in [
2929            (None, DEFAULT_TIMEOUT_SECS),
2930            (Some(30.0), 30.0),
2931            (Some(0.0), DEFAULT_TIMEOUT_SECS),
2932            (Some(-1.0), DEFAULT_TIMEOUT_SECS),
2933        ] {
2934            let step: Step = serde_json::from_value(serde_json::json!({
2935                "op": "web_eval", "id": "page", "script": "document.title",
2936                "timeout_secs": timeout,
2937            }))
2938            .expect("web_eval step");
2939            assert_eq!(step.wait_budget_secs(), expected);
2940        }
2941    }
2942
2943    /// `menu: { id: … }` is the address that survives a label change (which is exactly what a
2944    /// checked item does to itself on every state flip), and it never falls back to the label,
2945    /// so a step naming an id that is not there fails instead of hitting a lookalike.
2946    #[test]
2947    fn menu_id_addresses_an_item_whose_label_moves() {
2948        use day_spec::MenuItem as MI;
2949        let model = |mark: &str| {
2950            vec![MI::Submenu {
2951                label: "View".into(),
2952                role: None,
2953                items: vec![
2954                    MI::Action {
2955                        id: Some("view-grid".into()),
2956                        action: 42,
2957                        label: format!("{mark}Grid"),
2958                        shortcut: None,
2959                        enabled: true,
2960                        checked: Some(mark == "\u{2713} "),
2961                        role: None,
2962                        icon: None,
2963                    },
2964                    MI::Action {
2965                        id: None,
2966                        action: 7,
2967                        label: "Grid".into(),
2968                        shortcut: None,
2969                        enabled: true,
2970                        checked: None,
2971                        role: None,
2972                        icon: None,
2973                    },
2974                ],
2975            }]
2976        };
2977        let by_id = |items: &[MI]| {
2978            find_menu_actions(items, "", None, Some("view-grid"), &[])
2979                .into_iter()
2980                .map(|(a, _, _)| a)
2981                .collect::<Vec<_>>()
2982        };
2983        // Same id on either side of the flip, though the label is a different string each time.
2984        assert_eq!(by_id(&model("\u{2713} ")), vec![42]);
2985        assert_eq!(by_id(&model("    ")), vec![42]);
2986        // The unmarked spelling matches the other item by label, which is the ambiguity an id
2987        // exists to avoid.
2988        assert_eq!(
2989            find_menu_actions(&model("    "), "Grid", None, None, &[])
2990                .into_iter()
2991                .map(|(a, _, _)| a)
2992                .collect::<Vec<_>>(),
2993            vec![7]
2994        );
2995        // An id that is not in the model matches nothing: never the same-named item by label.
2996        assert_eq!(
2997            find_menu_actions(&model("    "), "Grid", None, Some("view-ruler"), &[]),
2998            [] as [(u64, bool, std::vec::Vec<std::string::String>); 0]
2999        );
3000    }
3001}