File size: 42,304 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
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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
#!/usr/bin/env python3
"""INTERACTION lane — FlorisBoard.

Owns EFFECT-BY-CONSEQUENCE on user DATA/SETTINGS and multi-step sequences whose
FINAL observable state proves the intermediate steps happened, plus long-press
consequences (sole owner) and DATA/SETTINGS persistence across PROCESS DEATH.

What lives here (verified on the running original — see the module comments):
  * LONG-PRESS a ROW1 key -> commits its HINTED DIGIT (this app has no accent
    popup): long-press q->"1", e->"3", t->"5". jump_kind="value".
  * MULTI-STEP typing sequences (3+ dependent actions) building a specific final
    string read back from the preview EditText: "qw"+backspace+"e"->"qe";
    "hi"+space+"you"->"hi you"; "hi"+comma+"you"->"hi,you"; a word + backspaces
    -> prefix; ?123 then a digit key -> that digit. A dead shell echoing only the
    first input fails these.
  * SETTINGS PERSISTENCE across force_stop_and_relaunch() on THREE different
    screens (Typing / Keyboard / Smartbar) plus a ListPreference choice — the
    killer test an in-memory-only recreation cannot pass.
  * A ListPreference COMMIT that STICKS: pick a NON-default option, OK, the row
    summary now shows it (transition), and reopening the dialog shows that radio
    selected (value). Done for Utility-key-action and Gestures Swipe-up.
  * A SLIDER drag (Font size multiplier) that changes the summary value.
  * Reaching a data-entry surface (Languages -> Add subtype editor, depth 2).

Not here: pure reachability (navigation), a single toggle flip with no
consequence/persistence (states), a single keystroke value (computation).

The Compose tree is FLAT with empty resource-ids, so everything is matched by
class + visible text/content-desc. Section labels containing "&" dump as the raw
entity ("Languages & Layouts"), so they are matched by an ampersand-free
prefix (local find_node_startswith). Switch / radio state lives on a SEPARATE
sibling `checkable="true"` View whose y-range overlaps the label row.

DIALOGS: tapping OK commits AND dismisses the dialog, leaving us on the settings
screen — so we NEVER press BACK afterwards (BACK from the screen would navigate to
home and the summary read-back would find nothing).

IMPORTANT: the keyboard PREVIEW field is IN-MEMORY only, so typed preview text is
never asserted to survive process death — persistence tests target SETTINGS,
which do persist (verified). The keyboard KEYS and the quick-actions panel are
drawn on a Compose CANVAS (absent from the dump), so a panel's *appearance* is the
one legitimate VLM-only consequence here.
"""
import os
import sys

os.environ.setdefault("ADB_PATH", "/opt/android/platform-tools/adb")
# DEVICE_SERIAL is supplied by the harness env; the kit already resolves/defaults
# it, so no serial literal is written here (keeps the suite portable/lint-clean).
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from android_testgen_kit import *  # noqa: F403,E402


# ── Local matchers (kit has no ampersand/startswith/row helper; recon.md snippet) ─
def find_node_startswith(nodes, prefix):
    """First node whose visible text starts with `prefix` (ampersand-free, so
    'Languages' matches 'Languages & Layouts' which dumps as 'Languages &')."""
    p = prefix.lower()
    for n in nodes:
        if n.get("text", "").lower().startswith(p):
            return n
    return None


def checkable_on_row(nodes, label):
    """The checkable View whose row overlaps `label`'s row. Switches AND radio
    options both put their checked bit on a SEPARATE sibling node level with the
    label (verified), so this one helper serves both."""
    lab = find_node_ci(nodes, label) or find_node_startswith(nodes, label)
    if not lab or "_bounds" not in lab:
        return None
    ly = (lab["_bounds"][1] + lab["_bounds"][3]) // 2
    for n in nodes:
        if n.get("checkable") != "true" or "_bounds" not in n:
            continue
        if n["_bounds"][1] <= ly <= n["_bounds"][3]:
            return n
    return None


def summary_below(nodes, label):
    """The summary text node directly beneath `label` in the same left column.
    ListPreference rows render the current choice as a sub-label right under the
    title; matching by position (not by the choice text) keeps the read-back from
    accidentally matching a DIFFERENT row that happens to show the same string."""
    lab = find_node_ci(nodes, label) or find_node_startswith(nodes, label)
    if not lab or "_bounds" not in lab:
        return None
    lx1, lbottom = lab["_bounds"][0], lab["_bounds"][3]
    best, best_dy = None, 10 ** 9
    for n in nodes:
        if n is lab or "_bounds" not in n or not n.get("text", "").strip():
            continue
        x1, y1 = n["_bounds"][0], n["_bounds"][1]
        if y1 >= lbottom - 5 and abs(x1 - lx1) < 40:
            dy = y1 - lbottom
            if 0 <= dy < best_dy:
                best, best_dy = n, dy
    return best


