File size: 37,245 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
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
#!/usr/bin/env python3
"""INTERACTION lane — Urik Keyboard (com.urik.keyboard).

EFFECT-BY-CONSEQUENCE on user DATA/state: theme selection & favorites (CRUD-ish,
persist across activity navigation AND process death), LayoutMapper custom-char
multi-step (navigate depth 3 -> open sheet -> type -> save), multi-step settings
sequences (Spell Check disables two dependent rows), settings persistence across
process death (Haptic / Key Press Highlight / Suggestion Count), and test_field
input echo.

Every test restarts the app and navigates FORWARD (nested back() chains are flaky
per recon). Every mutated piece of state is RESTORED so the baseline stays clean.

    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


# ── shared helpers (plain; the and_enter/and_reach NAMES back declared depth) ────

def switch_for(nodes, title):
    """The Switch widget whose center-y is closest to the row `title` TextView.
    All switches share resource-id .../switchWidget, so id alone cannot pick one."""
    tn = find_node(nodes, text=title)
    if not tn:
        return None
    ty = tn["_center"][1]
    cands = [n for n in nodes
             if "Switch" in n.get("class", "")
             and n.get("resource-id", "").endswith("switchWidget")]
    return min(cands, key=lambda n: abs(n["_center"][1] - ty)) if cands else None


def summary_near(nodes, title, ymax=90):
    """The .../summary TextView vertically adjacent to the row `title`."""
    tn = find_node(nodes, text=title)
    if not tn:
        return None
    ty = tn["_center"][1]
    best = None
    for n in nodes:
        if n.get("resource-id", "").endswith("summary"):
            cy = n.get("_center", (0, 10 ** 9))[1]
            if abs(cy - ty) < ymax:
                best = n
    return best


def main_theme_label(nodes):
    """The theme-name TextView under the preview card on the launcher (no id).
    It sits below the rendered keyboard, above the buttons."""
    for n in nodes:
        if (n.get("class", "").endswith("TextView")
                and 1100 < n.get("_center", (0, 0))[1] < 1400
                and n.get("text", "")):
            return n
    return None


# ── surface-entry helpers (named and_enter_* / and_reach_* to back depth) ────────

def and_enter_settings():
    """Launcher -> SettingsActivity (MainSettingsFragment). depth +1."""
    nodes = ui()
    trig = find_node_ci(nodes, "Open Settings")
    if not trig or not tap_node(trig):
        return None
    and_enter("settings")
    return ui()


def and_enter_fragment(title):
    """SettingsActivity -> a preference sub-fragment by row title. depth +1.
    Assumes the settings list is already showing."""
    nodes = ui()
    row = find_node(nodes, text=title) or scroll_into_view(title)
    if not row or not tap_node(row):
        return None
    and_enter(title)
    return ui()


def and_reach_frag_from_launcher(title):
    """Launcher -> Settings -> <fragment>. Returns the fragment's node list or None.
    Two surfaces crossed (depth ends at 2)."""
    restart_app()
    wait_for_foreground()
    if and_enter_settings() is None:
        return None
    return and_enter_fragment(title)


def and_enter_theme_picker_from_main():
    """Launcher -> ThemePickerActivity by tapping the theme-name label. depth +1."""
    restart_app()
    wait_for_foreground()
    label = main_theme_label(ui())
    if not label or not tap_node(label):
        return None
    and_enter("theme_picker")
    settle("tap")
    return ui()


# ── ThemePicker robustness: the RecyclerView reorders (favorites float up) and
#    recycles children, so always scroll to the top then scan DOWN by text. ──────

def _scroll_picker_top(times=5):
    for _ in range(times):
        scroll_up(0.8)


def find_theme_card(name, max_swipes=8):
    """The FrameLayout card for `name` (content-desc "<name> theme"[, currently
    selected]), located by scrolling from the top."""
    _scroll_picker_top()
    for _ in range(max_swipes):
        nodes = ui()
        for n in nodes:
            cd = n.get("content-desc", "")
            if cd == f"{name} theme" or cd.startswith(f"{name} theme,"):
                return n, cd
        scroll_down(0.5)
    return None, None


def find_fav_control(name, max_swipes=8):
    """The favorite ImageView for `name`, whose content-desc is either
    'Add <name> to favorites' or 'Remove <name> from favorites'. Scrolls from
    the top so a just-favorited (floated-up) row is still found."""
    _scroll_picker_top()
    want = (f"Add {name} to favorites", f"Remove {name} from favorites")
    for _ in range(max_swipes):
        nodes = ui()
        for n in nodes:
            if n.get("content-desc", "") in want:
                return n, n.get("content-desc", "")
        scroll_down(0.5)
    return None, None


def select_theme_card(name):
    """Tap the theme card if it is not already selected. Returns the resulting
    content-desc (contains 'currently selected' when applied) or None."""
    card, cd = find_theme_card(name)
    if not card:
        return None
    if "currently selected" not in (cd or ""):
        tap_node(card)
        settle("tap")
    _c, cd2 = find_theme_card(name)
    return cd2


def restore_default_theme():
    """Set the theme back to Default so the suite leaves a clean baseline."""
    if and_enter_theme_picker_from_main() is None:
        return
    select_theme_card("Default")


def unfavorite(name):
    """Ensure `name` is NOT favorited (best-effort cleanup)."""
    n, cd = find_fav_control(name)
    if n and cd and cd.startswith("Remove"):
        tap_node(n)
        settle("tap")


# ══════════════════════════════════════════════════════════════════════════════
# THEMES — selection & favorites: persist across navigation and process death
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_theme_selection_persists_to_main",
                   "interaction_theme_selection_persists_to_main_vlm"))
def test_theme_selection_persists_to_main():
    """Select the Light theme in the picker, return to the launcher, and read the
    NEW theme name off the main-screen label — a consequence that crossed two
    surfaces (picker -> launcher). Then screenshot the recoloured preview."""
    NAME = "interaction_theme_selection_persists_to_main"
    if and_enter_theme_picker_from_main() is None:
        record(NAME, False,
               "setup_failed: could not open ThemePicker from the launcher label",
               depth=1, jump_kind="transition", expect="main label 'Light'")
        vlm_assert(NAME, "Does this screen show a keyboard theme picker with "
                   "multiple theme preview cards?", expect="YES",
                   depth=1, jump_kind="transition", tag="layout")
        return
    cd = select_theme_card("Light")
    applied = bool(cd and "currently selected" in cd)
    # cross back to the launcher (theme is persisted, not on the back stack)
    restart_app()
    wait_for_foreground()
    label = main_theme_label(ui())
    text_after = label.get("text") if label else None
    ok = applied and text_after == "Light"
    record(NAME, ok,
           "" if ok else f"behavior_wrong: main label was {text_after!r}, "
           f"expected 'Light' after selecting the Light theme",
           depth=2, jump_kind="transition", expect="main label 'Light'")
    # VLM: the main-screen preview keyboard should now render in LIGHT colours
    # (white/pale keys) instead of the dark Default palette.
    vlm_assert(NAME,
               "The keyboard preview card near the centre of this screen: are its "
               "keys drawn on a predominantly WHITE / very light background "
               "(a light colour theme), rather than dark?",
               expect="YES", depth=2, jump_kind="transition", tag="color")
    restore_default_theme()


@and_test(expects=("interaction_theme_selection_survives_restart",))
def test_theme_selection_survives_restart():
    """Select Abyss, kill the process, relaunch, and confirm the launcher label
    still reads Abyss — an in-memory-only recreation cannot pass this."""
    NAME = "interaction_theme_selection_survives_restart"
    if and_enter_theme_picker_from_main() is None:
        record(NAME, False,
               "setup_failed: could not open ThemePicker from the launcher label",
               depth=1, jump_kind="transition", expect="main label 'Abyss'")
        return
    cd = select_theme_card("Abyss")
    applied = bool(cd and "currently selected" in cd)
    force_stop_and_relaunch()
    wait_for_foreground()
    label = main_theme_label(ui())
    text_after = label.get("text") if label else None
    ok = applied and text_after == "Abyss"
    record(NAME, ok,
           "" if ok else f"behavior_wrong: main label was {text_after!r} after "
           f"process death, expected persisted 'Abyss'",
           depth=1, jump_kind="transition", expect="main label 'Abyss' after relaunch")
    restore_default_theme()


@and_test(expects=("interaction_theme_favorite_persists",
                   "interaction_theme_favorite_persists_vlm"))
def test_theme_favorite_persists():
    """Favorite the Crimson theme: its heart control flips Add->Remove, and the
    favorite survives a process restart (re-found after the list reorders)."""
    NAME = "interaction_theme_favorite_persists"
    if and_enter_theme_picker_from_main() is None:
        record(NAME, False, "setup_failed: could not open ThemePicker",
               depth=1, jump_kind="transition",
               expect="Remove Crimson from favorites")
        vlm_assert(NAME, "Is a favorite (heart) icon shown filled/solid on one of "
                   "the theme cards?", expect="YES",
                   depth=1, jump_kind="transition", tag="shape")
        return
    n0, cd0 = find_fav_control("Crimson")
    absent_before = cd0 == "Add Crimson to favorites"
    if n0 is None:
        record(NAME, False, "feature_missing: no favorite control on Crimson card",
               depth=1, jump_kind="transition",
               expect="Remove Crimson from favorites")
        vlm_assert(NAME, "Is a favorite (heart) icon shown on the Crimson theme "
                   "card, drawn as a filled/solid heart?", expect="YES",
                   depth=1, jump_kind="transition", tag="shape")
        return
    tap_node(n0)
    settle("tap")
    _n1, cd1 = find_fav_control("Crimson")
    flipped = cd1 == "Remove Crimson from favorites"
    # persistence across process death
    force_stop_and_relaunch()
    wait_for_foreground()
    if and_enter_theme_picker_from_main() is None:
        record(NAME, False, "setup_failed: could not reopen ThemePicker after restart",
               depth=1, jump_kind="transition",
               expect="Remove Crimson from favorites")
    else:
        _n2, cd2 = find_fav_control("Crimson")
        persisted = cd2 == "Remove Crimson from favorites"
        ok = absent_before and flipped and persisted
        record(NAME, ok,
               "" if ok else f"behavior_wrong: favorite flip/persist failed "
               f"(before={cd0!r} after={cd1!r} restart={cd2!r})",
               depth=1, jump_kind="transition",
               expect="Remove Crimson from favorites after relaunch")
    # VLM: the favorited Crimson card should show a FILLED heart
    find_fav_control("Crimson")     # scroll it into view for the screenshot
    vlm_assert(NAME,
               "On this theme list, is at least one theme card's favorite heart "
               "icon drawn as a FILLED / solid heart (as opposed to an empty "
               "outline)?",
               expect="YES", depth=1, jump_kind="transition", tag="shape")
    unfavorite("Crimson")           # restore clean baseline


@and_test(expects=("interaction_theme_favorite_multi_integrity",))
def test_theme_favorite_multi_integrity():
    """Favorite TWO themes (Crimson then Forest) and confirm BOTH independently
    report favorited — a recreation that keeps only one 'favorite' slot fails."""
    NAME = "interaction_theme_favorite_multi_integrity"
    if and_enter_theme_picker_from_main() is None:
        record(NAME, False, "setup_failed: could not open ThemePicker",
               depth=1, jump_kind="value",
               expect="Crimson & Forest both 'Remove ... from favorites'")
        return
    results = {}
    for name in ("Crimson", "Forest"):
        n, cd = find_fav_control(name)
        if n and cd and cd.startswith("Add"):
            tap_node(n)
            settle("tap")
        _n2, cd2 = find_fav_control(name)
        results[name] = cd2
    both = (results.get("Crimson") == "Remove Crimson from favorites"
            and results.get("Forest") == "Remove Forest from favorites")
    record(NAME, both,
           "" if both else f"behavior_wrong: expected both favorited, got {results!r}",
           depth=1, jump_kind="value",
           expect="Crimson='Remove Crimson from favorites' & "
                  "Forest='Remove Forest from favorites'")
    unfavorite("Crimson")
    unfavorite("Forest")


@and_test(expects=("interaction_theme_reselect_sequence",))
def test_theme_reselect_sequence():
    """3-step dependent sequence: select Light (becomes selected) -> then select
    Abyss -> assert the FINAL selection is Abyss AND Light is no longer marked
    selected. A dead shell that echoes the first pick fails the last step."""
    NAME = "interaction_theme_reselect_sequence"
    if and_enter_theme_picker_from_main() is None:
        record(NAME, False, "setup_failed: could not open ThemePicker",
               depth=1, jump_kind="value",
               expect="Abyss selected, Light not selected")
        return
    cd_light = select_theme_card("Light")
    light_sel = bool(cd_light and "currently selected" in cd_light)
    cd_abyss = select_theme_card("Abyss")
    abyss_sel = bool(cd_abyss and "currently selected" in cd_abyss)
    # re-read Light: it must no longer be selected
    _c, cd_light2 = find_theme_card("Light")
    light_cleared = bool(cd_light2) and "currently selected" not in cd_light2
    ok = light_sel and abyss_sel and light_cleared
    record(NAME, ok,
           "" if ok else f"behavior_wrong: light_sel={light_sel} abyss_sel="
           f"{abyss_sel} light_after={cd_light2!r}",
           depth=1, jump_kind="value",
           expect="final selected='Abyss theme, currently selected', "
                  "Light no longer selected")
    restore_default_theme()


# ══════════════════════════════════════════════════════════════════════════════
# LAYOUT MAPPER — long-press-key customization, multi-step (depth 3)
# ══════════════════════════════════════════════════════════════════════════════

def and_reach_layout_mapper():
    """Launcher -> Settings -> Layout & Input -> Customize Keys (LayoutMapper).
    Three surfaces. Returns the mapper node list (with the QWERTY buttons) or None."""
    restart_app()
    wait_for_foreground()
    if and_enter_settings() is None:
        return None
    nodes = ui()
    row = (find_node(nodes, text="Layout &amp; Input")
           or find_node(nodes, text="Number row, space bar size")
           or scroll_into_view("Number row, space bar size"))
    if not row or not tap_node(row):
        return None
    and_enter("layout_input")
    ck = scroll_into_view("Customize Keys")
    if not ck or not tap_node(ck):
        return None
    and_enter("layout_mapper")
    settle("tap")                       # let the rendered keyboard settle
    return ui()


def _reset_all_mappings():
    """Tap 'Reset All' and confirm — non-destructive to user vocab, clears only
    custom key maps (safe cleanup per recon)."""
    nodes = ui()
    rst = find_node_ci(nodes, "Reset All")
    if not rst or not tap_node(rst):
        return
    settle("tap")
    nodes = ui()
    for n in nodes:                     # the confirm dialog's Reset button
        if n.get("class", "").endswith("Button") and n.get("text", "") == "Reset":
            tap_node(n)
            settle("tap")
            return


@and_test(expects=("interaction_layoutmapper_custom_char",
                   "interaction_layoutmapper_custom_char_vlm"))
def test_layoutmapper_custom_char():
    """Multi-step (navigate depth 3 -> open bottom sheet -> type -> save): tap the
    'G' key, the 'Edit key: G' sheet appears, type 'z' into its EditText (field
    then HOLDS 'z'), tap Save, and the sheet CLOSES. Reset All to restore."""
    NAME = "interaction_layoutmapper_custom_char"
    nodes = and_reach_layout_mapper()
    if nodes is None:
        record(NAME, False,
               "setup_failed: could not reach LayoutMapper (Customize Keys)",
               depth=3, jump_kind="transition", expect="edit field holds 'z'")
        vlm_assert(NAME, "Is a bottom sheet titled like 'Edit key' shown over a "
                   "rendered keyboard?", expect="YES",
                   depth=3, jump_kind="transition", tag="layout")
        return
    # pick a stable middle-row key ('G' is reliably on screen)
    letters = [n for n in nodes
               if n.get("class", "").endswith("Button")
               and len(n.get("text", "")) == 1 and n.get("text", "").isalpha()]
    key = next((n for n in letters if n.get("text") == "G"),
               letters[0] if letters else None)
    if key is None:
        record(NAME, False, "feature_missing: no rendered letter keys to remap",
               depth=3, jump_kind="transition", expect="edit field holds 'z'")
        vlm_assert(NAME, "Is a bottom sheet titled like 'Edit key' shown over a "
                   "rendered keyboard?", expect="YES",
                   depth=3, jump_kind="transition", tag="layout")
        return
    letter = key.get("text")
    tap_node(key)
    settle("tap")
    nodes = ui()
    sheet_title = find_node(nodes, text=f"Edit key: {letter}")
    # the sheet's EditText is the one that is NOT the bottom test_field
    edits = [e for e in find_by_class(nodes, "EditText")
             if not e.get("resource-id", "").endswith("test_field")]
    edit = edits[0] if edits else None
    field_holds = False
    sheet_closed = False
    if sheet_title and edit:
        type_text(edit, "z")
        nodes = ui()
        fresh = find_closest_match(nodes, edit)
        field_holds = bool(fresh and fresh.get("text") == "z")
        # capture the sheet for the VLM before dismissing it
        vlm_assert(NAME,
                   "Is a bottom sheet / panel (containing a text input field and a "
                   "'Save' button) displayed in the lower part of the screen, "
                   "overlaying a rendered keyboard above it?",
                   expect="YES", depth=3, jump_kind="transition", tag="layout")
        save = find_node_ci(ui(), "Save")
        if save:
            tap_node(save)
            settle("tap")
        after = ui()
        sheet_closed = find_node(after, text=f"Edit key: {letter}") is None
    else:
        vlm_assert(NAME,
                   "Is a bottom sheet / panel (containing a text input field and a "
                   "'Save' button) displayed in the lower part of the screen, "
                   "overlaying a rendered keyboard above it?",
                   expect="YES", depth=3, jump_kind="transition", tag="layout")
    ok = bool(sheet_title) and field_holds and sheet_closed
    record(NAME, ok,
           "" if ok else f"behavior_wrong: sheet={bool(sheet_title)} "
           f"field_holds_z={field_holds} sheet_closed_after_save={sheet_closed}",
           depth=3, jump_kind="transition",
           expect=f"'Edit key: {letter}' sheet, field holds 'z', closes on Save")
    _reset_all_mappings()               # restore clean key-map state


# ══════════════════════════════════════════════════════════════════════════════
# MULTI-STEP SETTINGS SEQUENCE — one toggle changes TWO dependent rows
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_spellcheck_disables_dependents",))
def test_spellcheck_disables_dependents():
    """Multi-step consequence: toggle Spell Check OFF and read BACK the enabled
    state of the TWO dependent rows ('Pause on Misspelled Word' and
    'Autocorrection'), which both drop to enabled=false. Restore Spell Check ON."""
    NAME = "interaction_spellcheck_disables_dependents"
    if and_reach_frag_from_launcher("Auto-Correct Settings") is None:
        record(NAME, False,
               "setup_failed: could not reach Auto-Correct Settings",
               depth=2, jump_kind="transition",
               expect="Pause & Autocorrection enabled=false")
        return
    nodes = ui()
    sc = switch_for(nodes, "Spell Check")
    pause_b = find_node(nodes, text="Pause on Misspelled Word")
    auto_b = find_node(nodes, text="Autocorrection")
    both_enabled_before = (pause_b and pause_b.get("enabled") == "true"
                           and auto_b and auto_b.get("enabled") == "true")
    if not sc:
        record(NAME, False, "feature_missing: no Spell Check switch",
               depth=2, jump_kind="transition",
               expect="Pause & Autocorrection enabled=false")
        return
    tap_node(sc)
    settle("tap")
    nodes = ui()
    pause_a = find_node(nodes, text="Pause on Misspelled Word")
    auto_a = find_node(nodes, text="Autocorrection")
    both_disabled_after = (pause_a and pause_a.get("enabled") == "false"
                           and auto_a and auto_a.get("enabled") == "false")
    ok = bool(both_enabled_before) and bool(both_disabled_after)
    record(NAME, ok,
           "" if ok else "behavior_wrong: dependent rows did not both flip to "
           f"enabled=false (before both_enabled={bool(both_enabled_before)}, "
           f"after both_disabled={bool(both_disabled_after)})",
           depth=2, jump_kind="transition",
           expect="Pause & Autocorrection both enabled=false after Spell Check OFF")
    # restore Spell Check ON
    sc2 = switch_for(ui(), "Spell Check")
    if sc2 and sc2.get("checked") == "false":
        tap_node(sc2)
        settle("tap")


# ══════════════════════════════════════════════════════════════════════════════
# SETTINGS PERSISTENCE ACROSS PROCESS DEATH (DATA survival)
# ══════════════════════════════════════════════════════════════════════════════

def _toggle_switch_survives_restart(name, frag, title):
    """Toggle the switch `title` in fragment `frag` OFF, kill+relaunch, renavigate,
    and assert it is STILL off; then restore ON. Records `name`."""
    if and_reach_frag_from_launcher(frag) is None:
        record(name, False, f"setup_failed: could not reach {frag}",
               depth=2, jump_kind="transition", expect=f"{title} checked=false after restart")
        return
    scroll_into_view(title)
    sw = switch_for(ui(), title)
    if not sw:
        record(name, False, f"feature_missing: no {title} switch",
               depth=2, jump_kind="transition", expect=f"{title} checked=false after restart")
        return
    was_on = sw.get("checked") == "true"
    if was_on:
        tap_node(sw)
        settle("tap")
    off_now = switch_for(ui(), title)
    turned_off = off_now and off_now.get("checked") == "false"
    # process death + renavigate FORWARD
    force_stop_and_relaunch()
    wait_for_foreground()
    if and_reach_frag_from_launcher(frag) is None:
        record(name, False, f"setup_failed: could not re-reach {frag} after restart",
               depth=2, jump_kind="transition", expect=f"{title} checked=false after restart")
        return
    scroll_into_view(title)
    sw2 = switch_for(ui(), title)
    still_off = sw2 and sw2.get("checked") == "false"
    ok = bool(was_on) and bool(turned_off) and bool(still_off)
    record(name, ok,
           "" if ok else f"behavior_wrong: {title} did not persist OFF across "
           f"process death (was_on={bool(was_on)} off_now={bool(turned_off)} "
           f"still_off={bool(still_off)})",
           depth=2, jump_kind="transition",
           expect=f"{title} checked=false after relaunch")
    # restore ON
    sw3 = switch_for(ui(), title)
    if sw3 and sw3.get("checked") == "false":
        tap_node(sw3)
        settle("tap")


@and_test(expects=("interaction_haptic_survives_restart",))
def test_haptic_survives_restart():
    """Haptic Feedback OFF -> force stop + relaunch -> renavigate -> still OFF."""
    _toggle_switch_survives_restart(
        "interaction_haptic_survives_restart",
        "Typing Behavior Settings", "Haptic Feedback")


@and_test(expects=("interaction_keypress_highlight_survives_restart",))
def test_keypress_highlight_survives_restart():
    """Key Press Highlight OFF -> force stop + relaunch -> renavigate -> still OFF."""
    _toggle_switch_survives_restart(
        "interaction_keypress_highlight_survives_restart",
        "Appearance", "Key Press Highlight")


@and_test(expects=("interaction_suggestion_count_survives_restart",))
def test_suggestion_count_survives_restart():
    """Pick Suggestion Count '1' -> the ListPref summary becomes '1' -> force stop
    + relaunch -> renavigate -> summary STILL '1'. Restore to '3'."""
    NAME = "interaction_suggestion_count_survives_restart"
    if and_reach_frag_from_launcher("Auto-Correct Settings") is None:
        record(NAME, False, "setup_failed: could not reach Auto-Correct Settings",
               depth=2, jump_kind="transition", expect="Suggestion Count summary '1'")
        return
    scroll_into_view("Suggestion Count")
    nodes = ui()
    summ0 = summary_near(nodes, "Suggestion Count")
    before = summ0.get("text") if summ0 else None
    title = find_node(nodes, text="Suggestion Count")
    if not title:
        record(NAME, False, "feature_missing: no Suggestion Count preference",
               depth=2, jump_kind="transition", expect="Suggestion Count summary '1'")
        return
    tap_node(title)
    settle("tap")
    nodes = ui()
    opt1 = next((n for n in nodes
                 if n.get("class", "").endswith("CheckedTextView")
                 and n.get("text", "") == "1"), None)
    picked = False
    if opt1:
        tap_node(opt1)
        settle("tap")
        picked = True
    nodes = ui()
    summ1 = summary_near(nodes, "Suggestion Count")
    after_pick = summ1.get("text") if summ1 else None
    # process death + renavigate
    force_stop_and_relaunch()
    wait_for_foreground()
    persisted_val = None
    if and_reach_frag_from_launcher("Auto-Correct Settings") is not None:
        scroll_into_view("Suggestion Count")
        summ2 = summary_near(ui(), "Suggestion Count")
        persisted_val = summ2.get("text") if summ2 else None
    ok = picked and after_pick == "1" and persisted_val == "1"
    record(NAME, ok,
           "" if ok else f"behavior_wrong: Suggestion Count did not persist "
           f"(before={before!r} after_pick={after_pick!r} after_restart="
           f"{persisted_val!r})",
           depth=2, jump_kind="transition",
           expect="Suggestion Count summary '1' after relaunch")
    # restore to '3'
    nodes = ui()
    title = find_node(nodes, text="Suggestion Count")
    if title:
        tap_node(title)
        settle("tap")
        opt3 = next((n for n in ui()
                     if n.get("class", "").endswith("CheckedTextView")
                     and n.get("text", "") == "3"), None)
        if opt3:
            tap_node(opt3)
            settle("tap")


# ══════════════════════════════════════════════════════════════════════════════
# test_field INPUT ECHO — input persists in the field within a fragment
# ══════════════════════════════════════════════════════════════════════════════

def _test_field_echo(name, frag, marker):
    """Type `marker` into the fragment's bottom test_field and read it back.
    Asserts the marker was ABSENT before typing and PRESENT after."""
    if and_reach_frag_from_launcher(frag) is None:
        record(name, False, f"setup_failed: could not reach {frag}",
               depth=2, jump_kind="value", expect=f"test_field holds {marker!r}")
        return
    scroll_into_view("Test changes")
    tf = node_by_id(ui(), "test_field")
    if not tf:
        record(name, False, "feature_missing: no test_field EditText",
               depth=2, jump_kind="value", expect=f"test_field holds {marker!r}")
        return
    absent_before = tf.get("text", "") != marker
    type_text(tf, marker)
    fresh = node_by_id(ui(), "test_field")
    present_after = bool(fresh and fresh.get("text") == marker)
    ok = absent_before and present_after
    record(name, ok,
           "" if ok else f"behavior_wrong: test_field held "
           f"{(fresh or {}).get('text')!r}, expected {marker!r}",
           depth=2, jump_kind="value", expect=f"test_field holds {marker!r}")


@and_test(expects=("interaction_test_field_echo_autocorrect",))
def test_test_field_echo_autocorrect():
    """Type a distinctive marker into the Auto-Correct fragment's test_field."""
    _test_field_echo("interaction_test_field_echo_autocorrect",
                     "Auto-Correct Settings", "kit_echo_A")


