File size: 43,604 Bytes
c1c6a0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
#!/usr/bin/env python3
"""STRUCTURE lane — Simple Time Tracker.

This module owns exactly two things:
  1. THE GATE — the app launches, is foregrounded, and its top-level surfaces
     exist: the bottom tab bar `mainTabs` (4 tabs), the `mainPager`, and the
     Timers list `rvRunningRecordsList`. These are jump_kind="none".
  2. TREE-SHAPE DELTAS — an interaction that changes the view tree's SHAPE (a
     class/count of widgets appears or disappears, a page subtree swaps). Each is
     recorded as jump_kind="transition" with the observed before->after, and
     reversed to assert it restores.

Everything content-flavored (strings, checked/selected, reachability of a named
screen, computed values, CRUD) is CEDED to the other lanes — this file only
asserts SHAPE via node-class/id counts and `surface_changed`.

Shape numbers here were derived by DRIVING THE RUNNING ORIGINAL (see the values
in each `expect=`). Nothing is invented.

NOTE on the ViewPager: `mainPager` keeps ADJACENT pages in its offscreen buffer,
so a settings subtree does NOT leave the tree on Settings->Records (2 apart) but
DOES on Settings->Timers (farthest). Tab-shape deltas below only use transitions
that were verified to be deterministic.

DEPTH: a page/screen we open before asserting is one surface crossed. Every test
that declares depth>=1 reaches its surface through a depth-family helper
(and_enter_add_screen / and_enter_settings_tab / and_enter_tab / and_enter), so
the kit's depth audit can back the claim.
"""
import os
import sys

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

PACKAGE = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("PACKAGE", "")
RESULTS_DIR = (sys.argv[2] if len(sys.argv) > 2
               else os.environ.get("RESULTS_DIR", "/workspace/testgen/eval"))

# The kit's settling table has no "nav" key; alias it to a tap-length settle so
# the recon recipes copied below read naturally.
SETTLE.setdefault("nav", SETTLE["tap"])          # noqa: F405


# ─────────────────────────────────────────────────────────────────────────────
# Helper recipes (from recon.md) — kit-only, no hardcoded package/coords/serials.
# ─────────────────────────────────────────────────────────────────────────────
def tile(nodes, label):
    """The CLICKABLE tile container whose bounds enclose the name TextView."""
    name = next((n for n in nodes if (n.get("text") or "") == label
                 and (n.get("resource-id") or "").endswith("tvRecordTypeItemName")),
                None)
    if not name:
        return None
    nb = name["_bounds"]
    for n in nodes:
        if ((n.get("resource-id") or "").endswith("viewRecordTypeItem")
                and n.get("clickable") == "true"):
            b = n["_bounds"]
            if b[0] <= nb[0] and b[2] >= nb[2] and b[1] <= nb[1] and b[3] >= nb[3]:
                return n
    return None


def goto_tab(desc):
    """Switch to a bottom tab by content-desc (Timers/Records/Statistics/Settings).
    A plain switch that does NOT count a surface — used for setup navigation."""
    nodes = ui()                                                  # noqa: F405
    t = next((n for n in nodes if (n.get("content-desc") or "") == desc), None)
    if t:
        tap_node(t)                                              # noqa: F405
        settle("nav")                                           # noqa: F405
    return ui()                                                  # noqa: F405


def and_enter_tab(desc):
    """Switch to a bottom tab AND count it as one surface crossed. This backs a
    depth>=1 declaration for tests whose asserted shape lives on the tab they
    navigate to (the kit's depth audit matches the and_enter_ prefix)."""
    nodes = ui()                                                  # noqa: F405
    t = next((n for n in nodes if (n.get("content-desc") or "") == desc), None)
    if t:
        tap_node(t)                                              # noqa: F405
        settle("nav")                                           # noqa: F405
        and_enter(f"tab_{desc}")                                  # noqa: F405
    return ui()                                                  # noqa: F405


def count_id(nodes, suffix):
    """How many nodes have this resource-id LAST segment (package-agnostic)."""
    return len([n for n in nodes
                if (n.get("resource-id") or "").rsplit("/", 1)[-1] == suffix])


def has_id(nodes, suffix):
    return node_by_id(nodes, suffix) is not None                 # noqa: F405


def open_add_screen():
    """From Timers, open the Add-activity screen. Depth-family helper: names
    starting with and_enter_/and_reach_ back a depth>=1 declaration (kit audit)."""
    return and_enter_add_screen()