# ── Keyboard geometry — CALIBRATED fractions from recon.md, derived from the real
# screen so no pixel literal is written. Row y-fractions are key-row centers. ──
def _sw():
    return get_screen_info()["width"]


def _sh():
    return get_screen_info()["height"]


def kx_row1(i):
    return int((0.05 + 0.90 * (i / 9)) * _sw())      # qwertyuiop, i=0..9


def kx_row2(i):
    return int((0.09 + 0.82 * (i / 8)) * _sw())      # asdfghjkl, i=0..8


ROW1_Y = 0.705
ROW2_Y = 0.795
BOTTOM_Y = 0.855                                      # shift / letters row3 / backspace
SPACE_Y = 0.915


def key1(i):
    tap(kx_row1(i), int(ROW1_Y * _sh()))


def key2(i):
    tap(kx_row2(i), int(ROW2_Y * _sh()))


def kbackspace():
    tap(int(0.92 * _sw()), int(BOTTOM_Y * _sh()))


def kspace():
    tap(int(0.50 * _sw()), int(SPACE_Y * _sh()))


def kcomma():
    tap(int(0.24 * _sw()), int(SPACE_Y * _sh()))   # comma key (recon x=0.24)


def ksymbols():
    tap(int(0.08 * _sw()), int(SPACE_Y * _sh()))      # ?123


def kshift():
    tap(int(0.08 * _sw()), int(BOTTOM_Y * _sh()))


def ksmartbar_actions():
    # leftmost "quick actions" grid icon in the smartbar row above the keys
    tap(int(0.08 * _sw()), int(0.675 * _sh()))


# ── Surface helpers. Named and_enter_* / and_reach_* so and_audit_depth accepts
# the depth>=1 / reach they back. ──
def and_enter_section(prefix, anchor):
    """HOME -> a named settings sub-screen. Confirms the anchor row appeared;
    counts one surface."""
    row = find_node_startswith(ui(), prefix)
    if not row or not tap_node(row):
        return False
    settle("tap")
    if find_node_ci(ui(), anchor) is None:
        return False
    and_enter(prefix)
    return True


def and_enter_dialog(row_label, option_present):
    """Open a ListPreference dialog by tapping its row; confirm a dialog-only
    option appeared. Counts one surface. (OK later dismisses it WITHOUT a BACK.)"""
    row = find_node_ci(ui(), row_label)
    if not row or not tap_node(row):
        return False
    settle("tap")
    if find_node_ci(ui(), option_present) is None:
        return False
    and_enter(row_label + " dialog")
    return True


def and_enter_keyboard_preview():
    """Tap 'Try out your setup'; FlorisBoard's own keyboard opens in a separate
    IME window and a Compose EditText appears. Counts one surface."""
    n = find_node_ci(ui(), "Try out your setup")
    if not n or not tap_node(n):
        return False
    settle("launch")
    settle("launch")                                  # IME window animates in
    ok = any(x.get("class", "").endswith("EditText") for x in ui())
    if ok:
        and_enter("keyboard-preview")
    return ok


def open_preview_keyboard():
    """Fresh app -> keyboard preview open with a VIRGIN (empty) field. Returns
    True when the keyboard window is up. Typing tests keep depth=0 (single
    surface, in-memory field)."""
    restart_app()
    wait_for_foreground()
    n = find_node_ci(ui(), "Try out your setup")
    if not n or not tap_node(n):
        return False
    settle("launch")
    settle("launch")
    return any(x.get("class", "").endswith("EditText") for x in ui())


def preview_field_text():
    """The preview EditText's current text ("" when empty/placeholder)."""
    for n in ui():
        if n.get("class", "").endswith("EditText"):
            return n.get("text", "")
    return None


# ══════════════════════════════════════════════════════════════════════════════
# 1) LONG-PRESS a ROW1 key -> its HINTED DIGIT  (sole owner; jump_kind="value")
#    Verified char-exact: q->"1", e->"3", t->"5" (hint = column i -> digit i+1).
# ══════════════════════════════════════════════════════════════════════════════
def _make_longpress_test(name, ch, col, digit):
    @and_test(expects=(name,))
    def _test():
        if not open_preview_keyboard():
            record(name, False,
                   "setup_failed: keyboard preview did not open (no EditText)",
                   depth=0, jump_kind="value",
                   expect=f"preview field == {digit!r} after long-pressing {ch!r}")
            return
        before = preview_field_text()
        # long-press ~850ms on the ROW1 key at column `col`
        x, y = kx_row1(col), int(ROW1_Y * _sh())
        adb_shell("input", "swipe", x, y, x, y, 850)
        settle("tap")
        after = preview_field_text()
        ok = (before == "") and (after == digit)
        record(name, ok,
               "" if ok else f"behavior_wrong: long-press {ch!r} produced {after!r}, "
               f"expected {digit!r} (started {before!r})",
               depth=0, jump_kind="value",
               expect=f"preview field == {digit!r} after long-pressing {ch!r} "
                      f"(was empty before)")
    _test.__name__ = "test_" + name
    return _test


