File size: 39,002 Bytes
41dfd8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
#!/usr/bin/env python3
"""INTERACTION module — FastTimes (intermittent-fasting tracker).

Owns EFFECT-BY-CONSEQUENCE on user DATA: CRUD lifecycle (create a fast / a
profile and read it back), multi-step sequences (3+ dependent actions), multi-
record integrity (N records survive a mutation to one), long-press context menus
(SOLE owner), and — the highest-value assertion — DATA persistence across process
death. Every test drives the running original through the real user path, then
reads the consequence out of a FRESH ui() and asserts it equals what was observed.

CEDES to sibling lanes: a toggle's checked bit / settings persistence -> states;
a computed value -> computation; the exact label wording -> text; whether a screen
is reachable -> navigation; view-tree shape -> structure.

Data model (verified live on the original):
  * A completed fast is a HISTORY record: start the debug "Test Timer" goal cell
    (a 10-second fast), wait ~11s for "Goal Reached!", tap "End Fast" -> the
    "Fast Complete!" summary modal (5 clickable star Views + Save) -> Save. The
    Dashboard "Fasts" count increments and the fast lands in History (Room DB) and
    survives process death.
  * A profile is created from Manage Profiles -> "Add Profile" FAB -> a dialog with
    3 EditText (Profile Name / Description / Duration) + Save; the new card appears
    in "Other Profiles". Save's clickable parent is disabled until a name is typed.
  * Long-pressing a profile card reveals an "Edit | Favourite | Delete" button
    group; "Favourite" moves the card into the "Favourite Fast" section.

Compose renders as android.view.View / TextView with NO resource-ids, so every
target and every read-back key is a visible text / content-desc / a clickable View
located by bounds.

VLM budget for this lane = 8 (visual DATA states unreadable from the dump): the
summary-modal 4-filled-star row, the Daily-Details 4-green-star rating, the
Edit-Fast 4-green-star rating, the long-press outlined card, the populated
Favourite Fast card, the newly created profile card in the grid, the running
active-fast ring after a process kill, and the multi-record history list.

SAFETY: never taps "Delete" / "Delete Fast" (destructive); every exploratory tap
goes through safe_tap(). The Add Profile dialog is Compose and dismisses on an
outside-tap / BACK, so the kit's hide_keyboard() would close it — this module
therefore taps the dialog's Save control DIRECTLY with the keyboard up (verified),
and never sends a raw ESCAPE keyevent.

Run:  python3 test_android_interaction.py <PACKAGE> <RESULTS_DIR>
"""
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)

RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else RESULTS_DIR  # noqa: F405

MARK = "kitprofZ"          # distinctive marker for a created profile record


# ── Portable launcher (LeakCanary registers a 2nd LAUNCHER activity; monkey opens
# it ~half the time). Resolve THIS package's real MainActivity at runtime. ──────
def _main_component():
    out = adb_shell("cmd", "package", "query-activities", "--brief",
                    "-a", "android.intent.action.MAIN",
                    "-c", "android.intent.category.LAUNCHER")
    cands = [l.strip() for l in out.splitlines() if (PACKAGE + "/") in l]
    good = [c for c in cands if "leakcanary" not in c.lower()]
    return (good or cands or [""])[0]


def open_main():
    """Force-stop then launch the REAL MainActivity (never LeakCanary)."""
    force_stop()
    comp = _main_component()
    if comp:
        adb_shell("am", "start", "-n", comp)
    else:
        launch_app()
    settle("launch")
    wait_for_foreground()
    if "leakcanary" in get_current_activity().lower() and comp:
        adb_shell("am", "start", "-n", comp)
        settle("launch")


def open_main_clear():
    """Virgin state: wipe data (no active fast, empty history), then open Main."""
    clear_data()
    open_main()


def kill_and_reopen():
    """Process-death probe WITHOUT monkey: force-stop the app, then relaunch the
    real MainActivity. An in-memory-only recreation cannot survive this."""
    force_stop()
    settle("key")
    open_main()


