File size: 30,551 Bytes
966ca88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
#!/usr/bin/env python3
"""COMPUTATION lane for NextPlayer (package = argv[1]; NEVER a literal).

This lane owns input -> output VALUE tests: a user feeds an input through the real
UI path and the app DERIVES a specific value that we read back and assert against
the value OBSERVED on the running original (never computed here, never read from
source). It is the sole owner of jump_kind="value".

The app is a video player, so its "computations" are:

  A) SEARCH FILTER COUNT (Home -> Search icon -> type a query -> the results screen
     shows a header "Videos (N)" / "Folders (N)" and the matching rows). The count
     and which rows appear are DERIVED from the query against the 3 fixture videos.
     Ground truth OBSERVED on the original:
        "beta"  -> Videos (1), row beta_movie   (alpha/gamma absent)
        "gamma" -> Videos (1), row gamma_reel
        "clip"  -> Videos (1), row alpha_clip   (matches alpha_clip's title)
        "movie" -> Videos (1), row beta_movie
        "a"     -> Folders (1) + Videos (3), all three rows (substring in all)
        "_"     -> Videos (3), all three rows, NO Folders header (folder name has no '_')
        "zzzznomatch" -> NO Videos/Folders header, none of the three rows
     The strongest, most robust value surface, so several variants live here.

  B) PLAYBACK-SPEED dialog (Player -> speed icon -> "Select playback speed"): a big
     current-value TextView, a chip grid (0.2 .. 4.0), and a -/+ stepper. OBSERVED:
     tapping the "2.0" chip sets the big value to "2.0", the "0.5" chip to "0.5";
     the "+" stepper increments by 0.1. depth=3 (folder -> player -> dialog). The
     dialog opens at the app's REMEMBERED speed (Remember selections persists it),
     so chip tests assert the ABSOLUTE value (chip-independent of the start) and
     the stepper test asserts start + 0.1 read off the SAME dialog.

  C) FOLDER DURATION AGGREGATE (Home): the Download folder row shows a total
     duration badge derived from its 3 clips (00:05 + 00:08 + 00:03 = "00:16") and
     a "3 Videos" count chip. depth=0, a derived aggregate value.

The speed VALUE, the search COUNT header, and the folder duration are all plain
TEXT in the tree, so every core assertion is a rule (dump) assertion; VLM is used
for exactly three rendered-property confirmations as OR-companions.

Fixtures: the 3 sample videos (alpha_clip.mp4 / beta_movie.mp4 / gamma_reel.mp4)
are authored into fixtures/ and mirrored to the device by push_fixtures() (called
by run_suite()); every test reaches them through the picker, never a pushed path.
"""
import os
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from android_testgen_kit import *          # noqa: F403,E402

require_kit(1)

# ── Ground-truth constants (strings/values OBSERVED on the running original) ─────
FOLDER_NAME = "Download"
VIDEO_TITLES = ("alpha_clip", "beta_movie", "gamma_reel")
FIXTURE_VIDEOS = ("alpha_clip.mp4", "beta_movie.mp4", "gamma_reel.mp4")
PLAYER_MARKER = "Play/Pause"                 # content-desc unique to the player
SPEED_DIALOG_TITLE = "Select playback speed"
FOLDER_TOTAL_DURATION = "00:16"              # 00:05 + 00:08 + 00:03, observed
FOLDER_COUNT_CHIP = "3 Videos"
SPEED_STEP = 0.1                             # observed "+"/"−" increment


# ══════════════════════════════════════════════════════════════════════════════
# Setup / navigation helpers. Navigation helpers are named and_enter_* /
# and_reach_* so an and_enter() call backs every declared depth>=1 (audit_depth).
# ══════════════════════════════════════════════════════════════════════════════

def and_grant_media():
    """Tap the runtime media-permission 'Allow all' if it is showing (no-op
    otherwise). restart_app() keeps the grant, so this is only a safety net."""
    for label in ("Allow all", "While using the app", "Allow"):
        n = find_node_ci(ui(), label)
        if n:
            tap_node(n)
            settle("tap")
            return True
    return False


