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

EFFECT-BY-CONSEQUENCE: multi-step sequences whose consequence on app state is
read back out of a fresh ui(), and DATA/SETTING persistence across full process
death. A dead shell that ignores the taps must FAIL here.

Run:
  ADB_PATH=/opt/android/platform-tools/adb DEVICE_SERIAL=emulator-5554 \
    python3 test_android_interaction.py <PACKAGE> <RESULTS_DIR>
"""
import os
import re
import sys

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

RD = sys.argv[2] if len(sys.argv) > 2 else RESULTS_DIR


# ── local helpers (never touch adb directly) ───────────────────────────────────

def li_text():
    """Current level_indicator text (e.g. '0 / 10', 'SOS mode'), or None."""
    n = node_by_id(ui(), "level_indicator")
    return n.get("text") if n else None


def qa_text():
    """Current quick_actions_view text, or None."""
    n = node_by_id(ui(), "quick_actions_view")
    return n.get("text") if n else None


def tap_home_level(rid):
    """Tap a home level button by id-suffix; return the resulting level text."""
    if not tap_node(node_by_id(ui(), rid)):
        return None
    return li_text()


def tap_seekbar_fraction(frac):
    """Tap the custom seek_bar at `frac` from its TOP (top=max, bottom=0).

    level = round(10*(1-frac)). Coordinates are derived live from the node's
    bounds — never a literal. Returns the resulting level text.
    """
    sb = node_by_id(ui(), "seek_bar")
    if not sb or "_bounds" not in sb:
        return None
    x1, y1, x2, y2 = sb["_bounds"]
    cx = (x1 + x2) // 2
    ty = int(y1 + frac * (y2 - y1))
    tap(cx, ty)
    return li_text()


def _yc(node):
    b = node["_bounds"]
    return (b[1] + b[3]) // 2


def switch_for_title(nodes, title):
    """The Switch node on the same settings row as `title` — the one whose
    y-centre is closest (within ~80px) to the title's."""
    t = find_node(nodes, text=title)
    if not t or "_bounds" not in t:
        return None
    ty = _yc(t)
    best, best_d = None, 10 ** 9
    for s in find_by_class(nodes, "Switch"):
        if "_bounds" not in s:
            continue
        d = abs(_yc(s) - ty)
        if d < best_d:
            best, best_d = s, d
    return best if best_d <= 80 else None


def pref_level_summary(nodes):
    """The 'Preferred level' summary TextView (ends ': <value>'), or None."""
    pl = find_node(nodes, text="Preferred level")
    if not pl or "_bounds" not in pl:
        return None
    ply = _yc(pl)
    cands = [x for x in nodes
             if x.get("class", "").endswith("TextView")
             and x.get("text", "")
             and "_bounds" in x
             and _yc(x) > ply and abs(_yc(x) - ply) < 120]
    return cands[0].get("text") if cands else None


def new_val_in_dialog(nodes):
    """Parse the 'New: N' number in the Set preferred level dialog, or None."""
    for x in nodes:
        t = x.get("text", "")
        if t.startswith("New:"):
            m = re.search(r"New:\s*(\d+)", t)
            return m.group(1) if m else None
    return None


# ── depth-family helpers (their and_enter_* NAME backs a declared depth>=1) ─────

def and_enter_settings():
    """Open the Settings activity from the home toolbar. Counts one surface."""
    if not tap_node(node_by_id(ui(), "settings_action")):
        return False
    settle("launch")
    and_enter("settings")
    return True


def and_enter_morse_dialog():
    """Open the Morse dialog from the home screen. Counts one surface."""
    if not tap_node(node_by_id(ui(), "morse_button")):
        return False
    settle("tap")
    and_enter("morse_dialog")
    return True


def and_enter_interval_dialog():
    """Open the Interval dialog from the home screen. Counts one surface."""
    if not tap_node(node_by_id(ui(), "interval_button")):
        return False
    settle("tap")
    and_enter("interval_dialog")
    return True


def and_enter_preferred_level_dialog():
    """From an open Settings screen, open the Set preferred level dialog."""
    if not tap_node(find_node(ui(), text="Preferred level")):
        return False
    settle("tap")
    and_enter("preferred_level_dialog")
    return True