# ── Domain helpers ───────────────────────────────────────────────────────────
def _dismiss_notif_rationale():
    """The first-run "Notification Preferences" rationale appears on the first goal
    tap after clear_data(). Dismiss it with a NON-destructive choice (the choice is
    irrelevant to the data operations under test). Returns True if it was shown."""
    nodes = ui()
    if not find_node(nodes, text="Notification Preferences"):
        return False
    for label in ("No Notifications", "Skip", "Not Now", "Enable Notifications"):
        n = find_node(nodes, text=label)
        if n and is_safe(n):
            tap_node(n)
            settle("tap")
            return True
    return False


def _on_dashboard(nodes=None):
    nodes = ui() if nodes is None else nodes
    return find_node(nodes, text="Set your goal") is not None


def _fasts_count(nodes=None):
    """Read the integer under the Dashboard 'Fasts' stat blob (the record count).
    Returns int or None. The number TextView sits directly below the 'Fasts' label
    and roughly x-aligned with it."""
    nodes = ui() if nodes is None else nodes
    lbl = find_node(nodes, text="Fasts")
    if not lbl or "_bounds" not in lbl:
        return None
    lx = lbl["_center"][0]
    ly2 = lbl["_bounds"][3]
    best = None
    for n in nodes:
        t = n.get("text", "").strip()
        b = n.get("_bounds")
        if not b or not t.isdigit():
            continue
        if b[1] > ly2 and (b[1] - ly2) < 160 and abs(n["_center"][0] - lx) < 140:
            if best is None or b[1] < best[1]:
                best = (int(t), b[1])
    return best[0] if best else None


def _start_goal(cell_text):
    """From a CLEAN dashboard, tap a goal cell by its name and land on the
    ACTIVE-FAST card (desc='End Fast'). Handles the first-run notification
    rationale. Returns True on success."""
    cell = find_node(ui(), text=cell_text)
    if not cell:
        return False
    tap_node(cell)
    settle("tap")
    _dismiss_notif_rationale()
    if find_node(ui(), content_desc="End Fast"):
        return True
    # the rationale dialog may have consumed the first tap; retry the cell once
    cell = find_node(ui(), text=cell_text)
    if cell:
        tap_node(cell)
        settle("tap")
        _dismiss_notif_rationale()
    return find_node(ui(), content_desc="End Fast") is not None


def _wait_goal_reached(polls=16):
    """Poll until the Test Timer flips to 'Goal Reached!' (~11s). Bounded so a slow
    emulator never hangs the suite. Returns whether it flipped."""
    for _ in range(polls):
        if find_node(ui(), text="Goal Reached!"):
            return True
        settle("tap")
    return False


def _modal_star_views():
    """The 5 clickable rating stars in the 'Fast Complete!' summary modal: they are
    empty-text clickable android.view.View nodes laid out in ONE horizontal row
    (near-square, same y-band). Returned x-sorted, so index 3 == the 4th star."""
    nodes = ui()
    clk = [n for n in nodes
           if n.get("class", "").endswith("view.View")
           and n.get("clickable") == "true"
           and not n.get("text", "").strip()
           and not n.get("content-desc", "").strip()
           and "_bounds" in n]
    # keep only near-square cells (a star), then the most populous single y-row
    stars = []
    for n in clk:
        x1, y1, x2, y2 = n["_bounds"]
        w, h = x2 - x1, y2 - y1
        if w < 40 or h < 40:
            continue
        if 0.6 <= w / h <= 1.7:
            stars.append(n)
    if len(stars) < 5:
        return []
    # group by y-centre band; pick the band with the most members (the star row)
    stars.sort(key=lambda n: n["_center"][1])
    rows, cur = [], [stars[0]]
    for n in stars[1:]:
        if abs(n["_center"][1] - cur[-1]["_center"][1]) <= 30:
            cur.append(n)
        else:
            rows.append(cur)
            cur = [n]
    rows.append(cur)
    row = max(rows, key=len)
    row.sort(key=lambda n: n["_center"][0])
    return row


def _tap_summary_save():
    """Tap 'Save' in the summary modal. 'Save' is a non-clickable TextView; its
    centre lies inside the clickable parent View, so tapping the text centre works.
    """
    n = find_node(ui(), text="Save")
    return tap_node(n) if n else False