def and_enter_add_screen():
    """Tap the Add tile and confirm the change-record-type surface appeared.
    Returns the fresh tree, or None if the surface never opened."""
    nodes = ui()                                                  # noqa: F405
    before = and_showing(nodes)                                   # noqa: F405
    add = tile(nodes, "Add")
    if not tap_node(add):                                         # noqa: F405
        return None
    settle("nav")                                                # noqa: F405
    after = ui()                                                  # noqa: F405
    if not has_id(after, "etChangeRecordTypeName"):
        return None
    if not surface_changed(before, and_showing(after)):          # noqa: F405
        return None
    and_enter("add_activity")                                     # noqa: F405
    return after


def and_enter_settings_tab():
    """Switch to the Settings tab and confirm its content list appeared."""
    nodes = ui()                                                  # noqa: F405
    before = and_showing(nodes)                                   # noqa: F405
    t = next((n for n in nodes if (n.get("content-desc") or "") == "Settings"), None)
    if not tap_node(t):                                          # noqa: F405
        return None
    settle("nav")                                                # noqa: F405
    after = ui()                                                  # noqa: F405
    if not has_id(after, "rvSettingsContent"):
        return None
    and_enter("settings_tab")                                     # noqa: F405
    return after


def running_card_center(nodes):
    """Centre of the CANVAS running-record card (not a dump node): the strip of
    `rvRunningRecordsList` above the first activity tile. Derived from bounds."""
    rv = node_by_id(nodes, "rvRunningRecordsList")               # noqa: F405
    if not rv:
        return None
    b = rv["_bounds"]
    tiles = [n for n in nodes
             if (n.get("resource-id") or "").endswith("viewRecordTypeItem")]
    tile_top = min((t["_bounds"][1] for t in tiles), default=b[1] + 300)
    cx = (b[0] + b[2]) // 2
    cy = (b[1] + tile_top) // 2
    return cx, cy


def stop_any_running_timer():
    """Best-effort cleanup: if a timer is running, tap the card region to stop it.
    Safe to call unconditionally at the end of a test."""
    goto_tab("Timers")
    nodes = ui()                                                  # noqa: F405
    c = running_card_center(nodes)
    if c:
        tap(c[0], c[1])                                          # noqa: F405
        settle("nav")                                           # noqa: F405


def make_activity(name):
    """Create an activity from the Timers tab; leaves you on Timers."""
    nodes = ui()                                                  # noqa: F405
    tap_node(tile(nodes, "Add"))                                 # noqa: F405
    settle("nav")                                               # noqa: F405
    type_text(node_by_id(ui(), "etChangeRecordTypeName"), name)  # noqa: F405
    hide_keyboard()                                              # noqa: F405
    tap_node(node_by_id(ui(), "btnChangeRecordTypeSave"))        # noqa: F405
    settle("nav")                                               # noqa: F405
    return ui()                                                  # noqa: F405


# ═════════════════════════════════════════════════════════════════════════════
# GATE (jump_kind="none", depth=0) — kept minimal (the one legitimate existence
# lane). 4 records total, well under the 30% existence ceiling for this module.
# ═════════════════════════════════════════════════════════════════════════════

@and_test(expects=("structure_gate_launch",))
def test_gate_launch():
    restart_app()                                               # noqa: F405
    fg = wait_for_foreground()                                  # noqa: F405
    nodes = ui()                                                 # noqa: F405
    # A single-Activity app: the top-level container ViewGroup must exist.
    ok = bool(fg) and len(find_by_class(nodes, "ViewGroup")) > 0  # noqa: F405
    record("structure_gate_launch", ok,                         # noqa: F405
           "" if ok else "setup_failed: app did not reach the foreground with a "
                         "top-level ViewGroup",
           depth=0, jump_kind="none")


@and_test(expects=("structure_gate_tabbar",))
def test_gate_tabbar():
    restart_app()                                               # noqa: F405
    wait_for_foreground()                                       # noqa: F405
    nodes = ui()                                                 # noqa: F405
    tabs_host = has_id(nodes, "mainTabs")
    descs = [n.get("content-desc") for n in nodes
             if (n.get("content-desc") or "") in
             ("Timers", "Records", "Statistics", "Settings")]
    ok = tabs_host and set(descs) == {"Timers", "Records", "Statistics", "Settings"}
    record("structure_gate_tabbar", bool(ok),                   # noqa: F405
           "" if ok else f"feature_missing: mainTabs host or its 4 tab children "
                         f"absent (found {sorted(set(descs))})",
           depth=0, jump_kind="none")


@and_test(expects=("structure_gate_pager",))
def test_gate_pager():
    restart_app()                                               # noqa: F405
    wait_for_foreground()                                       # noqa: F405
    nodes = ui()                                                 # noqa: F405
    ok = has_id(nodes, "mainPager")
    record("structure_gate_pager", bool(ok),                    # noqa: F405
           "" if ok else "feature_missing: mainPager (the 4-tab ViewPager host) "
                         "not present",
           depth=0, jump_kind="none")