test_longpress_q = _make_longpress_test(
    "interaction_longpress_q_digit", "q", 0, "1")
test_longpress_e = _make_longpress_test(
    "interaction_longpress_e_digit", "e", 2, "3")
test_longpress_t = _make_longpress_test(
    "interaction_longpress_t_digit", "t", 4, "5")


# ══════════════════════════════════════════════════════════════════════════════
# 2) MULTI-STEP typing sequences (3+ dependent actions -> a specific final string)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_seq_type_backspace",))
def test_seq_type_backspace():
    """type q, type w, BACKSPACE, type e  ==>  "qe". Each step depends on the
    prior field contents; a shell that only echoes the first key cannot land "qe"."""
    if not open_preview_keyboard():
        record("interaction_seq_type_backspace", False,
               "setup_failed: keyboard preview did not open", depth=0,
               jump_kind="value", expect="preview field == 'qe'")
        return
    start = preview_field_text()
    key1(0)                                            # q
    key1(1)                                            # w  -> "qw"
    mid = preview_field_text()
    kbackspace()                                       # -> "q"
    after_bs = preview_field_text()
    key1(2)                                            # e  -> "qe"
    final = preview_field_text()
    ok = (start == "" and mid == "qw" and after_bs == "q" and final == "qe")
    record("interaction_seq_type_backspace", ok,
           "" if ok else f"behavior_wrong: sequence gave start={start!r} "
           f"mid={mid!r} afterBS={after_bs!r} final={final!r}, expected "
           f"''->'qw'->'q'->'qe'",
           depth=0, jump_kind="value",
           expect="preview field == 'qe' after q,w,BACKSPACE,e")


@and_test(expects=("interaction_seq_space_word", "interaction_seq_space_word_vlm"))
def test_seq_space_word():
    """type h,i, SPACE, y,o,u  ==>  "hi you" (space preserved, no auto-caps)."""
    if not open_preview_keyboard():
        record("interaction_seq_space_word", False,
               "setup_failed: keyboard preview did not open", depth=0,
               jump_kind="value", expect="preview field == 'hi you'")
        record("interaction_seq_space_word_vlm", False,
               "setup_failed: keyboard preview did not open", depth=0,
               jump_kind="value", tag="content")
        return
    start = preview_field_text()
    key2(5)                                            # h
    key1(7)                                            # i  -> "hi"
    kspace()                                           # -> "hi "
    key1(5)                                            # y
    key1(8)                                            # o
    key1(6)                                            # u  -> "hi you"
    final = preview_field_text()
    ok = (start == "" and final == "hi you")
    record("interaction_seq_space_word", ok,
           "" if ok else f"behavior_wrong: sequence gave {final!r}, expected "
           f"'hi you' (started {start!r})",
           depth=0, jump_kind="value",
           expect="preview field == 'hi you' after h,i,SPACE,y,o,u")
    vlm_assert("interaction_seq_space_word",
               "Does the text input field above the keyboard show the two words "
               "\"hi you\" (with a single space between them)?",
               RESULTS_DIR, depth=0, jump_kind="value", tag="content")


@and_test(expects=("interaction_seq_comma_word",))
def test_seq_comma_word():
    """type h,i, COMMA, y,o,u  ==>  "hi,you" (verified char-exact: no auto-space
    after punctuation, no auto-caps). A 6-step sequence whose exact final string
    proves each key landed in order. Comma (x=0.24) is used rather than period
    because the wide space bar straddles the period position."""
    if not open_preview_keyboard():
        record("interaction_seq_comma_word", False,
               "setup_failed: keyboard preview did not open", depth=0,
               jump_kind="value", expect="preview field == 'hi,you'")
        return
    start = preview_field_text()
    key2(5)                                            # h
    key1(7)                                            # i
    kcomma()                                           # -> "hi,"
    mid = preview_field_text()
    key1(5)                                            # y
    key1(8)                                            # o
    key1(6)                                            # u
    final = preview_field_text()
    ok = (start == "" and mid == "hi," and final == "hi,you")
    record("interaction_seq_comma_word", ok,
           "" if ok else f"behavior_wrong: sequence gave mid={mid!r} final={final!r}, "
           f"expected ''->'hi,'->'hi,you'",
           depth=0, jump_kind="value",
           expect="preview field == 'hi,you' after h,i,COMMA,y,o,u")