# ════════════════════════════════════════════════════════════════════════════
# A. Multi-step level sequences (consequence = level_indicator), depth 0
# ════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_seq_max_half_min_off",))
def test_seq_max_half_min_off():
    """4-step ordered progression driven by four different buttons; each step's
    consequence depends on the previous surface being live."""
    # clear_data() guarantees a virgin launch at '0 / 10' — a bare restart_app()
    # resumes the app's surviving task in whatever level a prior test left it.
    clear_data()
    restart_app()
    wait_for_foreground()
    if node_by_id(ui(), "max_button") is None:
        record("interaction_seq_max_half_min_off", False,
               "setup_failed: home level buttons not present",
               depth=0, jump_kind="transition",
               expect="'0 / 10'->'10 / 10'->'5 / 10'->'1 / 10'->'0 / 10'")
        return
    s0 = li_text()                          # launch: "0 / 10"
    s_max = tap_home_level("max_button")    # "10 / 10"
    s_half = tap_home_level("half_button")  # "5 / 10"
    s_min = tap_home_level("min_button")    # "1 / 10"
    s_off = tap_home_level("off_button")    # "0 / 10"
    ok = (s0 == "0 / 10" and s_max == "10 / 10" and s_half == "5 / 10"
          and s_min == "1 / 10" and s_off == "0 / 10")
    record("interaction_seq_max_half_min_off", ok,
           "" if ok else f"behavior_wrong: progression was "
                         f"{s0}->{s_max}->{s_half}->{s_min}->{s_off}",
           depth=0, jump_kind="transition",
           expect="Max->Half->Min->Off = '10 / 10'->'5 / 10'->'1 / 10'->'0 / 10' (final '0 / 10')")


@and_test(expects=("interaction_seq_toggle_through",))
def test_seq_off_max_off_half():
    """Off->Max->Off->Half. Toggling max ON then OFF then half proves each tap
    re-commits state rather than echoing the first input."""
    restart_app()
    wait_for_foreground()
    if node_by_id(ui(), "off_button") is None:
        record("interaction_seq_toggle_through", False,
               "setup_failed: home level buttons not present",
               depth=0, jump_kind="transition", expect="final '5 / 10' after Off->Max->Off->Half")
        return
    s_off1 = tap_home_level("off_button")   # "0 / 10"
    s_max = tap_home_level("max_button")    # "10 / 10"
    s_off2 = tap_home_level("off_button")   # "0 / 10"
    s_half = tap_home_level("half_button")  # "5 / 10"
    ok = (s_off1 == "0 / 10" and s_max == "10 / 10"
          and s_off2 == "0 / 10" and s_half == "5 / 10")
    record("interaction_seq_toggle_through", ok,
           "" if ok else f"behavior_wrong: progression was "
                         f"{s_off1}->{s_max}->{s_off2}->{s_half}",
           depth=0, jump_kind="transition",
           expect="Off->Max->Off->Half = '0 / 10'->'10 / 10'->'0 / 10'->'5 / 10' (final '5 / 10')")


@and_test(expects=("interaction_seq_min_then_max_override",))
def test_seq_min_then_max_override():
    """Min sets '1 / 10', then Max must OVERRIDE to '10 / 10' — a later action
    winning over an earlier one, not being ignored."""
    restart_app()
    wait_for_foreground()
    if node_by_id(ui(), "min_button") is None:
        record("interaction_seq_min_then_max_override", False,
               "setup_failed: home level buttons not present",
               depth=0, jump_kind="transition", expect="'1 / 10' then '10 / 10'")
        return
    s_min = tap_home_level("min_button")   # "1 / 10"
    s_max = tap_home_level("max_button")   # "10 / 10"
    ok = (s_min == "1 / 10" and s_max == "10 / 10")
    record("interaction_seq_min_then_max_override", ok,
           "" if ok else f"behavior_wrong: Min={s_min}, then Max={s_max}",
           depth=0, jump_kind="transition",
           expect="Min='1 / 10' then Max overrides to '10 / 10'")


@and_test(expects=("interaction_button_seekbar_same_state",
                   "interaction_button_seekbar_same_state_vlm"))