@and_test(expects=("structure_gate_timers_list",))
def test_gate_timers_list():
    restart_app()                                               # noqa: F405
    wait_for_foreground()                                       # noqa: F405
    nodes = goto_tab("Timers")
    # The Timers home shows the running-records RecyclerView and >=1 activity tile
    # (fresh install: Pomodoro / Add / Default).
    ok = has_id(nodes, "rvRunningRecordsList") and count_id(nodes, "viewRecordTypeItem") >= 1
    record("structure_gate_timers_list", bool(ok),              # noqa: F405
           "" if ok else "feature_missing: rvRunningRecordsList or activity tiles "
                         "absent on the Timers tab",
           depth=0, jump_kind="none")


# ═════════════════════════════════════════════════════════════════════════════
# IN-PLACE SHAPE DELTAS on the Add screen (depth=1, backed by and_enter_add_screen).
# ═════════════════════════════════════════════════════════════════════════════

@and_test(expects=("structure_more_less_fields", "structure_more_less_fields_vlm"))
def test_more_less_fields():
    """More<->Less flips a CLASS of setting fields (Categories/Goal/Note) in/out
    of the tree. The toggle STATE PERSISTS across launches, so we measure the
    current state, flip, assert it inverted, flip back, assert it restored."""
    restart_app()                                               # noqa: F405
    wait_for_foreground()                                       # noqa: F405
    if open_add_screen() is None:
        record("structure_more_less_fields", False,             # noqa: F405
               "setup_failed: could not open the Add-activity screen",
               depth=1, jump_kind="transition",
               expect="Category/Goal/Note fields toggle in/out on More<->Less")
    else:
        markers = ("fieldChangeRecordTypeCategory", "fieldChangeRecordTypeGoalTime",
                   "etChangeRecordTypeNote")

        def field_count(nodes):
            return sum(count_id(nodes, m) for m in markers)

        before = field_count(ui())                              # noqa: F405
        tap_node(node_by_id(ui(), "tvChangeRecordTypeMoreFields"))  # noqa: F405
        settle("nav")                                          # noqa: F405
        after = field_count(ui())                              # noqa: F405
        # Toggle inverts presence: 3 fields present <-> 0 fields present.
        flipped = (before == 0 and after == 3) or (before == 3 and after == 0)
        # reverse
        tap_node(node_by_id(ui(), "tvChangeRecordTypeMoreFields"))  # noqa: F405
        settle("nav")                                          # noqa: F405
        restored = field_count(ui()) == before                # noqa: F405
        ok = flipped and restored
        record("structure_more_less_fields", ok,               # noqa: F405
               "" if ok else f"behavior_wrong: More/Less field count "
                             f"{before}->{after} (expected a 0<->3 flip) "
                             f"restored={restored}",
               depth=1, jump_kind="transition",
               expect="3 extra field nodes (Category/Goal/Note) appear on More, "
                      "removed on Less; restores to start state")
        # For the VLM, drive to the EXPANDED state so the extra fields are visible.
        if field_count(ui()) == 0:
            tap_node(node_by_id(ui(), "tvChangeRecordTypeMoreFields"))  # noqa: F405
            settle("nav")                                      # noqa: F405
        vlm_assert("structure_more_less_fields",               # noqa: F405
                   "Is the Add-activity form a vertical stack of at least five "
                   "labeled rounded rectangular fields (including Color, Icon, "
                   "Categories, Goal, Note) stacked top to bottom?",
                   RESULTS_DIR, depth=1, jump_kind="transition", tag="layout")