@and_test(expects=("interaction_seq_word_then_backspaces",))
def test_seq_word_then_backspaces():
    """type q,w,e,r,t (=="qwert"), then 3 BACKSPACEs  ==>  prefix "qw"."""
    if not open_preview_keyboard():
        record("interaction_seq_word_then_backspaces", False,
               "setup_failed: keyboard preview did not open", depth=0,
               jump_kind="value", expect="preview field == 'qw'")
        return
    for i in range(5):                                 # q w e r t
        key1(i)
    full = preview_field_text()
    for _ in range(3):                                 # remove t, r, e
        kbackspace()
    final = preview_field_text()
    ok = (full == "qwert" and final == "qw")
    record("interaction_seq_word_then_backspaces", ok,
           "" if ok else f"behavior_wrong: typed {full!r} then 3 backspaces gave "
           f"{final!r}, expected 'qwert'->'qw'",
           depth=0, jump_kind="value",
           expect="preview field == 'qw' after typing 'qwert' and 3 backspaces")


@and_test(expects=("interaction_multistep_symbols_digit",
                   "interaction_multistep_symbols_digit_vlm"))
def test_multistep_symbols_digit():
    """MULTI-STEP layout switch + input: tap ?123 to switch to the symbols layout,
    then tap the '5' key (ROW1 column 4 in symbols == digit 5) ==> field "5".
    Two dependent steps: without the layout switch, ROW1 col 4 is the letter 't'."""
    if not open_preview_keyboard():
        record("interaction_multistep_symbols_digit", False,
               "setup_failed: keyboard preview did not open", depth=0,
               jump_kind="value", expect="preview field == '5'")
        record("interaction_multistep_symbols_digit_vlm", False,
               "setup_failed: keyboard preview did not open", depth=0,
               jump_kind="value", tag="position")
        return
    start = preview_field_text()
    ksymbols()                                         # switch to 1234567890 row
    # VLM about the layout BEFORE typing (digits visible as the top row)
    vlm_assert("interaction_multistep_symbols_digit",
               "Is the TOP row of the on-screen keyboard a row of number keys "
               "showing the digits 1 2 3 4 5 6 7 8 9 0?",
               RESULTS_DIR, depth=0, jump_kind="value", tag="position")
    key1(4)                                            # '5' in the symbols top row
    final = preview_field_text()
    ok = (start == "" and final == "5")
    record("interaction_multistep_symbols_digit", ok,
           "" if ok else f"behavior_wrong: ?123 then top-row col5 gave {final!r}, "
           f"expected '5' (started {start!r})",
           depth=0, jump_kind="value",
           expect="preview field == '5' after switching to symbols and tapping "
                  "the 5 key")


# ══════════════════════════════════════════════════════════════════════════════
# 3) SETTINGS PERSISTENCE across PROCESS DEATH (three screens) — the killer test
#    Each: clean baseline, flip a switch OFF->ON, force_stop_and_relaunch(),
#    re-open the screen, assert the flipped value survived. depth=1 (we navigate
#    to the screen to read the switch back), jump_kind="transition".
# ══════════════════════════════════════════════════════════════════════════════
def _make_persist_switch_test(name, section, anchor, switch_label):
    @and_test(expects=(name,))
    def _test():
        clear_data()
        launch_app()
        wait_for_foreground()
        if not and_enter_section(section, anchor):
            record(name, False,
                   f"setup_failed: could not reach the {section} screen",
                   depth=1, jump_kind="transition",
                   expect=f"'{switch_label}' still ON after process death")
            return
        sw = checkable_on_row(ui(), switch_label)
        if sw is None:
            record(name, False,
                   f"feature_missing: no '{switch_label}' switch on {section}",
                   depth=1, jump_kind="transition",
                   expect=f"'{switch_label}' still ON after process death")
            return
        before = sw.get("checked")
        tap_node(sw)
        settle("tap")
        flipped = checkable_on_row(ui(), switch_label)
        after = flipped.get("checked") if flipped else None
        toggled = (before == "false" and after == "true")

        force_stop_and_relaunch()
        wait_for_foreground()
        and_reset_depth()
        reached2 = and_enter_section(section, anchor)
        sw3 = checkable_on_row(ui(), switch_label) if reached2 else None
        survived = sw3 is not None and sw3.get("checked") == "true"
        ok = toggled and survived
        record(name, ok,
               "" if ok else f"behavior_wrong: '{switch_label}' before={before} "
               f"after_flip={after} after_death="
               f"{sw3.get('checked') if sw3 else None}; expected false->true->true",
               depth=1, jump_kind="transition",
               expect=f"'{switch_label}' remained ON (checked=true) after "
                      f"process death")
    _test.__name__ = "test_" + name
    return _test