def test_button_and_seekbar_drive_same_state():
    """Max button -> '10 / 10', Min button -> '1 / 10', then a seekbar tap near
    the TOP must return '10 / 10' — proving buttons and the custom seekbar drive
    the SAME level state. VLM confirms the segmented fill matches level 10."""
    restart_app()
    wait_for_foreground()
    if node_by_id(ui(), "seek_bar") is None or node_by_id(ui(), "max_button") is None:
        record("interaction_button_seekbar_same_state", False,
               "setup_failed: seek_bar or level buttons missing",
               depth=0, jump_kind="transition",
               expect="'10 / 10' -> '1 / 10' -> seekbar '10 / 10'")
        vlm_assert("interaction_button_seekbar_same_state",
                   "Is the vertical segmented bar completely filled (all ~10 segments "
                   "highlighted) and does the level read 10 / 10?",
                   RD, expect="YES", depth=0, jump_kind="transition", tag="shape")
        return
    s_max = tap_home_level("max_button")   # "10 / 10"
    s_min = tap_home_level("min_button")   # "1 / 10"
    s_seek = tap_seekbar_fraction(0.05)    # back to "10 / 10"
    ok = (s_max == "10 / 10" and s_min == "1 / 10" and s_seek == "10 / 10")
    record("interaction_button_seekbar_same_state", ok,
           "" if ok else f"behavior_wrong: Max={s_max}, Min={s_min}, seekTop={s_seek}",
           depth=0, jump_kind="transition",
           expect="Max='10 / 10', Min='1 / 10', seekbar-top back to '10 / 10' (shared state)")
    # VLM #1: seekbar fully filled at level 10
    vlm_assert("interaction_button_seekbar_same_state",
               "Is the vertical segmented bar completely filled (all ~10 segments "
               "highlighted) and does the level read 10 / 10?",
               RD, expect="YES", depth=0, jump_kind="transition", tag="shape")


@and_test(expects=("interaction_seekbar_min_fill_vlm",))
def test_seekbar_min_fill_vlm():
    """Tap Min, then have the VLM verify only the bottom-most seekbar segment is
    lit — a canvas-drawn fill that the view tree never exposes."""
    restart_app()
    wait_for_foreground()
    s_min = tap_home_level("min_button")   # "1 / 10" (rule-side sanity for the screenshot)
    if s_min != "1 / 10":
        record("interaction_seekbar_min_fill_vlm", False,
               f"setup_failed: Min gave {s_min!r}, not '1 / 10'; screenshot unreliable",
               depth=0, jump_kind="none", tag="shape")
        return
    # VLM #2: only bottom segment lit
    vlm_assert("interaction_seekbar_min_fill",
               "Is only the bottom-most segment of the vertical bar highlighted while "
               "the rest are dark?",
               RD, expect="YES", depth=0, jump_kind="transition", tag="shape")


@and_test(expects=("interaction_seekbar_mid_fill_vlm",))
def test_seekbar_mid_fill_vlm():
    """Tap the seekbar mid, verify level '5 / 10', then have the VLM confirm the
    bar is filled about halfway from the bottom."""
    restart_app()
    wait_for_foreground()
    s_mid = tap_seekbar_fraction(0.5)      # "5 / 10"
    if s_mid != "5 / 10":
        record("interaction_seekbar_mid_fill_vlm", False,
               f"setup_failed: seekbar-mid gave {s_mid!r}, not '5 / 10'",
               depth=0, jump_kind="none", tag="shape")
        return
    # VLM #6: bar filled about halfway
    vlm_assert("interaction_seekbar_mid_fill",
               "Is the vertical segmented bar filled about halfway from the bottom "
               "(roughly the lower half of the segments highlighted, the upper half dark)?",
               RD, expect="YES", depth=0, jump_kind="transition", tag="shape")


# ════════════════════════════════════════════════════════════════════════════
# B. SOS mode enter -> exit (consequence = multiple widgets change), depth 0
# ════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_sos_enter_exit",
                   "interaction_sos_enter_exit_vlm"))