@and_test(expects=("structure_color_expand", "structure_color_expand_vlm"))
def test_color_expand():
    """Tapping the Color field expands an inline swatch grid: rvChangeRecordTypeColor
    appears with ~19 layoutColorItem cells. Collapse removes them."""
    restart_app()                                              # noqa: F405
    wait_for_foreground()                                      # noqa: F405
    if open_add_screen() is None:
        record("structure_color_expand", False,                # noqa: F405
               "setup_failed: could not open the Add-activity screen",
               depth=1, jump_kind="transition",
               expect="color swatch grid (rvChangeRecordTypeColor, ~19 cells) appears")
    else:
        before = count_id(ui(), "layoutColorItem")            # noqa: F405
        had_rv_before = has_id(ui(), "rvChangeRecordTypeColor")  # noqa: F405
        tap_node(node_by_id(ui(), "fieldChangeRecordTypeColor"))  # noqa: F405
        settle("nav")                                         # noqa: F405
        nodes = ui()                                           # noqa: F405
        swatches = count_id(nodes, "layoutColorItem")
        has_rv = has_id(nodes, "rvChangeRecordTypeColor")
        grew = (before == 0 and not had_rv_before
                and has_rv and swatches >= 15)
        # collapse (tap the Color field again)
        tap_node(node_by_id(ui(), "fieldChangeRecordTypeColor"))  # noqa: F405
        settle("nav")                                         # noqa: F405
        restored = count_id(ui(), "layoutColorItem") == 0     # noqa: F405
        ok = grew and restored
        record("structure_color_expand", ok,                   # noqa: F405
               "" if ok else f"behavior_wrong: color swatches {before}->{swatches} "
                             f"(rv={has_rv}); expected 0->~19; restored={restored}",
               depth=1, jump_kind="transition",
               expect="rvChangeRecordTypeColor + ~19 layoutColorItem swatches "
                      "appear on tap, removed on collapse")
        # VLM: re-expand for the screenshot.
        if not has_id(ui(), "rvChangeRecordTypeColor"):        # noqa: F405
            tap_node(node_by_id(ui(), "fieldChangeRecordTypeColor"))  # noqa: F405
            settle("nav")                                     # noqa: F405
        vlm_assert("structure_color_expand",                   # noqa: F405
                   "Below the Color field, is there a grid of many small colored "
                   "square swatches arranged in multiple rows (at least 3 rows)?",
                   RESULTS_DIR, depth=1, jump_kind="transition", tag="shape")


@and_test(expects=("structure_icon_expand", "structure_icon_expand_vlm"))
def test_icon_expand():
    """Tapping the Icon field expands a large icon grid: rvIconSelection appears
    with the ICON/TEXT/EMOJI mode buttons (btnButtonsRowView x3) and dozens of
    icon cells. The tree grows dramatically (~41 -> ~180 nodes)."""
    restart_app()                                              # noqa: F405
    wait_for_foreground()                                      # noqa: F405
    if open_add_screen() is None:
        record("structure_icon_expand", False,                 # noqa: F405
               "setup_failed: could not open the Add-activity screen",
               depth=1, jump_kind="transition",
               expect="rvIconSelection icon grid (dozens of cells) appears")
    else:
        before_total = len(ui())                              # noqa: F405
        tap_node(node_by_id(ui(), "fieldChangeRecordTypeIcon"))  # noqa: F405
        settle("nav")                                         # noqa: F405
        settle("nav")                                         # noqa: F405
        nodes = ui()                                           # noqa: F405
        after_total = len(nodes)
        has_grid = has_id(nodes, "rvIconSelection")
        cells = count_id(nodes, "layoutIconSelectionItem")
        modebtns = count_id(nodes, "btnButtonsRowView")
        grew = (has_grid and cells >= 20 and modebtns == 3
                and after_total >= before_total + 60)
        record("structure_icon_expand", bool(grew),            # noqa: F405
               "" if grew else f"behavior_wrong: icon grid nodes {before_total}->"
                               f"{after_total} grid={has_grid} cells={cells} "
                               f"modebtns={modebtns}; expected a large grid",
               depth=1, jump_kind="transition",
               expect="rvIconSelection appears; layoutIconSelectionItem>=20; "
                      "btnButtonsRowView==3 (ICON/TEXT/EMOJI); total ~41->~182")
        vlm_assert("structure_icon_expand",                    # noqa: F405
                   "Does a large grid of many small square icon tiles fill most "
                   "of the screen below the Icon field (at least four rows of "
                   "icons)?",
                   RESULTS_DIR, depth=1, jump_kind="transition", tag="size")


@and_test(expects=("structure_color_icon_exclusive",))
def test_color_icon_exclusive():
    """Opening the Color expander SWAPS out the name/icon field subtree (they are
    mutually exclusive inline expanders): with the color grid open, the Icon
    field node is no longer in the tree; closing restores it. A shape swap, not
    a mere count bump."""
    restart_app()                                              # noqa: F405
    wait_for_foreground()                                      # noqa: F405
    if open_add_screen() is None:
        record("structure_color_icon_exclusive", False,        # noqa: F405
               "setup_failed: could not open the Add-activity screen",
               depth=1, jump_kind="transition",
               expect="Icon field node disappears while the color grid is open")
    else:
        icon_before = has_id(ui(), "fieldChangeRecordTypeIcon")  # noqa: F405
        tap_node(node_by_id(ui(), "fieldChangeRecordTypeColor"))  # noqa: F405
        settle("nav")                                         # noqa: F405
        nodes = ui()                                           # noqa: F405
        icon_gone = not has_id(nodes, "fieldChangeRecordTypeIcon")
        color_grid = has_id(nodes, "rvChangeRecordTypeColor")
        # close
        tap_node(node_by_id(ui(), "fieldChangeRecordTypeColor"))  # noqa: F405
        settle("nav")                                         # noqa: F405
        icon_back = has_id(ui(), "fieldChangeRecordTypeIcon")  # noqa: F405
        ok = icon_before and color_grid and icon_gone and icon_back
        record("structure_color_icon_exclusive", bool(ok),     # noqa: F405
               "" if ok else f"behavior_wrong: icon field before={icon_before} "
                             f"gone_while_color={icon_gone} back={icon_back} "
                             f"color_grid={color_grid}",
               depth=1, jump_kind="transition",
               expect="fieldChangeRecordTypeIcon present -> absent while color grid "
                      "open -> present again after collapse")