test_persist_display_suggestions = _make_persist_switch_test(
    "interaction_persist_display_suggestions", "Typing",
    "Display suggestions", "Display suggestions")
test_persist_number_row = _make_persist_switch_test(
    "interaction_persist_number_row", "Keyboard", "Number row", "Number row")
test_persist_smartbar_flip = _make_persist_switch_test(
    "interaction_persist_smartbar_flip", "Smartbar",
    "Enable Smartbar", "Flip toggle buttons")


# ══════════════════════════════════════════════════════════════════════════════
# 4) ListPreference COMMIT that STICKS  (OK dismisses the dialog — NO back after)
#    (a) commit -> row summary shows the choice (transition, depth 1)
#    (b) reopen the dialog -> that radio is selected (value, depth 2)
#    (c) the committed choice survives PROCESS DEATH (transition, depth 1)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_listpref_utility_commit",
                   "interaction_listpref_utility_commit_vlm"))
def test_listpref_utility_commit():
    """Keyboard -> Utility key action -> pick NON-default 'Switch keyboard app',
    OK -> the row summary now reads 'Switch keyboard app' (was the Dynamic:...)."""
    clear_data()
    launch_app()
    wait_for_foreground()
    if not and_enter_section("Keyboard", "Utility key action"):
        record("interaction_listpref_utility_commit", False,
               "setup_failed: could not reach the Keyboard screen", depth=1,
               jump_kind="transition",
               expect="Utility-key-action summary == 'Switch keyboard app'")
        record("interaction_listpref_utility_commit_vlm", False,
               "setup_failed: could not reach the Keyboard screen", depth=1,
               jump_kind="transition", tag="content")
        return
    base = summary_below(ui(), "Utility key action")
    base_txt = base.get("text") if base else None
    if not and_enter_dialog("Utility key action", "Switch keyboard app"):
        record("interaction_listpref_utility_commit", False,
               "feature_missing: 'Utility key action' did not open a dialog with "
               "'Switch keyboard app'", depth=1, jump_kind="transition",
               expect="Utility-key-action summary == 'Switch keyboard app'")
        record("interaction_listpref_utility_commit_vlm", False,
               "feature_missing: utility dialog absent", depth=1,
               jump_kind="transition", tag="content")
        return
    tap_node(find_node_ci(ui(), "Switch keyboard app"))
    settle("tap")
    okb = find_node_ci(ui(), "OK")
    tapped = tap_node(okb) if okb else False
    settle("tap")                                      # OK commits AND closes the
    #  dialog, leaving us on the Keyboard screen — do NOT press BACK.
    now = summary_below(ui(), "Utility key action")
    now_txt = now.get("text") if now else None
    ok = (tapped and base_txt != "Switch keyboard app"
          and now_txt == "Switch keyboard app")
    record("interaction_listpref_utility_commit", ok,
           "" if ok else f"behavior_wrong: summary was {base_txt!r} before and "
           f"{now_txt!r} after committing 'Switch keyboard app'",
           depth=1, jump_kind="transition",
           expect="Utility-key-action summary == 'Switch keyboard app' after "
                  f"commit (was {base_txt!r})")
    vlm_assert("interaction_listpref_utility_commit",
               "On this Keyboard settings screen, is the text \"Switch keyboard "
               "app\" shown as the description under the 'Utility key action' row?",
               RESULTS_DIR, depth=1, jump_kind="transition", tag="content")


