Skip to main content

iphone_cli/
steps.rs

1//! Steps: the pieces `iph batch` runs from a JSON list, and that scripts call
2//! as `waitFor`, `readField` and `readList`.
3//!
4//! A step is a one-key map. Kinds: `launch`, `wait_for`, `tap`, `type`,
5//! `swipe`, `scroll_until`, `read_field`, `read_list`, `assert`, `button`,
6//! `key`, `sleep`. Any step may add `when: "a == b"` (run the
7//! step only then) and `hint: "…"` (what to tell the person if it fails). A
8//! step that fails stops the run; nothing is guessed.
9//!
10//! Strings may use today's date and the date some days ago:
11//! `{{today.day}}`, `{{ago.6.month}}`, `{{ago.6.year}}`.
12
13use std::time::{Duration, Instant};
14
15use regex::Regex;
16use serde_json::{Map, Value, json};
17
18use crate::{
19    actions::{self, ButtonArgs, KeyArgs, LaunchArgs, ScrollArgs, SwipeArgs, TapArgs, TypeArgs, brief},
20    ax::{
21        attrs,
22        tree::{BuildOptions, Element, Rect, Screen},
23    },
24    device::session::{Fresh, Session, reuse},
25    fields,
26    i18n::t,
27    reply::{Fail, Res},
28    selector::{Selector, dedupe_targets},
29};
30
31const KINDS: &[&str] = &[
32    "launch",
33    "wait_for",
34    "tap",
35    "type",
36    "swipe",
37    "scroll_until",
38    "read_field",
39    "read_list",
40    "assert",
41    "button",
42    "key",
43    "sleep",
44];
45
46/// Keys a step may carry next to its kind.
47const MODIFIERS: &[&str] = &["when", "hint"];
48
49/// Split a step into (kind, body).
50fn split_step(step: &Value) -> Result<(&str, &Value), String> {
51    let map = step.as_object().ok_or("a step is a map like `tap: {...}`")?;
52    for key in ["when", "hint"] {
53        if map.get(key).is_some_and(|v| !v.is_string()) {
54            return Err(format!("`{key}` must be text"));
55        }
56    }
57    if let Some(expr) = map.get("when").and_then(|v| v.as_str()) {
58        // Only the form is checked here; the values come at run time.
59        if !expr.contains("==") && !expr.contains("!=") {
60            return Err("`when` must be `a == b` or `a != b`".into());
61        }
62    }
63    let mut kinds = map.iter().filter(|(k, _)| !MODIFIERS.contains(&k.as_str()));
64    let (kind, body) = kinds.next().ok_or("a step needs a kind")?;
65    if kinds.next().is_some() {
66        return Err("a step has exactly one kind (plus optional `when`, `hint`)".into());
67    }
68    if !KINDS.contains(&kind.as_str()) {
69        return Err(format!("unknown step kind `{kind}` ({})", KINDS.join(", ")));
70    }
71    Ok((kind.as_str(), body))
72}
73
74/// Whether a step's `when` holds: `a == b` or `a != b`, compared as text
75/// after the arguments and dates have been filled in.
76fn holds(expr: &str) -> Result<bool, String> {
77    let (left, right, equal) = match (expr.split_once("!="), expr.split_once("==")) {
78        (Some((l, r)), _) => (l, r, false),
79        (None, Some((l, r))) => (l, r, true),
80        (None, None) => return Err(format!("`when: {expr}` must be `a == b` or `a != b`")),
81    };
82    Ok((left.trim() == right.trim()) == equal)
83}
84
85/// Days since 1970-01-01 of a calendar date, and back (proleptic Gregorian).
86fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
87    let y = if m <= 2 { y - 1 } else { y };
88    let era = y.div_euclid(400);
89    let yoe = y.rem_euclid(400);
90    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
91    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
92    era * 146_097 + doe - 719_468
93}
94
95fn civil_from_days(z: i64) -> (i64, i64, i64) {
96    let z = z + 719_468;
97    let era = z.div_euclid(146_097);
98    let doe = z.rem_euclid(146_097);
99    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
100    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
101    let mp = (5 * doy + 2) / 153;
102    let d = doy - (153 * mp + 2) / 5 + 1;
103    let m = if mp < 10 { mp + 3 } else { mp - 9 };
104    (yoe + era * 400 + i64::from(m <= 2), m, d)
105}
106
107/// Today in the Mac's time zone as days since 1970-01-01. `IPH_TODAY`
108/// (YYYY-MM-DD) overrides it, to try a run as if it were another day.
109fn today_days() -> i64 {
110    if let Ok(text) = std::env::var("IPH_TODAY") {
111        let parts: Vec<i64> = text.split('-').filter_map(|p| p.parse().ok()).collect();
112        if let [y, m, d] = parts[..] {
113            return days_from_civil(y, m, d);
114        }
115    }
116    let now = std::time::SystemTime::now()
117        .duration_since(std::time::UNIX_EPOCH)
118        .map(|d| d.as_secs() as libc::time_t)
119        .unwrap_or(0);
120    // SAFETY: localtime_r / localtime_s fill the struct they are given and keep nothing.
121    let tm = unsafe {
122        let mut tm: libc::tm = std::mem::zeroed();
123        #[cfg(unix)]
124        libc::localtime_r(&now, &mut tm);
125        #[cfg(windows)]
126        libc::localtime_s(&mut tm, &now);
127        tm
128    };
129    days_from_civil(i64::from(tm.tm_year) + 1900, i64::from(tm.tm_mon) + 1, i64::from(tm.tm_mday))
130}
131
132/// Fill in `{{today.day}}`, `{{ago.6.month}}` and the like.
133fn fill_dates(text: &str, today: i64) -> String {
134    static DATE: std::sync::OnceLock<Regex> = std::sync::OnceLock::new();
135    let re = DATE.get_or_init(|| {
136        Regex::new(r"\{\{\s*(?:today|ago\.(\d{1,4}))\.(year|month|day)\s*\}\}").expect("date pattern")
137    });
138    re.replace_all(text, |c: &regex::Captures| {
139        let back: i64 = c.get(1).and_then(|m| m.as_str().parse().ok()).unwrap_or(0);
140        let (y, m, d) = civil_from_days(today - back);
141        match &c[2] {
142            "year" => y.to_string(),
143            "month" => m.to_string(),
144            _ => d.to_string(),
145        }
146    })
147    .into_owned()
148}
149
150/// Replace `{{name}}` and the date expressions in every string of `v`.
151fn substitute(v: &Value, args: &Map<String, Value>, today: i64) -> Value {
152    match v {
153        Value::String(s) => {
154            let mut out = s.clone();
155            for (k, val) in args {
156                let needle = format!("{{{{{k}}}}}");
157                if out.contains(&needle) {
158                    let rep = match val {
159                        Value::String(s) => s.clone(),
160                        other => other.to_string(),
161                    };
162                    out = out.replace(&needle, &rep);
163                }
164            }
165            if out.contains("{{") {
166                out = fill_dates(&out, today);
167            }
168            Value::String(out)
169        }
170        Value::Array(a) => Value::Array(a.iter().map(|x| substitute(x, args, today)).collect()),
171        Value::Object(m) => Value::Object(
172            m.iter()
173                .map(|(k, x)| (k.clone(), substitute(x, args, today)))
174                .collect(),
175        ),
176        other => other.clone(),
177    }
178}
179
180/// A step body that is either the selector itself or `{selector: …, …}`.
181fn selector_and_options(body: &Value) -> Result<(Selector, Map<String, Value>), Fail> {
182    let (sel_value, options) = match body.as_object() {
183        Some(map) if map.contains_key("selector") => {
184            let mut rest = map.clone();
185            let sel = rest.remove("selector").unwrap();
186            (sel, rest)
187        }
188        _ => (body.clone(), Map::new()),
189    };
190    let sel = Selector::from_value(&sel_value).map_err(|e| Fail::invalid(e.to_string()))?;
191    Ok((sel, options))
192}
193
194fn opt_u64(options: &Map<String, Value>, key: &str) -> Option<u64> {
195    options.get(key).and_then(|v| v.as_u64())
196}
197
198/// Text of an element for `take`. `value` falls back to the part of a
199/// "name, value" label after the name.
200fn take(el: &Element, what: &str) -> Option<String> {
201    match what {
202        "label" => el.label.clone(),
203        "identifier" => el.identifier.clone(),
204        "text" => el.value.clone().or_else(|| el.label.clone()),
205        _ => el.value.clone().or_else(|| {
206            el.label
207                .as_deref()
208                .and_then(|l| l.split_once(", "))
209                .map(|(_, rest)| rest.to_string())
210        }),
211    }
212}
213
214fn apply_regex(text: Option<String>, pattern: Option<&str>) -> Result<Option<String>, Fail> {
215    let (Some(text), Some(pattern)) = (text.clone(), pattern) else {
216        return Ok(text);
217    };
218    let re = Regex::new(pattern).map_err(|e| Fail::invalid(format!("bad regex: {e}")))?;
219    Ok(re.captures(&text).map(|c| {
220        c.get(1)
221            .or_else(|| c.get(0))
222            .map(|m| m.as_str().to_string())
223            .unwrap_or_default()
224    }))
225}
226
227/// One list row on one reading: what is reported for it, what identifies it,
228/// and where it sat.
229#[derive(Debug, Clone)]
230struct Row {
231    value: Value,
232    key: String,
233    y: f64,
234}
235
236/// Key of the entry that stands for a group heading among the rows while a
237/// list is being collected. It never reaches the result.
238const GROUP_MARK: &str = "\u{1}group";
239/// On a row: the heading that stood above it on the reading it was taken
240/// from. Removed before the result goes out.
241const GROUP_OF: &str = "\u{1}group_of";
242
243/// Give every row the text of the heading it stands under (as column `name`)
244/// and drop the headings. With `below`, rows under a heading whose number is
245/// smaller are dropped too.
246fn settle_groups(items: Vec<Value>, name: &str, below: Option<i64>) -> Vec<Value> {
247    let mut current: Option<String> = None;
248    let mut out = Vec::new();
249    for item in items {
250        if let Some(heading) = item.get(GROUP_MARK) {
251            current = heading.as_str().map(String::from);
252            continue;
253        }
254        let mut row = item;
255        // The heading the row was seen under wins over the last heading
256        // collected: rows can come in out of order (the app put new rows in
257        // above while the list was being read), and they would otherwise be
258        // filed under whatever heading happened to come last.
259        let seen_under = match &mut row {
260            Value::Object(map) => map.remove(GROUP_OF).and_then(|v| v.as_str().map(String::from)),
261            _ => None,
262        };
263        let heading = seen_under.or_else(|| current.clone());
264        let number = heading.as_deref().and_then(|c| c.trim().parse::<i64>().ok());
265        if let (Some(limit), Some(n)) = (below, number)
266            && n < limit
267        {
268            continue;
269        }
270        if let Value::Object(map) = &mut row {
271            map.insert(name.to_string(), heading.map(Value::String).unwrap_or(Value::Null));
272        }
273        out.push(row);
274    }
275    out
276}
277
278/// Whether a heading with a number below `limit` has been collected.
279fn passed_below(items: &[Value], limit: i64) -> bool {
280    items
281        .iter()
282        .filter_map(|i| i.get(GROUP_MARK).and_then(|g| g.as_str()))
283        .filter_map(|g| g.trim().parse::<i64>().ok())
284        .any(|n| n < limit)
285}
286
287/// How far the rows moved between two readings, if they moved as one block:
288/// the distance that at least two thirds of the rows appearing once in both
289/// readings agree on. None when nothing recognisable moved, or when the rows
290/// did not move together (a list stretching at its end, a reading taken
291/// mid-motion).
292fn scroll_distance(prev: &[Row], page: &[Row]) -> Option<f64> {
293    let once = |rows: &[Row], key: &str| rows.iter().filter(|r| r.key == key).count() == 1;
294    let deltas: Vec<f64> = page
295        .iter()
296        .filter(|r| once(page, &r.key) && once(prev, &r.key))
297        .filter_map(|r| prev.iter().find(|p| p.key == r.key).map(|p| p.y - r.y))
298        .filter(|d| d.abs() > 2.0)
299        .collect();
300    // The value with the most neighbours within 3 points.
301    let (agree, distance) = deltas
302        .iter()
303        .map(|d| (deltas.iter().filter(|o| (*o - d).abs() <= 3.0).count(), *d))
304        .max_by_key(|(n, _)| *n)?;
305    (agree * 3 >= deltas.len() * 2).then_some(distance)
306}
307
308/// Rows of `page` that were not on the previous reading.
309///
310/// When the rows moved as one block, position decides: a row was there
311/// already if the same row sat where this one would have been before the
312/// scroll, or sits exactly where it sat (a pinned element, not a list row).
313/// That keeps two identical rows apart and survives pinned headers and
314/// toolbars that match the row selector.
315///
316/// A row can also be moved by something other than the scroll: more rows
317/// loading in above it, a heading growing. It is then not where the scroll
318/// would have put it and looks new, though it was there before (2026-11-11:
319/// the first row after the part of a list that had loaded came back twice).
320/// So a previous row that should still be on screen and is not at its place
321/// takes one of the "new" rows with its text off the list.
322///
323/// When they did not move as one block, only rows whose text the previous
324/// reading did not have count as new (more of the same text than before
325/// counts for the surplus). That can miss an identical neighbour, but never
326/// reports a row twice.
327fn new_rows(prev: &[Row], page: &[Row]) -> Vec<Value> {
328    fresh_rows(prev, page).into_iter().map(|r| r.value.clone()).collect()
329}
330
331/// The rows `new_rows` hands back, as they are on `page`.
332fn fresh_rows<'a>(prev: &[Row], page: &'a [Row]) -> Vec<&'a Row> {
333    match scroll_distance(prev, page) {
334        Some(dy) => {
335            let at = |r: &Row, y: f64, slack: f64| (r.y - y).abs() <= slack;
336            let mut fresh: Vec<&Row> = page
337                .iter()
338                .filter(|r| {
339                    let pinned = prev.iter().any(|p| p.key == r.key && at(r, p.y, 2.0));
340                    let seen = prev.iter().any(|p| p.key == r.key && at(r, p.y - dy, 3.0));
341                    !pinned && !seen
342                })
343                .collect();
344            let lo = page.iter().map(|r| r.y).fold(f64::INFINITY, f64::min);
345            let hi = page.iter().map(|r| r.y).fold(f64::NEG_INFINITY, f64::max);
346            for p in prev {
347                let now = p.y - dy;
348                let still_on_screen = now >= lo - 3.0 && now <= hi + 3.0;
349                let found = page.iter().any(|r| r.key == p.key && (at(r, now, 3.0) || at(r, p.y, 2.0)));
350                if !still_on_screen || found {
351                    continue;
352                }
353                let nearest = fresh
354                    .iter()
355                    .enumerate()
356                    .filter(|(_, r)| r.key == p.key)
357                    .min_by(|a, b| (a.1.y - now).abs().total_cmp(&(b.1.y - now).abs()))
358                    .map(|(i, _)| i);
359                if let Some(i) = nearest {
360                    fresh.remove(i);
361                }
362            }
363            fresh
364        }
365        None => {
366            let mut out = Vec::new();
367            for (i, r) in page.iter().enumerate() {
368                let before = prev.iter().filter(|p| p.key == r.key).count();
369                let so_far = page[..=i].iter().filter(|p| p.key == r.key).count();
370                if so_far > before {
371                    out.push(r);
372                }
373            }
374            out
375        }
376    }
377}
378
379/// Whether the rows moved against the reading direction between two
380/// readings: the list went back, so nothing on the later reading lies beyond
381/// what was already read.
382fn moved_back(prev: &[Row], page: &[Row], direction: &str) -> bool {
383    match scroll_distance(prev, page) {
384        // Reading down, rows move up the screen: y gets smaller.
385        Some(dy) if direction == "down" => dy < -3.0,
386        Some(dy) => dy > 3.0,
387        None => false,
388    }
389}
390
391/// Rows of `page` that lie beyond the end of `at_end`, the last reading
392/// before the end check (scroll back, scroll forward, read).
393///
394/// Only those can be new: a list that has really ended shows nothing past
395/// `at_end`, and one whose scrolls had not arrived shows more of itself past
396/// it. Rows on the near side of `at_end`'s last row were read on the way down
397/// already. They do appear when the forward scroll falls short of the back
398/// scroll or the reading is older than the forward scroll (2026-11-11, B7:
399/// 4 of 19 readings of Settings > General ended with two middle rows a second
400/// time, because the end check took everything not on `at_end` for new).
401///
402/// `None` when the two readings cannot be lined up (the rows did not move as
403/// one block) and the page has rows `at_end` has not: then it cannot be told
404/// which side they lie on.
405fn past_end(at_end: &[Row], page: &[Row], direction: &str) -> Option<Vec<Value>> {
406    let fresh = fresh_rows(at_end, page);
407    if fresh.is_empty() {
408        return Some(Vec::new());
409    }
410    let dy = scroll_distance(at_end, page)?;
411    // Where `at_end`'s far edge sits on this reading.
412    let edge = if direction == "down" {
413        at_end.iter().map(|r| r.y).fold(f64::NEG_INFINITY, f64::max) - dy
414    } else {
415        at_end.iter().map(|r| r.y).fold(f64::INFINITY, f64::min) - dy
416    };
417    let beyond = |r: &Row| if direction == "down" { r.y > edge + 3.0 } else { r.y < edge - 3.0 };
418    Some(fresh.into_iter().filter(|r| beyond(r)).map(|r| r.value.clone()).collect())
419}
420
421/// How far to scroll a list between two readings.
422///
423/// A fixed step (a third of the screen) reads every row two or three times.
424/// The step that reads each row once depends on the phone and the app: how
425/// tall the list's window is, how much of it stays readable under pinned
426/// headers, how much shorter the list moves than the finger. So it is worked
427/// out from what the readings show.
428#[derive(Debug, Default)]
429struct Stride {
430    /// Highest place a list item has been seen at (smallest y). Items stay
431    /// in the accessibility tree up to here, also under a pinned header.
432    top: Option<f64>,
433    /// How much shorter the list moved than the finger, on the last scroll.
434    lost: f64,
435    /// The finger's travel on the last scroll, 0 when it was a fixed step.
436    last: f64,
437}
438
439impl Stride {
440    /// Share of the screen's height the finger may cross in one scroll.
441    const REACH: f64 = 0.72;
442    /// The item brought up stops this far below the top, so that it stays
443    /// readable when the list moves a little further than meant.
444    const MARGIN: f64 = 8.0;
445
446    /// Take in what a reading shows: where items can be, and how far the
447    /// last scroll really moved them.
448    fn learn(&mut self, before: &[Row], page: &[Row]) {
449        if let Some(y) = page.iter().map(|r| r.y).reduce(f64::min) {
450            self.top = Some(self.top.map_or(y, |t| t.min(y)));
451        }
452        if self.last > 0.0
453            && let Some(moved) = scroll_distance(before, page)
454        {
455            self.lost = (self.last - moved.abs()).clamp(0.0, 200.0);
456        }
457    }
458
459    /// The finger's travel for the next scroll, or `None` when the reading
460    /// gives nothing to go by (fewer than three items) and a fixed step has
461    /// to do.
462    fn next(&mut self, page: &[Row], screen_height: f64) -> Option<f64> {
463        let top = self.top?;
464        let mut ys: Vec<f64> = page.iter().map(|r| r.y).collect();
465        ys.sort_by(f64::total_cmp);
466        if ys.len() < 3 || screen_height <= 0.0 {
467            return None;
468        }
469        // The item before the last one goes to the top: two items in common.
470        let want = ys[ys.len() - 2] - (top + Self::MARGIN);
471        // Until a scroll has been measured, count on losing little: that
472        // errs towards moving too short, which only costs overlap.
473        let lost = if self.last > 0.0 { self.lost } else { 40.0 };
474        let travel = (want + lost).min(screen_height * Self::REACH);
475        if travel < 120.0 {
476            return None;
477        }
478        self.last = travel;
479        Some(travel)
480    }
481}
482
483/// Where each row of a reading sat, for the trace: "y:mark" pairs. The mark is
484/// a short hash of the row's text, so the log shows which rows repeat or
485/// jump without holding what they say.
486fn page_marks(page: &[Row]) -> String {
487    page.iter()
488        .map(|r| {
489            // FNV-1a, 32 bits.
490            let hash = r.key.bytes().fold(0x811c_9dc5u32, |h, b| (h ^ u32::from(b)).wrapping_mul(0x0100_0193));
491            format!("{:.0}:{:06x}", r.y, hash & 0x00ff_ffff)
492        })
493        .collect::<Vec<_>>()
494        .join(" ")
495}
496
497/// Wrap a step's failure in the run's report: which step, why, and
498/// what the screen showed.
499fn step_failure(
500    index: usize,
501    raw: &Value,
502    f: Fail,
503    kind: &str,
504    records: &[Value],
505    outputs: &Map<String, Value>,
506    ms: u64,
507) -> Fail {
508    let mut extra = f.extra.clone();
509    let summary = extra.remove("screen_summary");
510    let mut out = Fail::new(
511        f.outcome,
512        "step_failed",
513        format!("step {index} ({kind}) failed: {}", f.message),
514    );
515    out.hint = f.hint.clone();
516    out = out
517        .with("failed_step", json!({ "index": index, "kind": kind, "step": raw, "elapsed_ms": ms }))
518        .with("reason", json!({ "code": f.code, "message": f.message }))
519        .with("screen_summary", summary.unwrap_or(Value::Null))
520        .with("steps", json!(records))
521        .with("outputs", json!(outputs));
522    for (k, v) in extra {
523        out.extra.entry(k).or_insert(v);
524    }
525    out
526}
527
528/// Extra fields for a step's record and, for read steps, the value read.
529type StepOutput = (Map<String, Value>, Option<(String, Value)>);
530
531impl Session {
532    pub(crate) async fn wait_for(&mut self, sel: &Selector, timeout: Duration) -> Res<Element> {
533        let started = Instant::now();
534        let full = sel.needs_identifier();
535        let mut fresh = Fresh::MaxAge(reuse());
536        let last: Option<Screen>;
537        loop {
538            let (_, screen) = self.screen(fresh, full, BuildOptions::default()).await?;
539            if let Some(el) = dedupe_targets(sel.find(&screen)).first() {
540                return Ok((*el).clone());
541            }
542            if started.elapsed() >= timeout {
543                last = Some(screen);
544                break;
545            }
546            // Each further look asks the phone again (about 1.1 s).
547            fresh = Fresh::Force;
548        }
549        Err(Fail::not_sent(
550            "wait_timeout",
551            format!("{} did not appear within {} ms", sel.describe(), timeout.as_millis()),
552        )
553        .with("screen_summary", last.map(|s| s.summary(12)).unwrap_or(Value::Null)))
554    }
555
556    /// Wait until the element a step is about to tap holds still: two
557    /// readings in a row with it at the same place. A screen that has just
558    /// come up may still be loading and move its rows; a tap aimed at where
559    /// the row was then lands on its neighbour (2026-11-11: right after a
560    /// launch a tap on one row of a home screen opened the page of the row
561    /// above it).
562    pub(crate) async fn settle_target(&mut self, sel: &Selector) -> Res<()> {
563        let full = sel.needs_identifier();
564        let place = |screen: &Screen| -> Option<(i64, i64, i64, i64)> {
565            match dedupe_targets(sel.find(screen)).as_slice() {
566                [one] => one.frame.map(|f| {
567                    (f.x.round() as i64, f.y.round() as i64, f.w.round() as i64, f.h.round() as i64)
568                }),
569                _ => None,
570            }
571        };
572        let (_, screen) = self.screen(Fresh::MaxAge(reuse()), full, BuildOptions::default()).await?;
573        if self.held_still(sel, &screen).await {
574            return Ok(());
575        }
576        let mut last = place(&screen);
577        for _ in 0..4 {
578            let (_, again) = self.screen(Fresh::Force, full, BuildOptions::default()).await?;
579            let now = place(&again);
580            if now.is_some() && now == last {
581                return Ok(());
582            }
583            last = now;
584        }
585        // Still moving after four looks: the tap goes ahead on the last one,
586        // as it would have without this check.
587        Ok(())
588    }
589
590    /// Whether the one element `sel` finds on `screen` is still where that
591    /// reading put it, asked of the phone directly (tens of milliseconds where
592    /// a fresh reading takes over a second). A target on the move is asked
593    /// again until two answers agree. False sends `settle_target` to full
594    /// readings: no single match, no answer, or the element is gone.
595    async fn held_still(&mut self, sel: &Selector, screen: &Screen) -> bool {
596        let el = match dedupe_targets(sel.find(screen)).as_slice() {
597            [one] => (*one).clone(),
598            _ => return false,
599        };
600        let (Some(key), Some(frame)) = (el.key, el.frame) else { return false };
601        let round = |r: &Rect| (r.x.round() as i64, r.y.round() as i64, r.w.round() as i64, r.h.round() as i64);
602        let mut last = round(&frame);
603        for _ in 0..8 {
604            let Some(ax) = self.ax.as_mut() else { return false };
605            let now = ax
606                .ask(key, attrs::FRAME, Duration::from_secs(1))
607                .await
608                .and_then(|v| v.get("NS.rectval").and_then(|r| r.as_str()).and_then(Rect::parse));
609            let Some(now) = now.map(|r| round(&r)) else { return false };
610            if now.2 == 0 && now.3 == 0 {
611                return false;
612            }
613            if now == last {
614                return true;
615            }
616            last = now;
617            tokio::time::sleep(Duration::from_millis(150)).await;
618        }
619        false
620    }
621
622    /// `name` is what a batch files the value under; a script has no use for it.
623    pub(crate) async fn read_field(&mut self, body: &Value) -> Res<(String, Value)> {
624        let map = body.as_object().ok_or_else(|| Fail::invalid("read_field needs a map"))?;
625        let name = map.get("name").and_then(|v| v.as_str()).unwrap_or("value");
626        let sel_value = map.get("selector").ok_or_else(|| Fail::invalid("read_field needs `selector`"))?;
627        let sel = Selector::from_value(sel_value).map_err(|e| Fail::invalid(e.to_string()))?;
628        let what = map.get("take").and_then(|v| v.as_str()).unwrap_or("value");
629        let pattern = map.get("regex").and_then(|v| v.as_str());
630        let timeout = Duration::from_millis(opt_u64(map, "timeout_ms").unwrap_or(5000));
631        // The element may still be on its way in.
632        Box::pin(self.wait_for(&sel, timeout)).await?;
633        let (_, screen) = self
634            .screen(Fresh::MaxAge(reuse()), sel.needs_identifier() || what == "identifier", BuildOptions::default())
635            .await?;
636        let el = actions::resolve_one(&sel, &screen)?;
637        let mut text = apply_regex(take(el, what), pattern)?;
638        // What a run hands back must not come from a reading that was
639        // already out of date: look again until two readings give the same.
640        let needs_ids = sel.needs_identifier() || what == "identifier";
641        for _ in 0..2 {
642            let (_, again) = self.screen(Fresh::Force, needs_ids, BuildOptions::default()).await?;
643            let next = match dedupe_targets(sel.find(&again)).as_slice() {
644                [one] => apply_regex(take(one, what), pattern)?,
645                _ => None,
646            };
647            let same = next == text;
648            text = next;
649            if same {
650                break;
651            }
652        }
653        let el = actions::resolve_one(&sel, &screen)?;
654        match text {
655            Some(text) => Ok((name.to_string(), Value::String(text))),
656            None => Err(Fail::not_sent(
657                "no_value",
658                format!("{} has no {what} to read", sel.describe()),
659            )
660            .with("element", brief(el))),
661        }
662    }
663
664    /// `key`: the columns that say which row a row is. Without it the whole
665    /// row does, which takes a row whose text changes while the list is read
666    /// (a clock, a counter) for a new one.
667    fn rows_on_screen(
668        screen: &Screen,
669        row: &Selector,
670        columns: Option<&Map<String, Value>>,
671        key: &[String],
672    ) -> Res<Vec<Row>> {
673        let mut out = Vec::new();
674        for el in dedupe_targets(row.find(screen)) {
675            let y = el.frame.map(|f| f.y).unwrap_or(0.0);
676            // Two rows are the same row when label and value agree.
677            let identity = format!(
678                "{}\u{1}{}",
679                el.label.as_deref().unwrap_or(""),
680                el.value.as_deref().unwrap_or("")
681            );
682            let Some(cols) = columns else {
683                let mut v = json!({});
684                if let Some(l) = &el.label {
685                    v["label"] = json!(l);
686                }
687                if let Some(val) = &el.value {
688                    v["value"] = json!(val);
689                }
690                out.push(Row { value: v, key: identity, y });
691                continue;
692            };
693            let mut rec = Map::new();
694            for (col, spec) in cols {
695                let spec_map = spec.as_object();
696                // `{value: "…"}` is the same text on every row (a month, a tag).
697                if let Some(fixed) = spec_map.and_then(|m| m.get("value")) {
698                    rec.insert(col.clone(), fixed.clone());
699                    continue;
700                }
701                let what = spec_map
702                    .and_then(|m| m.get("take"))
703                    .and_then(|v| v.as_str())
704                    .or_else(|| spec.as_str())
705                    .unwrap_or("label");
706                let pattern = spec_map.and_then(|m| m.get("regex")).and_then(|v| v.as_str());
707                // A column either reads the row itself or an element inside it.
708                let source: Option<&Element> = match spec_map.and_then(|m| m.get("selector")) {
709                    Some(inner) => {
710                        let inner = Selector::from_value(inner).map_err(|e| Fail::invalid(e.to_string()))?;
711                        let scoped = Selector {
712                            within: Some(Box::new(Selector {
713                                id: Some(crate::selector::TextMatch::Exact(el.id.clone())),
714                                ..Default::default()
715                            })),
716                            ..inner
717                        };
718                        scoped.find(screen).first().copied()
719                    }
720                    None => Some(el),
721                };
722                let text = apply_regex(source.and_then(|e| take(e, what)), pattern)?;
723                rec.insert(col.clone(), text.map(Value::String).unwrap_or(Value::Null));
724            }
725            let key = if key.is_empty() {
726                format!("{identity}\u{1}{}", Value::Object(rec.clone()))
727            } else {
728                key.iter()
729                    .map(|k| rec.get(k).map(|v| v.to_string()).unwrap_or_default())
730                    .collect::<Vec<_>>()
731                    .join("\u{1}")
732            };
733            out.push(Row { value: Value::Object(rec), key, y });
734        }
735        Ok(out)
736    }
737
738    /// The rows on one reading, with the group headings among them when the
739    /// list has groups, top to bottom.
740    fn list_page(
741        screen: &Screen,
742        row: &Selector,
743        columns: Option<&Map<String, Value>>,
744        key: &[String],
745        group: Option<&(Selector, String, Option<String>, String)>,
746    ) -> Res<Vec<Row>> {
747        let mut page = Self::rows_on_screen(screen, row, columns, key)?;
748        if let Some((sel, what, pattern, _)) = group {
749            // Headings travel with the rows, so the same position logic that
750            // keeps rows apart puts each heading where it belongs.
751            for el in dedupe_targets(sel.find(screen)) {
752                let Some(text) = apply_regex(take(el, what), pattern.as_deref())? else {
753                    continue;
754                };
755                page.push(Row {
756                    key: format!("{GROUP_MARK}\u{1}{}", el.label.as_deref().unwrap_or("")),
757                    value: json!({ GROUP_MARK: text }),
758                    y: el.frame.map(|f| f.y).unwrap_or(0.0),
759                });
760            }
761            page.sort_by(|a, b| a.y.total_cmp(&b.y));
762            // Note on every row which heading stands above it on this reading.
763            let mut above: Option<Value> = None;
764            for item in page.iter_mut() {
765                if let Some(heading) = item.value.get(GROUP_MARK) {
766                    above = Some(heading.clone());
767                } else if let (Some(heading), Value::Object(map)) = (&above, &mut item.value) {
768                    map.insert(GROUP_OF.to_string(), heading.clone());
769                }
770            }
771        }
772        Ok(page)
773    }
774
775    /// Drag the list by `travel` points of finger movement, slowing to a
776    /// stop. "down" shows what is further down.
777    async fn stride_drag(&mut self, direction: &str, travel: f64) -> Res<bool> {
778        let (_, screen) = self.screen(Fresh::MaxAge(reuse()), false, BuildOptions::default()).await?;
779        let (w, h) = (screen.width, screen.height);
780        let (low, high) = (h * 0.88, h * 0.88 - travel);
781        let (from, to) = if direction == "down" { (low, high) } else { (high, low) };
782        // A longer way takes the finger longer, as a hand's would.
783        let duration = Duration::from_millis((350.0 + travel * 0.6) as u64);
784        let (changed, _) = Box::pin(self.drag_points(
785            (w / 2.0, from),
786            (w / 2.0, to),
787            duration,
788            crate::device::input::Motion::Place,
789        ))
790        .await?;
791        Ok(changed)
792    }
793
794    /// One scroll step of a list; whether the screen moved.
795    async fn list_scroll(&mut self, direction: &str) -> Res<bool> {
796        let r = Box::pin(self.cmd_scroll(ScrollArgs {
797            direction: direction.to_string(),
798            until: None,
799            max: None,
800        }))
801        .await?;
802        Ok(r.get("screen_changed").and_then(|v| v.as_bool()).unwrap_or(false))
803    }
804
805    pub(crate) async fn read_list(&mut self, body: &Value) -> Res<(String, Value, Value)> {
806        let map = body.as_object().ok_or_else(|| Fail::invalid("read_list needs a map"))?;
807        let name = map.get("name").and_then(|v| v.as_str()).unwrap_or("rows");
808        let row = Selector::from_value(map.get("row").ok_or_else(|| Fail::invalid("read_list needs `row`"))?)
809            .map_err(|e| Fail::invalid(e.to_string()))?;
810        let columns = map.get("columns").and_then(|v| v.as_object());
811        // `key: "city"` (or a list): the columns that identify a row.
812        let key: Vec<String> = match map.get("key") {
813            None | Some(Value::Null) => Vec::new(),
814            Some(Value::String(k)) => vec![k.clone()],
815            Some(Value::Array(ks)) => ks
816                .iter()
817                .map(|k| k.as_str().map(String::from).ok_or_else(|| Fail::invalid("key takes column names")))
818                .collect::<Res<_>>()?,
819            Some(_) => return Err(Fail::invalid("key takes a column name or a list of them")),
820        };
821        if let Some(missing) = key.iter().find(|k| !columns.is_some_and(|c| c.contains_key(k.as_str()))) {
822            return Err(Fail::invalid(format!("key names `{missing}`, which is not one of the columns")));
823        }
824        let until = match map.get("until") {
825            Some(v) => Some(Selector::from_value(v).map_err(|e| Fail::invalid(e.to_string()))?),
826            None => None,
827        };
828        let max_scrolls = opt_u64(map, "max_scrolls").unwrap_or(15).min(200) as u32;
829        let limit = opt_u64(map, "limit").unwrap_or(500) as usize;
830        let direction = map.get("direction").and_then(|v| v.as_str()).unwrap_or("down").to_string();
831        // `group: {selector, take, regex, as}`: headings between the rows (a
832        // date above each day's rows). Every row gets the heading it stands
833        // under as column `as`.
834        let group = match map.get("group") {
835            Some(Value::Object(g)) => {
836                let sel = Selector::from_value(g.get("selector").ok_or_else(|| Fail::invalid("group needs `selector`"))?)
837                    .map_err(|e| Fail::invalid(e.to_string()))?;
838                let what = g.get("take").and_then(|v| v.as_str()).unwrap_or("label").to_string();
839                let pattern = g.get("regex").and_then(|v| v.as_str()).map(String::from);
840                let name = g.get("as").and_then(|v| v.as_str()).unwrap_or("group").to_string();
841                Some((sel, what, pattern, name))
842            }
843            Some(_) => return Err(Fail::invalid("group must be a map: {selector, take, regex, as}")),
844            None => None,
845        };
846        // `stop_below: N`: stop once a heading whose number is below N has
847        // come up, and leave its rows out (a list that runs back in time,
848        // read down to a day of the month).
849        let stop_below = match map.get("stop_below") {
850            None | Some(Value::Null) => None,
851            Some(v) => Some(
852                v.as_i64()
853                    .or_else(|| v.as_str().and_then(|s| s.trim().parse().ok()))
854                    .ok_or_else(|| Fail::invalid("stop_below must be a whole number"))?,
855            ),
856        };
857        if stop_below.is_some() && group.is_none() {
858            return Err(Fail::invalid("stop_below needs `group`"));
859        }
860        let full = row.needs_identifier()
861            || until.as_ref().is_some_and(|u| u.needs_identifier())
862            || group.as_ref().is_some_and(|g| g.0.needs_identifier());
863
864        let mut all: Vec<Value> = Vec::new();
865        let mut prev: Option<Vec<Row>> = None;
866        let mut scrolls = 0u32;
867        // Readings in a row that brought no new row.
868        let mut barren = 0u32;
869        // Whether the end of the list has been checked by scrolling back and forth.
870        let mut end_checked = false;
871        let back = if direction == "down" { "up" } else { "down" };
872        let mut stride = Stride::default();
873        let ended;
874        loop {
875            // One reading a page: the scroll before it already asked the
876            // phone for the new screen, and this takes that reading over.
877            let (_, mut screen) = self.screen(Fresh::MaxAge(reuse()), full, BuildOptions::default()).await?;
878            let mut page = Self::list_page(&screen, &row, columns, &key, group.as_ref())?;
879            if let Some(before) = &prev {
880                let stitched = page.iter().any(|r| before.iter().any(|p| p.key == r.key));
881                if !stitched && !page.is_empty() && !before.is_empty() && stride.last > 0.0 {
882                    // The scroll carried the list past everything that was on
883                    // screen, so rows may lie unseen in between. Come back
884                    // half way and read again.
885                    crate::device::ax::trace(|| "read_list: no row in common after the scroll; coming back half way".into());
886                    self.stride_drag(back, stride.last / 2.0).await?;
887                    stride.lost += 40.0;
888                    (_, screen) = self.screen(Fresh::MaxAge(reuse()), full, BuildOptions::default()).await?;
889                    page = Self::list_page(&screen, &row, columns, &key, group.as_ref())?;
890                }
891                stride.learn(before, &page);
892            } else {
893                stride.learn(&[], &page);
894            }
895            match &prev {
896                None => all.extend(page.iter().map(|r| r.value.clone())),
897                Some(before) if moved_back(before, &page, &direction) => {
898                    // A reading from before the scroll arrived, or the list
899                    // bounced back: the rows on it were read already. Keep
900                    // the furthest reading to compare the next one with, or
901                    // rows read before would come back as new.
902                    crate::device::ax::trace(|| format!("read_list page: moved back [{}]", page_marks(&page)));
903                    barren += 1;
904                    if until.as_ref().is_some_and(|u| !u.find(&screen).is_empty()) {
905                        ended = "until";
906                        break;
907                    }
908                    if scrolls >= max_scrolls {
909                        ended = "max_scrolls";
910                        break;
911                    }
912                    self.list_scroll(&direction).await?;
913                    stride.last = 0.0;
914                    scrolls += 1;
915                    continue;
916                }
917                Some(before) => {
918                    let fresh_rows = new_rows(before, &page);
919                    crate::device::ax::trace(|| {
920                        format!(
921                            "read_list page: rows={} moved={:?} new={} [{}]",
922                            page.len(),
923                            scroll_distance(before, &page),
924                            fresh_rows.len(),
925                            page_marks(&page),
926                        )
927                    });
928                    barren = if fresh_rows.is_empty() { barren + 1 } else { 0 };
929                    all.extend(fresh_rows);
930                }
931            }
932            prev = Some(page);
933            if stop_below.is_some_and(|n| passed_below(&all, n)) {
934                ended = "stop_below";
935                break;
936            }
937            if all.iter().filter(|i| i.get(GROUP_MARK).is_none()).count() >= limit {
938                ended = "limit";
939                break;
940            }
941            if until.as_ref().is_some_and(|u| !u.find(&screen).is_empty()) {
942                ended = "until";
943                break;
944            }
945            if barren >= 2 {
946                // Two readings without a new row. That is the end of the list,
947                // or scrolls that never arrived: an input session the phone
948                // has stopped listening to looks exactly the same, and a list
949                // cut short there reads as complete (2026-11-11: two scrolls
950                // right after a Face ID prompt moved nothing, and a week of
951                // rows came back as two days). So the end is checked once by
952                // scrolling back and forward: at a real end the list moves
953                // back and returns to the same rows.
954                if end_checked {
955                    ended = "end_of_list";
956                    break;
957                }
958                end_checked = true;
959                let at_end = prev.clone().unwrap_or_default();
960                let mut moved = self.list_scroll(back).await?;
961                if !moved {
962                    // Nothing moves either way: once more on a new input session.
963                    self.close_input().await;
964                    moved = self.list_scroll(back).await?;
965                }
966                if !moved {
967                    // A list that fits the screen.
968                    ended = "end_of_list";
969                    break;
970                }
971                self.list_scroll(&direction).await?;
972                let mut fresh = Fresh::MaxAge(reuse());
973                let mut looks = 0;
974                let (page, fresh_rows) = loop {
975                    let (_, screen) = self.screen(fresh, full, BuildOptions::default()).await?;
976                    let page = Self::list_page(&screen, &row, columns, &key, group.as_ref())?;
977                    let past = past_end(&at_end, &page, &direction);
978                    crate::device::ax::trace(|| {
979                        format!(
980                            "read_list end check: moved={:?} new={:?} beyond={:?} [{}]",
981                            scroll_distance(&at_end, &page),
982                            new_rows(&at_end, &page).len(),
983                            past.as_ref().map(|p| p.len()),
984                            page_marks(&page),
985                        )
986                    });
987                    match past {
988                        Some(rows) => break (page, rows),
989                        // Rows the end did not have, but not lined up with
990                        // it: the reading may be mid-motion. Look again.
991                        None if looks < 2 => {
992                            looks += 1;
993                            fresh = Fresh::Force;
994                        }
995                        None => {
996                            return Err(Fail::unknown(
997                                "list_uncertain",
998                                "at the end of the list, the screen could not be lined up with what was read; rows may be missing or repeated",
999                            )
1000                            .hint(t(
1001                                "목록을 끝까지 읽었는지 확신할 수 없어 결과를 내지 않았습니다. 다시 실행하세요.",
1002                                "Not sure the whole list was read, so no result was given. Run it again.",
1003                            ))
1004                            .with("rows_so_far", all.len())
1005                            .with("scrolls", scrolls));
1006                        }
1007                    }
1008                };
1009                if fresh_rows.is_empty() {
1010                    ended = "end_of_list";
1011                    break;
1012                }
1013                all.extend(fresh_rows);
1014                barren = 0;
1015                prev = Some(page);
1016                if stop_below.is_some_and(|n| passed_below(&all, n)) {
1017                    ended = "stop_below";
1018                    break;
1019                }
1020            }
1021            if scrolls >= max_scrolls {
1022                ended = "max_scrolls";
1023                break;
1024            }
1025            // Scroll by as much as the screen allows: the last two items of
1026            // this reading go to the top of the next, so that the two
1027            // readings can be stitched and nothing in between is skipped.
1028            match stride.next(prev.as_deref().unwrap_or(&[]), screen.height) {
1029                Some(travel) => {
1030                    self.stride_drag(&direction, travel).await?;
1031                }
1032                None => {
1033                    self.list_scroll(&direction).await?;
1034                    stride.last = 0.0;
1035                }
1036            }
1037            scrolls += 1;
1038        }
1039        let mut rows = match &group {
1040            Some((_, _, _, column)) => settle_groups(all, column, stop_below),
1041            None => all,
1042        };
1043        rows.truncate(limit);
1044        Ok((
1045            name.to_string(),
1046            Value::Array(rows),
1047            json!({ "scrolls": scrolls, "ended": ended }),
1048        ))
1049    }
1050
1051    /// A failure when the latest reading shows another app in front than the
1052    /// one this run launched (a notification was tapped, a link opened …).
1053    pub(crate) fn unexpected_app(&self, expected_pid: Option<i64>) -> Option<Fail> {
1054        let expected = expected_pid?;
1055        let (_, dump, _) = self.ax.as_ref()?.latest()?;
1056        if dump.applications.iter().any(|a| a.pid == expected) {
1057            return None;
1058        }
1059        let screen = Screen::build(&dump, BuildOptions::default());
1060        Some(
1061            Fail::not_sent(
1062                "unexpected_app",
1063                format!(
1064                    "another app came to the front: {}",
1065                    screen
1066                        .apps
1067                        .iter()
1068                        .filter_map(|a| a.name.clone())
1069                        .collect::<Vec<_>>()
1070                        .join(", ")
1071                ),
1072            )
1073            .hint(t(
1074                "알림 배너를 눌렀거나 다른 앱이 열렸을 수 있습니다. 화면을 확인하세요. 집중 모드(방해금지)를 켜 두면 배너가 뜨지 않습니다.",
1075                "A notification banner may have been tapped or another app opened. Check the screen. A Focus (Do Not Disturb) keeps banners away.",
1076            ))
1077            .with("screen_summary", screen.summary(6)),
1078        )
1079    }
1080
1081    /// Run one step. Returns extra fields for the step's record and, for read
1082    /// steps, the value read.
1083    async fn run_step(&mut self, kind: &str, body: &Value) -> Res<StepOutput> {
1084        fn no_value(f: Map<String, Value>) -> Res<StepOutput> {
1085            Ok((f, None))
1086        }
1087        match kind {
1088            "launch" => {
1089                let args: LaunchArgs = match body {
1090                    Value::String(s) => LaunchArgs { app: s.clone(), restart: false },
1091                    other => actions::parse_args(other)?,
1092                };
1093                let app = args.app.clone();
1094                let r = Box::pin(self.cmd_launch(args)).await?;
1095                if r.get("foreground").and_then(|v| v.as_bool()) != Some(true) {
1096                    return Err(Fail::unknown(
1097                        "launch_not_verified",
1098                        format!("{app} was launched but is not in front"),
1099                    ));
1100                }
1101                no_value(fields! {
1102                    "bundle_id": r.get("bundle_id").cloned().unwrap_or(Value::Null),
1103                    "pid": r.get("pid").cloned().unwrap_or(Value::Null),
1104                })
1105            }
1106            "wait_for" => {
1107                let (sel, options) = selector_and_options(body)?;
1108                let timeout = Duration::from_millis(opt_u64(&options, "timeout_ms").unwrap_or(8000));
1109                let el = Box::pin(self.wait_for(&sel, timeout)).await?;
1110                no_value(fields! { "element": brief(&el) })
1111            }
1112            "assert" => {
1113                let (sel, _) = selector_and_options(body)?;
1114                // One patient look: the screen may be a moment behind.
1115                let el = Box::pin(self.wait_for(&sel, Duration::from_millis(1500))).await.map_err(|mut f| {
1116                    f.code = "assert_failed".into();
1117                    f.message = format!("expected {} on screen", sel.describe());
1118                    f
1119                })?;
1120                no_value(fields! { "element": brief(&el) })
1121            }
1122            "tap" if body.is_array() => {
1123                let r = Box::pin(self.tap_sequence(body.as_array().unwrap())).await?;
1124                no_value(fields! {
1125                    "screen_changed": r.get("screen_changed").cloned().unwrap_or(Value::Null),
1126                    "taps": r.get("taps").cloned().unwrap_or(Value::Null),
1127                })
1128            }
1129            "tap" => {
1130                let (sel, options) = selector_and_options(body)?;
1131                // Give the target a moment to appear, as a person would.
1132                let timeout = Duration::from_millis(opt_u64(&options, "timeout_ms").unwrap_or(5000));
1133                Box::pin(self.wait_for(&sel, timeout)).await?;
1134                if options.get("settle").and_then(|v| v.as_bool()).unwrap_or(true) {
1135                    Box::pin(self.settle_target(&sel)).await?;
1136                }
1137                let target = match body.as_object() {
1138                    Some(m) if m.contains_key("selector") => m["selector"].clone(),
1139                    _ => body.clone(),
1140                };
1141                let r = Box::pin(self.cmd_tap(TapArgs {
1142                    target,
1143                    long_ms: opt_u64(&options, "long_ms"),
1144                    double: options.get("double").and_then(|v| v.as_bool()).unwrap_or(false),
1145                    no_wait: options.get("no_wait").and_then(|v| v.as_bool()).unwrap_or(false),
1146                }))
1147                .await?;
1148                no_value(fields! {
1149                    "screen_changed": r.get("screen_changed").cloned().unwrap_or(Value::Null),
1150                    "element": r.get("element").cloned().unwrap_or(Value::Null),
1151                })
1152            }
1153            "type" => {
1154                let args: TypeArgs = match body {
1155                    Value::String(s) => TypeArgs { text: s.clone(), ..Default::default() },
1156                    other => actions::parse_args(other)?,
1157                };
1158                let r = Box::pin(self.cmd_type(args)).await?;
1159                no_value(fields! {
1160                    "value": r.get("value").cloned().unwrap_or(Value::Null),
1161                    "clipboard_restored": r.get("clipboard_restored").cloned().unwrap_or(Value::Null),
1162                })
1163            }
1164            "swipe" => {
1165                let args: SwipeArgs = match body {
1166                    Value::String(s) => SwipeArgs { direction: Some(s.clone()), ..Default::default() },
1167                    other => actions::parse_args(other)?,
1168                };
1169                let r = Box::pin(self.cmd_swipe(args)).await?;
1170                no_value(fields! { "screen_changed": r.get("screen_changed").cloned().unwrap_or(Value::Null) })
1171            }
1172            "scroll_until" => {
1173                let (_, options) = selector_and_options(body)?;
1174                let until = match body.as_object() {
1175                    Some(m) if m.contains_key("selector") => m["selector"].clone(),
1176                    _ => body.clone(),
1177                };
1178                let r = Box::pin(self.cmd_scroll(ScrollArgs {
1179                    direction: options
1180                        .get("direction")
1181                        .and_then(|v| v.as_str())
1182                        .unwrap_or("down")
1183                        .to_string(),
1184                    until: Some(until),
1185                    max: opt_u64(&options, "max").map(|n| n as u32),
1186                }))
1187                .await?;
1188                no_value(fields! {
1189                    "scrolls": r.get("scrolls").cloned().unwrap_or(Value::Null),
1190                    "element": r.get("element").cloned().unwrap_or(Value::Null),
1191                })
1192            }
1193            "read_field" => {
1194                let (name, value) = Box::pin(self.read_field(body)).await?;
1195                Ok((fields! { "name": name.clone(), "value": value.clone() }, Some((name, value))))
1196            }
1197            "read_list" => {
1198                let (name, rows, info) = Box::pin(self.read_list(body)).await?;
1199                let count = rows.as_array().map(|a| a.len()).unwrap_or(0);
1200                Ok((
1201                    fields! { "name": name.clone(), "count": count, "scrolls": info["scrolls"], "ended": info["ended"] },
1202                    Some((name, rows)),
1203                ))
1204            }
1205            "button" => {
1206                let button = body.as_str().ok_or_else(|| Fail::invalid("button needs a name"))?;
1207                let r = Box::pin(self.cmd_button(ButtonArgs { button: button.to_string() })).await?;
1208                no_value(fields! { "screen_changed": r.get("screen_changed").cloned().unwrap_or(Value::Null) })
1209            }
1210            "key" => {
1211                let key = body.as_str().ok_or_else(|| Fail::invalid("key needs a name"))?;
1212                let r = Box::pin(self.cmd_key(KeyArgs { key: key.to_string() })).await?;
1213                no_value(fields! { "screen_changed": r.get("screen_changed").cloned().unwrap_or(Value::Null) })
1214            }
1215            "sleep" => {
1216                let ms = body.as_u64().ok_or_else(|| Fail::invalid("sleep needs milliseconds"))?;
1217                tokio::time::sleep(Duration::from_millis(ms.min(60_000))).await;
1218                no_value(Map::new())
1219            }
1220            other => Err(Fail::invalid(format!("unknown step kind `{other}`"))),
1221        }
1222    }
1223
1224    /// Run steps in order and stop at the first failure.
1225    pub async fn run_steps(&mut self, steps: &[Value], args: &Map<String, Value>) -> Res {
1226        let mut records: Vec<Value> = Vec::new();
1227        let mut outputs = Map::new();
1228        // The app the last `launch` step brought to the front. Every later
1229        // step must still find it there.
1230        let mut expected_pid: Option<i64> = None;
1231        // Steps that sent something to the phone and completed.
1232        let mut inputs_sent = 0u32;
1233        let today = today_days();
1234        for (i, raw) in steps.iter().enumerate() {
1235            let index = i + 1;
1236            let started = Instant::now();
1237            let step = substitute(raw, args, today);
1238            let (kind, body) = match split_step(&step) {
1239                Ok(x) => x,
1240                Err(e) => return Err(step_failure(index, raw, Fail::invalid(e), "?", &records, &outputs, 0)),
1241            };
1242            if let Some(expr) = step.get("when").and_then(|v| v.as_str()) {
1243                match holds(expr) {
1244                    Ok(true) => {}
1245                    Ok(false) => {
1246                        records.push(json!({ "index": index, "kind": kind, "ok": true, "skipped": true, "when": expr }));
1247                        continue;
1248                    }
1249                    Err(e) => return Err(step_failure(index, raw, Fail::invalid(e), kind, &records, &outputs, 0)),
1250                }
1251            }
1252            // A `wait_for` may sit out something the system puts over the app
1253            // for a moment (a Face ID prompt); every other step needs the app
1254            // in front.
1255            if kind != "wait_for"
1256                && let Some(f) = self.unexpected_app(expected_pid)
1257            {
1258                return Err(step_failure(index, raw, f, kind, &records, &outputs, 0));
1259            }
1260            let hint = step.get("hint").and_then(|v| v.as_str()).map(String::from);
1261            // Boxed: the step futures are large and would otherwise pile up on
1262            // the stack of whoever polls the run.
1263            let result = Box::pin(self.run_step(kind, body)).await;
1264            let ms = started.elapsed().as_millis() as u64;
1265            match result {
1266                Ok((extra, value)) => {
1267                    if kind == "launch" {
1268                        expected_pid = extra.get("pid").and_then(|v| v.as_i64());
1269                    }
1270                    if matches!(
1271                        kind,
1272                        "launch" | "tap" | "type" | "swipe" | "scroll_until" | "read_list" | "button" | "key"
1273                    ) {
1274                        inputs_sent += 1;
1275                    }
1276                    let mut rec = fields! { "index": index, "kind": kind, "ok": true, "elapsed_ms": ms };
1277                    for (k, v) in extra {
1278                        if !v.is_null() {
1279                            rec.insert(k, v);
1280                        }
1281                    }
1282                    records.push(Value::Object(rec));
1283                    if let Some((name, value)) = value {
1284                        outputs.insert(name, value);
1285                    }
1286                }
1287                Err(mut f) => {
1288                    // Whoever wrote the steps knows what this one usually waits on.
1289                    if let Some(hint) = hint {
1290                        f.hint = Some(hint);
1291                    }
1292                    return Err(step_failure(index, raw, f, kind, &records, &outputs, ms)
1293                        .with("inputs_sent", inputs_sent));
1294                }
1295            }
1296        }
1297        if let Some(f) = self.unexpected_app(expected_pid) {
1298            return Err(step_failure(steps.len(), &Value::Null, f, "end", &records, &outputs, 0));
1299        }
1300        Ok(fields! { "steps": records, "outputs": outputs })
1301    }
1302}
1303
1304#[cfg(test)]
1305mod tests {
1306    use super::*;
1307
1308    #[test]
1309    fn rejects_bad_steps() {
1310        assert!(split_step(&json!({"fly": "away"})).unwrap_err().contains("unknown step kind"));
1311        assert!(split_step(&json!({"tap": "a", "type": "b"})).unwrap_err().contains("exactly one kind"));
1312        assert!(split_step(&json!({"tap": "a", "hint": "look"})).is_ok());
1313        assert!(split_step(&json!({"tap": "a", "confirm": true})).is_err());
1314    }
1315
1316    #[test]
1317    fn substitutes_arguments() {
1318        let step = json!({"type": {"text": "{{a}}×{{b}}"}});
1319        let mut args = Map::new();
1320        args.insert("a".into(), json!("12"));
1321        args.insert("b".into(), json!(34));
1322        assert_eq!(substitute(&step, &args, 0)["type"]["text"], "12×34");
1323    }
1324
1325    #[test]
1326    fn dates_fill_in_and_cross_months_and_years() {
1327        // 2026-11-03: six days earlier is 28 October.
1328        let day = days_from_civil(2026, 11, 3);
1329        assert_eq!(civil_from_days(day), (2026, 11, 3));
1330        assert_eq!(fill_dates("{{today.month}}/{{today.day}}", day), "11/3");
1331        assert_eq!(fill_dates("{{ago.6.month}}/{{ago.6.day}}", day), "10/28");
1332        assert_eq!(fill_dates("{{ ago.0.year }}", day), "2026");
1333        // 2027-01-02: six days earlier is in the year before.
1334        let day = days_from_civil(2027, 1, 2);
1335        assert_eq!(fill_dates("{{ago.6.year}}-{{ago.6.month}}-{{ago.6.day}}", day), "2026-12-27");
1336        // A leap day.
1337        assert_eq!(civil_from_days(days_from_civil(2028, 3, 1) - 1), (2028, 2, 29));
1338        // Anything else in braces is left for the arguments.
1339        assert_eq!(fill_dates("{{name}} {{today.week}}", day), "{{name}} {{today.week}}");
1340        let step = json!({"read_list": {"stop_below": "{{ago.6.day}}"}, "when": "{{ago.6.month}} != {{today.month}}"});
1341        let filled = substitute(&step, &Map::new(), days_from_civil(2026, 11, 3));
1342        assert_eq!(filled["read_list"]["stop_below"], "28");
1343        assert_eq!(filled["when"], "10 != 11");
1344    }
1345
1346    #[test]
1347    fn when_compares_text() {
1348        assert!(holds("11 == 11").unwrap());
1349        assert!(!holds("10 == 11").unwrap());
1350        assert!(holds("10 != 11").unwrap());
1351        assert!(!holds(" 11 !=11 ").unwrap());
1352        assert!(holds("soon").is_err());
1353        assert!(split_step(&json!({"tap": "a", "when": "maybe"})).unwrap_err().contains("when"));
1354        assert!(split_step(&json!({"tap": "a", "when": "{{ago.6.month}} != {{today.month}}"})).is_ok());
1355    }
1356
1357    /// A reading of Settings > General: rows `from` onwards, the first at
1358    /// `top`, one every 52 points down to the bottom of the screen.
1359    fn general(from: &str, top: f64) -> Vec<Row> {
1360        const ROWS: [&str; 24] = [
1361            "설정", "정보", "소프트웨어 업데이트", "iPhone 저장 공간", "AppleCare 및 보증", "AirDrop",
1362            "AirPlay 및 연속성", "화면 속 화면", "화면 캡처", "CarPlay", "게임 컨트롤러", "날짜 및 시간",
1363            "백그라운드 앱 새로 고침", "사전", "서체", "언어 및 지역", "자동 완성 및 암호", "키보드",
1364            "트랙패드", "TV 제공업체", "VPN 및 기기 관리", "법률 및 규제 정보", "전송 또는 iPhone 재설정",
1365            "시스템 종료",
1366        ];
1367        let start = ROWS.iter().position(|r| *r == from).unwrap();
1368        ROWS[start..]
1369            .iter()
1370            .enumerate()
1371            .map(|(i, label)| (label, top + 52.0 * i as f64))
1372            .take_while(|(_, y)| *y < 880.0)
1373            .map(|(label, y)| Row { value: json!({ "label": label }), key: label.to_string(), y })
1374            .collect()
1375    }
1376
1377    #[test]
1378    fn the_end_check_does_not_take_rows_read_on_the_way_down() {
1379        // B7 (2026-11-11), 4 of 19: at the end of the list, the scroll back
1380        // and the scroll forward did not cancel out, and the reading after
1381        // them stood 104 points short of the end. Two rows above the end's
1382        // first row came back as new.
1383        let at_end = general("서체", 120.0);
1384        let short = general("백그라운드 앱 새로 고침", 120.0);
1385        assert_eq!(scroll_distance(&at_end, &short), Some(-104.0));
1386        assert_eq!(labels(&new_rows(&at_end, &short)), ["백그라운드 앱 새로 고침", "사전"]);
1387        assert!(moved_back(&at_end, &short, "down"));
1388        assert_eq!(past_end(&at_end, &short, "down"), Some(vec![]));
1389        // Back at the same place: nothing new either.
1390        assert_eq!(past_end(&at_end, &at_end, "down"), Some(vec![]));
1391    }
1392
1393    #[test]
1394    fn the_end_check_takes_rows_past_the_end() {
1395        // The scrolls before the check had not arrived: the list moves on
1396        // and shows rows past the last reading, which are new.
1397        let stuck = general("AirDrop", 120.0);
1398        let further = general("날짜 및 시간", 120.0);
1399        assert_eq!(stuck.last().unwrap().key, "TV 제공업체");
1400        let past = past_end(&stuck, &further, "down").unwrap();
1401        assert_eq!(
1402            labels(&past),
1403            ["VPN 및 기기 관리", "법률 및 규제 정보", "전송 또는 iPhone 재설정", "시스템 종료"]
1404        );
1405        assert!(!moved_back(&stuck, &further, "down"));
1406    }
1407
1408    #[test]
1409    fn the_end_check_gives_up_on_a_reading_it_cannot_line_up() {
1410        // Rows in common but each at a different offset (a reading taken
1411        // mid-motion), and two rows the end did not have.
1412        let at_end = general("서체", 120.0);
1413        let mut smeared = general("백그라운드 앱 새로 고침", 120.0);
1414        for (i, r) in smeared.iter_mut().enumerate() {
1415            r.y += 17.0 * i as f64;
1416        }
1417        assert_eq!(scroll_distance(&at_end, &smeared), None);
1418        assert_eq!(past_end(&at_end, &smeared, "down"), None);
1419    }
1420
1421    #[test]
1422    fn reading_up_the_list_mirrors_reading_down() {
1423        // Reading upward, the list's end is its top.
1424        let at_top = general("설정", 120.0);
1425        let short = general("화면 속 화면", 120.0);
1426        assert!(moved_back(&at_top, &short, "up"));
1427        assert_eq!(past_end(&at_top, &short, "up"), Some(vec![]));
1428    }
1429
1430    fn mark(text: &str) -> Value {
1431        json!({ GROUP_MARK: text })
1432    }
1433
1434    #[test]
1435    fn rows_take_the_heading_they_stand_under() {
1436        let items = vec![
1437            json!({"label": "before any heading"}),
1438            mark("11"),
1439            json!({"label": "a"}),
1440            json!({"label": "b"}),
1441            mark("9"),
1442            json!({"label": "c"}),
1443            mark("4"),
1444            json!({"label": "d"}),
1445        ];
1446        let rows = settle_groups(items.clone(), "day", None);
1447        let days: Vec<Value> = rows.iter().map(|r| r["day"].clone()).collect();
1448        assert_eq!(days, [Value::Null, json!("11"), json!("11"), json!("9"), json!("4")]);
1449        // Reading down to day 5: the rows of day 4 are left out.
1450        assert!(!passed_below(&items[..6], 5));
1451        assert!(passed_below(&items, 5));
1452        let rows = settle_groups(items, "day", Some(5));
1453        assert_eq!(labels(&rows), ["before any heading", "a", "b", "c"]);
1454    }
1455
1456    #[test]
1457    fn a_row_keeps_the_heading_it_was_seen_under() {
1458        // Day 11's rows were collected, then the heading of day 10 and its
1459        // row. Then the app put three new rows in at the top of day 11; they
1460        // arrive last, but were seen under "11".
1461        let late = |label: &str| json!({ "label": label, GROUP_OF: "11" });
1462        let items = vec![
1463            mark("11"),
1464            json!({"label": "a"}),
1465            mark("10"),
1466            json!({"label": "b"}),
1467            late("new 1"),
1468            late("new 2"),
1469        ];
1470        let rows = settle_groups(items, "day", None);
1471        let got: Vec<(&str, &str)> = rows.iter().map(|r| (r["day"].as_str().unwrap(), r["label"].as_str().unwrap())).collect();
1472        assert_eq!(got, [("11", "a"), ("10", "b"), ("11", "new 1"), ("11", "new 2")]);
1473        assert!(rows.iter().all(|r| r.get(GROUP_OF).is_none()));
1474    }
1475
1476    #[test]
1477    fn headings_move_with_the_rows_from_one_reading_to_the_next() {
1478        let heading = |text: &str, y: f64| Row { value: mark(text), key: format!("{GROUP_MARK}\u{1}{text}"), y };
1479        let row = |label: &str, y: f64| Row { value: json!({ "label": label }), key: label.to_string(), y };
1480        // Two days with the same transfer on each; the list moved up by 130.
1481        let before = vec![heading("11", 100.0), row("이체 100,000원", 140.0), row("커피", 205.0), heading("10", 270.0)];
1482        let after = vec![row("커피", 75.0), heading("10", 140.0), row("이체 100,000원", 180.0), heading("9", 245.0)];
1483        let mut all: Vec<Value> = before.iter().map(|r| r.value.clone()).collect();
1484        all.extend(new_rows(&before, &after));
1485        let rows = settle_groups(all, "day", None);
1486        let got: Vec<(String, String)> = rows
1487            .iter()
1488            .map(|r| (r["day"].as_str().unwrap().to_string(), r["label"].as_str().unwrap().to_string()))
1489            .collect();
1490        assert_eq!(
1491            got,
1492            [
1493                ("11".to_string(), "이체 100,000원".to_string()),
1494                ("11".to_string(), "커피".to_string()),
1495                ("10".to_string(), "이체 100,000원".to_string()),
1496            ]
1497        );
1498    }
1499
1500    fn rows(items: &[(&str, f64)]) -> Vec<Row> {
1501        items
1502            .iter()
1503            .map(|(label, y)| Row { value: json!({ "label": label }), key: label.to_string(), y: *y })
1504            .collect()
1505    }
1506
1507    fn labels(v: &[Value]) -> Vec<&str> {
1508        v.iter().map(|x| x["label"].as_str().unwrap()).collect()
1509    }
1510
1511    #[test]
1512    fn only_rows_that_were_not_on_the_previous_reading_are_new() {
1513        // The list moved up by 160 points.
1514        let before = rows(&[("a", 100.0), ("b", 180.0), ("c", 260.0), ("d", 340.0)]);
1515        let after = rows(&[("c", 100.0), ("d", 180.0), ("e", 260.0), ("f", 340.0)]);
1516        assert_eq!(scroll_distance(&before, &after), Some(160.0));
1517        assert_eq!(labels(&new_rows(&before, &after)), ["e", "f"]);
1518    }
1519
1520    #[test]
1521    fn pinned_elements_that_match_the_row_selector_are_counted_once() {
1522        // "합계" stays at the top and "받아쓰기" at the bottom on every reading.
1523        let before = rows(&[("합계", 60.0), ("a", 100.0), ("b", 180.0), ("받아쓰기", 860.0)]);
1524        let after = rows(&[("합계", 60.0), ("b", 100.0), ("c", 180.0), ("받아쓰기", 860.0)]);
1525        assert_eq!(labels(&new_rows(&before, &after)), ["c"]);
1526    }
1527
1528    #[test]
1529    fn identical_rows_are_kept_apart_by_position() {
1530        // Three purchases that read the same; the list moved up by 80.
1531        let before = rows(&[("커피 4,500원", 100.0), ("커피 4,500원", 180.0), ("빵 3,000원", 260.0)]);
1532        let after = rows(&[
1533            ("커피 4,500원", 100.0),
1534            ("빵 3,000원", 180.0),
1535            ("커피 4,500원", 260.0),
1536            ("우유 2,000원", 340.0),
1537        ]);
1538        // The first two are the old second and third rows; the coffee at 260
1539        // and the milk are new.
1540        assert_eq!(labels(&new_rows(&before, &after)), ["커피 4,500원", "우유 2,000원"]);
1541    }
1542
1543    #[test]
1544    fn the_stride_brings_the_last_two_items_to_the_top() {
1545        let mut stride = Stride::default();
1546        // First reading: the list starts half way down the screen.
1547        let first = rows(&[("a", 500.0), ("b", 565.0), ("c", 630.0), ("d", 695.0), ("e", 760.0), ("f", 825.0)]);
1548        stride.learn(&[], &first);
1549        // "e" (the one before the last) should go to the top (500 + margin);
1550        // nothing measured yet, so 40 is added for what the list lags.
1551        let travel = stride.next(&first, 932.0).unwrap();
1552        assert_eq!(travel, 760.0 - 508.0 + 40.0);
1553        // The list moved 232 for a travel of 292: it lags by 60.
1554        let second = rows(&[("e", 528.0), ("f", 593.0), ("g", 658.0), ("h", 723.0), ("i", 788.0), ("j", 853.0)]);
1555        stride.learn(&first, &second);
1556        assert_eq!(stride.lost, 60.0);
1557        assert_eq!(stride.top, Some(500.0));
1558        // Next: "i" to the top, with the lag that was measured.
1559        assert_eq!(stride.next(&second, 932.0).unwrap(), 788.0 - 508.0 + 60.0);
1560        // Never further than the finger can go on this screen.
1561        let far = rows(&[("x", 100.0), ("y", 800.0), ("z", 900.0)]);
1562        stride.top = Some(100.0);
1563        assert_eq!(stride.next(&far, 932.0).unwrap(), 932.0 * Stride::REACH);
1564        // Too little on screen to go by: a fixed step instead.
1565        assert_eq!(stride.next(&rows(&[("a", 500.0), ("b", 565.0)]), 932.0), None);
1566    }
1567
1568    #[test]
1569    fn a_row_pushed_down_by_rows_loading_above_it_is_not_new() {
1570        // The list moved up by 270. Meanwhile more of it loaded, which pushed
1571        // the last row 40 further down than the scroll alone would have.
1572        let before = rows(&[("a", 400.0), ("b", 465.0), ("c", 530.0), ("d", 595.0), ("last loaded", 660.0)]);
1573        let after = rows(&[
1574            ("a", 130.0),
1575            ("b", 195.0),
1576            ("c", 260.0),
1577            ("d", 325.0),
1578            ("last loaded", 430.0),
1579            ("next", 495.0),
1580        ]);
1581        assert_eq!(scroll_distance(&before, &after), Some(270.0));
1582        assert_eq!(labels(&new_rows(&before, &after)), ["next"]);
1583        // Two rows that read the same, one of them pushed: the other is new.
1584        let before = rows(&[("a", 400.0), ("b", 465.0), ("c", 530.0), ("커피", 595.0)]);
1585        let after = rows(&[("a", 130.0), ("b", 195.0), ("c", 260.0), ("커피", 365.0), ("커피", 430.0)]);
1586        assert_eq!(new_rows(&before, &after).len(), 1);
1587    }
1588
1589    #[test]
1590    fn rows_that_did_not_move_together_are_matched_by_text() {
1591        // The end of a list stretching under the finger: every row shifted by
1592        // a different amount. Nothing is new.
1593        let before = rows(&[("a", 94.0), ("b", 143.0), ("c", 193.0), ("d", 242.0), ("e", 326.0)]);
1594        let after = rows(&[("a", 114.0), ("b", 173.0), ("c", 238.0), ("d", 302.0), ("e", 406.0)]);
1595        assert_eq!(scroll_distance(&before, &after), None);
1596        assert!(new_rows(&before, &after).is_empty());
1597        // The same, with one row that was not there before.
1598        let after = rows(&[("b", 173.0), ("c", 238.0), ("d", 302.0), ("e", 406.0), ("f", 470.0)]);
1599        assert_eq!(labels(&new_rows(&before, &after)), ["f"]);
1600    }
1601
1602    #[test]
1603    fn a_reading_with_nothing_in_common_is_all_new() {
1604        let before = rows(&[("a", 100.0), ("b", 180.0)]);
1605        let after = rows(&[("x", 100.0), ("y", 180.0)]);
1606        assert_eq!(scroll_distance(&before, &after), None);
1607        assert_eq!(labels(&new_rows(&before, &after)), ["x", "y"]);
1608    }
1609
1610    #[test]
1611    fn a_key_column_keeps_a_row_whose_text_changed_from_counting_twice() {
1612        // A world clock: the minute turns between two readings of the list.
1613        let screen = |minute: u32, top: f64, cities: &[&str]| -> Screen {
1614            let elements: Vec<Value> = cities
1615                .iter()
1616                .enumerate()
1617                .map(|(i, city)| {
1618                    json!({
1619                        "id": format!("row{i}{minute}"), "role": "text", "traits": ["static_text"],
1620                        "label": format!("{city}, 오후 2:{minute:02}, 오늘, +0시간"),
1621                        "frame": { "x": 0, "y": top + 90.0 * i as f64, "w": 430, "h": 90 },
1622                    })
1623                })
1624                .collect();
1625            serde_json::from_value(json!({ "width": 430.0, "height": 932.0, "apps": [], "elements": elements })).unwrap()
1626        };
1627        let row = Selector::from_value(&json!({ "role": "text" })).unwrap();
1628        let columns = json!({
1629            "city": { "take": "label", "regex": "^([^,]+)" },
1630            "time": { "take": "label", "regex": "(오후 [0-9:]+)" },
1631        });
1632        let columns = columns.as_object();
1633        let before = screen(3, 200.0, &["서울", "도쿄", "런던", "파리"]);
1634        let after = screen(4, 20.0, &["런던", "파리", "뉴욕"]);
1635        let cities = |key: &[String]| -> Vec<String> {
1636            let prev = Session::rows_on_screen(&before, &row, columns, key).unwrap();
1637            let page = Session::rows_on_screen(&after, &row, columns, key).unwrap();
1638            new_rows(&prev, &page).iter().map(|r| r["city"].as_str().unwrap().to_string()).collect()
1639        };
1640        // By the whole row, the two that were there already look new.
1641        assert_eq!(cities(&[]), ["런던", "파리", "뉴욕"]);
1642        assert_eq!(cities(&["city".to_string()]), ["뉴욕"]);
1643    }
1644
1645    #[test]
1646    fn take_value_falls_back_to_the_label_remainder() {
1647        let mut el = Element {
1648            id: "a".into(),
1649            role: "button".into(),
1650            label: Some("iOS 버전, 27.0.1".into()),
1651            value: None,
1652            identifier: None,
1653            hint: None,
1654            frame: None,
1655            traits: vec![],
1656            enabled: true,
1657            selected: false,
1658            focused: false,
1659            parent: None,
1660            depth: 1,
1661            pid: 1,
1662            on_screen: true,
1663            raw: None,
1664            key: None,
1665        };
1666        assert_eq!(take(&el, "value").as_deref(), Some("27.0.1"));
1667        assert_eq!(take(&el, "label").as_deref(), Some("iOS 버전, 27.0.1"));
1668        el.value = Some("실제 값".into());
1669        assert_eq!(take(&el, "value").as_deref(), Some("실제 값"));
1670        assert_eq!(
1671            apply_regex(Some("합계 12,300원".into()), Some(r"([\d,]+)원")).unwrap().as_deref(),
1672            Some("12,300")
1673        );
1674    }
1675}