def save_test_timer_fast():
    """Complete + SAVE one Test Timer fast from a clean dashboard (rating it 4
    stars), landing back on the Dashboard with the fast persisted. Returns True on
    success."""
    if not _start_goal("Test Timer"):
        return False
    _wait_goal_reached()
    ef = find_node(ui(), content_desc="End Fast")
    if not ef:
        return False
    tap_node(ef)
    settle("tap")
    stars = _modal_star_views()
    if len(stars) >= 4:
        tap_node(stars[3])                    # 4th star
        settle("tap")
    if not _tap_summary_save():
        return False
    settle("tap")
    return _on_dashboard()


def open_history_via_link():
    """Dashboard -> History pane via the 'Go to History' arrow. Returns True when
    the month header is showing."""
    n = find_node(ui(), content_desc="Go to History")
    if not n:
        return False
    tap_node(n)
    settle("tap")
    return find_node(ui(), text="August 2026") is not None


def open_daily_details_day5():
    """From the History pane, open day-5's Daily Details bottom sheet (day 5 holds
    the saved fast). Returns True when the sheet is showing."""
    nodes = ui()
    day = find_node(nodes, text="5")
    marker = find_node(nodes, content_desc="Goal Met")
    if day and marker and "_center" in day and "_center" in marker:
        x = (day["_center"][0] + marker["_center"][0]) // 2
        y = (day["_center"][1] + marker["_center"][1]) // 2
        tap(x, y)
    elif marker:
        tap_node(marker)
    elif day:
        tap_node(day)
    else:
        return False
    return any("details for" in k.lower() for k in and_showing())


def _tap_enabled_dialog_save():
    """Tap 'Save' in an in-place dialog (Add Profile), robustly and WITHOUT
    dismissing the dialog. 'Save' is a non-clickable TextView whose ENABLED
    clickable parent must be tapped; that parent is enabled=false until a name is
    entered. The kit's hide_keyboard() would close this Compose dialog (outside-tap
    / BACK), so this tolerates the keyboard being up: it re-dumps for fresh
    (keyboard-shifted) bounds, then taps the SMALLEST enabled clickable View that
    contains the 'Save' text centre. Returns True only when it tapped an ENABLED
    Save control."""
    d = ui()
    save = find_node(d, text="Save")
    if not save or "_center" not in save:
        return False
    sx, sy = save["_center"]
    best = None
    for n in d:
        if (n.get("clickable") == "true" and n.get("enabled") == "true"
                and "_bounds" in n):
            x1, y1, x2, y2 = n["_bounds"]
            if x1 <= sx <= x2 and y1 <= sy <= y2:
                area = (x2 - x1) * (y2 - y1)
                if best is None or area < best[0]:
                    best = (area, ((x1 + x2) // 2, (y1 + y2) // 2))
    if best is None:
        return False                 # Save present but its clickable parent disabled
    tap(*best[1])
    settle("tap")
    return True


# ── Named depth helpers (the and_enter_*/and_reach_* NAME backs a depth>=1 claim;
# each body is a real, proven jump). ───────────────────────────────────────────
def and_reach_profiles():
    """Dashboard -> Manage Profiles. Proven: 'Other Profiles' appears, the goal card
    'Set your goal' vanishes. Counts one surface (jump_kind='reach')."""
    n = find_node(ui(), text="Manage Profiles") or find_node_ci(ui(), "Manage Profiles")
    if not n:
        return False
    return and_reach_surface(n, "Other Profiles", "Set your goal")


def and_enter_add_profile_dialog():
    """Manage Profiles -> the 'Add Profile' dialog (a new window layer with 3
    EditText). Counts one surface (depth+1)."""
    n = find_node(ui(), content_desc="Add Profile")
    if not n or not tap_node(n):
        return False
    if len(find_by_class(ui(), "EditText")) < 3:
        return False
    and_enter("Add Profile dialog")
    return True


def and_reach_daily_details():
    """History pane -> Daily Details sheet for day 5. Counts one surface."""
    before = and_showing()
    if not open_daily_details_day5():
        return False
    after = and_showing()
    ok = and_reach(before, after, "Details for", "August 2026")
    if ok:
        and_enter("Daily Details")
    return ok


def and_reach_edit_fast():
    """Daily Details sheet -> Edit Fast dialog (pencil). Counts one surface."""
    n = find_node(ui(), content_desc="Edit Fast")
    if not n:
        return False
    return and_reach_surface(n, "Start Time", "Details for")


def long_press_profile(name_or_duration):
    """Long-press a profile card body -> the 'Edit | Favourite | Delete' button
    group. Returns True when the menu appears. SOLE-OWNER long-press."""
    n = find_node(ui(), text=name_or_duration)
    if not n:
        return False
    long_press(n, ms=1000)
    menu = ui()
    return (find_node(menu, text="Favourite") is not None
            and find_node(menu, text="Edit") is not None)


# ═══════════════════════════════════════════════════════════════════════════════
# (1) CRUD CREATE + PERSISTENCE — the primary create flow, survives process death
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_create_fast_persists",
                   "interaction_create_fast_persists_vlm"))