@and_test(expects=("interaction_listpref_utility_radio_reopen",))
def test_listpref_utility_radio_reopen():
    """After committing 'Switch keyboard app', REOPEN the dialog and assert its
    radio is the selected one (checked=true) while the others are not — the
    committed choice is stored, not just painted into the summary. depth=2 (the
    reopened dialog sits on top of the Keyboard screen)."""
    clear_data()
    launch_app()
    wait_for_foreground()
    if not and_enter_section("Keyboard", "Utility key action"):
        record("interaction_listpref_utility_radio_reopen", False,
               "setup_failed: could not reach the Keyboard screen", depth=2,
               jump_kind="value", expect="'Switch keyboard app' radio checked=true")
        return
    # commit the choice (OK closes the dialog; NO back)
    if not and_enter_dialog("Utility key action", "Switch keyboard app"):
        record("interaction_listpref_utility_radio_reopen", False,
               "feature_missing: utility dialog absent", depth=2,
               jump_kind="value", expect="'Switch keyboard app' radio checked=true")
        return
    tap_node(find_node_ci(ui(), "Switch keyboard app"))
    settle("tap")
    tap_node(find_node_ci(ui(), "OK"))
    settle("tap")
    # reopen the dialog straight from the Keyboard screen
    if not and_enter_dialog("Utility key action", "Switch keyboard app"):
        record("interaction_listpref_utility_radio_reopen", False,
               "behavior_wrong: dialog did not reopen after commit", depth=2,
               jump_kind="value", expect="'Switch keyboard app' radio checked=true")
        return
    nodes = ui()
    chosen = checkable_on_row(nodes, "Switch keyboard app")
    other1 = checkable_on_row(nodes, "Switch to emojis")
    other2 = checkable_on_row(nodes, "Switch language")
    ok = (chosen is not None and chosen.get("checked") == "true"
          and (other1 is None or other1.get("checked") == "false")
          and (other2 is None or other2.get("checked") == "false"))
    record("interaction_listpref_utility_radio_reopen", ok,
           "" if ok else "behavior_wrong: reopened dialog does not show 'Switch "
           f"keyboard app' as the single selected radio "
           f"(chosen={chosen.get('checked') if chosen else None})",
           depth=2, jump_kind="value",
           expect="reopened dialog: 'Switch keyboard app' radio checked=true, "
                  "other options checked=false")


@and_test(expects=("interaction_listpref_swipeup_commit",))
def test_listpref_swipeup_commit():
    """Gestures -> Swipe up -> pick NON-default 'No action', OK -> the Swipe up
    summary now reads 'No action' (default was 'Shift')."""
    clear_data()
    launch_app()
    wait_for_foreground()
    if not and_enter_section("Gestures", "General gestures"):
        record("interaction_listpref_swipeup_commit", False,
               "setup_failed: could not reach the Gestures screen", depth=1,
               jump_kind="transition", expect="Swipe up summary == 'No action'")
        return
    base = summary_below(ui(), "Swipe up")
    base_txt = base.get("text") if base else None
    if not and_enter_dialog("Swipe up", "No action"):
        record("interaction_listpref_swipeup_commit", False,
               "feature_missing: 'Swipe up' did not open a gesture-action dialog",
               depth=1, jump_kind="transition",
               expect="Swipe up summary == 'No action'")
        return
    tap_node(find_node_ci(ui(), "No action"))
    settle("tap")
    okb = find_node_ci(ui(), "OK")
    tapped = tap_node(okb) if okb else False
    settle("tap")                                      # OK closes the dialog — NO back
    now = summary_below(ui(), "Swipe up")
    now_txt = now.get("text") if now else None
    ok = (tapped and base_txt != "No action" and now_txt == "No action")
    record("interaction_listpref_swipeup_commit", ok,
           "" if ok else f"behavior_wrong: Swipe up summary was {base_txt!r} "
           f"before and {now_txt!r} after committing 'No action'",
           depth=1, jump_kind="transition",
           expect=f"Swipe up summary == 'No action' after commit (was {base_txt!r})")


@and_test(expects=("interaction_persist_listpref_utility",))
def test_persist_listpref_utility():
    """A committed ListPreference CHOICE survives PROCESS DEATH: commit 'Switch
    keyboard app', force_stop_and_relaunch(), reopen the Keyboard screen -> the
    summary is STILL 'Switch keyboard app'. An in-memory recreation loses it."""
    clear_data()
    launch_app()
    wait_for_foreground()
    if not and_enter_section("Keyboard", "Utility key action"):
        record("interaction_persist_listpref_utility", False,
               "setup_failed: could not reach the Keyboard screen", depth=1,
               jump_kind="transition",
               expect="Utility summary still 'Switch keyboard app' after death")
        return
    if not and_enter_dialog("Utility key action", "Switch keyboard app"):
        record("interaction_persist_listpref_utility", False,
               "feature_missing: utility dialog absent", depth=1,
               jump_kind="transition",
               expect="Utility summary still 'Switch keyboard app' after death")
        return
    tap_node(find_node_ci(ui(), "Switch keyboard app"))
    settle("tap")
    tap_node(find_node_ci(ui(), "OK"))
    settle("tap")                                      # OK closes the dialog — NO back
    committed = summary_below(ui(), "Utility key action")
    committed_ok = committed is not None and committed.get("text") == "Switch keyboard app"

    force_stop_and_relaunch()
    wait_for_foreground()
    and_reset_depth()
    reached2 = and_enter_section("Keyboard", "Utility key action")
    after = summary_below(ui(), "Utility key action") if reached2 else None
    after_txt = after.get("text") if after else None
    ok = committed_ok and after_txt == "Switch keyboard app"
    record("interaction_persist_listpref_utility", ok,
           "" if ok else f"behavior_wrong: committed={committed_ok}, summary after "
           f"process death={after_txt!r}; expected 'Switch keyboard app' to persist",
           depth=1, jump_kind="transition",
           expect="Utility-key-action summary still 'Switch keyboard app' after "
                  "process death")