# ═════════════════════════════════════════════════════════════════════════════
# TAB-SWITCH SHAPE DELTAS (page subtree swap). depth=1, backed by
# and_enter_settings_tab / and_enter_tab. Only transitions verified DETERMINISTIC
# against the ViewPager offscreen buffer.
# ═════════════════════════════════════════════════════════════════════════════

@and_test(expects=("structure_tab_timers_settings", "structure_tab_timers_settings_vlm"))
def test_tab_timers_to_settings():
    """Switching Timers->Settings swaps the whole page subtree: the settings
    RecyclerView (rvSettingsContent + several tvItemSettingsTitle rows + a
    checkbox) appears while the Timers content (viewRecordTypeItem tiles +
    rvRunningRecordsList) leaves the tree. Reverse restores the Timers shape."""
    restart_app()                                              # noqa: F405
    wait_for_foreground()                                      # noqa: F405
    timers = goto_tab("Timers")
    tiles0 = count_id(timers, "viewRecordTypeItem")
    rv0 = has_id(timers, "rvRunningRecordsList")
    if and_enter_settings_tab() is None:
        record("structure_tab_timers_settings", False,         # noqa: F405
               "feature_missing: Settings page (rvSettingsContent) never appeared",
               depth=1, jump_kind="transition",
               expect="Settings list appears; Timers tiles disappear")
    else:
        st = ui()                                              # noqa: F405
        settings_appeared = (has_id(st, "rvSettingsContent")
                             and count_id(st, "tvItemSettingsTitle") >= 5
                             and has_id(st, "checkboxItemSettings"))
        timers_gone = (count_id(st, "viewRecordTypeItem") == 0
                       and not has_id(st, "rvRunningRecordsList"))
        # reverse (Settings->Timers is the farthest transition, deterministically
        # evicting the settings subtree and restoring the Timers content)
        back_timers = goto_tab("Timers")
        restored = (count_id(back_timers, "viewRecordTypeItem") == tiles0
                    and has_id(back_timers, "rvRunningRecordsList") == rv0)
        ok = settings_appeared and timers_gone and restored
        record("structure_tab_timers_settings", bool(ok),      # noqa: F405
               "" if ok else f"behavior_wrong: settings_shape={settings_appeared} "
                             f"timers_gone={timers_gone} restored={restored}",
               depth=1, jump_kind="transition",
               expect="rvSettingsContent+>=5 titles+checkbox appear; "
                      "viewRecordTypeItem/rvRunningRecordsList disappear; restores")
        # VLM: Settings is a vertical scrollable list of setting rows.
        and_enter_settings_tab()
        vlm_assert("structure_tab_timers_settings",            # noqa: F405
                   "Is the Settings screen a vertically scrolling list of text "
                   "setting rows (such as 'Allow multitasking', 'Dark mode', "
                   "'Language') stacked top to bottom?",
                   RESULTS_DIR, depth=1, jump_kind="transition", tag="layout")