def test_create_fast_survives_process_death():
    """Full create -> verify -> persist: start Test Timer, End, rate 4 stars, Save;
    assert the Dashboard 'Fasts' count went 0 -> 1 and a fast appeared in History;
    then KILL the process and relaunch and assert the record is STILL there. The
    negative half (count 0 + empty history before) is what makes it discriminating."""
    open_main_clear()
    absent_before = (_fasts_count() == 0
                     and find_node_ci(ui(), "No recent fasts to show.") is not None)
    made = save_test_timer_fast()
    if not made:
        record("interaction_create_fast_persists", False,
               "feature_missing: could not complete+Save a Test Timer fast (no goal "
               "cell / no summary modal / no Save)",
               depth=0, jump_kind="value",
               expect="Dashboard 'Fasts' 0->1 and a History fast after Save+relaunch")
        # spend the paired VLM record on whatever is on screen
        vlm_assert("interaction_create_fast_persists",
                   "In the 'Rate your fast' star row of the completion dialog, are "
                   "exactly 4 of the 5 stars filled in (coloured) and the 5th star an "
                   "empty outline? Answer YES or NO.",
                   RESULTS_DIR, tag="shape", depth=0, jump_kind="value")
        return
    after_save = ui()
    created = (_fasts_count(after_save) == 1
               and find_node(after_save, text="This Week") is not None)
    # process-death probe — the highest-value assertion for this lane
    kill_and_reopen()
    survived = ui()
    persisted = (_fasts_count(survived) == 1
                 and find_node(survived, text="This Week") is not None)
    ok = absent_before and created and persisted
    record("interaction_create_fast_persists", bool(ok),
           "" if ok else ("behavior_wrong: 'Fasts' count / History did not reflect "
                          "the saved fast" if not created
                          else "behavior_wrong: the saved fast did NOT survive process "
                               "death ('Fasts' count reset or History empty after "
                               "relaunch)"),
           depth=0, jump_kind="value",
           expect="Dashboard 'Fasts' 0->1 + History 'This Week'; both still present "
                  "after force-stop+relaunch")
    # VLM (persistence, visual): the History section on the surviving Dashboard shows
    # the completed fast with its Goal-Reached check.
    vlm_assert("interaction_create_fast_persists",
               "After the app was restarted, does the 'History' section near the "
               "bottom of the dashboard list a completed fast entry (a duration like "
               "'0h 2m' under a 'This Week' heading with a green check icon) rather "
               "than an empty 'No recent fasts' message? Answer YES or NO.",
               RESULTS_DIR, tag="content", depth=0, jump_kind="value")


# ═══════════════════════════════════════════════════════════════════════════════
# (2) MULTI-RECORD INTEGRITY — add 3 fasts; the count reflects all 3, survives kill
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_multi_record_integrity",
                   "interaction_multi_record_integrity_vlm"))