def _home_ready(nodes):
    """True once the Home picker has actually rendered its media list."""
    return bool(find_node(nodes, text=FOLDER_NAME)) or any(
        find_node(nodes, text=t) for t in VIDEO_TITLES)


def home_ready():
    """Mirror fixtures, restart (keeps the media grant), wait until Home actually
    rendered, return fresh Home nodes. Retries the launch once."""
    push_fixtures()
    _ = [fixture_on_device(v) for v in FIXTURE_VIDEOS]      # explicit dependency
    nodes = []
    for _attempt in range(2):
        restart_app()
        if not wait_for_foreground():
            continue
        and_grant_media()
        for _ in range(6):
            nodes = ui()
            if _home_ready(nodes):
                return nodes
            settle("dump")
        if _home_ready(nodes):
            break
    return nodes


def tap_topbar(nodes, desc):
    """Tap a top-bar icon by content-desc. The desc node itself is not clickable —
    its parent View is — so tap the tightest clickable ancestor by bounds
    containment, falling back to the desc node's centre."""
    target = find_node(nodes, content_desc=desc)
    if not target or "_bounds" not in target:
        return False
    tcx, tcy = target["_center"]
    best, best_area = None, None
    for n in nodes:
        if n.get("clickable") != "true" or "_bounds" not in n:
            continue
        x1, y1, x2, y2 = n["_bounds"]
        if x1 <= tcx <= x2 and y1 <= tcy <= y2:
            area = (x2 - x1) * (y2 - y1)
            if best_area is None or area < best_area:
                best, best_area = n, area
    return tap_node(best) if best else tap_node(target)


def find_folder_row(nodes):
    """The TIGHTEST clickable node that contains the 'Download' label — the tappable
    row, never the full-screen root container. Falls back to the smallest bounded
    (non-full-screen) container, then to the label node itself."""
    label = find_node(nodes, text=FOLDER_NAME)
    if not label or "_bounds" not in label:
        return None
    lx, ly = label["_center"]
    s = get_screen_info()
    clickable_best, clickable_area = None, None
    box_best, box_area = None, None
    for n in nodes:
        b = n.get("_bounds")
        if not b:
            continue
        x1, y1, x2, y2 = b
        if not (x1 <= lx <= x2 and y1 <= ly <= y2):
            continue
        w, h = x2 - x1, y2 - y1
        if w < 200 or h < 60:
            continue
        # never the whole screen (the root container swallows every tap)
        if w >= s["width"] and h >= int(s["height"] * 0.8):
            continue
        area = w * h
        if n.get("clickable") == "true":
            if clickable_area is None or area < clickable_area:
                clickable_best, clickable_area = n, area
        if box_area is None or area < box_area:
            box_best, box_area = n, area
    return clickable_best or box_best or label


def _headers(nodes):
    """Every 'Videos (N)' / 'Folders (N)' header string currently on screen."""
    out = []
    for n in find_by_class(nodes, "TextView"):
        t = n.get("text", "").strip()
        if t.startswith("Videos (") or t.startswith("Folders ("):
            out.append(t)
    return out


def _videos_header(headers):
    for h in headers:
        if h.startswith("Videos ("):
            return h
    return ""


def and_reach_search(nodes):
    """Home -> tap the Search top-bar icon -> Search screen (an EditText appears).
    Proves the jump and counts one surface. Returns fresh search nodes or [].

    The topbar tap occasionally lands before the icon is laid out, so it is
    retried (re-dumping Home between tries) until the search EditText appears."""
    for _ in range(3):
        if not tap_topbar(nodes, "Search"):
            nodes = ui()
            continue
        settle("tap")
        after_nodes = ui()
        if find_by_class(after_nodes, "EditText"):
            and_enter("search")
            return after_nodes
        nodes = ui()
        if not find_node(nodes, content_desc="Search"):
            break                                          # navigated elsewhere; bail
    return []


