File size: 36,421 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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
#!/usr/bin/env python3
"""STRUCTURE lane for NextPlayer (dev.anilbeesetti.nextplayer.debug).

This lane owns exactly two things:
  (1) the LAUNCH GATE — the app comes up, Home shows its top-level surfaces
      (three top-bar icon controls by content-desc + the media list); jump_kind
      "none", kept to a single case.
  (2) tree-SHAPE deltas — an interaction changes the view-tree's SHAPE (child
      count / arrangement / a new window layer), asserted by counting a widget
      class or a marker-string set BEFORE and AFTER the user path, then reversed
      to prove it restores. jump_kind "transition".

Compose a11y does NOT expose toggle/selection state on this app (every Switch /
segment / chip reports checked=false selected=false regardless of visual state),
so this file NEVER asserts checked/selected — it asserts SHAPE (counts) or hands
the rendered-layout question to the VLM.

IMPORTANT — the picker VIEW MODE (Folders/Videos/Tree) and LAYOUT (List/Grid) are
PERSISTED preferences that survive force-stop, so a test that switches to Videos
leaves the app in Videos on the next launch. Every test therefore normalizes the
picker back to Folders + List in home_ready() before it asserts, and tests that
mutate the mode restore it. This is what keeps the cases independent.

Ground truth (observed on the running original, see recon.md + recon_shots/):
  * Home top bar: 3 clickable Views whose child carries content-desc
    "Search" / "Menu" / "Settings"; body is a list; a desc-less FAB View bottom-right.
  * Every media/list/settings ROW carries a RadioButton child, so a RadioButton
    COUNT is a robust row count:  Home Folders view = 1 (the "Download" folder),
    folder contents / Videos view = 3 (alpha/beta/gamma), Settings root = 9.
  * FAB expands to 3 pill labels: "Open network stream" / "Open local video" /
    "Recently played" (0 -> 3), and an X collapses them (3 -> 0).
  * Menu opens a "Quick Settings" bottom sheet whose distinctive section headers
    are {"Quick Settings","Media view mode","Media Layout","Sort","Fields"} plus
    a "Done"/"Cancel" row (0 markers on Home -> 5 in the sheet).
  * A video row opens PlayerActivity (landscape): picker markers ("Download"
    title / "3 Videos") vanish, player marker content-desc "Play/Pause" appears.
  * Search shows a "Popular folders" header (empty query); typing "beta" replaces
    it with a "Videos (1)" result section (header shape change).

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(); every
test reaches them through fixture_on_device(name), never a hand-pushed path.
"""
import os
import sys

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

require_kit(1)

# ── Ground-truth marker sets (strings observed on the running original) ─────────
TOPBAR_DESCS = ("Search", "Menu", "Settings")
FAB_PILLS = ("Open network stream", "Open local video", "Recently played")
QS_MARKERS = ("Quick Settings", "Media view mode", "Media Layout", "Sort", "Fields")
SETTINGS_ROWS = 9                 # Appearance ... About
PLAYER_MARKER = "Play/Pause"      # content-desc that only exists in the player
PICKER_TITLE = "Next Player Debug"
FOLDER_NAME = "Download"
VIDEO_TITLES = ("alpha_clip", "beta_movie", "gamma_reel")
# The fixture videos the picker opens; declared via fixture_on_device so the
# dependency is explicit and the kit pushes the bytes on a fresh emulator.
FIXTURE_VIDEOS = ("alpha_clip.mp4", "beta_movie.mp4", "gamma_reel.mp4")