@and_test(expects=("interaction_test_field_echo_appearance",))
def test_test_field_echo_appearance():
    """Type a distinctive marker into the Appearance fragment's test_field."""
    _test_field_echo("interaction_test_field_echo_appearance",
                     "Appearance", "kit_echo_B")


# ══════════════════════════════════════════════════════════════════════════════
# EXTRA VLM — visual consequences that the dump cannot express
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_theme_dark_applied_vlm",))
def test_theme_dark_applied_vlm():
    """Select the dark Abyss theme, return to the launcher, and confirm the
    preview keyboard renders in a DARK/BLACK palette (colour consequence)."""
    NAME = "interaction_theme_dark_applied"
    if and_enter_theme_picker_from_main() is None:
        vlm_assert(NAME, "Is a keyboard theme picker with multiple preview cards "
                   "shown?", expect="YES", depth=2, jump_kind="transition",
                   tag="color")
        return
    select_theme_card("Abyss")
    restart_app()
    wait_for_foreground()
    ui()   # settle the launcher render before the screenshot
    vlm_assert(NAME,
               "The keyboard preview card near the centre of this screen: are its "
               "keys drawn on a predominantly BLACK / very dark background "
               "(a dark colour theme)?",
               expect="YES", depth=2, jump_kind="transition", tag="color")
    restore_default_theme()