@and_test(expects=("structure_tab_settings_timers_shape",))
def test_tab_settings_to_timers_shape():
    """The Settings page has a rich, distinct shape (settings rows) that the
    Timers page lacks. Switching Settings->Timers (the farthest tab hop, which
    the ViewPager evicts deterministically) drops the entire settings subtree
    and brings in the Timers content — a genuine page-subtree swap. surface_changed
    is the honest primitive for 'the page shape changed materially'."""
    restart_app()                                              # noqa: F405
    wait_for_foreground()                                      # noqa: F405
    if and_enter_settings_tab() is None:
        record("structure_tab_settings_timers_shape", False,   # noqa: F405
               "feature_missing: Settings page never appeared",
               depth=1, jump_kind="transition",
               expect="settings subtree leaves and Timers tiles enter on "
                      "Settings->Timers")
    else:
        before = and_showing()                                # noqa: F405
        settings_present = (has_id(ui(), "rvSettingsContent")  # noqa: F405
                            and count_id(ui(), "tvItemSettingsTitle") >= 5)
        timers = and_enter_tab("Timers")
        after = and_showing(timers)                           # noqa: F405
        settings_gone = (not has_id(timers, "rvSettingsContent")
                         and count_id(timers, "tvItemSettingsTitle") == 0)
        timers_appeared = (has_id(timers, "rvRunningRecordsList")
                           and count_id(timers, "viewRecordTypeItem") >= 1)
        changed = surface_changed(before, after, min_delta=4)  # noqa: F405
        ok = settings_present and settings_gone and timers_appeared and changed
        record("structure_tab_settings_timers_shape", bool(ok),  # noqa: F405
               "" if ok else f"behavior_wrong: settings_present={settings_present} "
                             f"settings_gone={settings_gone} "
                             f"timers_appeared={timers_appeared} "
                             f"surface_changed={changed}",
               depth=1, jump_kind="transition",
               expect="rvSettingsContent + >=5 tvItemSettingsTitle present on "
                      "Settings, absent on Timers; rvRunningRecordsList + tiles "
                      "present on Timers; surface changes materially")


@and_test(expects=("structure_stats_chart_region_vlm",))
def test_stats_chart_region_vlm():
    """The Statistics pie chart is a custom CANVAS view whose content never
    reaches the dump — the only honest probe of its rendered shape is the VLM."""
    restart_app()                                             # noqa: F405
    wait_for_foreground()                                     # noqa: F405
    # Populate stats so the chart renders: create + start a timer.
    make_activity("Reading")
    tap_node(tile(ui(), "Reading"))                           # noqa: F405
    settle("nav")                                            # noqa: F405
    settle("nav")                                            # noqa: F405
    and_enter_tab("Statistics")                               # backs depth=1
    vlm_assert("structure_stats_chart_region",               # noqa: F405
               "Is there a large circular ring (donut) chart occupying the upper "
               "part of the Statistics screen?",
               RESULTS_DIR, depth=1, jump_kind="transition", tag="shape")
    stop_any_running_timer()


# ═════════════════════════════════════════════════════════════════════════════
# COLLAPSE/EXPAND SHAPE DELTA inside a page (Settings section header). depth=1.
# ═════════════════════════════════════════════════════════════════════════════

@and_test(expects=("structure_settings_section_collapse",))
def test_settings_section_collapse():
    """Tapping the 'Notification settings' collapsible header expands a group of
    sub-settings: a new titled row + a new checkbox enter the tree. Collapsing
    removes them. (tvItemSettingsTitle 9->10, checkboxItemSettings 1->2.)"""
    restart_app()                                             # noqa: F405
    wait_for_foreground()                                     # noqa: F405
    if and_enter_settings_tab() is None:
        record("structure_settings_section_collapse", False,  # noqa: F405
               "feature_missing: Settings page never appeared",
               depth=1, jump_kind="transition",
               expect="Notification settings expands: +1 title row, +1 checkbox")
    else:
        header = find_node(ui(), text="Notification settings")  # noqa: F405
        if not header:
            record("structure_settings_section_collapse", False,  # noqa: F405
                   "feature_missing: 'Notification settings' collapsible header "
                   "not found",
                   depth=1, jump_kind="transition",
                   expect="Notification settings expands: +1 title row, +1 checkbox")
        else:
            t0 = count_id(ui(), "tvItemSettingsTitle")        # noqa: F405
            c0 = count_id(ui(), "checkboxItemSettings")       # noqa: F405
            tap_node(header)                                  # noqa: F405
            settle("nav")                                     # noqa: F405
            t1 = count_id(ui(), "tvItemSettingsTitle")        # noqa: F405
            c1 = count_id(ui(), "checkboxItemSettings")       # noqa: F405
            grew = t1 > t0 and c1 > c0
            # collapse
            header2 = find_node(ui(), text="Notification settings")  # noqa: F405
            tap_node(header2)                                 # noqa: F405
            settle("nav")                                     # noqa: F405
            restored = (count_id(ui(), "tvItemSettingsTitle") == t0  # noqa: F405
                        and count_id(ui(), "checkboxItemSettings") == c0)
            ok = grew and restored
            record("structure_settings_section_collapse", bool(ok),  # noqa: F405
                   "" if ok else f"behavior_wrong: titles {t0}->{t1}, checkboxes "
                                 f"{c0}->{c1} (expected both to grow); "
                                 f"restored={restored}",
                   depth=1, jump_kind="transition",
                   expect="tvItemSettingsTitle & checkboxItemSettings each +>=1 on "
                          "expand, restored on collapse")