def test_sos_enter_then_exit():
    """Tap SOS: indicator -> 'SOS mode', quick_actions -> 'Morse:...', the
    Max/Half/Min/Morse/Interval buttons DISAPPEAR, sos disabled, seek disabled.
    Then tap Off: EVERYTHING restores. Asserts BOTH halves of the sequence."""
    restart_app()
    wait_for_foreground()
    if node_by_id(ui(), "sos_button") is None:
        record("interaction_sos_enter_exit", False,
               "feature_missing: no sos_button on the main surface",
               depth=0, jump_kind="transition",
               expect="'SOS mode' + buttons hidden, then restored to '0 / 10'")
        vlm_assert("interaction_sos_enter_exit",
                   "Have the Maximum/Half/Minimum buttons disappeared, leaving only "
                   "SOS and Off in the left column?",
                   RD, expect="YES", depth=0, jump_kind="transition", tag="position")
        return
    # enter
    tap_node(node_by_id(ui(), "sos_button"))
    n = ui()
    entered_li = (node_by_id(n, "level_indicator") or {}).get("text")
    entered_qa = (node_by_id(n, "quick_actions_view") or {}).get("text") or ""
    hidden = all(node_by_id(n, rid) is None for rid in
                 ("morse_button", "interval_button", "max_button",
                  "half_button", "min_button"))
    sos_disabled = (node_by_id(n, "sos_button") or {}).get("enabled") == "false"
    seek_disabled = (node_by_id(n, "seek_bar") or {}).get("enabled") == "false"
    entered_ok = (entered_li == "SOS mode" and entered_qa.startswith("Morse:")
                  and hidden and sos_disabled and seek_disabled)
    # VLM #3: brightness buttons gone in SOS mode
    vlm_assert("interaction_sos_enter_exit",
               "Have the Maximum/Half/Minimum buttons disappeared, leaving only "
               "SOS and Off in the left column?",
               RD, expect="YES", depth=0, jump_kind="transition", tag="position")
    # exit
    tap_node(node_by_id(ui(), "off_button"))
    m = ui()
    restored_li = (node_by_id(m, "level_indicator") or {}).get("text")
    restored_qa = (node_by_id(m, "quick_actions_view") or {}).get("text")
    buttons_back = all(node_by_id(m, rid) is not None for rid in
                       ("morse_button", "interval_button", "max_button",
                        "half_button", "min_button"))
    restored_ok = (restored_li == "0 / 10" and restored_qa == "Quick Actions"
                   and buttons_back)
    ok = entered_ok and restored_ok
    record("interaction_sos_enter_exit", ok,
           "" if ok else f"behavior_wrong: entered(li={entered_li!r},hidden={hidden},"
                         f"sosOff={sos_disabled},seekOff={seek_disabled}) "
                         f"restored(li={restored_li!r},qa={restored_qa!r},back={buttons_back})",
           depth=0, jump_kind="transition",
           expect="SOS enter: li='SOS mode', qa startswith 'Morse:', buttons hidden, "
                  "sos+seek disabled; Off exit restores li='0 / 10', qa='Quick Actions', buttons back")


# ════════════════════════════════════════════════════════════════════════════
# C. Morse dialog input sequence (3+ steps), depth 1
# ════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_morse_dialog_flow",
                   "interaction_morse_dialog_flow_vlm"))