def test_multi_record_integrity():
    """Create THREE Test Timer fasts in a row, reading the Dashboard 'Fasts' count
    back out after each Save. A recreation that keeps only one row (an in-memory
    'latest fast' instead of a real table) fails: the count must climb 0->1->2->3
    monotonically, never stall at 1. Then relaunch and assert all 3 still counted."""
    open_main_clear()
    counts = [_fasts_count()]                 # baseline: expect 0
    for _ in range(3):
        if not save_test_timer_fast():
            break
        counts.append(_fasts_count(ui()))
    # the count must be a strictly-increasing 0,1,2,3
    monotonic = (len(counts) == 4
                 and all(c is not None for c in counts)
                 and counts == [0, 1, 2, 3])
    # persistence of the aggregate across a kill: still 3
    kill_and_reopen()
    persisted = _fasts_count(ui()) == 3
    ok = monotonic and persisted
    record("interaction_multi_record_integrity", bool(ok),
           "" if ok else ("behavior_wrong: the 'Fasts' count did not climb "
                          f"0->1->2->3 across three saves (saw {counts}) — only one "
                          "record is being kept" if not monotonic
                          else "behavior_wrong: the three-fast total (3) did not "
                               "survive process death"),
           depth=0, jump_kind="value",
           expect=f"Dashboard 'Fasts' count 0,1,2,3 across three saves, still 3 "
                  f"after relaunch (observed {counts})")
    # VLM: after 3 fasts the History section is non-empty; assert a populated list.
    vlm_assert("interaction_multi_record_integrity",
               "Does the 'History' section of the dashboard show at least one "
               "completed fast entry with a duration value and a green check icon "
               "(i.e. it is NOT the empty 'No recent fasts to show.' state)? "
               "Answer YES or NO.",
               RESULTS_DIR, tag="content", depth=0, jump_kind="value")


# ═══════════════════════════════════════════════════════════════════════════════
# (3) RATING WRITTEN IN SUMMARY, READ BACK IN TWO SURFACES (data integrity)
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_rating_in_daily_details",
                   "interaction_rating_in_daily_details_vlm"))
def test_rating_persists_daily_details():
    """The 4-star rating written into the summary modal must read back in the Daily
    Details sheet. Multi-step: create+rate the fast, open History, open day 5's
    sheet, and assert the rated fast row is shown. (The exact star FILL is a drawn
    property -> the paired _vlm; the dump-readable half is that the correct fast row
    'Test Timer' appears in the 'Details for ...' sheet.)"""
    open_main_clear()
    made = save_test_timer_fast()
    on_hist = made and open_history_via_link()          # depth 1
    on_sheet = on_hist and and_reach_daily_details()    # depth 2
    sheet = ui() if on_sheet else []
    # the sheet shows the created record: its goal chip within a 'Details for' sheet
    row_ok = (on_sheet
              and find_node(sheet, text="Test Timer") is not None
              and any("details for" in k.lower() for k in and_showing(sheet)))
    ok = bool(row_ok)
    record("interaction_rating_in_daily_details", ok,
           "" if ok else ("setup_failed: could not build "
                          "create->History->Daily-Details" if not on_sheet
                          else "behavior_wrong: the Daily Details sheet did not show "
                               "the created 'Test Timer' fast row"),
           depth=2, jump_kind="value",
           expect="Daily Details for Aug 5 shows the 'Test Timer' fast row (created "
                  "with 4 stars)")
    # VLM (data integrity, visual): the rating on that row is 4 filled + 1 empty star.
    vlm_assert("interaction_rating_in_daily_details",
               "In this daily-details panel, does the fast entry (labelled 'Test "
               "Timer', duration '0h 2m') show a rating of exactly 4 filled/coloured "
               "stars followed by 1 empty outline star? Answer YES or NO.",
               RESULTS_DIR, tag="shape", depth=2, jump_kind="value")


@and_test(expects=("interaction_rating_in_edit_fast",
                   "interaction_rating_in_edit_fast_vlm"))