# ═════════════════════════════════════════════════════════════════════════════
# INTERACTION-DRIVEN SHAPE DELTAS (a class of widget appears after a user action).
# ═════════════════════════════════════════════════════════════════════════════

@and_test(expects=("structure_stats_populate_shape",))
def test_stats_populate_shape():
    """Empty Statistics has NO legend list; starting a timer makes the stats
    legend subtree materialise: rvStatisticsList + tvStatisticsItemName rows
    appear where there were none. A shape delta driven by the core loop."""
    clear_data()                                             # noqa: F405
    launch_app()                                             # noqa: F405
    wait_for_foreground()                                    # noqa: F405
    make_activity("Reading")
    st0 = goto_tab("Statistics")
    empty_ok = (not has_id(st0, "rvStatisticsList")
                and count_id(st0, "tvStatisticsItemName") == 0)
    # start the timer via the Timers tile
    goto_tab("Timers")
    tap_node(tile(ui(), "Reading"))                          # noqa: F405
    settle("nav")                                            # noqa: F405
    settle("nav")                                            # noqa: F405
    st1 = and_enter_tab("Statistics")                        # backs depth=1
    grew = (has_id(st1, "rvStatisticsList")
            and count_id(st1, "tvStatisticsItemName") >= 1)
    ok = empty_ok and grew
    record("structure_stats_populate_shape", bool(ok),       # noqa: F405
           "" if ok else f"behavior_wrong: empty_stats={empty_ok} "
                         f"populated={grew} (rvStatisticsList/tvStatisticsItemName "
                         f"should appear after starting a timer)",
           depth=1, jump_kind="transition",
           expect="rvStatisticsList + >=1 tvStatisticsItemName appear once a timer "
                  "runs (0 legend rows -> populated)")
    stop_any_running_timer()


@and_test(expects=("structure_records_populate_shape",))
def test_records_populate_shape():
    """The Records list has zero viewRecordItem rows on a fresh install; running
    then stopping a timer persists a record, so a viewRecordItem row enters the
    tree. Shape delta on the empty->populated list."""
    clear_data()                                             # noqa: F405
    launch_app()                                             # noqa: F405
    wait_for_foreground()                                    # noqa: F405
    make_activity("Reading")
    rec0 = goto_tab("Records")
    empty_ok = count_id(rec0, "viewRecordItem") == 0
    # start then stop
    goto_tab("Timers")
    tap_node(tile(ui(), "Reading"))                          # noqa: F405
    settle("nav")                                            # noqa: F405
    settle("nav")                                            # noqa: F405
    stop_any_running_timer()                                 # taps the canvas card
    rec1 = and_enter_tab("Records")                          # backs depth=1
    grew = count_id(rec1, "viewRecordItem") >= 1
    ok = empty_ok and grew
    record("structure_records_populate_shape", bool(ok),     # noqa: F405
           "" if ok else f"behavior_wrong: empty_records={empty_ok} "
                         f"populated={grew} (a viewRecordItem row should appear "
                         f"after a completed timer)",
           depth=1, jump_kind="transition",
           expect="viewRecordItem rows 0 -> >=1 after start+stop of a timer")


@and_test(expects=("structure_longpress_edit_shape",))
def test_longpress_edit_shape():
    """Long-pressing an activity tile opens the EDIT variant of the change screen,
    which has action buttons the ADD variant lacks: btnChangeRecordTypeArchive
    (Statistics/Archive/Delete row). Their presence is a tree-shape delta between
    the plain Timers surface and the edit surface."""
    clear_data()                                             # noqa: F405
    launch_app()                                             # noqa: F405
    wait_for_foreground()                                    # noqa: F405
    make_activity("Reading")
    goto_tab("Timers")
    t = tile(ui(), "Reading")                                # noqa: F405
    if not t:
        record("structure_longpress_edit_shape", False,      # noqa: F405
               "setup_failed: 'Reading' tile not found",
               depth=1, jump_kind="transition",
               expect="edit-only action buttons appear after long-press")
    else:
        before = and_showing()                               # noqa: F405
        long_press(t)                                        # noqa: F405
        and_enter("edit_activity")                           # backs depth=1
        settle("nav")                                        # noqa: F405
        nodes = ui()                                          # noqa: F405
        after = and_showing(nodes)                           # noqa: F405
        # Edit variant markers absent from the Add variant.
        edit_only = (has_id(nodes, "btnChangeRecordTypeArchive")
                     and has_id(nodes, "btnChangeRecordTypeStatistics"))
        name_field = has_id(nodes, "etChangeRecordTypeName")
        changed = surface_changed(before, after, min_delta=3)  # noqa: F405
        ok = edit_only and name_field and changed
        record("structure_longpress_edit_shape", bool(ok),   # noqa: F405
               "" if ok else f"behavior_wrong: edit_buttons={edit_only} "
                             f"name_field={name_field} surface_changed={changed}",
               depth=1, jump_kind="transition",
               expect="btnChangeRecordTypeArchive + btnChangeRecordTypeStatistics "
                      "(edit-only) appear on the change screen after long-press")