@and_test(expects=("interaction_spellcheck_dependents_dimmed_vlm",))
def test_spellcheck_dependents_dimmed_vlm():
    """After Spell Check OFF the two dependent rows are disabled — visually they
    render greyed/dimmed. Screenshot the AutoCorrect list in that state."""
    NAME = "interaction_spellcheck_dependents_dimmed"
    if and_reach_frag_from_launcher("Auto-Correct Settings") is None:
        vlm_assert(NAME, "Is a settings list with several toggle switches shown?",
                   expect="YES", depth=2, jump_kind="transition", tag="color")
        return
    sc = switch_for(ui(), "Spell Check")
    toggled = False
    if sc and sc.get("checked") == "true":
        tap_node(sc)
        settle("tap")
        toggled = True
    vlm_assert(NAME,
               "In this settings list, are the 'Pause on Misspelled Word' and "
               "'Autocorrection' rows shown greyed-out / dimmed (a faded, "
               "disabled appearance) compared with the fully-black active rows "
               "above them?",
               expect="YES", depth=2, jump_kind="transition", tag="color")
    # restore Spell Check ON
    sc2 = switch_for(ui(), "Spell Check")
    if toggled and sc2 and sc2.get("checked") == "false":
        tap_node(sc2)
        settle("tap")


@and_test(expects=("interaction_favorite_floats_to_top_vlm",))
def test_favorite_floats_to_top_vlm():
    """Favoriting a theme reorders the list so the favorited card floats up.
    Favorite Ocean, scroll to the top, and ask whether a filled-heart card is at
    the top of the list (position consequence)."""
    NAME = "interaction_favorite_floats_to_top"
    if and_enter_theme_picker_from_main() is None:
        vlm_assert(NAME, "Is a scrollable list of keyboard theme cards shown?",
                   expect="YES", depth=1, jump_kind="transition", tag="position")
        return
    n, cd = find_fav_control("Ocean")
    if n and cd and cd.startswith("Add"):
        tap_node(n)
        settle("tap")
    _scroll_picker_top()
    ui()
    vlm_assert(NAME,
               "At the very TOP of this theme list (the first one or two cards), "
               "is there a theme card whose favorite heart icon is FILLED / solid "
               "rather than an empty outline?",
               expect="YES", depth=1, jump_kind="transition", tag="position")
    unfavorite("Ocean")     # restore clean baseline


