File size: 34,280 Bytes
d292518
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""STRUCTURE lane — the GATE + tree-SHAPE deltas for DetoxDroid.

Owns two things only:
  1. The GATE — the app launches, is foreground, and its top-level home surfaces
     exist (chart region, InfoCard, feature-tile rows, FAB). jump_kind="none".
  2. Tree-SHAPE deltas — a user interaction changes the view tree's SHAPE (opens a
     feature detail, a number-picker dialog, the schedule bottom-sheet, search).
     Recorded as jump_kind="transition" via surface_changed()/count deltas, then
     REVERSED to assert the shape restores.

Content -> text, checked/state -> states, reachability -> navigation, values ->
computation, CRUD -> interaction. This file asserts SHAPE only.
"""
import os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from android_testgen_kit import *  # noqa: F403,E402

TESTS = []


def test(fn):
    TESTS.append(fn)
    return fn


# ── depth-backing navigation helpers (named and_enter_*/and_reach_* so the AST
#    depth audit sees a real backing call behind every declared depth>=1) ──────

def and_enter_feature(nodes, tile_text):
    """Open a feature detail by tapping its (title or subtitle) tile text, then
    confirm the detail scaffold appeared (a "Back" affordance). Counts 1 surface."""
    if not (tap_text(nodes, tile_text)):
        return False
    det = ui()
    ok = bool(find_node(det, content_desc="Back"))
    if ok:
        and_enter(tile_text)
    return ok


def and_enter_subscreen(content_desc):
    """From a feature detail, open a sub-surface (App Exceptions / Feature
    Schedule) by its tile content-desc. Confirms surface changed. Counts 1."""
    before = and_showing()
    n = find_node(ui(), content_desc=content_desc)
    if not (n and tap_node(n)):
        return False
    after = and_showing()
    if surface_changed(before, after):
        and_enter(content_desc)
        return True
    return False


def _activation_switch(nodes):
    """The feature-detail activation Switch: a checkable, clickable View in the
    top-right of the app bar (located by position, since Compose exposes no id)."""
    for n in nodes:
        b = n.get("_bounds")
        if (n.get("checkable") == "true" and b and b[0] > 700 and b[1] < 300):
            return n
    return None


# ══════════════════════════════════════════════════════════════════════════════
# 1. THE GATE — launch + top-level home surfaces exist (the one legit existence
#    test; jump_kind="none", depth=0). Everything else is a shape delta.
# ══════════════════════════════════════════════════════════════════════════════

@test
@and_test(expects=("structure_gate_launch", "structure_gate_home_layout_vlm"))
def test_gate_launch():
    restart_app()
    fg = wait_for_foreground()
    nodes = ui()
    # Top-level home surfaces: a main container host, the screen-time chart region,
    # the InfoCard text host, at least the first feature-tile rows, and the FAB.
    # This Compose app exposes its container as a FrameLayout/LinearLayout/
    # ComposeView spanning the window (not a literal "ViewGroup" class), so match
    # any real container host by class rather than an internal id.
    has_container = any(bool(find_by_class(nodes, c))
                        for c in ("FrameLayout", "LinearLayout", "ComposeView"))
    has_chart = any("Screen time today" in n.get("content-desc", "")
                    or "Screen time today" in n.get("text", "") for n in nodes)
    n_tiles = len(find_nodes(nodes, content_desc="Feature Icon"))
    has_open = bool(find_nodes(nodes, content_desc="Open feature settings"))
    has_fab = bool(find_node(nodes, content_desc="Run/Stop DetoxDroid"))
    ok = bool(fg and has_container and has_chart and n_tiles >= 3 and has_open and has_fab)
    msg = ""
    if not ok:
        if not fg:
            msg = "setup_failed: app did not reach the foreground"
        else:
            msg = ("feature_missing: home is missing a top-level surface "
                   f"(container={has_container} chart={has_chart} tiles={n_tiles} "
                   f"open_settings={has_open} fab={has_fab})")
    record("structure_gate_launch", ok, msg, depth=0, jump_kind="none")
    vlm_assert("structure_gate_home_layout",
               "Does this screen show a large circular donut/ring chart near the "
               "top with a vertical list of rows below it?",
               RESULTS_DIR, depth=0, jump_kind="none", tag="shape")


@test
@and_test(expects=("structure_gate_fab_position_vlm",))
def test_gate_fab_position():
    # Existence-class VLM: the FAB is a rendered affordance, not dump-readable as a
    # position. Home only.
    restart_app()
    wait_for_foreground()
    ui()
    vlm_assert("structure_gate_fab_position",
               "Is there a floating action button (a pill/rounded button) anchored "
               "in the bottom area of the screen?",
               RESULTS_DIR, depth=0, jump_kind="none", tag="position")


# ══════════════════════════════════════════════════════════════════════════════
# 2. SHAPE DELTA — tapping a feature tile flips home-list shape -> detail shape.
#    depth=1 (one surface crossed), transition, reversed via and_back().
# ══════════════════════════════════════════════════════════════════════════════

@test
@and_test(expects=("structure_open_feature_shape", "structure_feature_appbar_vlm"))
def test_open_feature_changes_shape():
    restart_app()
    wait_for_foreground()
    before = and_showing()
    home_fab_before = bool(find_node(ui(), content_desc="Run/Stop DetoxDroid"))
    entered = and_enter_feature(ui(), "Automatic Grayscale")
    after = and_showing()
    det = ui()
    # SHAPE delta: home FAB layer gone, a detail-only "Back" affordance appeared,
    # and the surface changed materially.
    fab_gone = not bool(find_node(det, content_desc="Run/Stop DetoxDroid"))
    has_back = bool(find_node(det, content_desc="Back"))
    changed = surface_changed(before, after)
    # Reverse: back should restore the home shape (FAB layer returns).
    and_back()
    restored = bool(find_node(ui(), content_desc="Run/Stop DetoxDroid"))
    ok = bool(entered and home_fab_before and changed and fab_gone and has_back and restored)
    msg = ""
    if not ok:
        msg = ("behavior_wrong: tapping a feature tile did not flip home->detail "
               f"shape (changed={changed} fab_gone={fab_gone} back={has_back} "
               f"restored={restored})")
    record("structure_open_feature_shape", ok, msg, depth=1, jump_kind="transition",
           expect="home FAB layer replaced by detail scaffold (Back) on open, "
                  "restored on back")
    # VLM on the detail app-bar (drive back into detail for the screenshot).
    restart_app(); wait_for_foreground()
    and_enter_feature(ui(), "Automatic Grayscale")
    vlm_assert("structure_feature_appbar",
               "Is there a back arrow in the top-left corner and a toggle switch "
               "in the top-right corner of the app bar?",
               RESULTS_DIR, depth=1, jump_kind="transition", tag="position")


# ══════════════════════════════════════════════════════════════════════════════
# 3. SHAPE DELTA — the feature-detail BODY is richer than a bare screen:
#    InfoCard + a column of setting tiles (activation switch + >=2 checkboxes).
#    depth=1, transition (home shape -> populated detail body).
# ══════════════════════════════════════════════════════════════════════════════

@test
@and_test(expects=("structure_detail_body_shape",))
def test_detail_body_shape():
    restart_app()
    wait_for_foreground()
    home_showing = len(and_showing())
    entered = and_enter_feature(ui(), "Automatic Grayscale")
    det = ui()
    det_showing = len(and_showing(det))
    # Grayscale detail body: activation switch (top-right checkable View) + at
    # least two setting CheckBoxes (Extra Dim, Ignore Non-Fullscreen) + the two
    # sub-screen tiles. A bare shell would have none of this structure.
    has_switch = bool(_activation_switch(det))
    n_checkboxes = len(find_by_class(det, "CheckBox"))
    has_scope = bool(find_node(det, content_desc="Manage App Scope"))
    has_sched = bool(find_node(det, content_desc="Manage Schedule"))
    ok = bool(entered and has_switch and n_checkboxes >= 2 and has_scope
              and has_sched and det_showing != home_showing)
    msg = ""
    if not ok:
        msg = ("behavior_wrong: detail body lacks the expected shape "
               f"(switch={has_switch} checkboxes={n_checkboxes} scope={has_scope} "
               f"sched={has_sched})")
    record("structure_detail_body_shape", ok, msg, depth=1, jump_kind="transition",
           expect="Grayscale body = activation switch + >=2 setting checkboxes + "
                  "App-Scope & Schedule tiles")


# ══════════════════════════════════════════════════════════════════════════════
# 4. SHAPE DELTA — opening the NumberPickerDialog swaps in a picker layer
#    (Cancel/Save appear), reversed via Cancel. depth=2 (detail + dialog).
# ══════════════════════════════════════════════════════════════════════════════

@test
@and_test(expects=("structure_picker_dialog_shape", "structure_picker_dialog_vlm"))
def test_picker_dialog_shape():
    restart_app()
    wait_for_foreground()
    entered = and_enter_feature(ui(), "Automatic Grayscale")
    before = and_showing()
    # Open the picker via the "Allowed Daily Color Screen Time" tile.
    n = find_node(ui(), text="Allowed Daily Color Screen Time")
    opened = bool(n and tap_node(n))
    if opened:
        and_enter("picker")
    after = and_showing()
    dlg = ui()
    has_buttons = bool(find_node(dlg, text="Save")) and bool(find_node(dlg, text="Cancel"))
    changed = surface_changed(before, after)
    # New keys the picker layer adds (Save/Cancel absent from the detail).
    added_picker = any("save" in k.lower() for k in (after - before))
    # Reverse: Cancel restores the detail body (its tile is back, picker gone).
    tap_text(ui(), "Cancel")
    restored = (not find_node(ui(), text="Save")) and bool(
        find_node(ui(), text="App Exceptions"))
    ok = bool(entered and opened and changed and has_buttons and added_picker and restored)
    msg = ""
    if not ok:
        msg = ("behavior_wrong: picker layer did not appear/restore "
               f"(changed={changed} buttons={has_buttons} restored={restored})")
    record("structure_picker_dialog_shape", ok, msg, depth=2, jump_kind="transition",
           expect="picker layer adds Cancel/Save over the detail, restored on Cancel")
    # VLM on the picker (drive back into detail+picker for the screenshot).
    restart_app(); wait_for_foreground()
    and_enter_feature(ui(), "Automatic Grayscale")
    p = find_node(ui(), text="Allowed Daily Color Screen Time")
    if p:
        tap_node(p)
        and_enter("picker")
    vlm_assert("structure_picker_dialog",
               "Is a modal picker showing a vertical number wheel (values like "
               "'0 min'/'15 min') with Cancel and Save buttons at the bottom?",
               RESULTS_DIR, depth=2, jump_kind="transition", tag="shape")


# ══════════════════════════════════════════════════════════════════════════════
# 5. SHAPE DELTA — opening the Schedule bottom-sheet adds a sheet LAYER
#    (node count grows, "Close sheet"/"Drag handle" appear), reversed by
#    dismissing the scrim. depth=2 (detail via Schedule tile + sheet).
# ══════════════════════════════════════════════════════════════════════════════

@test
@and_test(expects=("structure_schedule_sheet_shape", "structure_schedule_sheet_vlm"))
def test_schedule_sheet_shape():
    restart_app()
    wait_for_foreground()
    entered = and_enter_feature(ui(), "Automatic Grayscale")
    into_sched = and_enter_subscreen("Manage Schedule")
    before = and_showing()
    cnt_before = len(ui())
    add = find_node(ui(), content_desc="Add")
    opened = bool(add and tap_node(add))
    if opened:
        and_enter("sheet")
    after = and_showing()
    sheet = ui()
    cnt_after = len(sheet)
    has_handle = bool(find_node(sheet, content_desc="Close sheet")) or bool(
        find_node(sheet, content_desc="Drag handle"))
    grew = cnt_after > cnt_before
    changed = surface_changed(before, after)
    # Reverse: dismiss the sheet via the "Close sheet" scrim (tap its top strip,
    # which is inert), sheet layer should disappear.
    scrim = find_node(ui(), content_desc="Close sheet")
    if scrim and "_center" in scrim:
        tap(scrim["_center"][0], 200)
        settle("tap")
    restored = not bool(find_node(ui(), content_desc="Close sheet"))
    ok = bool(entered and into_sched and opened and grew and changed
              and has_handle and restored)
    msg = ""
    if not ok:
        msg = ("behavior_wrong: schedule sheet layer did not appear/restore "
               f"(grew={grew} changed={changed} handle={has_handle} "
               f"restored={restored})")
    record("structure_schedule_sheet_shape", ok, msg, depth=2, jump_kind="transition",
           expect="Add opens a bottom-sheet layer (Close sheet/Drag handle; node "
                  "count grows), restored on dismiss")
    # VLM on the sheet.
    restart_app(); wait_for_foreground()
    and_enter_feature(ui(), "Automatic Grayscale")
    and_enter_subscreen("Manage Schedule")
    a2 = find_node(ui(), content_desc="Add")
    if a2:
        tap_node(a2)
        and_enter("sheet")
    vlm_assert("structure_schedule_sheet",
               "Did a bottom sheet slide up from the bottom of the screen showing "
               "'From' and 'To' time fields and a Save button?",
               RESULTS_DIR, depth=2, jump_kind="transition", tag="position")


# ══════════════════════════════════════════════════════════════════════════════
# 6. SHAPE DELTA — opening Search in App Exceptions adds an EditText layer
#    (0 -> 1 EditText, "Close Search" appears), reversed via Close Search.
#    depth=2 (detail via App-Scope tile + search-open state).
# ══════════════════════════════════════════════════════════════════════════════

@test
@and_test(expects=("structure_search_edittext_shape",))
def test_search_edittext_shape():
    restart_app()
    wait_for_foreground()
    entered = and_enter_feature(ui(), "Automatic Grayscale")
    into_exc = and_enter_subscreen("Manage App Scope")
    edits_before = len(find_by_class(ui(), "EditText"))
    srch = find_node(ui(), content_desc="Search")
    opened = bool(srch and tap_node(srch))
    edits_after = len(find_by_class(ui(), "EditText"))
    has_close = bool(find_node(ui(), content_desc="Close Search"))
    # SHAPE delta: exactly one EditText layer appears.
    added = edits_after == edits_before + 1
    # Reverse: Close Search removes the EditText layer.
    close = find_node(ui(), content_desc="Close Search")
    if close:
        tap_node(close)
    edits_restored = len(find_by_class(ui(), "EditText"))
    restored = (edits_restored == edits_before) and bool(
        find_node(ui(), content_desc="Search"))
    ok = bool(entered and into_exc and opened and added and has_close and restored)
    msg = ""
    if not ok:
        msg = ("behavior_wrong: search EditText layer did not appear/restore "
               f"(before={edits_before} after={edits_after} close={has_close} "
               f"restored={restored})")
    record("structure_search_edittext_shape", ok, msg, depth=2, jump_kind="transition",
           expect="Search adds exactly one EditText (0->1) + Close Search, "
                  "restored to 0 on close")


# ══════════════════════════════════════════════════════════════════════════════
# 7. SHAPE DELTA — App Exceptions body is populated (scope OptionsRow + an app
#    row with a trailing checkbox), a richer shape than a bare list.
#    depth=2 (detail + App Exceptions subscreen).
# ══════════════════════════════════════════════════════════════════════════════

@test
@and_test(expects=("structure_app_exceptions_shape",))
def test_app_exceptions_shape():
    restart_app()
    wait_for_foreground()
    entered = and_enter_feature(ui(), "Automatic Grayscale")
    into_exc = and_enter_subscreen("Manage App Scope")
    exc = ui()
    # Body shape: the scope OptionsRow (two checkable Views in the top card) + at
    # least one app-row CheckBox lower down + Search/Filter toolbar affordances.
    scope_options = [n for n in exc if n.get("checkable") == "true"
                     and n.get("_bounds") and n["_bounds"][1] < 700]
    app_row_cbs = [n for n in find_by_class(exc, "CheckBox")
                   if n.get("_bounds") and n["_bounds"][1] > 700]
    has_search = bool(find_node(exc, content_desc="Search"))
    has_filter = bool(find_node(exc, content_desc="Filter"))
    ok = bool(entered and into_exc and len(scope_options) >= 2
              and len(app_row_cbs) >= 1 and has_search and has_filter)
    msg = ""
    if not ok:
        msg = ("behavior_wrong: App Exceptions body lacks the expected shape "
               f"(scope_options={len(scope_options)} app_rows={len(app_row_cbs)} "
               f"search={has_search} filter={has_filter})")
    record("structure_app_exceptions_shape", ok, msg, depth=2, jump_kind="transition",
           expect="scope OptionsRow (>=2 options) + >=1 app-row checkbox + "
                  "Search/Filter toolbar")


# ══════════════════════════════════════════════════════════════════════════════
# 8. SHAPE — Commitment Password screen: a vertical column of feature rows each
#    with a trailing checkbox (5 checkboxes). depth=1, transition + VLM.
# ══════════════════════════════════════════════════════════════════════════════

@test
@and_test(expects=("structure_commitment_checkbox_column", "structure_commitment_column_vlm"))
def test_commitment_checkbox_column():
    restart_app()
    wait_for_foreground()
    scroll_into_view("Lock settings with a passphrase")
    entered = and_enter_feature(ui(), "Lock settings with a passphrase")
    scr = ui()
    # SHAPE: a column of 5 feature checkboxes, all right-aligned (x-center > 700),
    # plus All/None controls.
    cbs = find_by_class(scr, "CheckBox")
    right_cbs = [n for n in cbs if "_center" in n and n["_center"][0] > 700]
    has_all = bool(find_node(scr, text="All"))
    has_none = bool(find_node(scr, text="None"))
    ok = bool(entered and len(right_cbs) == 5 and has_all and has_none)
    msg = ""
    if not ok:
        msg = ("behavior_wrong: commitment screen lacks a 5-checkbox column "
               f"(right_checkboxes={len(right_cbs)} all={has_all} none={has_none})")
    record("structure_commitment_checkbox_column", ok, msg, depth=1,
           jump_kind="transition",
           expect="vertical column of 5 right-aligned feature checkboxes + All/None")
    vlm_assert("structure_commitment_column",
               "Is there a vertical list of feature rows where every row has a "
               "checkbox aligned in a single column down the RIGHT edge?",
               RESULTS_DIR, depth=1, jump_kind="transition", tag="position")


# ══════════════════════════════════════════════════════════════════════════════
# 9. SHAPE — Disable Apps: Operation Mode segmented row (two side-by-side
#    checkable options). depth=1, transition + VLM (position).
# ══════════════════════════════════════════════════════════════════════════════

@test
@and_test(expects=("structure_disable_apps_optionsrow", "structure_disable_optionsrow_vlm"))
def test_disable_apps_optionsrow():
    restart_app()
    wait_for_foreground()
    entered = and_enter_feature(ui(), "Disable Apps")
    scr = ui()
    # SHAPE: an OptionsRow = two checkable Views on the SAME row (similar y), one
    # per segment (Block / Deactivate).
    seg = [n for n in scr if n.get("checkable") == "true" and n.get("clickable") == "true"
           and "_center" in n]
    same_row = False
    if len(seg) >= 2:
        ys = sorted(n["_center"][1] for n in seg)
        # two segments share a row if their centers are within ~40px vertically
        for i in range(len(ys) - 1):
            if abs(ys[i] - ys[i + 1]) < 40:
                same_row = True
                break
    has_block = bool(find_node(scr, text="Block"))
    has_deact = bool(find_node(scr, text="Deactivate"))
    ok = bool(entered and len(seg) >= 2 and same_row and has_block and has_deact)
    msg = ""
    if not ok:
        msg = ("behavior_wrong: Operation Mode segmented row not found "
               f"(segments={len(seg)} same_row={same_row} block={has_block} "
               f"deactivate={has_deact})")
    record("structure_disable_apps_optionsrow", ok, msg, depth=1,
           jump_kind="transition",
           expect="Operation Mode = two side-by-side checkable segments Block/Deactivate")
    vlm_assert("structure_disable_optionsrow",
               "Near the bottom, are there two selectable options placed "
               "side-by-side on the same horizontal row (a segmented control)?",
               RESULTS_DIR, depth=1, jump_kind="transition", tag="position")


# ══════════════════════════════════════════════════════════════════════════════
# 10. SHAPE DELTA — opening the About screen swaps the home shape for an About
#     shape (home FAB gone, About-only rows appear). depth=1, transition + VLM.
# ══════════════════════════════════════════════════════════════════════════════

@test
@and_test(expects=("structure_about_shape", "structure_about_list_vlm"))
def test_about_shape():
    restart_app()
    wait_for_foreground()
    scroll_into_view("About")
    before = and_showing()
    home_fab = bool(find_node(ui(), content_desc="Run/Stop DetoxDroid"))
    entered = and_enter_feature(ui(), "About")
    after = and_showing()
    ab = ui()
    # About shape: header block + a column of tappable rows; the home FAB layer is
    # gone. Count TextViews to prove the body populated (>= several rows).
    fab_gone = not bool(find_node(ab, content_desc="Run/Stop DetoxDroid"))
    n_text = len(find_by_class(ab, "TextView"))
    changed = surface_changed(before, after)
    # Reverse restores home.
    and_back()
    restored = bool(find_node(ui(), content_desc="Run/Stop DetoxDroid"))
    ok = bool(entered and home_fab and changed and fab_gone and n_text >= 8 and restored)
    msg = ""
    if not ok:
        msg = ("behavior_wrong: About did not replace home shape "
               f"(changed={changed} fab_gone={fab_gone} text_rows={n_text} "
               f"restored={restored})")
    record("structure_about_shape", ok, msg, depth=1, jump_kind="transition",
           expect="About replaces home FAB layer with a header + multi-row list, "
                  "restored on back")
    # VLM on the About list.
    restart_app(); wait_for_foreground()
    scroll_into_view("About")
    and_enter_feature(ui(), "About")
    vlm_assert("structure_about_list",
               "Below a centered title/version header, is there a vertical list of "
               "several tappable text rows stacked one above another?",
               RESULTS_DIR, depth=1, jump_kind="transition", tag="layout")


# ══════════════════════════════════════════════════════════════════════════════
# 11. SHAPE DELTA — opening the Logs screen swaps home shape for a scrollable log
#     list (home FAB gone, many rows). depth=1, transition + VLM.
# ══════════════════════════════════════════════════════════════════════════════

@test
@and_test(expects=("structure_logs_list_shape", "structure_logs_list_vlm"))
def test_logs_list_shape():
    restart_app()
    wait_for_foreground()
    before = and_showing()
    logs_icon = find_node(ui(), content_desc="View Logs")
    opened = bool(logs_icon and tap_node(logs_icon))
    if opened:
        and_enter("logs")
    after = and_showing()
    lg = ui()
    fab_gone = not bool(find_node(lg, content_desc="Run/Stop DetoxDroid"))
    has_back = bool(find_node(lg, content_desc="Back"))
    n_text = len(find_by_class(lg, "TextView"))
    changed = surface_changed(before, after)
    # Reverse restores home.
    and_back()
    restored = bool(find_node(ui(), content_desc="Run/Stop DetoxDroid"))
    # Logs is a populated list (many TextViews) in this DEBUG build.
    ok = bool(opened and changed and fab_gone and has_back and n_text >= 8 and restored)
    msg = ""
    if not ok:
        msg = ("behavior_wrong: Logs did not open as a list shape "
               f"(changed={changed} fab_gone={fab_gone} back={has_back} "
               f"text_rows={n_text} restored={restored})")
    record("structure_logs_list_shape", ok, msg, depth=1, jump_kind="transition",
           expect="View Logs replaces home with a Back-scaffold list of many rows, "
                  "restored on back")
    # VLM on the logs list.
    restart_app(); wait_for_foreground()
    li = find_node(ui(), content_desc="View Logs")
    if li:
        tap_node(li)
        and_enter("logs")
    vlm_assert("structure_logs_list",
               "Does this screen show a densely packed vertical list of many small "
               "text log entries filling most of the screen?",
               RESULTS_DIR, depth=1, jump_kind="transition", tag="size")


# ══════════════════════════════════════════════════════════════════════════════
# 12-14. SHAPE DELTA across other feature details — each opens from home and grows
#     a distinct populated body (DND / Disable Apps / Pause), reversed via back.
#     These prove the tree SHAPE flips per feature, not just a pixel shell.
# ══════════════════════════════════════════════════════════════════════════════

@test
@and_test(expects=("structure_dnd_open_shape",))
def test_dnd_open_shape():
    restart_app()
    wait_for_foreground()
    before = and_showing()
    entered = and_enter_feature(ui(), "Make it your new default")
    after = and_showing()
    det = ui()
    has_switch = bool(_activation_switch(det))
    has_sched = bool(find_node(det, content_desc="Manage Schedule"))
    changed = surface_changed(before, after)
    and_back()
    restored = bool(find_node(ui(), content_desc="Run/Stop DetoxDroid"))
    ok = bool(entered and changed and has_switch and has_sched and restored)
    msg = ""
    if not ok:
        msg = ("behavior_wrong: DND detail shape not as expected "
               f"(changed={changed} switch={has_switch} sched={has_sched} "
               f"restored={restored})")
    record("structure_dnd_open_shape", ok, msg, depth=1, jump_kind="transition",
           expect="DND detail = activation switch + Schedule tile, restored on back")


@test
@and_test(expects=("structure_disable_open_shape",))
def test_disable_open_shape():
    restart_app()
    wait_for_foreground()
    before = and_showing()
    entered = and_enter_feature(ui(), "Disable Apps")
    after = and_showing()
    det = ui()
    has_switch = bool(_activation_switch(det))
    has_scope = bool(find_node(det, content_desc="Manage App Scope"))
    changed = surface_changed(before, after)
    and_back()
    restored = bool(find_node(ui(), content_desc="Run/Stop DetoxDroid"))
    ok = bool(entered and changed and has_switch and has_scope and restored)
    msg = ""
    if not ok:
        msg = ("behavior_wrong: Disable Apps detail shape not as expected "
               f"(changed={changed} switch={has_switch} scope={has_scope} "
               f"restored={restored})")
    record("structure_disable_open_shape", ok, msg, depth=1, jump_kind="transition",
           expect="Disable Apps detail = activation switch + Manage-App-Scope tile, "
                  "restored on back")


@test
@and_test(expects=("structure_pause_open_shape",))
def test_pause_open_shape():
    restart_app()
    wait_for_foreground()
    scroll_into_view("Take intentional breaks")
    before = and_showing()
    entered = and_enter_feature(ui(), "Take intentional breaks")
    after = and_showing()
    det = ui()
    has_switch = bool(_activation_switch(det))
    # Pause body has the "Pause Duration" and "Minimum Time Between Pauses" tiles.
    has_duration = bool(find_node(det, text="Pause Duration"))
    changed = surface_changed(before, after)
    and_back()
    restored = bool(find_node(ui(), content_desc="Run/Stop DetoxDroid")) or bool(
        find_node(ui(), content_desc="Feature Icon"))
    ok = bool(entered and changed and has_switch and has_duration and restored)
    msg = ""
    if not ok:
        msg = ("behavior_wrong: Pause detail shape not as expected "
               f"(changed={changed} switch={has_switch} duration={has_duration} "
               f"restored={restored})")
    record("structure_pause_open_shape", ok, msg, depth=1, jump_kind="transition",
           expect="Pause detail = activation switch + Pause Duration tile, "
                  "restored on back")


# ══════════════════════════════════════════════════════════════════════════════
# 15. SHAPE DELTA — Break Infinite Scrolling detail opens with its own body
#     (activation switch + App-Scope tile), reversed via back. depth=1.
# ══════════════════════════════════════════════════════════════════════════════

@test
@and_test(expects=("structure_doomscroll_open_shape",))
def test_doomscroll_open_shape():
    restart_app()
    wait_for_foreground()
    before = and_showing()
    entered = and_enter_feature(ui(), "Break Infinite Scrolling")
    after = and_showing()
    det = ui()
    has_switch = bool(_activation_switch(det))
    has_scope = bool(find_node(det, content_desc="Manage App Scope"))
    changed = surface_changed(before, after)
    and_back()
    restored = bool(find_node(ui(), content_desc="Run/Stop DetoxDroid"))
    ok = bool(entered and changed and has_switch and has_scope and restored)
    msg = ""
    if not ok:
        msg = ("behavior_wrong: Break Infinite Scrolling detail shape not as "
               f"expected (changed={changed} switch={has_switch} scope={has_scope} "
               f"restored={restored})")
    record("structure_doomscroll_open_shape", ok, msg, depth=1, jump_kind="transition",
           expect="Doomscroll detail = activation switch + App-Scope tile, "
                  "restored on back")


if __name__ == "__main__":
    if not device_online():
        print("WARNING: device offline — every test will record setup_failed")
    run_suite(TESTS, "structure")