@and_test(expects=("structure_icon_mode_shape",))
def test_icon_mode_shape():
    """Switching the icon picker's mode ICON->TEXT changes the grid's SHAPE in the
    dump: the icon image cells (ivIconSelectionItem x48) leave the tree and a text
    search field (etIconSelectionText) enters it. Switching back restores the icon
    grid. A dump-readable shape delta on a mode switch."""
    restart_app()                                            # noqa: F405
    wait_for_foreground()                                    # noqa: F405
    if open_add_screen() is None:
        record("structure_icon_mode_shape", False,           # noqa: F405
               "setup_failed: could not open the Add-activity screen",
               depth=1, jump_kind="transition",
               expect="icon image cells leave the tree in TEXT mode, restored in ICON")
    else:
        tap_node(node_by_id(ui(), "fieldChangeRecordTypeIcon"))  # noqa: F405
        settle("nav")                                        # noqa: F405
        settle("nav")                                        # noqa: F405
        icon_cells0 = count_id(ui(), "ivIconSelectionItem")  # noqa: F405
        has_search0 = has_id(ui(), "etIconSelectionText")    # noqa: F405
        tapped = tap_text(ui(), "TEXT")                      # noqa: F405
        settle("nav")                                        # noqa: F405
        settle("nav")                                        # noqa: F405
        if not tapped:
            record("structure_icon_mode_shape", False,       # noqa: F405
                   "feature_missing: TEXT mode button not found in the icon picker",
                   depth=1, jump_kind="transition",
                   expect="icon image cells leave the tree in TEXT mode, restored")
        else:
            text_nodes = ui()                                # noqa: F405
            cells_gone = count_id(text_nodes, "ivIconSelectionItem") == 0
            search_appeared = (has_id(text_nodes, "etIconSelectionText")
                               and not has_search0)
            # switch back to ICON and confirm the grid returns
            tap_text(ui(), "ICON")                           # noqa: F405
            settle("nav")                                    # noqa: F405
            settle("nav")                                    # noqa: F405
            restored = count_id(ui(), "ivIconSelectionItem") == icon_cells0  # noqa: F405
            ok = (icon_cells0 >= 20 and cells_gone and search_appeared
                  and restored)
            record("structure_icon_mode_shape", bool(ok),    # noqa: F405
                   "" if ok else f"behavior_wrong: icon cells {icon_cells0}->0? "
                                 f"gone={cells_gone} search_appeared={search_appeared} "
                                 f"restored={restored}",
                   depth=1, jump_kind="transition",
                   expect="ivIconSelectionItem (>=20) -> 0 with etIconSelectionText "
                          "added in TEXT mode; grid restored in ICON mode")


@and_test(expects=("structure_tabbar_row_vlm",))
def test_tabbar_row_vlm():
    """Spatial GATE the dump can confirm only loosely: the 4 tab icons form a
    single evenly-spaced horizontal row pinned to the bottom edge."""
    restart_app()                                            # noqa: F405
    wait_for_foreground()                                    # noqa: F405
    goto_tab("Timers")
    vlm_assert("structure_tabbar_row",                       # noqa: F405
               "At the very bottom of the screen, is there a horizontal navigation "
               "bar with exactly four evenly spaced icons in a single row?",
               RESULTS_DIR, depth=0, jump_kind="none", tag="position")


TESTS = [
    # GATE (existence, jump_kind="none") — 4
    test_gate_launch,
    test_gate_tabbar,
    test_gate_pager,
    test_gate_timers_list,
    # In-place Add-screen shape deltas — depth 1
    test_more_less_fields,
    test_color_expand,
    test_icon_expand,
    test_color_icon_exclusive,
    # Tab-switch shape deltas — depth 1
    test_tab_timers_to_settings,
    test_tab_settings_to_timers_shape,
    test_stats_chart_region_vlm,
    # In-page collapse/expand — depth 1
    test_settings_section_collapse,
    # Interaction-driven shape deltas — depth 1
    test_stats_populate_shape,
    test_records_populate_shape,
    test_longpress_edit_shape,
    test_icon_mode_shape,
    # Spatial tab bar (VLM) — depth 0
    test_tabbar_row_vlm,
]

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