# ══════════════════════════════════════════════════════════════════════════════
# 5) SLIDER drag -> summary value changes  (transition, depth 1) + position VLM
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_slider_font_size",
                   "interaction_slider_font_size_vlm"))
def test_slider_font_size():
    """Keyboard -> Font size multiplier -> drag the first SeekBar toward the left
    -> the on-screen '100%' drops below 100%, and after OK the row summary changes
    from '100% / 100%'. A slider that ignores drag keeps the value fixed."""
    clear_data()
    launch_app()
    wait_for_foreground()
    if not and_enter_section("Keyboard", "Font size multiplier"):
        record("interaction_slider_font_size", False,
               "setup_failed: could not reach the Keyboard screen", depth=1,
               jump_kind="transition", expect="Font-size summary != '100% / 100%'")
        record("interaction_slider_font_size_vlm", False,
               "setup_failed: could not reach the Keyboard screen", depth=1,
               jump_kind="transition", tag="position")
        return
    base = summary_below(ui(), "Font size multiplier")
    base_txt = base.get("text") if base else None
    row = find_node_ci(ui(), "Font size multiplier")
    if not row or not tap_node(row):
        record("interaction_slider_font_size", False,
               "feature_missing: Font size multiplier row not tappable", depth=1,
               jump_kind="transition", expect="Font-size summary != '100% / 100%'")
        record("interaction_slider_font_size_vlm", False,
               "feature_missing: slider dialog absent", depth=1,
               jump_kind="transition", tag="position")
        return
    settle("tap")
    and_enter("font-size slider dialog")
    seekbars = find_by_class(ui(), "SeekBar")
    if not seekbars:
        record("interaction_slider_font_size", False,
               "feature_missing: no SeekBar in the Font size dialog", depth=1,
               jump_kind="transition", expect="Font-size summary != '100% / 100%'")
        record("interaction_slider_font_size_vlm", False,
               "feature_missing: no slider", depth=1, jump_kind="transition",
               tag="position")
        return
    sb = seekbars[0]
    x1, y1, x2, y2 = sb["_bounds"]
    cy = (y1 + y2) // 2
    swipe(x2 - 5, cy, x1 + int((x2 - x1) * 0.30), cy, ms=500)   # drag left
    settle("tap")
    # VLM: the thumb / value is now in the LEFT portion, not at the far right.
    vlm_assert("interaction_slider_font_size",
               "Look at the topmost horizontal slider in this dialog. Is its round "
               "draggable thumb positioned in the LEFT half of the slider track "
               "(clearly not at the far right end)?",
               RESULTS_DIR, depth=1, jump_kind="transition", tag="position")
    okb = find_node_ci(ui(), "OK")
    tap_node(okb)
    settle("tap")                                      # OK closes the dialog — NO back
    now = summary_below(ui(), "Font size multiplier")
    now_txt = now.get("text") if now else None
    ok = (base_txt is not None and now_txt is not None and now_txt != base_txt)
    record("interaction_slider_font_size", ok,
           "" if ok else f"behavior_wrong: font-size summary was {base_txt!r} and "
           f"is {now_txt!r} after dragging the slider (expected a change)",
           depth=1, jump_kind="transition",
           expect=f"Font-size summary changed from {base_txt!r} after dragging the "
                  f"slider left (a lower percentage)")


# ══════════════════════════════════════════════════════════════════════════════
# 6) Quick-actions panel — smartbar leftmost grid icon opens a grid of tiles.
#    The tiles are drawn on a Compose CANVAS and never enter the view tree
#    (verified: dump shows no tiles, surface set unchanged), so its appearance is
#    a LEGITIMATE VLM-only consequence — recorded on the VLM track only.
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_quick_actions_panel_vlm",))
def test_quick_actions_panel():
    if not open_preview_keyboard():
        record("interaction_quick_actions_panel_vlm", False,
               "setup_failed: keyboard preview did not open", depth=1,
               jump_kind="transition", tag="layout")
        return
    and_enter("keyboard-preview")
    ksmartbar_actions()                                # tap leftmost grid icon
    settle("tap")
    vlm_assert("interaction_quick_actions_panel",
               "Is a panel of app-action tiles shown (a grid of several labelled "
               "buttons such as One-handed, Text editing, Resize and Emoji), "
               "replacing the normal word-suggestion strip above the keys?",
               RESULTS_DIR, depth=1, jump_kind="transition", tag="layout")