def test_rating_persists_edit_fast():
    """The SAME 4-star rating must also read back in the Edit Fast dialog (a second
    surface). Deep multi-step: create+rate, History, Daily Details, Edit Fast; assert
    the dialog shows the record's Start/End times + a 'Rating' row. Cancel out
    without editing (never taps the red 'Delete Fast')."""
    open_main_clear()
    made = save_test_timer_fast()
    on_hist = made and open_history_via_link()          # depth 1
    on_sheet = on_hist and and_reach_daily_details()    # depth 2
    on_dialog = on_sheet and and_reach_edit_fast()      # depth 3
    dlg = ui() if on_dialog else []
    dialog_ok = (on_dialog
                 and find_node(dlg, text="Rating") is not None
                 and find_node(dlg, text="Start Time") is not None
                 and find_node(dlg, text="End Time") is not None)
    # VLM WHILE THE DIALOG IS OPEN (before the Cancel that reverses it)
    vlm_assert("interaction_rating_in_edit_fast",
               "In this 'Edit Fast' dialog, does the 'Rating' row show exactly 4 "
               "filled/coloured stars followed by 1 empty outline star? "
               "Answer YES or NO.",
               RESULTS_DIR, tag="shape", depth=3, jump_kind="value")
    # leave the dialog non-destructively (Cancel; NEVER 'Delete Fast')
    cancel = find_node(ui(), text="Cancel")
    if cancel and is_safe(cancel):
        tap_node(cancel)
    else:
        and_back()
    ok = bool(dialog_ok)
    record("interaction_rating_in_edit_fast", ok,
           "" if ok else ("setup_failed: could not build "
                          "create->History->Daily-Details->Edit-Fast" if not on_dialog
                          else "behavior_wrong: the Edit Fast dialog did not show the "
                               "record's Start/End Time + Rating rows"),
           depth=3, jump_kind="value",
           expect="Edit Fast dialog shows Start Time / End Time / Rating for the "
                  "created 4-star fast")


# ═══════════════════════════════════════════════════════════════════════════════
# (4) LONG-PRESS CONTEXT MENU (SOLE OWNER) + the data change it drives
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_longpress_menu",
                   "interaction_longpress_menu_vlm"))
def test_longpress_context_menu():
    """SOLE-OWNER long-press: long-pressing a profile card reveals an 'Edit |
    Favourite | Delete' button group that is ABSENT beforehand. Assert the
    absent->present flip of the menu (the outlined-card highlight is drawn -> the
    paired _vlm)."""
    open_main_clear()
    reached = and_reach_profiles()                       # depth 1
    if not reached:
        record("interaction_longpress_menu", False,
               "setup_failed: Manage Profiles not reached",
               depth=1, jump_kind="transition",
               expect="long-press adds an 'Edit | Favourite | Delete' button group")
        vlm_assert("interaction_longpress_menu",
                   "Is exactly one fasting-profile card outlined/highlighted with a "
                   "coloured border distinct from the other cards? Answer YES or NO.",
                   RESULTS_DIR, tag="color", depth=1, jump_kind="transition")
        return
    before = ui()
    menu_absent_before = find_node(before, text="Favourite") is None
    appeared = long_press_profile("12 Hours")
    ok = menu_absent_before and appeared
    record("interaction_longpress_menu", bool(ok),
           "" if ok else ("feature_missing: long-pressing a profile card did not "
                          "reveal an 'Edit | Favourite | Delete' button group"),
           depth=1, jump_kind="transition",
           expect="Long-press: 'Edit'+'Favourite'+'Delete' button group appeared "
                  "(absent before)")
    # VLM: the long-pressed card gets a coloured outline distinct from the others.
    vlm_assert("interaction_longpress_menu",
               "Is exactly one fasting-profile card outlined/highlighted with a "
               "coloured border that is distinct from the other cards' borders? "
               "Answer YES or NO.",
               RESULTS_DIR, tag="color", depth=1, jump_kind="transition")


@and_test(expects=("interaction_longpress_set_favourite",
                   "interaction_longpress_set_favourite_vlm"))
