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    /// Reconnection discards the old accessibility subscription. Re-read before
1052    /// using a remembered launch guard, so it cannot silently become a no-op.
1053    pub(crate) async fn check_expected_app(&mut self, expected_pid: Option<i64>) -> Res<()> {
1054        self.refresh_connection();
1055        if expected_pid.is_some() && self.ax.as_ref().is_none_or(|ax| ax.is_closed()) {
1056            Box::pin(self.cmd_read(Default::default())).await?;
1057        }
1058        match self.unexpected_app(expected_pid) {
1059            Some(f) => Err(f),
1060            None => Ok(()),
1061        }
1062    }
1063
1064    /// A failure when the latest reading shows another app in front than the
1065    /// one this run launched (a notification was tapped, a link opened …).
1066    pub(crate) fn unexpected_app(&self, expected_pid: Option<i64>) -> Option<Fail> {
1067        let expected = expected_pid?;
1068        let (_, dump, _) = self.ax.as_ref()?.latest()?;
1069        if dump.applications.iter().any(|a| a.pid == expected) {
1070            return None;
1071        }
1072        let screen = Screen::build(&dump, BuildOptions::default());
1073        Some(
1074            Fail::not_sent(
1075                "unexpected_app",
1076                format!(
1077                    "another app came to the front: {}",
1078                    screen
1079                        .apps
1080                        .iter()
1081                        .filter_map(|a| a.name.clone())
1082                        .collect::<Vec<_>>()
1083                        .join(", ")
1084                ),
1085            )
1086            .hint(t(
1087                "알림 배너를 눌렀거나 다른 앱이 열렸을 수 있습니다. 화면을 확인하세요. 집중 모드(방해금지)를 켜 두면 배너가 뜨지 않습니다.",
1088                "A notification banner may have been tapped or another app opened. Check the screen. A Focus (Do Not Disturb) keeps banners away.",
1089            ))
1090            .with("screen_summary", screen.summary(6)),
1091        )
1092    }
1093
1094    /// Run one step. Returns extra fields for the step's record and, for read
1095    /// steps, the value read.
1096    async fn run_step(&mut self, kind: &str, body: &Value) -> Res<StepOutput> {
1097        fn no_value(f: Map<String, Value>) -> Res<StepOutput> {
1098            Ok((f, None))
1099        }
1100        match kind {
1101            "launch" => {
1102                let args: LaunchArgs = match body {
1103                    Value::String(s) => LaunchArgs { app: s.clone(), restart: false },
1104                    other => actions::parse_args(other)?,
1105                };
1106                let app = args.app.clone();
1107                let r = Box::pin(self.cmd_launch(args)).await?;
1108                if r.get("foreground").and_then(|v| v.as_bool()) != Some(true) {
1109                    return Err(Fail::unknown(
1110                        "launch_not_verified",
1111                        format!("{app} was launched but is not in front"),
1112                    ));
1113                }
1114                no_value(fields! {
1115                    "bundle_id": r.get("bundle_id").cloned().unwrap_or(Value::Null),
1116                    "pid": r.get("pid").cloned().unwrap_or(Value::Null),
1117                })
1118            }
1119            "wait_for" => {
1120                let (sel, options) = selector_and_options(body)?;
1121                let timeout = Duration::from_millis(opt_u64(&options, "timeout_ms").unwrap_or(8000));
1122                let el = Box::pin(self.wait_for(&sel, timeout)).await?;
1123                no_value(fields! { "element": brief(&el) })
1124            }
1125            "assert" => {
1126                let (sel, _) = selector_and_options(body)?;
1127                // One patient look: the screen may be a moment behind.
1128                let el = Box::pin(self.wait_for(&sel, Duration::from_millis(1500))).await.map_err(|mut f| {
1129                    f.code = "assert_failed".into();
1130                    f.message = format!("expected {} on screen", sel.describe());
1131                    f
1132                })?;
1133                no_value(fields! { "element": brief(&el) })
1134            }
1135            "tap" if body.is_array() => {
1136                let r = Box::pin(self.tap_sequence(body.as_array().unwrap())).await?;
1137                no_value(fields! {
1138                    "screen_changed": r.get("screen_changed").cloned().unwrap_or(Value::Null),
1139                    "taps": r.get("taps").cloned().unwrap_or(Value::Null),
1140                })
1141            }
1142            "tap" => {
1143                let (sel, options) = selector_and_options(body)?;
1144                // Give the target a moment to appear, as a person would.
1145                let timeout = Duration::from_millis(opt_u64(&options, "timeout_ms").unwrap_or(5000));
1146                Box::pin(self.wait_for(&sel, timeout)).await?;
1147                if options.get("settle").and_then(|v| v.as_bool()).unwrap_or(true) {
1148                    Box::pin(self.settle_target(&sel)).await?;
1149                }
1150                let target = match body.as_object() {
1151                    Some(m) if m.contains_key("selector") => m["selector"].clone(),
1152                    _ => body.clone(),
1153                };
1154                let r = Box::pin(self.cmd_tap(TapArgs {
1155                    target,
1156                    long_ms: opt_u64(&options, "long_ms"),
1157                    double: options.get("double").and_then(|v| v.as_bool()).unwrap_or(false),
1158                    no_wait: options.get("no_wait").and_then(|v| v.as_bool()).unwrap_or(false),
1159                }))
1160                .await?;
1161                no_value(fields! {
1162                    "screen_changed": r.get("screen_changed").cloned().unwrap_or(Value::Null),
1163                    "element": r.get("element").cloned().unwrap_or(Value::Null),
1164                })
1165            }
1166            "type" => {
1167                let args: TypeArgs = match body {
1168                    Value::String(s) => TypeArgs { text: s.clone(), ..Default::default() },
1169                    other => actions::parse_args(other)?,
1170                };
1171                let r = Box::pin(self.cmd_type(args)).await?;
1172                no_value(r)
1173            }
1174            "swipe" => {
1175                let args: SwipeArgs = match body {
1176                    Value::String(s) => SwipeArgs { direction: Some(s.clone()), ..Default::default() },
1177                    other => actions::parse_args(other)?,
1178                };
1179                let r = Box::pin(self.cmd_swipe(args)).await?;
1180                no_value(fields! { "screen_changed": r.get("screen_changed").cloned().unwrap_or(Value::Null) })
1181            }
1182            "scroll_until" => {
1183                let (_, options) = selector_and_options(body)?;
1184                let until = match body.as_object() {
1185                    Some(m) if m.contains_key("selector") => m["selector"].clone(),
1186                    _ => body.clone(),
1187                };
1188                let r = Box::pin(self.cmd_scroll(ScrollArgs {
1189                    direction: options
1190                        .get("direction")
1191                        .and_then(|v| v.as_str())
1192                        .unwrap_or("down")
1193                        .to_string(),
1194                    until: Some(until),
1195                    max: opt_u64(&options, "max").map(|n| n as u32),
1196                }))
1197                .await?;
1198                no_value(fields! {
1199                    "scrolls": r.get("scrolls").cloned().unwrap_or(Value::Null),
1200                    "element": r.get("element").cloned().unwrap_or(Value::Null),
1201                })
1202            }
1203            "read_field" => {
1204                let (name, value) = Box::pin(self.read_field(body)).await?;
1205                Ok((fields! { "name": name.clone(), "value": value.clone() }, Some((name, value))))
1206            }
1207            "read_list" => {
1208                let (name, rows, info) = Box::pin(self.read_list(body)).await?;
1209                let count = rows.as_array().map(|a| a.len()).unwrap_or(0);
1210                Ok((
1211                    fields! { "name": name.clone(), "count": count, "scrolls": info["scrolls"], "ended": info["ended"] },
1212                    Some((name, rows)),
1213                ))
1214            }
1215            "button" => {
1216                let button = body.as_str().ok_or_else(|| Fail::invalid("button needs a name"))?;
1217                let r = Box::pin(self.cmd_button(ButtonArgs { button: button.to_string() })).await?;
1218                no_value(fields! { "screen_changed": r.get("screen_changed").cloned().unwrap_or(Value::Null) })
1219            }
1220            "key" => {
1221                let key = body.as_str().ok_or_else(|| Fail::invalid("key needs a name"))?;
1222                let r = Box::pin(self.cmd_key(KeyArgs { key: key.to_string() })).await?;
1223                no_value(fields! { "screen_changed": r.get("screen_changed").cloned().unwrap_or(Value::Null) })
1224            }
1225            "sleep" => {
1226                let ms = body.as_u64().ok_or_else(|| Fail::invalid("sleep needs milliseconds"))?;
1227                tokio::time::sleep(Duration::from_millis(ms.min(60_000))).await;
1228                no_value(Map::new())
1229            }
1230            other => Err(Fail::invalid(format!("unknown step kind `{other}`"))),
1231        }
1232    }
1233
1234    /// Run steps in order and stop at the first failure.
1235    pub async fn run_steps(&mut self, steps: &[Value], args: &Map<String, Value>) -> Res {
1236        let mut records: Vec<Value> = Vec::new();
1237        let mut outputs = Map::new();
1238        // The app the last `launch` step brought to the front. Every later
1239        // step must still find it there.
1240        let mut expected_pid: Option<i64> = None;
1241        // Steps that sent input, or may have, including the failing step.
1242        let mut inputs_sent = 0u32;
1243        let today = today_days();
1244        for (i, raw) in steps.iter().enumerate() {
1245            let index = i + 1;
1246            let started = Instant::now();
1247            let step = substitute(raw, args, today);
1248            let (kind, body) = match split_step(&step) {
1249                Ok(x) => x,
1250                Err(e) => return Err(step_failure(index, raw, Fail::invalid(e), "?", &records, &outputs, 0)),
1251            };
1252            if let Some(expr) = step.get("when").and_then(|v| v.as_str()) {
1253                match holds(expr) {
1254                    Ok(true) => {}
1255                    Ok(false) => {
1256                        records.push(json!({ "index": index, "kind": kind, "ok": true, "skipped": true, "when": expr }));
1257                        continue;
1258                    }
1259                    Err(e) => return Err(step_failure(index, raw, Fail::invalid(e), kind, &records, &outputs, 0)),
1260                }
1261            }
1262            // A `wait_for` may sit out something the system puts over the app
1263            // for a moment (a Face ID prompt); every other step needs the app
1264            // in front.
1265            if kind != "wait_for"
1266                && let Err(f) = Box::pin(self.check_expected_app(expected_pid)).await
1267            {
1268                return Err(step_failure(index, raw, f, kind, &records, &outputs, 0));
1269            }
1270            let hint = step.get("hint").and_then(|v| v.as_str()).map(String::from);
1271            // Boxed: the step futures are large and would otherwise pile up on
1272            // the stack of whoever polls the run.
1273            let result = Box::pin(self.run_step(kind, body)).await;
1274            let ms = started.elapsed().as_millis() as u64;
1275            match result {
1276                Ok((extra, value)) => {
1277                    if kind == "launch" {
1278                        expected_pid = extra.get("pid").and_then(|v| v.as_i64());
1279                    }
1280                    if matches!(
1281                        kind,
1282                        "launch" | "tap" | "type" | "swipe" | "scroll_until" | "read_list" | "button" | "key"
1283                    ) {
1284                        inputs_sent += 1;
1285                    }
1286                    let mut rec = fields! { "index": index, "kind": kind, "ok": true, "elapsed_ms": ms };
1287                    for (k, v) in extra {
1288                        if !v.is_null() || kind == "type" {
1289                            rec.insert(k, v);
1290                        }
1291                    }
1292                    records.push(Value::Object(rec));
1293                    if let Some((name, value)) = value {
1294                        outputs.insert(name, value);
1295                    }
1296                }
1297                Err(mut f) => {
1298                    if f.outcome != crate::reply::Outcome::NotSent {
1299                        inputs_sent += 1;
1300                    }
1301                    // Whoever wrote the steps knows what this one usually waits on.
1302                    if let Some(hint) = hint {
1303                        f.hint = Some(hint);
1304                    }
1305                    return Err(step_failure(index, raw, f, kind, &records, &outputs, ms)
1306                        .with("inputs_sent", inputs_sent));
1307                }
1308            }
1309        }
1310        if let Some(f) = self.unexpected_app(expected_pid) {
1311            return Err(step_failure(steps.len(), &Value::Null, f, "end", &records, &outputs, 0));
1312        }
1313        Ok(fields! { "steps": records, "outputs": outputs })
1314    }
1315}
1316
1317#[cfg(test)]
1318mod tests {
1319    use super::*;
1320
1321    #[test]
1322    fn rejects_bad_steps() {
1323        assert!(split_step(&json!({"fly": "away"})).unwrap_err().contains("unknown step kind"));
1324        assert!(split_step(&json!({"tap": "a", "type": "b"})).unwrap_err().contains("exactly one kind"));
1325        assert!(split_step(&json!({"tap": "a", "hint": "look"})).is_ok());
1326        assert!(split_step(&json!({"tap": "a", "confirm": true})).is_err());
1327    }
1328
1329    #[test]
1330    fn substitutes_arguments() {
1331        let step = json!({"type": {"text": "{{a}}×{{b}}"}});
1332        let mut args = Map::new();
1333        args.insert("a".into(), json!("12"));
1334        args.insert("b".into(), json!(34));
1335        assert_eq!(substitute(&step, &args, 0)["type"]["text"], "12×34");
1336    }
1337
1338    #[test]
1339    fn dates_fill_in_and_cross_months_and_years() {
1340        // 2026-11-03: six days earlier is 28 October.
1341        let day = days_from_civil(2026, 11, 3);
1342        assert_eq!(civil_from_days(day), (2026, 11, 3));
1343        assert_eq!(fill_dates("{{today.month}}/{{today.day}}", day), "11/3");
1344        assert_eq!(fill_dates("{{ago.6.month}}/{{ago.6.day}}", day), "10/28");
1345        assert_eq!(fill_dates("{{ ago.0.year }}", day), "2026");
1346        // 2027-01-02: six days earlier is in the year before.
1347        let day = days_from_civil(2027, 1, 2);
1348        assert_eq!(fill_dates("{{ago.6.year}}-{{ago.6.month}}-{{ago.6.day}}", day), "2026-12-27");
1349        // A leap day.
1350        assert_eq!(civil_from_days(days_from_civil(2028, 3, 1) - 1), (2028, 2, 29));
1351        // Anything else in braces is left for the arguments.
1352        assert_eq!(fill_dates("{{name}} {{today.week}}", day), "{{name}} {{today.week}}");
1353        let step = json!({"read_list": {"stop_below": "{{ago.6.day}}"}, "when": "{{ago.6.month}} != {{today.month}}"});
1354        let filled = substitute(&step, &Map::new(), days_from_civil(2026, 11, 3));
1355        assert_eq!(filled["read_list"]["stop_below"], "28");
1356        assert_eq!(filled["when"], "10 != 11");
1357    }
1358
1359    #[test]
1360    fn when_compares_text() {
1361        assert!(holds("11 == 11").unwrap());
1362        assert!(!holds("10 == 11").unwrap());
1363        assert!(holds("10 != 11").unwrap());
1364        assert!(!holds(" 11 !=11 ").unwrap());
1365        assert!(holds("soon").is_err());
1366        assert!(split_step(&json!({"tap": "a", "when": "maybe"})).unwrap_err().contains("when"));
1367        assert!(split_step(&json!({"tap": "a", "when": "{{ago.6.month}} != {{today.month}}"})).is_ok());
1368    }
1369
1370    /// A reading of Settings > General: rows `from` onwards, the first at
1371    /// `top`, one every 52 points down to the bottom of the screen.
1372    fn general(from: &str, top: f64) -> Vec<Row> {
1373        const ROWS: [&str; 24] = [
1374            "설정", "정보", "소프트웨어 업데이트", "iPhone 저장 공간", "AppleCare 및 보증", "AirDrop",
1375            "AirPlay 및 연속성", "화면 속 화면", "화면 캡처", "CarPlay", "게임 컨트롤러", "날짜 및 시간",
1376            "백그라운드 앱 새로 고침", "사전", "서체", "언어 및 지역", "자동 완성 및 암호", "키보드",
1377            "트랙패드", "TV 제공업체", "VPN 및 기기 관리", "법률 및 규제 정보", "전송 또는 iPhone 재설정",
1378            "시스템 종료",
1379        ];
1380        let start = ROWS.iter().position(|r| *r == from).unwrap();
1381        ROWS[start..]
1382            .iter()
1383            .enumerate()
1384            .map(|(i, label)| (label, top + 52.0 * i as f64))
1385            .take_while(|(_, y)| *y < 880.0)
1386            .map(|(label, y)| Row { value: json!({ "label": label }), key: label.to_string(), y })
1387            .collect()
1388    }
1389
1390    #[test]
1391    fn the_end_check_does_not_take_rows_read_on_the_way_down() {
1392        // B7 (2026-11-11), 4 of 19: at the end of the list, the scroll back
1393        // and the scroll forward did not cancel out, and the reading after
1394        // them stood 104 points short of the end. Two rows above the end's
1395        // first row came back as new.
1396        let at_end = general("서체", 120.0);
1397        let short = general("백그라운드 앱 새로 고침", 120.0);
1398        assert_eq!(scroll_distance(&at_end, &short), Some(-104.0));
1399        assert_eq!(labels(&new_rows(&at_end, &short)), ["백그라운드 앱 새로 고침", "사전"]);
1400        assert!(moved_back(&at_end, &short, "down"));
1401        assert_eq!(past_end(&at_end, &short, "down"), Some(vec![]));
1402        // Back at the same place: nothing new either.
1403        assert_eq!(past_end(&at_end, &at_end, "down"), Some(vec![]));
1404    }
1405
1406    #[test]
1407    fn the_end_check_takes_rows_past_the_end() {
1408        // The scrolls before the check had not arrived: the list moves on
1409        // and shows rows past the last reading, which are new.
1410        let stuck = general("AirDrop", 120.0);
1411        let further = general("날짜 및 시간", 120.0);
1412        assert_eq!(stuck.last().unwrap().key, "TV 제공업체");
1413        let past = past_end(&stuck, &further, "down").unwrap();
1414        assert_eq!(
1415            labels(&past),
1416            ["VPN 및 기기 관리", "법률 및 규제 정보", "전송 또는 iPhone 재설정", "시스템 종료"]
1417        );
1418        assert!(!moved_back(&stuck, &further, "down"));
1419    }
1420
1421    #[test]
1422    fn the_end_check_gives_up_on_a_reading_it_cannot_line_up() {
1423        // Rows in common but each at a different offset (a reading taken
1424        // mid-motion), and two rows the end did not have.
1425        let at_end = general("서체", 120.0);
1426        let mut smeared = general("백그라운드 앱 새로 고침", 120.0);
1427        for (i, r) in smeared.iter_mut().enumerate() {
1428            r.y += 17.0 * i as f64;
1429        }
1430        assert_eq!(scroll_distance(&at_end, &smeared), None);
1431        assert_eq!(past_end(&at_end, &smeared, "down"), None);
1432    }
1433
1434    #[test]
1435    fn reading_up_the_list_mirrors_reading_down() {
1436        // Reading upward, the list's end is its top.
1437        let at_top = general("설정", 120.0);
1438        let short = general("화면 속 화면", 120.0);
1439        assert!(moved_back(&at_top, &short, "up"));
1440        assert_eq!(past_end(&at_top, &short, "up"), Some(vec![]));
1441    }
1442
1443    fn mark(text: &str) -> Value {
1444        json!({ GROUP_MARK: text })
1445    }
1446
1447    #[test]
1448    fn rows_take_the_heading_they_stand_under() {
1449        let items = vec![
1450            json!({"label": "before any heading"}),
1451            mark("11"),
1452            json!({"label": "a"}),
1453            json!({"label": "b"}),
1454            mark("9"),
1455            json!({"label": "c"}),
1456            mark("4"),
1457            json!({"label": "d"}),
1458        ];
1459        let rows = settle_groups(items.clone(), "day", None);
1460        let days: Vec<Value> = rows.iter().map(|r| r["day"].clone()).collect();
1461        assert_eq!(days, [Value::Null, json!("11"), json!("11"), json!("9"), json!("4")]);
1462        // Reading down to day 5: the rows of day 4 are left out.
1463        assert!(!passed_below(&items[..6], 5));
1464        assert!(passed_below(&items, 5));
1465        let rows = settle_groups(items, "day", Some(5));
1466        assert_eq!(labels(&rows), ["before any heading", "a", "b", "c"]);
1467    }
1468
1469    #[test]
1470    fn a_row_keeps_the_heading_it_was_seen_under() {
1471        // Day 11's rows were collected, then the heading of day 10 and its
1472        // row. Then the app put three new rows in at the top of day 11; they
1473        // arrive last, but were seen under "11".
1474        let late = |label: &str| json!({ "label": label, GROUP_OF: "11" });
1475        let items = vec![
1476            mark("11"),
1477            json!({"label": "a"}),
1478            mark("10"),
1479            json!({"label": "b"}),
1480            late("new 1"),
1481            late("new 2"),
1482        ];
1483        let rows = settle_groups(items, "day", None);
1484        let got: Vec<(&str, &str)> = rows.iter().map(|r| (r["day"].as_str().unwrap(), r["label"].as_str().unwrap())).collect();
1485        assert_eq!(got, [("11", "a"), ("10", "b"), ("11", "new 1"), ("11", "new 2")]);
1486        assert!(rows.iter().all(|r| r.get(GROUP_OF).is_none()));
1487    }
1488
1489    #[test]
1490    fn headings_move_with_the_rows_from_one_reading_to_the_next() {
1491        let heading = |text: &str, y: f64| Row { value: mark(text), key: format!("{GROUP_MARK}\u{1}{text}"), y };
1492        let row = |label: &str, y: f64| Row { value: json!({ "label": label }), key: label.to_string(), y };
1493        // Two days with the same transfer on each; the list moved up by 130.
1494        let before = vec![heading("11", 100.0), row("이체 100,000원", 140.0), row("커피", 205.0), heading("10", 270.0)];
1495        let after = vec![row("커피", 75.0), heading("10", 140.0), row("이체 100,000원", 180.0), heading("9", 245.0)];
1496        let mut all: Vec<Value> = before.iter().map(|r| r.value.clone()).collect();
1497        all.extend(new_rows(&before, &after));
1498        let rows = settle_groups(all, "day", None);
1499        let got: Vec<(String, String)> = rows
1500            .iter()
1501            .map(|r| (r["day"].as_str().unwrap().to_string(), r["label"].as_str().unwrap().to_string()))
1502            .collect();
1503        assert_eq!(
1504            got,
1505            [
1506                ("11".to_string(), "이체 100,000원".to_string()),
1507                ("11".to_string(), "커피".to_string()),
1508                ("10".to_string(), "이체 100,000원".to_string()),
1509            ]
1510        );
1511    }
1512
1513    fn rows(items: &[(&str, f64)]) -> Vec<Row> {
1514        items
1515            .iter()
1516            .map(|(label, y)| Row { value: json!({ "label": label }), key: label.to_string(), y: *y })
1517            .collect()
1518    }
1519
1520    fn labels(v: &[Value]) -> Vec<&str> {
1521        v.iter().map(|x| x["label"].as_str().unwrap()).collect()
1522    }
1523
1524    #[test]
1525    fn only_rows_that_were_not_on_the_previous_reading_are_new() {
1526        // The list moved up by 160 points.
1527        let before = rows(&[("a", 100.0), ("b", 180.0), ("c", 260.0), ("d", 340.0)]);
1528        let after = rows(&[("c", 100.0), ("d", 180.0), ("e", 260.0), ("f", 340.0)]);
1529        assert_eq!(scroll_distance(&before, &after), Some(160.0));
1530        assert_eq!(labels(&new_rows(&before, &after)), ["e", "f"]);
1531    }
1532
1533    #[test]
1534    fn pinned_elements_that_match_the_row_selector_are_counted_once() {
1535        // "합계" stays at the top and "받아쓰기" at the bottom on every reading.
1536        let before = rows(&[("합계", 60.0), ("a", 100.0), ("b", 180.0), ("받아쓰기", 860.0)]);
1537        let after = rows(&[("합계", 60.0), ("b", 100.0), ("c", 180.0), ("받아쓰기", 860.0)]);
1538        assert_eq!(labels(&new_rows(&before, &after)), ["c"]);
1539    }
1540
1541    #[test]
1542    fn identical_rows_are_kept_apart_by_position() {
1543        // Three purchases that read the same; the list moved up by 80.
1544        let before = rows(&[("커피 4,500원", 100.0), ("커피 4,500원", 180.0), ("빵 3,000원", 260.0)]);
1545        let after = rows(&[
1546            ("커피 4,500원", 100.0),
1547            ("빵 3,000원", 180.0),
1548            ("커피 4,500원", 260.0),
1549            ("우유 2,000원", 340.0),
1550        ]);
1551        // The first two are the old second and third rows; the coffee at 260
1552        // and the milk are new.
1553        assert_eq!(labels(&new_rows(&before, &after)), ["커피 4,500원", "우유 2,000원"]);
1554    }
1555
1556    #[test]
1557    fn the_stride_brings_the_last_two_items_to_the_top() {
1558        let mut stride = Stride::default();
1559        // First reading: the list starts half way down the screen.
1560        let first = rows(&[("a", 500.0), ("b", 565.0), ("c", 630.0), ("d", 695.0), ("e", 760.0), ("f", 825.0)]);
1561        stride.learn(&[], &first);
1562        // "e" (the one before the last) should go to the top (500 + margin);
1563        // nothing measured yet, so 40 is added for what the list lags.
1564        let travel = stride.next(&first, 932.0).unwrap();
1565        assert_eq!(travel, 760.0 - 508.0 + 40.0);
1566        // The list moved 232 for a travel of 292: it lags by 60.
1567        let second = rows(&[("e", 528.0), ("f", 593.0), ("g", 658.0), ("h", 723.0), ("i", 788.0), ("j", 853.0)]);
1568        stride.learn(&first, &second);
1569        assert_eq!(stride.lost, 60.0);
1570        assert_eq!(stride.top, Some(500.0));
1571        // Next: "i" to the top, with the lag that was measured.
1572        assert_eq!(stride.next(&second, 932.0).unwrap(), 788.0 - 508.0 + 60.0);
1573        // Never further than the finger can go on this screen.
1574        let far = rows(&[("x", 100.0), ("y", 800.0), ("z", 900.0)]);
1575        stride.top = Some(100.0);
1576        assert_eq!(stride.next(&far, 932.0).unwrap(), 932.0 * Stride::REACH);
1577        // Too little on screen to go by: a fixed step instead.
1578        assert_eq!(stride.next(&rows(&[("a", 500.0), ("b", 565.0)]), 932.0), None);
1579    }
1580
1581    #[test]
1582    fn a_row_pushed_down_by_rows_loading_above_it_is_not_new() {
1583        // The list moved up by 270. Meanwhile more of it loaded, which pushed
1584        // the last row 40 further down than the scroll alone would have.
1585        let before = rows(&[("a", 400.0), ("b", 465.0), ("c", 530.0), ("d", 595.0), ("last loaded", 660.0)]);
1586        let after = rows(&[
1587            ("a", 130.0),
1588            ("b", 195.0),
1589            ("c", 260.0),
1590            ("d", 325.0),
1591            ("last loaded", 430.0),
1592            ("next", 495.0),
1593        ]);
1594        assert_eq!(scroll_distance(&before, &after), Some(270.0));
1595        assert_eq!(labels(&new_rows(&before, &after)), ["next"]);
1596        // Two rows that read the same, one of them pushed: the other is new.
1597        let before = rows(&[("a", 400.0), ("b", 465.0), ("c", 530.0), ("커피", 595.0)]);
1598        let after = rows(&[("a", 130.0), ("b", 195.0), ("c", 260.0), ("커피", 365.0), ("커피", 430.0)]);
1599        assert_eq!(new_rows(&before, &after).len(), 1);
1600    }
1601
1602    #[test]
1603    fn rows_that_did_not_move_together_are_matched_by_text() {
1604        // The end of a list stretching under the finger: every row shifted by
1605        // a different amount. Nothing is new.
1606        let before = rows(&[("a", 94.0), ("b", 143.0), ("c", 193.0), ("d", 242.0), ("e", 326.0)]);
1607        let after = rows(&[("a", 114.0), ("b", 173.0), ("c", 238.0), ("d", 302.0), ("e", 406.0)]);
1608        assert_eq!(scroll_distance(&before, &after), None);
1609        assert!(new_rows(&before, &after).is_empty());
1610        // The same, with one row that was not there before.
1611        let after = rows(&[("b", 173.0), ("c", 238.0), ("d", 302.0), ("e", 406.0), ("f", 470.0)]);
1612        assert_eq!(labels(&new_rows(&before, &after)), ["f"]);
1613    }
1614
1615    #[test]
1616    fn a_reading_with_nothing_in_common_is_all_new() {
1617        let before = rows(&[("a", 100.0), ("b", 180.0)]);
1618        let after = rows(&[("x", 100.0), ("y", 180.0)]);
1619        assert_eq!(scroll_distance(&before, &after), None);
1620        assert_eq!(labels(&new_rows(&before, &after)), ["x", "y"]);
1621    }
1622
1623    #[test]
1624    fn a_key_column_keeps_a_row_whose_text_changed_from_counting_twice() {
1625        // A world clock: the minute turns between two readings of the list.
1626        let screen = |minute: u32, top: f64, cities: &[&str]| -> Screen {
1627            let elements: Vec<Value> = cities
1628                .iter()
1629                .enumerate()
1630                .map(|(i, city)| {
1631                    json!({
1632                        "id": format!("row{i}{minute}"), "role": "text", "traits": ["static_text"],
1633                        "label": format!("{city}, 오후 2:{minute:02}, 오늘, +0시간"),
1634                        "frame": { "x": 0, "y": top + 90.0 * i as f64, "w": 430, "h": 90 },
1635                    })
1636                })
1637                .collect();
1638            serde_json::from_value(json!({ "width": 430.0, "height": 932.0, "apps": [], "elements": elements })).unwrap()
1639        };
1640        let row = Selector::from_value(&json!({ "role": "text" })).unwrap();
1641        let columns = json!({
1642            "city": { "take": "label", "regex": "^([^,]+)" },
1643            "time": { "take": "label", "regex": "(오후 [0-9:]+)" },
1644        });
1645        let columns = columns.as_object();
1646        let before = screen(3, 200.0, &["서울", "도쿄", "런던", "파리"]);
1647        let after = screen(4, 20.0, &["런던", "파리", "뉴욕"]);
1648        let cities = |key: &[String]| -> Vec<String> {
1649            let prev = Session::rows_on_screen(&before, &row, columns, key).unwrap();
1650            let page = Session::rows_on_screen(&after, &row, columns, key).unwrap();
1651            new_rows(&prev, &page).iter().map(|r| r["city"].as_str().unwrap().to_string()).collect()
1652        };
1653        // By the whole row, the two that were there already look new.
1654        assert_eq!(cities(&[]), ["런던", "파리", "뉴욕"]);
1655        assert_eq!(cities(&["city".to_string()]), ["뉴욕"]);
1656    }
1657
1658    #[test]
1659    fn take_value_falls_back_to_the_label_remainder() {
1660        let mut el = Element {
1661            id: "a".into(),
1662            role: "button".into(),
1663            label: Some("iOS 버전, 27.0.1".into()),
1664            value: None,
1665            identifier: None,
1666            hint: None,
1667            frame: None,
1668            traits: vec![],
1669            enabled: true,
1670            selected: false,
1671            focused: false,
1672            parent: None,
1673            depth: 1,
1674            pid: 1,
1675            on_screen: true,
1676            raw: None,
1677            key: None,
1678        };
1679        assert_eq!(take(&el, "value").as_deref(), Some("27.0.1"));
1680        assert_eq!(take(&el, "label").as_deref(), Some("iOS 버전, 27.0.1"));
1681        el.value = Some("실제 값".into());
1682        assert_eq!(take(&el, "value").as_deref(), Some("실제 값"));
1683        assert_eq!(
1684            apply_regex(Some("합계 12,300원".into()), Some(r"([\d,]+)원")).unwrap().as_deref(),
1685            Some("12,300")
1686        );
1687    }
1688}