# ══════════════════════════════════════════════════════════════════════════════
# Helpers (setup / navigation). Navigation helpers are named and_enter_* so an
# and_enter() call backs every declared depth>=1 (see and_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 just 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 tap_topbar(nodes, desc):
    """Tap the top-bar icon by content-desc. The desc node itself is not
    clickable — its PARENT View is — so tap the nearest 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 = None
    best_area = 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:            # contains the icon centre
            area = (x2 - x1) * (y2 - y1)
            if best_area is None or area < best_area:      # tightest clickable wrapper
                best, best_area = n, area
    return tap_node(best) if best else tap_node(target)


def open_quick_settings(nodes):
    """Tap Menu; returns fresh nodes once the Quick Settings sheet is up."""
    tap_topbar(nodes, "Menu")
    settle("tap")
    return ui()


def in_folders_mode(nodes):
    """Home is in the default Folders view iff the 'Download' folder row shows and
    the flat video titles do not."""
    return bool(find_node(nodes, text=FOLDER_NAME)) and not any(
        find_node(nodes, text=t) for t in VIDEO_TITLES)


def reset_view_mode(nodes):
    """Normalize the picker to Folders + List (the app's default), because those
    are PERSISTED across restart. Opens Quick Settings, selects Folders then List,
    taps Done. Returns fresh Home nodes."""
    qs = open_quick_settings(nodes)
    if find_node(qs, text="Folders"):
        tap_text(qs, "Folders")
        settle("tap")
    if find_node(ui(), text="List"):
        tap_text(ui(), "List")
        settle("tap")
    tap_node(find_node(ui(), text="Done"))
    settle("tap")
    return ui()


def _home_content_ready(nodes):
    """True once the Home picker has actually rendered (top-bar controls plus a
    folder row or the flat video titles), so we do not assert against a mid-load
    or launcher screen. wait_for_foreground() alone is too loose — it matches the
    package anywhere in the window dump even while backgrounded."""
    topbar = all(find_node(nodes, content_desc=d) for d in TOPBAR_DESCS)
    body = bool(find_node(nodes, text=FOLDER_NAME)) or any(
        find_node(nodes, text=t) for t in VIDEO_TITLES)
    return topbar and body


def home_ready(normalize=True):
    """Mirror the fixture videos, restart, grant media, WAIT until Home actually
    rendered; return fresh Home nodes in the DEFAULT Folders+List mode.

    push_fixtures() is idempotent (run_suite() also calls it once); doing it here
    keeps every test self-sufficient and makes the fixture dependency explicit —
    the files land at fixture_on_device('beta_movie.mp4') etc. A launch can be
    slow, so we poll for real content and retry the launch once; and because view
    mode PERSISTS across restart, we reset it to Folders unless a caller opts out."""
    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):                                 # poll for rendered Home
            nodes = ui()
            if _home_content_ready(nodes):
                break
            settle("dump")
        if _home_content_ready(nodes):
            break                                          # launched cleanly
    if not nodes:
        return []
    if normalize and not in_folders_mode(nodes):
        nodes = reset_view_mode(nodes)
    return nodes


def count_rows(nodes):
    """Number of media/list rows == number of RadioButton children on this app."""
    return len(find_by_class(nodes, "RadioButton"))


def marker_count(nodes, markers):
    """How many of `markers` appear as an exact text/content-desc on screen."""
    present = 0
    for m in markers:
        if find_node(nodes, text=m) or find_node(nodes, content_desc=m):
            present += 1
    return present


def find_fab(nodes):
    """The bottom-right expand FAB: a desc-less, text-less clickable View in the
    lower-right quadrant. Derived from a fresh dump — never a hardcoded coord."""
    s = get_screen_info()
    best = None
    for n in nodes:
        if n.get("clickable") != "true":
            continue
        if n.get("text", "").strip() or n.get("content-desc", "").strip():
            continue
        b = n.get("_bounds")
        if not b:
            continue
        cx, cy = n["_center"]
        if cx < s["width"] * 0.6 or cy < s["height"] * 0.6:
            continue
        w, h = b[2] - b[0], b[3] - b[1]
        if w < 60 or h < 60 or w > s["width"] * 0.6:   # a real FAB, not a big panel
            continue
        if best is None or (cy + cx) > (best["_center"][1] + best["_center"][0]):
            best = n
    return best


def and_enter_settings():
    """Home -> Settings. Proves the jump (Settings list appears) and counts one
    surface. Returns fresh Settings nodes or []."""
    nodes = home_ready()
    before = and_showing(nodes)
    tap_topbar(nodes, "Settings")
    settle("tap")
    after_nodes = ui()
    after = and_showing(after_nodes)
    if and_reach(before, after, "Appearance", source=None) or \
       find_node(after_nodes, text="Appearance"):
        and_enter("settings")
        return after_nodes
    return []


def and_enter_folder(name=FOLDER_NAME):
    """Home (Folders view) -> tap the named folder -> folder contents. Proves the
    jump ('Navigate up' present) and counts one surface. Returns fresh
    folder-contents nodes or []."""
    nodes = home_ready()
    row = find_node(nodes, text=name)
    if not row:
        return []
    before = and_showing(nodes)
    tap_node(row)
    settle("tap")
    after_nodes = ui()
    after = and_showing(after_nodes)
    if and_reach(before, after, "Navigate up", source=None) or \
       find_node(after_nodes, content_desc="Navigate up"):
        and_enter("folder")
        return after_nodes
    return []


def dump_center(nodes):
    """Centre of the CURRENT display in the dump's own coordinate frame. The
    player is landscape but `wm size` still reports the physical portrait size,
    so get_screen_info() cannot be trusted there; the dump's root bounds are in
    the correct rotated frame (e.g. 2400x1080)."""
    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 reveal_player_controls():
    """Tap the (rotated) screen centre until the auto-hiding player controls are
    up. Returns the fresh player nodes once 'Play/Pause' is present, else []."""
    for _ in range(5):
        nodes = ui()
        if find_node(nodes, content_desc=PLAYER_MARKER):
            return nodes
        cx, cy = dump_center(nodes)
        if not cx:
            break
        tap(cx, cy)
        settle("tap")
    nodes = ui()
    return nodes if find_node(nodes, content_desc=PLAYER_MARKER) else []


def and_enter_player(title="beta_movie"):
    """Home -> folder -> tap a video row -> PlayerActivity. Proves the jump
    (player 'Play/Pause' appears), counts a second surface, and REVEALS the
    auto-hiding controls. Returns fresh player nodes or []."""
    folder_nodes = and_enter_folder()
    if not folder_nodes:
        return []
    row = find_node(folder_nodes, text=title)
    if not row:
        return []
    before = and_showing(folder_nodes)
    tap_node(row)
    settle("launch")            # PlayerActivity start + autoplay
    global _screen_info
    _screen_info = None         # invalidate any cached (wrong) geometry
    player_nodes = reveal_player_controls()
    if player_nodes and (
            and_reach(before, and_showing(player_nodes), PLAYER_MARKER, source=None)
            or find_node(player_nodes, content_desc=PLAYER_MARKER)):
        and_enter("player")
        return player_nodes
    return []


# ══════════════════════════════════════════════════════════════════════════════
# (1) GATE — the one allowed existence case. jump_kind="none", depth=0.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("structure_gate_launch", "structure_gate_home_vlm"))
def test_gate_launch():
    nodes = home_ready()
    fg = wait_for_foreground()
    container = bool(find_by_class(nodes, "FrameLayout"))
    topbar = all(find_node(nodes, content_desc=d) for d in TOPBAR_DESCS)
    folder = bool(find_node(nodes, text=FOLDER_NAME))
    ok = fg and container and topbar and folder
    msg = ""
    if not fg or not container:
        msg = "setup_failed: app did not reach the foreground"
    elif not topbar:
        msg = "feature_missing: Home top bar lacks Search/Menu/Settings controls"
    elif not folder:
        msg = "setup_failed: Download folder row not visible (fixtures not scanned?)"
    record("structure_gate_launch", ok, msg, depth=0, jump_kind="none")

    vlm_assert("structure_gate_home",
               "In the top app bar of this video app, are there exactly three "
               "icon buttons (a magnifier, a grid/menu icon, and a gear) on the "
               "right side, arranged in a single horizontal row?",
               RESULTS_DIR, depth=0, jump_kind="none", tag="position")


# ══════════════════════════════════════════════════════════════════════════════
# (2) FAB expand — SHAPE delta: 0 -> 3 pill labels. transition, depth=1.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("structure_fab_expand", "structure_fab_expand_vlm"))
def test_fab_expand():
    nodes = home_ready()
    before = marker_count(nodes, FAB_PILLS)               # expect 0
    fab = find_fab(nodes)
    tapped = tap_node(fab) if fab else False
    settle("tap")
    after_nodes = ui()
    and_enter("fab_menu")                                 # backs depth=1
    after = marker_count(after_nodes, FAB_PILLS)          # expect 3
    ok = tapped and before == 0 and after == len(FAB_PILLS)
    msg = ""
    if not tapped:
        msg = "setup_failed: FAB not found / not tappable"
    elif after != len(FAB_PILLS):
        msg = (f"behavior_wrong: FAB action pills {before}->{after}, "
               f"expected 0->{len(FAB_PILLS)}")
    record("structure_fab_expand", ok, msg, depth=1, jump_kind="transition",
           expect=f"FAB action-pill labels {before}->{len(FAB_PILLS)} on expand")

    vlm_assert("structure_fab_expand",
               "Are there exactly three rounded pill-shaped buttons stacked "
               "vertically near the bottom-right (labelled about network stream, "
               "local video, and recently played), each with a leading icon?",
               RESULTS_DIR, depth=1, jump_kind="transition", tag="shape")


# ══════════════════════════════════════════════════════════════════════════════
# (3) FAB collapse — reverse of (2): 3 pills -> 0. transition, depth=1.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("structure_fab_collapse",))
def test_fab_collapse():
    nodes = home_ready()
    fab = find_fab(nodes)
    tap_node(fab)
    settle("tap")
    expanded = ui()
    and_enter("fab_menu")
    n_open = marker_count(expanded, FAB_PILLS)            # expect 3
    close = find_fab(expanded)                            # the X close FAB
    tapped = tap_node(close) if close else False
    settle("tap")
    collapsed = ui()
    and_back()
    n_closed = marker_count(collapsed, FAB_PILLS)         # expect 0
    ok = tapped and n_open == len(FAB_PILLS) and n_closed == 0
    msg = ""
    if n_open != len(FAB_PILLS):
        msg = f"setup_failed: FAB did not expand ({n_open} pills)"
    elif n_closed != 0:
        msg = (f"behavior_wrong: pills did not collapse "
               f"({n_open}->{n_closed}, expected {len(FAB_PILLS)}->0)")
    record("structure_fab_collapse", ok, msg, depth=1, jump_kind="transition",
           expect=f"FAB pills {len(FAB_PILLS)}->0 on close (X)")


# ══════════════════════════════════════════════════════════════════════════════
# (4) View mode Folders -> Videos — SHAPE delta: 1 folder row -> 3 video rows.
#     transition, depth=1. Tapping 'Done' dismisses the sheet (no extra BACK).
#     Restored to Folders at the end so the next test starts clean.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("structure_viewmode_folders_to_videos",
                   "structure_viewmode_folders_to_videos_vlm"))
def test_viewmode_folders_to_videos():
    nodes = home_ready()
    rows_folders = count_rows(nodes)                      # expect 1 (Download)
    qs = open_quick_settings(nodes)
    and_enter("quick_settings")
    ok_seg = tap_text(qs, "Videos")
    settle("tap")
    tap_node(find_node(ui(), text="Done"))                # Done closes the sheet
    settle("tap")
    videos_nodes = ui()
    rows_videos = count_rows(videos_nodes)                # expect 3 (flat list)
    files_present = sum(bool(find_node(videos_nodes, text=t)) for t in VIDEO_TITLES)
    folder_gone = not find_node(videos_nodes, text=FOLDER_NAME)
    ok = (ok_seg and rows_folders == 1 and rows_videos == 3
          and files_present == 3 and folder_gone)
    msg = ""
    if not ok_seg:
        msg = "setup_failed: 'Videos' segment not found in Quick Settings"
    elif rows_videos != 3:
        msg = (f"behavior_wrong: rows {rows_folders}->{rows_videos}, "
               f"expected 1 folder -> 3 videos")
    elif files_present != 3:
        msg = f"behavior_wrong: only {files_present}/3 video titles after switch"
    elif not folder_gone:
        msg = "behavior_wrong: folder row still present in Videos mode"
    record("structure_viewmode_folders_to_videos", ok, msg,
           depth=1, jump_kind="transition",
           expect="RadioButton rows 1(folder)->3(videos); alpha/beta/gamma shown")

    # VLM before restoring, so the screenshot shows the 3-video list.
    vlm_assert("structure_viewmode_folders_to_videos",
               "Is this a single-column vertical list of exactly three video "
               "items with red, blue and green thumbnails (top to bottom), "
               "rather than one folder entry?",
               RESULTS_DIR, depth=1, jump_kind="transition", tag="color")
    reset_view_mode(videos_nodes)                         # restore Folders+List


# ══════════════════════════════════════════════════════════════════════════════
# (5) Media Layout List -> Grid — a RENDERED layout change. Rule track asserts
#     the surface materially changed; the grid-vs-list judgement is VLM.
#     transition, depth=1.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("structure_layout_grid", "structure_layout_grid_vlm"))
def test_layout_grid():
    nodes = home_ready()
    # Switch to Videos first (several items) so a grid is visible, capture the
    # list surface, then switch to Grid — both in one Quick Settings visit.
    qs = open_quick_settings(nodes)
    and_enter("quick_settings")
    tap_text(qs, "Videos")
    settle("tap")
    tap_node(find_node(ui(), text="Done"))
    settle("tap")
    list_nodes = ui()
    before = and_showing(list_nodes)
    qs2 = open_quick_settings(list_nodes)
    grid = find_node(qs2, text="Grid")
    ok_grid = tap_node(grid) if grid else False
    settle("tap")
    tap_node(find_node(ui(), text="Done"))
    settle("tap")
    after_nodes = ui()
    after = and_showing(after_nodes)
    changed = surface_changed(before, after, min_delta=2)
    titles = sum(bool(find_node(after_nodes, text=t)) for t in VIDEO_TITLES)
    ok = ok_grid and (changed or titles >= 2)
    msg = ""
    if not ok_grid:
        msg = "setup_failed: 'Grid' segment not found in Quick Settings"
    elif not (changed or titles >= 2):
        msg = "behavior_wrong: picker did not re-render after selecting Grid"
    record("structure_layout_grid", ok, msg, depth=1, jump_kind="transition",
           expect="picker re-renders (List->Grid) with the 3 videos preserved")

    vlm_assert("structure_layout_grid",
               "Are the video thumbnails arranged in a multi-column grid with at "
               "least two thumbnails positioned SIDE BY SIDE in the same row, "
               "rather than stacked one-per-row?",
               RESULTS_DIR, depth=1, jump_kind="transition", tag="position")
    reset_view_mode(after_nodes)                          # restore Folders+List


# ══════════════════════════════════════════════════════════════════════════════
# (6) Enter Player — SHAPE: picker tree replaced by player tree. transition,
#     depth=2 (Home -> folder -> player), backed by and_enter_player().
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("structure_enter_player", "structure_enter_player_vlm"))
def test_enter_player():
    folder_nodes = and_enter_folder()
    picker_had_marker = bool(find_node(folder_nodes, content_desc="Navigate up")
                             or find_node(folder_nodes, text="3 Videos")
                             or any(find_node(folder_nodes, text=t) for t in VIDEO_TITLES))
    player_nodes = and_enter_player("beta_movie")
    has_player = bool(player_nodes and find_node(player_nodes, content_desc=PLAYER_MARKER))
    # picker markers must be GONE from the player tree (the tree was REPLACED)
    picker_gone = not (find_node(player_nodes, text=FOLDER_NAME)
                       or find_node(player_nodes, text="3 Videos"))
    ok = picker_had_marker and has_player and picker_gone
    msg = ""
    if not has_player:
        msg = "feature_missing: player controls (Play/Pause) not present after tap"
    elif not picker_gone:
        msg = "behavior_wrong: picker markers still present in the player tree"
    record("structure_enter_player", ok, msg, depth=2, jump_kind="transition",
           expect="picker tree (Download/3 Videos) replaced by player (Play/Pause control)")

    vlm_assert("structure_enter_player",
               "In this landscape video player, is there a play/pause control in "
               "the CENTRE of the screen and a horizontal seek bar near the "
               "BOTTOM edge?",
               RESULTS_DIR, depth=2, jump_kind="transition", tag="position")


# ══════════════════════════════════════════════════════════════════════════════
# (7) Quick Settings sheet — SHAPE: a new window layer with a distinctive
#     multi-section child set appears over Home. transition, depth=1.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("structure_quicksettings_sheet",
                   "structure_quicksettings_sheet_vlm"))
def test_quicksettings_sheet():
    nodes = home_ready()
    before = marker_count(nodes, QS_MARKERS)              # expect 0 on Home
    qs = open_quick_settings(nodes)
    and_enter("quick_settings")
    after = marker_count(qs, QS_MARKERS)                  # expect 5 in the sheet
    has_actions = bool(find_node(qs, text="Done") and find_node(qs, text="Cancel"))
    ok = before == 0 and after == len(QS_MARKERS) and has_actions
    msg = ""
    if after != len(QS_MARKERS):
        msg = (f"behavior_wrong: Quick Settings section markers {before}->{after}, "
               f"expected 0->{len(QS_MARKERS)}")
    elif not has_actions:
        msg = "behavior_wrong: sheet lacks the Done/Cancel action row"
    record("structure_quicksettings_sheet", ok, msg,
           depth=1, jump_kind="transition",
           expect="0->5 sheet section headers + Done/Cancel row appear over Home")

    vlm_assert("structure_quicksettings_sheet",
               "In this 'Quick Settings' bottom sheet, are the 'Cancel' and "
               "'Done' text buttons positioned at the BOTTOM of the sheet, with "
               "'Done' to the right of 'Cancel'?",
               RESULTS_DIR, depth=1, jump_kind="transition", tag="position")


# ══════════════════════════════════════════════════════════════════════════════
# (8) Settings list — SHAPE: a scrollable list of exactly 9 category rows.
#     transition, depth=1, backed by and_enter_settings().
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("structure_settings_list", "structure_settings_list_vlm"))
def test_settings_list():
    settings_nodes = and_enter_settings()
    reached = bool(settings_nodes)
    rows = count_rows(settings_nodes)                     # expect 9
    ok = reached and rows == SETTINGS_ROWS
    msg = ""
    if not reached:
        msg = "setup_failed: Settings screen not reached"
    elif rows != SETTINGS_ROWS:
        msg = (f"behavior_wrong: Settings category rows = {rows}, "
               f"expected {SETTINGS_ROWS}")
    record("structure_settings_list", ok, msg, depth=1, jump_kind="transition",
           expect=f"Settings root is a {SETTINGS_ROWS}-row category list")

    vlm_assert("structure_settings_list",
               "Is this a vertical, single-column list of setting category rows "
               "(each row a leading icon plus a title and a smaller subtitle "
               "beneath it), with roughly nine such rows?",
               RESULTS_DIR, depth=1, jump_kind="transition", tag="layout")


# ══════════════════════════════════════════════════════════════════════════════
# (9) Folder drill-down — SHAPE: 1 folder row -> 3 video rows, and a 'Navigate
#     up' control appears. transition, depth=1, backed by and_enter_folder().
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("structure_folder_drilldown",))
def test_folder_drilldown():
    home_nodes = home_ready()
    rows_home = count_rows(home_nodes)                    # expect 1 (Download)
    up_before = bool(find_node(home_nodes, content_desc="Navigate up"))  # False
    folder_nodes = and_enter_folder()
    reached = bool(folder_nodes)
    rows_folder = count_rows(folder_nodes)               # expect 3 videos
    up_after = bool(find_node(folder_nodes, content_desc="Navigate up"))  # True
    ok = (reached and rows_home == 1 and rows_folder == 3
          and not up_before and up_after)
    msg = ""
    if not reached:
        msg = "setup_failed: folder contents not reached"
    elif rows_folder != 3:
        msg = (f"behavior_wrong: rows {rows_home}(home)->{rows_folder}(folder), "
               f"expected 1->3")
    elif not up_after:
        msg = "behavior_wrong: 'Navigate up' control not added inside the folder"
    record("structure_folder_drilldown", ok, msg,
           depth=1, jump_kind="transition",
           expect="rows 1->3 and a 'Navigate up' back control appears")


# ══════════════════════════════════════════════════════════════════════════════
# (10) Search screen SHAPE — 'Popular folders' section (empty query) is replaced
#      by a filtered result section when a query is typed. transition, depth=1.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("structure_search_shape", "structure_search_shape_vlm"))
def test_search_shape():
    nodes = home_ready()
    tap_topbar(nodes, "Search")
    settle("tap")
    search_nodes = ui()
    and_enter("search")
    popular = bool(find_node(search_nodes, text="Popular folders"))
    edit = find_by_class(search_nodes, "EditText")
    typed = type_text(edit[0], "beta") if edit else False
    settle("text")
    results = ui()
    popular_gone = not find_node(results, text="Popular folders")
    result_header = bool(find_node(results, text="Videos (1)"))
    beta_row = bool(find_node(results, text="beta_movie"))
    ok = popular and typed and popular_gone and (result_header or beta_row)
    msg = ""
    if not popular:
        msg = "setup_failed: 'Popular folders' section not shown on empty search"
    elif not typed:
        msg = "setup_failed: could not type into the search field"
    elif not (result_header or beta_row):
        msg = "behavior_wrong: query 'beta' did not produce a filtered result section"
    elif not popular_gone:
        msg = "behavior_wrong: 'Popular folders' still present after a query"
    record("structure_search_shape", ok, msg, depth=1, jump_kind="transition",
           expect="'Popular folders' section -> 'Videos (1)' result row on typing 'beta'")

    vlm_assert("structure_search_shape",
               "Below a search box containing the text 'beta', is there a section "
               "header reading 'Videos (1)' with exactly one video result row "
               "beneath it?",
               RESULTS_DIR, depth=1, jump_kind="transition", tag="content")


# ══════════════════════════════════════════════════════════════════════════════
# (11) Network Stream dialog — SHAPE delta: FAB -> "Open network stream" adds a
#      NEW dialog window layer over Home (title + URL label + an EditText + a
#      Done/Cancel row). Home has 0 EditText; the dialog adds exactly 1 plus 4
#      marker strings. Cancel removes the layer and restores Home. transition,
#      depth=2 (Home -> FAB menu -> dialog), backed by two and_enter() calls.
#      Chosen for depth-2 over an in-player delta because it has no video clip to
#      race.
# ══════════════════════════════════════════════════════════════════════════════

NET_DIALOG_MARKERS = ("Network Stream", "Enter a network URL:", "Done", "Cancel")


@and_test(expects=("structure_network_stream_dialog",))
def test_network_stream_dialog():
    nodes = home_ready()
    edits_home = len(find_by_class(nodes, "EditText"))    # expect 0 on Home
    fab = find_fab(nodes)
    if not tap_node(fab):
        record("structure_network_stream_dialog", False,
               "setup_failed: FAB not found / not tappable", depth=2,
               jump_kind="transition",
               expect="Network Stream dialog adds an EditText + 4 markers over Home")
        return
    settle("tap")
    menu = ui()
    and_enter("fab_menu")                                 # surface 1: FAB menu
    if not tap_text(menu, "Open network stream"):
        record("structure_network_stream_dialog", False,
               "feature_missing: 'Open network stream' action not present", depth=2,
               jump_kind="transition",
               expect="Network Stream dialog adds an EditText + 4 markers over Home")
        return
    settle("tap")
    dlg = ui()
    and_enter("network_dialog")                           # surface 2: the dialog
    markers = marker_count(dlg, NET_DIALOG_MARKERS)       # expect 4
    edits_dlg = len(find_by_class(dlg, "EditText"))       # expect 1
    # reverse: Cancel removes the dialog layer and restores Home
    tap_text(dlg, "Cancel")
    settle("tap")
    restored = ui()
    dialog_gone = not find_node(restored, text="Network Stream")
    home_back = bool(find_node(restored, text=FOLDER_NAME))
    ok = (edits_home == 0 and markers == len(NET_DIALOG_MARKERS)
          and edits_dlg == 1 and dialog_gone and home_back)
    msg = ""
    if markers != len(NET_DIALOG_MARKERS):
        msg = (f"behavior_wrong: dialog markers {markers}/"
               f"{len(NET_DIALOG_MARKERS)} present")
    elif edits_dlg != 1 or edits_home != 0:
        msg = (f"behavior_wrong: EditText count home={edits_home} dialog={edits_dlg}, "
               f"expected 0->1")
    elif not dialog_gone:
        msg = "behavior_wrong: dialog layer not removed after Cancel"
    elif not home_back:
        msg = "behavior_wrong: Home not restored after Cancel"
    record("structure_network_stream_dialog", ok, msg, depth=2,
           jump_kind="transition",
           expect="dialog adds 1 EditText + 4 markers over Home; Cancel restores Home")


TESTS = [
    test_gate_launch,
    test_fab_expand,
    test_fab_collapse,
    test_viewmode_folders_to_videos,
    test_layout_grid,
    test_enter_player,
    test_quicksettings_sheet,
    test_settings_list,
    test_folder_drilldown,
    test_search_shape,
    test_network_stream_dialog,
]

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