def test_longpress_set_favourite():
    """Long-press -> tap 'Favourite' -> the 'Favourite Fast' section (empty hint
    beforehand) now holds the chosen profile card. Multi-step data change; assert
    the hint 'Press and hold a profile...' DISAPPEARS and the profile name appears in
    the favourite section. Then relaunch and assert the favourite PERSISTS."""
    open_main_clear()
    reached = and_reach_profiles()                       # depth 1
    hint_before = (reached
                   and find_node_ci(ui(),
                                    "Press and hold a profile to add it as your "
                                    "favourite") is not None)
    got_menu = reached and long_press_profile("12 Hours")
    if got_menu:
        fav = find_node(ui(), text="Favourite")
        if fav and is_safe(fav):
            tap_node(fav)
            settle("tap")
    after = ui()
    hint_gone = find_node_ci(after,
                             "Press and hold a profile to add it as your "
                             "favourite") is None
    # the favourite card now sits ABOVE the 'Other Profiles' heading
    fav_y = oth_y = None
    for n in after:
        if n.get("text", "") == "Favourite Fast" and "_bounds" in n:
            fav_y = n["_bounds"][3]
        if n.get("text", "") == "Other Profiles" and "_bounds" in n:
            oth_y = n["_bounds"][1]
    card = find_node(after, text="12-Hour Fast")
    in_fav_section = (card is not None and "_center" in card
                      and fav_y is not None and oth_y is not None
                      and fav_y < card["_center"][1] < oth_y)
    # persistence: the favourite survives a process kill
    kill_and_reopen()
    and_reset_depth()
    reopened = and_reach_profiles()
    persisted = (reopened
                 and find_node_ci(ui(),
                                  "Press and hold a profile to add it as your "
                                  "favourite") is None)
    ok = bool(hint_before and hint_gone and in_fav_section and persisted)
    record("interaction_longpress_set_favourite", ok,
           "" if ok else ("setup_failed: could not reach Manage Profiles / long-press"
                          if not got_menu
                          else "behavior_wrong: 'Favourite' did not move the profile "
                               "into the 'Favourite Fast' section, or it did not "
                               "survive relaunch"),
           depth=1, jump_kind="value",
           expect="After long-press->Favourite: hint gone + '12-Hour Fast' in the "
                  "Favourite Fast section; still favourited after relaunch")
    # VLM: a profile card now occupies the Favourite Fast section.
    vlm_assert("interaction_longpress_set_favourite",
               "Under the 'Favourite Fast' heading (above 'Other Profiles'), is there "
               "now a fasting-profile card, rather than only the grey hint text 'Press "
               "and hold a profile to add it as your favourite'? Answer YES or NO.",
               RESULTS_DIR, tag="position", depth=1, jump_kind="value")


# ═══════════════════════════════════════════════════════════════════════════════
# (5) CRUD CREATE — a new profile, read back in the grid, survives a fresh open
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_create_profile",
                   "interaction_create_profile_vlm"))
def test_create_profile():
    """Create a profile via Add Profile -> Save and read the new card back out of a
    fresh grid. Distinctive marker 'kitprofZ' so the read-back cannot match any
    seeded profile; asserted ABSENT before and PRESENT after. Then re-open Manage
    Profiles from scratch and assert it is STILL there (persisted).

    Note: only the Profile Name is required (Save's clickable parent enables once a
    name is present); the dialog's Save is tapped DIRECTLY with the keyboard up,
    because the kit's hide_keyboard() would close this Compose dialog."""
    open_main_clear()
    reached = and_reach_profiles()                       # depth 1
    absent_before = reached and scroll_into_view(MARK, max_swipes=6) is None
    opened = reached and and_enter_add_profile_dialog()  # depth 2
    if not opened:
        record("interaction_create_profile", False,
               "feature_missing: Add Profile dialog with 3 EditText not reached",
               depth=2, jump_kind="value",
               expect=f"profile card {MARK!r} present in Other Profiles after Save")
        vlm_assert("interaction_create_profile",
                   f"Is there a fasting-profile card labelled '{MARK}' in the profiles "
                   f"grid? Answer YES or NO.",
                   RESULTS_DIR, tag="content", depth=2, jump_kind="value")
        return
    # first EditText by y-order is the Profile Name field; typing it enables Save
    edits = sorted(find_by_class(ui(), "EditText"),
                   key=lambda n: n["_bounds"][1] if "_bounds" in n else 0)
    # verify_focus=False: this Compose dialog shifts the EditText bounds when
    # the keyboard animates in, which makes the kit's focus-verify retry
    # double-tap a stale node and lose the text; a single tap+type is reliable.
    typed = bool(edits) and type_text(edits[0], MARK, verify_focus=False)
    # tap the ENABLED Save control directly (keyboard up); do NOT hide_keyboard()
    saved = _tap_enabled_dialog_save()
    # read the created card back out of a FRESH, scrolled grid
    present_after = scroll_into_view(MARK, max_swipes=6) is not None
    # persistence: re-open Manage Profiles from scratch; the profile is still listed
    kill_and_reopen()
    and_reset_depth()
    reopened = and_reach_profiles()
    persisted = reopened and scroll_into_view(MARK, max_swipes=6) is not None
    ok = bool(absent_before and typed and saved and present_after and persisted)
    record("interaction_create_profile", ok,
           "" if ok else ("behavior_wrong: profile marker was already present before "
                          "creation" if not absent_before
                          else "behavior_wrong: the created profile "
                               f"{MARK!r} did not appear in the grid / did not survive "
                               "a fresh open"),
           depth=2, jump_kind="value",
           expect=f"profile card {MARK!r} absent before, present after Save, still "
                  f"present after relaunch")
    # re-locate the card so the VLM screenshot frames it
    scroll_into_view(MARK, max_swipes=4)
    vlm_assert("interaction_create_profile",
               f"Is there a fasting-profile card whose title text reads '{MARK}' in "
               f"the profiles grid? Answer YES or NO.",
               RESULTS_DIR, tag="content", depth=2, jump_kind="value")