@and_test(expects=("interaction_selected_theme_checkmark_vlm",))
def test_selected_theme_checkmark_vlm():
    """Selecting a theme marks exactly that card as chosen with a checkmark badge.
    Select Abyss, then screenshot the picker (Abyss scrolled into view) and ask
    whether that card carries a distinct check/tick mark (shape consequence)."""
    NAME = "interaction_selected_theme_checkmark"
    if and_enter_theme_picker_from_main() is None:
        vlm_assert(NAME, "Is a keyboard theme picker with preview cards shown?",
                   expect="YES", depth=1, jump_kind="transition", tag="shape")
        return
    select_theme_card("Abyss")
    find_theme_card("Abyss")   # bring the selected card into view for the shot
    ui()
    vlm_assert(NAME,
               "On this theme list, is exactly one theme card marked as the "
               "currently-selected one with a check-mark / tick badge (a small "
               "checkmark icon), while the other cards have no such checkmark?",
               expect="YES", depth=1, jump_kind="transition", tag="shape")
    restore_default_theme()


# ── registry & entry point ──────────────────────────────────────────────────────

TESTS = [
    test_theme_selection_persists_to_main,       # +1 vlm
    test_theme_selection_survives_restart,
    test_theme_favorite_persists,                # +1 vlm
    test_theme_favorite_multi_integrity,
    test_theme_reselect_sequence,
    test_layoutmapper_custom_char,               # +1 vlm
    test_spellcheck_disables_dependents,
    test_haptic_survives_restart,
    test_keypress_highlight_survives_restart,
    test_suggestion_count_survives_restart,
    test_test_field_echo_autocorrect,
    test_test_field_echo_appearance,
    test_theme_dark_applied_vlm,                 # vlm-only
    test_spellcheck_dependents_dimmed_vlm,       # vlm-only
    test_favorite_floats_to_top_vlm,             # vlm-only
    test_selected_theme_checkmark_vlm,           # vlm-only
]

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