def test_morse_dialog_input_flow():
    """3-step sequence inside the Morse dialog:
      1) open dialog,
      2) tap Flash with EMPTY input -> validation error appears AND dialog stays,
      3) type a message, tap Flash -> the dialog DISMISSES.
    Each step depends on the prior surface being live; a shell that ignores the
    empty-Flash tap would dismiss immediately at step 2 and fail."""
    restart_app()
    wait_for_foreground()
    if node_by_id(ui(), "morse_button") is None:
        record("interaction_morse_dialog_flow", False,
               "feature_missing: no morse_button on the main surface",
               depth=1, jump_kind="transition",
               expect="empty Flash -> error + dialog open; typed Flash -> dialog gone")
        vlm_assert("interaction_morse_dialog_flow",
                   "Is a dialog with a single-line text input field (hint about a message) "
                   "and a 'Flash' button visible on screen?",
                   RD, expect="YES", depth=1, jump_kind="transition", tag="layout")
        return
    if not and_enter_morse_dialog():
        record("interaction_morse_dialog_flow", False,
               "setup_failed: could not open the Morse dialog",
               depth=1, jump_kind="transition",
               expect="empty Flash -> error + dialog open; typed Flash -> dialog gone")
        vlm_assert("interaction_morse_dialog_flow",
                   "Is a dialog with a single-line text input field (hint about a message) "
                   "and a 'Flash' button visible on screen?",
                   RD, expect="YES", depth=1, jump_kind="transition", tag="layout")
        return
    dialog_open = node_by_id(ui(), "text_input_text") is not None
    # VLM #4: the morse input dialog is on screen
    vlm_assert("interaction_morse_dialog_flow",
               "Is a dialog with a single-line text input field (hint about a message) "
               "and a 'Flash' button visible on screen?",
               RD, expect="YES", depth=1, jump_kind="transition", tag="layout")
    # step 2: empty Flash -> error, dialog persists
    tap_node(node_by_id(ui(), "button1"))
    settle("tap")
    n = ui()
    still_open = node_by_id(n, "text_input_text") is not None
    err = find_node_ci(n, "Please enter your message") is not None
    # step 3: type + Flash -> dialog dismisses
    field = node_by_id(ui(), "text_input_text")
    typed = False
    if field:
        typed = type_text(field, "A")
        cur = node_by_id(ui(), "text_input_text")
        if cur is not None and cur.get("text") != "A":
            type_text(field, "A", method="ime")
        hide_keyboard()
    tap_node(node_by_id(ui(), "button1"))
    settle("tap")
    dismissed = node_by_id(ui(), "text_input_text") is None
    ok = dialog_open and still_open and err and dismissed
    record("interaction_morse_dialog_flow", ok,
           "" if ok else f"behavior_wrong: open={dialog_open}, emptyStillOpen={still_open}, "
                         f"error={err}, typed={typed}, dismissedAfterFlash={dismissed}",
           depth=1, jump_kind="transition",
           expect="empty Flash keeps dialog open with error 'Please enter your message'; "
                  "typed 'A' + Flash dismisses the dialog")


# ════════════════════════════════════════════════════════════════════════════
# D. Interval dialog TIME<->BPM mode-switch round-trip (3 states), depth 1
# ════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_interval_mode_roundtrip",
                   "interaction_interval_mode_roundtrip_vlm"))
def test_interval_mode_roundtrip():
    """Open Interval dialog (TIME default: input '500', suffix 'ms'), tap BPM
    (input '100', 'ms' gone), tap TIME (back to '500'/'ms'). Asserts the full
    3-state round-trip — each switch depends on the prior mode being live."""
    restart_app()
    wait_for_foreground()
    if node_by_id(ui(), "interval_button") is None:
        record("interaction_interval_mode_roundtrip", False,
               "feature_missing: no interval_button on the main surface",
               depth=1, jump_kind="transition",
               expect="TIME '500'/'ms' -> BPM '100'/none -> TIME '500'/'ms'")
        vlm_assert("interaction_interval_mode_roundtrip",
                   "Does the numeric input show 100 with no 'ms' suffix beside it?",
                   RD, expect="YES", depth=1, jump_kind="transition", tag="content")
        return
    if not and_enter_interval_dialog():
        record("interaction_interval_mode_roundtrip", False,
               "setup_failed: could not open the Interval dialog",
               depth=1, jump_kind="transition",
               expect="TIME '500'/'ms' -> BPM '100'/none -> TIME '500'/'ms'")
        vlm_assert("interaction_interval_mode_roundtrip",
                   "Does the numeric input show 100 with no 'ms' suffix beside it?",
                   RD, expect="YES", depth=1, jump_kind="transition", tag="content")
        return

    def snap():
        n = ui()
        return ((node_by_id(n, "number_input_text") or {}).get("text"),
                (node_by_id(n, "textinput_suffix_text") or {}).get("text"))

    t_num, t_suf = snap()                          # TIME default: 500 / ms
    tap_node(node_by_id(ui(), "bpm_button"))
    settle("tap")
    b_num, b_suf = snap()                           # BPM: 100 / None
    # VLM #5: BPM shows 100 with no ms suffix
    vlm_assert("interaction_interval_mode_roundtrip",
               "Does the numeric input show 100 with no 'ms' suffix beside it?",
               RD, expect="YES", depth=1, jump_kind="transition", tag="content")
    tap_node(node_by_id(ui(), "time_button"))
    settle("tap")
    r_num, r_suf = snap()                            # back to TIME: 500 / ms
    ok = (t_num == "500" and t_suf == "ms"
          and b_num == "100" and b_suf is None
          and r_num == "500" and r_suf == "ms")
    record("interaction_interval_mode_roundtrip", ok,
           "" if ok else f"behavior_wrong: TIME=({t_num},{t_suf}) BPM=({b_num},{b_suf}) "
                         f"TIME2=({r_num},{r_suf})",
           depth=1, jump_kind="transition",
           expect="TIME('500','ms') -> BPM('100',no suffix) -> TIME('500','ms') round-trip")