# ═══════════════════════════════════════════════════════════════════════════════
# (6) DATA PERSISTENCE ACROSS PROCESS DEATH — an ACTIVE fast survives the kill
# ═══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_active_fast_survives",
                   "interaction_active_fast_survives_vlm"))
def test_active_fast_survives_kill():
    """Start an Open Fast (∞ — counts up, 'Elapsed Time', never auto-completes), then
    KILL the process and relaunch: the Dashboard must STILL show the running fast
    ('Elapsed Time' + 'End Fast'), not the empty goal grid. An in-memory-only
    recreation shows the goal grid instead. Asserts the goal grid was present before
    starting (negative half) and gone after."""
    open_main_clear()
    grid_before = find_node(ui(), text="Set your goal") is not None
    started = _start_goal("Open Fast")
    active = ui()
    running_before_kill = (started
                           and find_node(active, text="Elapsed Time") is not None
                           and find_node(active, content_desc="End Fast") is not None)
    if not running_before_kill:
        record("interaction_active_fast_survives", False,
               "feature_missing: could not start an Open Fast ('Elapsed Time' / "
               "'End Fast' not shown)",
               depth=0, jump_kind="value",
               expect="active Open Fast ('Elapsed Time'+'End Fast') persists after "
                      "force-stop+relaunch")
        vlm_assert("interaction_active_fast_survives",
                   "Is there a circular ring or arc drawn around a large running "
                   "timer near the top-centre of the screen (an active fast in "
                   "progress)? Answer YES or NO.",
                   RESULTS_DIR, tag="shape", depth=0, jump_kind="value")
        return
    # process-death probe
    kill_and_reopen()
    survived = ui()
    still_running = (find_node(survived, text="Elapsed Time") is not None
                     and find_node(survived, content_desc="End Fast") is not None
                     and find_node(survived, text="Set your goal") is None)
    ok = bool(grid_before and still_running)
    record("interaction_active_fast_survives", ok,
           "" if ok else "behavior_wrong: the active Open Fast did NOT survive process "
                         "death (Dashboard fell back to the goal grid / lost 'Elapsed "
                         "Time'+'End Fast')",
           depth=0, jump_kind="value",
           expect="After force-stop+relaunch: 'Elapsed Time' + 'End Fast' still shown, "
                  "goal grid 'Set your goal' gone")
    # VLM (persistence, visual): the running-timer ring is still rendered after the kill.
    vlm_assert("interaction_active_fast_survives",
               "Is there a circular ring or arc drawn around a large running timer "
               "near the top-centre of the screen (an active fast still in progress), "
               "rather than a grid of goal-selection cells? Answer YES or NO.",
               RESULTS_DIR, tag="shape", depth=0, jump_kind="value")
    # clean up: end the fast (no save) so a later run starts from a known state
    ef = find_node(ui(), content_desc="End Fast")
    if ef:
        tap_node(ef)
        settle("tap")
        and_back()                                     # dismiss the summary, no save


# ═══════════════════════════════════════════════════════════════════════════════
TESTS = [
    test_create_fast_survives_process_death,
    test_multi_record_integrity,
    test_rating_persists_daily_details,
    test_rating_persists_edit_fast,
    test_longpress_context_menu,
    test_longpress_set_favourite,
    test_create_profile,
    test_active_fast_survives_kill,
]

if __name__ == "__main__":
    if not device_online():
        print("setup_failed: device offline / adb tunnel down — aborting")
        sys.exit(2)
    run_suite(TESTS, "interaction")