def run_search(query):
    """Home -> Search -> type `query` -> return (fresh result nodes, headers list).
    Retries the whole reach+type once, because the very first search after a fresh
    launch can miss the search-icon tap (observed as a lone transient flake)."""
    for _attempt in range(2):
        home = home_ready()
        snodes = and_reach_search(home)
        if snodes:
            eds = find_by_class(snodes, "EditText")
            if eds and type_text(eds[0], query):
                settle("keyboard")
                r = ui()
                return r, _headers(r)
        and_reset_depth()
    return None, []


# ── Player / speed-dialog helpers (depth family) ────────────────────────────────

def dump_center(nodes):
    """Centre of the CURRENT display in the dump's own (rotated) coordinate frame.
    The player is landscape but `wm size` still reports portrait, so
    get_screen_info() cannot be trusted there; the dump's root bounds are correct."""
    maxx = max((b[2] for b in (n.get("_bounds") for n in nodes) if b), default=0)
    maxy = max((b[3] for b in (n.get("_bounds") for n in nodes) if b), default=0)
    return (maxx // 2, maxy // 2) if maxx and maxy else (0, 0)


def raw_tap_node(node):
    """Tap a node's centre with a RAW `input tap`, bypassing tap_node's bounds
    check. In the landscape PlayerActivity, get_screen_info() reports the portrait
    size (wm size never rotates), so tap_node wrongly rejects any x beyond the
    portrait width — every chip/stepper in the landscape speed dialog. This taps
    the real (rotated) coordinate directly."""
    if not node or "_center" not in node:
        return False
    x, y = node["_center"]
    adb_shell("input", "tap", int(x), int(y))
    settle("tap")
    return True


def reveal_player_controls():
    """Tap the (rotated) centre until the auto-hiding controls are up. Returns
    fresh player nodes once 'Play/Pause' is present, else the last dump."""
    for _ in range(8):
        nodes = ui()
        if find_node(nodes, content_desc=PLAYER_MARKER):
            return nodes
        cx, cy = dump_center(nodes)
        if not cx:
            break
        tap(cx, cy)
        time.sleep(0.25)
    return ui()


def _loop_node(nodes):
    for n in nodes:
        if (n.get("content-desc", "") or "").startswith("Loop"):
            return n
    return None


def _topright_icons(nodes):
    """The four top-right icon Buttons in the player, sorted left->right. Index 1
    (2nd from left) is the playback-speed icon (observed)."""
    cx = dump_center(nodes)[0]
    btns = [n for n in nodes if "Button" in n.get("class", "") and "_bounds" in n
            and n["_bounds"][1] < 230 and n["_bounds"][0] > cx]
    btns.sort(key=lambda n: n["_bounds"][0])
    return btns


def and_enter_player(title="beta_movie"):
    """Home -> Download folder -> tap a video row -> PlayerActivity (autoplays).
    Enables Loop so the short clip keeps replaying (never exits mid-test), reveals
    the controls, and counts TWO surfaces (folder, player). Returns player nodes
    or []."""
    home = home_ready()
    if not find_node(home, text=FOLDER_NAME):
        return []
    # Open the folder and CONFIRM it opened (the video rows appear). The row tap can
    # miss on the first go, so retry from a fresh Home a couple of times.
    fnodes = []
    for _ in range(3):
        folder = find_folder_row(home) or find_node(home, text=FOLDER_NAME)
        tap_node(folder)
        settle("tap")
        fnodes = ui()
        if find_node(fnodes, text=title) or find_node(fnodes, content_desc="Navigate up"):
            break
        home = home_ready()
    if not find_node(fnodes, text=title):
        return []
    and_enter("folder")                                    # surface 1
    row = find_node(fnodes, text=title)
    before = and_showing(fnodes)
    tap_node(row)
    settle("launch")                                       # PlayerActivity + autoplay
    import android_testgen_kit as _kit
    _kit._screen_info = None                               # invalidate wrong geometry
    pnodes = reveal_player_controls()
    if not (find_node(pnodes, content_desc=PLAYER_MARKER) or and_reach(
            before, and_showing(pnodes), PLAYER_MARKER, source=None)):
        return []
    and_enter("player")                                    # surface 2
    ln = _loop_node(pnodes)
    if ln and ln.get("content-desc") == "Loop: Off":
        raw_tap_node(ln)                                   # keep the clip alive
        time.sleep(0.3)
        pnodes = reveal_player_controls()
    return pnodes


def and_reach_speed_dialog():
    """Player -> tap the speed icon (top-right, 2nd from left) -> the 'Select
    playback speed' dialog. Counts a THIRD surface. Returns fresh dialog nodes or [].

    The player controls auto-hide within ~a second, faster than a dump+tap round
    trip, so a naive reveal-then-tap loses the race often. This caches the speed
    icon's coordinate the first time controls are up, then repeatedly [taps centre
    to re-reveal, immediately taps the CACHED coordinate] — no dump between the
    reveal tap and the button tap — checking for the dialog after each. This is the
    sequence observed to open the dialog reliably within the retry budget."""
    pnodes = and_enter_player("beta_movie")
    if not pnodes:
        return []
    speed_xy = None
    for attempt in range(24):
        pnodes = reveal_player_controls()
        icons = _topright_icons(pnodes)
        if len(icons) >= 2:
            speed_xy = icons[1]["_center"]                 # refresh the cached coord
        if speed_xy is None:
            time.sleep(0.3)
            continue
        cx, cy = speed_xy
        adb_shell("input", "tap", cx, cy)                  # immediate, no dump in between
        time.sleep(0.9)
        d = ui()
        if find_node(d, text=SPEED_DIALOG_TITLE):
            and_enter("speed_dialog")                      # surface 3
            return d
    return []


def speed_big_value(nodes):
    """The big current-speed value: the numeric TextView above the chip grid.
    Chips sit at y>=400; the value sits near y~200, so filter on y<300."""
    for n in find_by_class(nodes, "TextView"):
        t = n.get("text", "").strip()
        if (t and all(c.isdigit() or c == "." for c in t)
                and n.get("_bounds") and n["_bounds"][1] < 300):
            return t
    return ""


def read_speed_value(retries=4):
    """Read the big speed value from a FRESH dump, re-dumping until it is a parseable
    number. The value TextView updates a beat after a tap, so a single early dump
    can catch the stale text — poll a few times."""
    val = ""
    for _ in range(retries):
        val = speed_big_value(ui())
        if val:
            try:
                float(val)
                return val
            except ValueError:
                pass
        settle("dump")
    return val


def speed_chip(nodes, label):
    """A speed chip (numeric TextView in the chip grid, y>=400)."""
    for n in find_by_class(nodes, "TextView"):
        if (n.get("text", "").strip() == label
                and n.get("_bounds") and n["_bounds"][1] >= 400):
            return n
    return None


def speed_steppers(nodes):
    """The -/+ Buttons flanking the big value (y ~169-295), sorted left->right so
    [0] is minus and [-1] is plus."""
    bs = [n for n in nodes if "Button" in n.get("class", "") and "_bounds" in n
          and 150 < n["_bounds"][1] < 310 and (n["_bounds"][3] - n["_bounds"][1]) < 160]
    bs.sort(key=lambda n: n["_center"][0])
    return bs


def _num_eq(a, b, tol=0.001):
    try:
        return abs(float(a) - float(b)) <= tol
    except (TypeError, ValueError):
        return False


# ══════════════════════════════════════════════════════════════════════════════
# A) SEARCH FILTER COUNT — the strongest value surface. depth=1, jump_kind=value.
#    Each test asserts the EXACT header count AND the exact rows present/absent.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_search_beta_count", "computation_search_beta_vlm"))
def test_search_beta():
    r, headers = run_search("beta")
    if r is None:
        record("computation_search_beta_count", False,
               "setup_failed: could not reach the search results screen",
               depth=1, jump_kind="value", expect="header 'Videos (1)'")
    else:
        vh = _videos_header(headers)
        has_beta = bool(find_node(r, text="beta_movie"))
        no_others = not find_node(r, text="alpha_clip") and not find_node(r, text="gamma_reel")
        ok = vh == "Videos (1)" and has_beta and no_others
        record("computation_search_beta_count", ok,
               "" if ok else f"behavior_wrong: header={vh!r} beta={has_beta} "
               f"others_absent={no_others}, expected 'Videos (1)' + only beta_movie",
               depth=1, jump_kind="value", expect="header 'Videos (1)', row beta_movie only")
    vlm_assert("computation_search_beta",
               "In this search results screen, is there exactly ONE video result "
               "row, and does its title read 'beta_movie'?",
               RESULTS_DIR, depth=1, jump_kind="value", tag="content")


@and_test(expects=("computation_search_gamma_count",))
def test_search_gamma():
    r, headers = run_search("gamma")
    if r is None:
        record("computation_search_gamma_count", False,
               "setup_failed: could not reach the search results screen",
               depth=1, jump_kind="value", expect="header 'Videos (1)'")
        return
    vh = _videos_header(headers)
    has_gamma = bool(find_node(r, text="gamma_reel"))
    no_others = not find_node(r, text="alpha_clip") and not find_node(r, text="beta_movie")
    ok = vh == "Videos (1)" and has_gamma and no_others
    record("computation_search_gamma_count", ok,
           "" if ok else f"behavior_wrong: header={vh!r} gamma={has_gamma} "
           f"others_absent={no_others}, expected 'Videos (1)' + only gamma_reel",
           depth=1, jump_kind="value", expect="header 'Videos (1)', row gamma_reel only")


@and_test(expects=("computation_search_clip_count",))
def test_search_clip():
    # "clip" is a substring of alpha_clip's title only.
    r, headers = run_search("clip")
    if r is None:
        record("computation_search_clip_count", False,
               "setup_failed: could not reach the search results screen",
               depth=1, jump_kind="value", expect="header 'Videos (1)'")
        return
    vh = _videos_header(headers)
    has_alpha = bool(find_node(r, text="alpha_clip"))
    no_others = not find_node(r, text="beta_movie") and not find_node(r, text="gamma_reel")
    ok = vh == "Videos (1)" and has_alpha and no_others
    record("computation_search_clip_count", ok,
           "" if ok else f"behavior_wrong: header={vh!r} alpha={has_alpha} "
           f"others_absent={no_others}, expected 'Videos (1)' + only alpha_clip",
           depth=1, jump_kind="value", expect="header 'Videos (1)', row alpha_clip only")


@and_test(expects=("computation_search_movie_count",))
def test_search_movie():
    r, headers = run_search("movie")
    if r is None:
        record("computation_search_movie_count", False,
               "setup_failed: could not reach the search results screen",
               depth=1, jump_kind="value", expect="header 'Videos (1)'")
        return
    vh = _videos_header(headers)
    has_beta = bool(find_node(r, text="beta_movie"))
    no_others = not find_node(r, text="alpha_clip") and not find_node(r, text="gamma_reel")
    ok = vh == "Videos (1)" and has_beta and no_others
    record("computation_search_movie_count", ok,
           "" if ok else f"behavior_wrong: header={vh!r} beta={has_beta} "
           f"others_absent={no_others}, expected 'Videos (1)' + only beta_movie",
           depth=1, jump_kind="value", expect="header 'Videos (1)', row beta_movie only")


@and_test(expects=("computation_search_multi_count",))
def test_search_multi():
    # "a" is a substring in ALL three titles -> Videos (3) plus a Folders (1).
    r, headers = run_search("a")
    if r is None:
        record("computation_search_multi_count", False,
               "setup_failed: could not reach the search results screen",
               depth=1, jump_kind="value", expect="header 'Videos (3)'")
        return
    vh = _videos_header(headers)
    all_present = all(find_node(r, text=t) for t in VIDEO_TITLES)
    ok = vh == "Videos (3)" and all_present
    record("computation_search_multi_count", ok,
           "" if ok else f"behavior_wrong: header={vh!r} all_rows={all_present}, "
           f"expected 'Videos (3)' + all three rows",
           depth=1, jump_kind="value", expect="header 'Videos (3)', all three rows")


@and_test(expects=("computation_search_underscore_count",))
def test_search_underscore():
    # "_" is in every FILE title but NOT in the folder name -> Videos (3), NO Folders header.
    r, headers = run_search("_")
    if r is None:
        record("computation_search_underscore_count", False,
               "setup_failed: could not reach the search results screen",
               depth=1, jump_kind="value", expect="header 'Videos (3)'")
        return
    vh = _videos_header(headers)
    all_present = all(find_node(r, text=t) for t in VIDEO_TITLES)
    no_folder = not any(h.startswith("Folders (") for h in headers)
    ok = vh == "Videos (3)" and all_present and no_folder
    record("computation_search_underscore_count", ok,
           "" if ok else f"behavior_wrong: headers={headers} all_rows={all_present} "
           f"no_folder={no_folder}, expected 'Videos (3)', all rows, no Folders header",
           depth=1, jump_kind="value", expect="header 'Videos (3)', all rows, no Folders header")


@and_test(expects=("computation_search_nomatch_count",))
def test_search_nomatch():
    # A query matching nothing -> no Videos/Folders header, none of the three rows.
    r, headers = run_search("zzzznomatch")
    if r is None:
        record("computation_search_nomatch_count", False,
               "setup_failed: could not reach the search results screen",
               depth=1, jump_kind="value", expect="no video result rows")
        return
    any_row = any(find_node(r, text=t) for t in VIDEO_TITLES)
    no_videos_header = not any(h.startswith("Videos (") for h in headers)
    ok = (not any_row) and no_videos_header
    record("computation_search_nomatch_count", ok,
           "" if ok else f"behavior_wrong: headers={headers} any_row={any_row}, "
           f"expected no Videos header and none of the three rows",
           depth=1, jump_kind="value", expect="no Videos header, zero result rows")


# ══════════════════════════════════════════════════════════════════════════════
# C) FOLDER DURATION AGGREGATE — derived total on the Home folder row. depth=0.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_folder_duration_total", "computation_folder_badges_vlm"))
def test_folder_duration_total():
    nodes = home_ready()
    have_total = bool(find_node(nodes, text=FOLDER_TOTAL_DURATION))
    have_count = bool(find_node(nodes, text=FOLDER_COUNT_CHIP))
    have_folder = bool(find_node(nodes, text=FOLDER_NAME))
    ok = have_total and have_count and have_folder
    if not have_folder:
        msg = "setup_failed: Download folder row not visible (fixtures not scanned?)"
    elif not (have_total and have_count):
        msg = (f"behavior_wrong: folder row badges total={have_total} "
               f"count={have_count}, expected '{FOLDER_TOTAL_DURATION}' and "
               f"'{FOLDER_COUNT_CHIP}'")
    else:
        msg = ""
    record("computation_folder_duration_total", ok, msg,
           depth=0, jump_kind="value",
           expect=f"folder row shows '{FOLDER_TOTAL_DURATION}' and '{FOLDER_COUNT_CHIP}'")

    vlm_assert("computation_folder_badges",
               "On the 'Download' folder row of this video app's home screen, are "
               "BOTH a total-duration badge reading '00:16' AND a count reading "
               "'3 Videos' displayed?",
               RESULTS_DIR, depth=0, jump_kind="value", tag="content")


# ══════════════════════════════════════════════════════════════════════════════
# B) PLAYBACK-SPEED dialog — input chip/stepper -> output value. depth=3.
#    Backed by and_reach_speed_dialog() (depth family). The dialog opens at the
#    app's remembered speed, so chip tests assert the ABSOLUTE value the chip sets
#    (start-independent) and the stepper test asserts start + 0.1 read off the same
#    dialog. One VLM companion reads the big rendered value after the "2.0" chip.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_speed_chip_2x", "computation_speed_chip_2x_vlm"))
def test_speed_chip_2x():
    d = and_reach_speed_dialog()
    if not d:
        record("computation_speed_chip_2x", False,
               "setup_failed: could not open the playback-speed dialog",
               depth=3, jump_kind="value", expect="big value '2.0'")
        vlm_assert("computation_speed_chip_2x",
                   "Is the large playback-speed value near the top of this dialog "
                   "showing '2.0'?",
                   RESULTS_DIR, depth=3, jump_kind="value", tag="content")
        return
    chip = speed_chip(d, "2.0")
    if not chip:
        record("computation_speed_chip_2x", False,
               "feature_missing: no '2.0' speed chip in the dialog",
               depth=3, jump_kind="value", expect="big value '2.0'")
    else:
        raw_tap_node(chip)
        got = read_speed_value()
        ok = _num_eq(got, "2.0")
        record("computation_speed_chip_2x", ok,
               "" if ok else f"behavior_wrong: big value shows {got!r} after tapping "
               f"the '2.0' chip, expected '2.0'",
               depth=3, jump_kind="value", expect="big value '2.0' after 2.0 chip")
    vlm_assert("computation_speed_chip_2x",
               "Is the large playback-speed value near the top of this dialog "
               "showing '2.0'?",
               RESULTS_DIR, depth=3, jump_kind="value", tag="content")


@and_test(expects=("computation_speed_chip_half",))
def test_speed_chip_half():
    d = and_reach_speed_dialog()
    if not d:
        record("computation_speed_chip_half", False,
               "setup_failed: could not open the playback-speed dialog",
               depth=3, jump_kind="value", expect="big value '0.5'")
        return
    chip = speed_chip(d, "0.5")
    if not chip:
        record("computation_speed_chip_half", False,
               "feature_missing: no '0.5' speed chip in the dialog",
               depth=3, jump_kind="value", expect="big value '0.5'")
        return
    raw_tap_node(chip)
    got = read_speed_value()
    ok = _num_eq(got, "0.5")
    record("computation_speed_chip_half", ok,
           "" if ok else f"behavior_wrong: big value shows {got!r} after tapping the "
           f"'0.5' chip, expected '0.5'",
           depth=3, jump_kind="value", expect="big value '0.5' after 0.5 chip")


@and_test(expects=("computation_speed_stepper_plus",))
def test_speed_stepper_plus():
    # The "+" stepper increments the big value by 0.1 (observed). Read the starting
    # value off THIS dialog (it opens at the remembered speed), tap +, assert +0.1.
    d = and_reach_speed_dialog()
    if not d:
        record("computation_speed_stepper_plus", False,
               "setup_failed: could not open the playback-speed dialog",
               depth=3, jump_kind="value", expect="value increases by 0.1")
        return
    # Anchor to a known chip first so the start value is deterministic (1.0).
    anchor = speed_chip(d, "1.0")
    if anchor:
        raw_tap_node(anchor)
    start = read_speed_value()
    steppers = speed_steppers(ui())
    if not start or len(steppers) < 2:
        record("computation_speed_stepper_plus", False,
               "feature_missing: could not read start value or find the +/- stepper",
               depth=3, jump_kind="value", expect="value increases by 0.1")
        return
    plus = steppers[-1]
    raw_tap_node(plus)
    got = read_speed_value()
    expected = round(float(start) + SPEED_STEP, 4)
    ok = _num_eq(got, expected)
    record("computation_speed_stepper_plus", ok,
           "" if ok else f"behavior_wrong: value {start!r} -> {got!r} after '+', "
           f"expected {expected}",
           depth=3, jump_kind="value",
           expect=f"value {start} + {SPEED_STEP} = {expected} after '+'")


TESTS = [
    test_search_beta,
    test_search_gamma,
    test_search_clip,
    test_search_movie,
    test_search_multi,
    test_search_underscore,
    test_search_nomatch,
    test_folder_duration_total,
    test_speed_chip_2x,
    test_speed_chip_half,
    test_speed_stepper_plus,
]


if __name__ == "__main__":
    run_suite(TESTS, "computation")