# ════════════════════════════════════════════════════════════════════════════
# E. PERSISTENCE across process death (this lane OWNS data/setting persistence)
# ════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_context_awareness_persists",))
def test_context_awareness_persists():
    """Toggle 'Context awareness' OFF->ON in Settings, force-stop + relaunch,
    reopen Settings, assert the switch is STILL checked. An in-memory-only
    recreation cannot survive the process death."""
    clear_data()
    launch_app()
    wait_for_foreground()
    if not and_enter_settings():
        record("interaction_context_awareness_persists", False,
               "setup_failed: could not open Settings",
               depth=1, jump_kind="transition",
               expect="'Context awareness' switch checked=true after relaunch")
        return
    sw = switch_for_title(ui(), "Context awareness")
    if sw is None:
        record("interaction_context_awareness_persists", False,
               "feature_missing: no 'Context awareness' switch in Settings",
               depth=1, jump_kind="transition",
               expect="'Context awareness' switch checked=true after relaunch")
        return
    was_off = sw.get("checked") == "false"
    tap_node(sw)
    settle("tap")
    sw2 = switch_for_title(ui(), "Context awareness")
    turned_on = (sw2 or {}).get("checked") == "true"
    # kill the process and relaunch
    force_stop_and_relaunch()
    wait_for_foreground()
    and_reset_depth()
    if not and_enter_settings():
        record("interaction_context_awareness_persists", False,
               "setup_failed: could not reopen Settings after relaunch",
               depth=1, jump_kind="transition",
               expect="'Context awareness' switch checked=true after relaunch")
        return
    sw3 = switch_for_title(ui(), "Context awareness")
    persisted = (sw3 or {}).get("checked") == "true"
    ok = was_off and turned_on and persisted
    record("interaction_context_awareness_persists", ok,
           "" if ok else f"behavior_wrong: wasOff={was_off}, turnedOn={turned_on}, "
                         f"stillOnAfterRestart={persisted}",
           depth=1, jump_kind="transition",
           expect="'Context awareness' OFF->ON then survives force_stop_and_relaunch (checked=true)")


@and_test(expects=("interaction_preferred_level_dialog_live_value",
                   "interaction_preferred_level_persists"))