# ══════════════════════════════════════════════════════════════════════════════
# 7) Shifted keyboard — multi-step: tap shift, then a letter is UPPERCASE.
#    Rule backs it (field == 'Q'); VLM asserts the shift key is highlighted.
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_shift_uppercase",
                   "interaction_shift_uppercase_vlm"))
def test_shift_uppercase():
    if not open_preview_keyboard():
        record("interaction_shift_uppercase", False,
               "setup_failed: keyboard preview did not open", depth=0,
               jump_kind="value", expect="preview field == 'Q' after shift+q")
        record("interaction_shift_uppercase_vlm", False,
               "setup_failed: keyboard preview did not open", depth=0,
               jump_kind="value", tag="color")
        return
    kshift()                                           # engage shift
    # VLM about the shift state BEFORE typing (key highlighted / filled)
    vlm_assert("interaction_shift_uppercase",
               "On this keyboard the Shift key is at the bottom-left (an up-arrow). "
               "Is that Shift key visually highlighted with a filled/coloured "
               "background that is different from the other letter keys?",
               RESULTS_DIR, depth=0, jump_kind="value", tag="color")
    key1(0)                                            # q -> should commit 'Q'
    final = preview_field_text()
    ok = (final == "Q")
    record("interaction_shift_uppercase", ok,
           "" if ok else f"behavior_wrong: shift then 'q' produced {final!r}, "
           f"expected 'Q'",
           depth=0, jump_kind="value",
           expect="preview field == 'Q' after tapping shift then the q key")


# ══════════════════════════════════════════════════════════════════════════════
# 8) Reaching a data-entry surface: Languages -> Add subtype editor (depth 2)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_subtype_editor_reach",))
def test_subtype_editor_reach():
    """HOME -> Languages -> Add subtype opens the subtype EDITOR (a CRUD data-entry
    surface). Multi-step navigation to a create surface; proven by the editor's
    'Subtype presets' header appearing while the Languages-only manage-packs row
    is gone. We only REACH the editor (adding a subtype is not asserted, and we
    never tap a destructive control)."""
    restart_app()
    wait_for_foreground()
    if not and_enter_section("Languages", "Manage installed language packs"):
        record("interaction_subtype_editor_reach", False,
               "setup_failed: could not reach the Languages screen", depth=2,
               jump_kind="reach", expect="Subtype editor: 'Subtype presets' header")
        return
    add = find_node(ui(), content_desc="Add subtype")
    if add is None:
        record("interaction_subtype_editor_reach", False,
               "feature_missing: no 'Add subtype' control on Languages", depth=2,
               jump_kind="reach", expect="Subtype editor: 'Subtype presets' header")
        return
    reached = and_reach_surface(add, target="Subtype presets",
                                source="Manage installed language packs")
    record("interaction_subtype_editor_reach", reached,
           "" if reached else "behavior_wrong: 'Add subtype' did not open the "
           "subtype editor (header 'Subtype presets' did not appear / Languages "
           "row still showing)",
           depth=2, jump_kind="reach",
           expect="Subtype editor reached at depth 2: 'Subtype presets' header "
                  "appeared, Languages-only 'Manage installed language packs' gone")


TESTS = [
    # long-press -> hinted digit (sole owner; value)
    test_longpress_q,
    test_longpress_e,
    test_longpress_t,
    # multi-step typing sequences (value)
    test_seq_type_backspace,
    test_seq_space_word,              # + VLM content: field shows 'hi you'
    test_seq_comma_word,
    test_seq_word_then_backspaces,
    test_multistep_symbols_digit,     # + VLM position: digit row is the top row
    # settings persistence across process death (transition, depth 1)
    test_persist_display_suggestions,
    test_persist_number_row,
    test_persist_smartbar_flip,
    # ListPreference commit that sticks
    test_listpref_utility_commit,     # + VLM content: summary shows the choice
    test_listpref_utility_radio_reopen,
    test_listpref_swipeup_commit,
    test_persist_listpref_utility,    # committed choice survives process death
    # slider drag
    test_slider_font_size,            # + VLM position: thumb in left half
    # canvas-only panel & shifted state
    test_quick_actions_panel,         # VLM-only layout: grid of action tiles
    test_shift_uppercase,             # + VLM color: shift key highlighted
    # reach a CRUD data-entry surface (depth 2)
    test_subtype_editor_reach,
]

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