def test_preferred_level_value_persists():
    """Two consequences on the 'Preferred level' preference:
      1) inside the slider dialog (depth 2), tapping the track sets the live
         'New: <value>' to the exact value the tap position maps to;
      2) after OK + force-stop + relaunch, the Settings summary STILL ends with
         the SAME ': <value>' and is NOT the untouched default ': 10'.
    A concrete VALUE surviving process death — an in-memory recreation fails (2)."""
    LIVE = "interaction_preferred_level_dialog_live_value"
    PERSIST = "interaction_preferred_level_persists"
    clear_data()
    launch_app()
    wait_for_foreground()
    if not and_enter_settings():
        record(LIVE, False, "setup_failed: could not open Settings",
               depth=2, jump_kind="value", expect="dialog 'New:' shows the tapped value '2'")
        record(PERSIST, False, "setup_failed: could not open Settings",
               depth=1, jump_kind="value",
               expect="'Preferred level' summary keeps its set value after relaunch")
        return
    if find_node(ui(), text="Preferred level") is None:
        record(LIVE, False, "feature_missing: no 'Preferred level' row in Settings",
               depth=2, jump_kind="value", expect="dialog 'New:' shows the tapped value '2'")
        record(PERSIST, False, "feature_missing: no 'Preferred level' row in Settings",
               depth=1, jump_kind="value",
               expect="'Preferred level' summary keeps its set value after relaunch")
        return
    default_summary = pref_level_summary(ui()) or ""
    if not and_enter_preferred_level_dialog():
        record(LIVE, False, "setup_failed: could not open the Set preferred level dialog",
               depth=2, jump_kind="value", expect="dialog 'New:' shows the tapped value '2'")
        record(PERSIST, False, "setup_failed: could not open the Set preferred level dialog",
               depth=2, jump_kind="value",
               expect="'Preferred level' summary keeps its set value after relaunch")
        return
    # The slider is a custom view with no distinct node; tap along its track strip
    # (derived from the container + 'New:' label bounds) to set a distinct value.
    d = ui()
    conts = [x for x in d if x.get("class", "").endswith("LinearLayout")
             and "_bounds" in x and x["_bounds"][1] > 1000]
    news = [x for x in d if x.get("text", "").startswith("New:") and "_bounds" in x]
    before_new = new_val_in_dialog(d)              # default "10"
    changed_new = None
    if conts and news:
        cont = min(conts, key=lambda c: (c["_bounds"][2] - c["_bounds"][0]))
        cx1, _, cx2, cy2 = cont["_bounds"]
        sy = (news[0]["_bounds"][3] + cy2) // 2
        # f=0.2 of the track -> value 2 (distinct from the default 10)
        tap(int(cx1 + 0.2 * (cx2 - cx1)), sy)
        changed_new = new_val_in_dialog(ui())
    # depth-2 value: the live "New:" readout reflects the tapped position (10 -> 2)
    live_ok = (before_new == "10" and changed_new == "2")
    record(LIVE, live_ok,
           "" if live_ok else f"behavior_wrong: 'New:' was {before_new!r}, after tapping "
                              f"track f=0.2 became {changed_new!r} (expected '2')",
           depth=2, jump_kind="value",
           expect="dialog 'New:' 10 -> '2' after tapping the slider track at fraction 0.2")
    tap_node(node_by_id(ui(), "button1"))          # OK
    settle("tap")
    set_summary = pref_level_summary(ui()) or ""
    set_value = None
    m = re.search(r":\s*(\d+)\s*$", set_summary)
    if m:
        set_value = m.group(1)
    # kill the process and relaunch
    force_stop_and_relaunch()
    wait_for_foreground()
    and_reset_depth()
    if not and_enter_settings():
        record(PERSIST, False,
               "setup_failed: could not reopen Settings after relaunch",
               depth=1, jump_kind="value",
               expect="'Preferred level' summary keeps its set value after relaunch")
        return
    after_summary = pref_level_summary(ui()) or ""
    changed_from_default = (set_summary != default_summary
                            and not set_summary.rstrip().endswith(": 10"))
    persisted = (bool(set_value) and after_summary == set_summary)
    ok = changed_from_default and persisted
    record(PERSIST, ok,
           "" if ok else f"behavior_wrong: default={default_summary[-12:]!r}, "
                         f"newInDialog={changed_new!r}, set={set_summary[-12:]!r}, "
                         f"afterRestart={after_summary[-12:]!r}",
           depth=1, jump_kind="value",
           expect=f"'Preferred level' summary ends ': {set_value}' both before and after "
                  f"force_stop_and_relaunch (and not the default ': 10')")


TESTS = [
    # A. multi-step level sequences (depth 0)
    test_seq_max_half_min_off,
    test_seq_off_max_off_half,
    test_seq_min_then_max_override,
    test_button_and_seekbar_drive_same_state,
    test_seekbar_min_fill_vlm,
    test_seekbar_mid_fill_vlm,
    # B. SOS enter/exit sequence (depth 0)
    test_sos_enter_then_exit,
    # C. Morse dialog input sequence (depth 1)
    test_morse_dialog_input_flow,
    # D. Interval dialog mode round-trip (depth 1)
    test_interval_mode_roundtrip,
    # E. persistence across process death (depth 1 / depth 2 value)
    test_context_awareness_persists,
    test_preferred_level_value_persists,
]

if __name__ == "__main__":
    if not device_online():
        print("device offline — the adb tunnel may have dropped")
    run_suite(TESTS, "interaction")