File size: 45,441 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
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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
#!/usr/bin/env python3
"""INTERACTION lane — effect-by-consequence on user DATA for the Aegis
Authenticator app (TOTP/HOTP 2FA). Sole owner of long-press / context menus and
of DATA persistence across process death.

Every test drives the app to Main via the portable resource-id path, performs a
data operation, and reads the consequence back out of a FRESH ui(). Nothing is
keyed on the package / paths / coordinates — the same file scores a from-scratch
recreation at a different package name.

Run:
  python3 test_android_interaction.py <PACKAGE> <RESULTS_DIR>
"""
import os
import sys

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

# Distinctive markers so a read-back cannot accidentally match pre-existing data.
SEC_A = "JBSWY3DPEHPK3PXP"
SEC_B = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"


# ── shared plumbing ─────────────────────────────────────────────────────────────

def _kb_off():
    """Dismiss the soft keyboard on the edit form WITHOUT navigating.

    The kit's hide_keyboard() falls back to BACK, and on EditEntryActivity BACK
    raises the "Your changes have not been saved" discard dialog instead of just
    lowering the keyboard — which corrupts a multi-field fill. KEYCODE_ESCAPE
    lowers the IME with no navigation and no dialog (verified on the original).
    """
    if keyboard_visible():
        press_key("KEYCODE_ESCAPE")
        settle("keyboard")
    return not keyboard_visible()


def and_enter_main(clear=False):
    """Get to MainActivity. clear=True wipes the vault first (virgin DB).

    Runs the 4-tap onboarding skip by resource-id only, choosing rb_none so the
    vault opens directly on every relaunch (no unlock screen). Returns the last
    fresh node list, or None if Main was never reached.
    """
    if clear:
        clear_data()
    restart_app()
    wait_for_foreground()
    n = ui()
    if node_by_id(n, "btnNext"):
        for rid in ("btnNext", "rb_none", "btnNext", "btnNext"):
            t = node_by_id(n, rid)
            if t is None or not tap_node(t):
                return None
            n = ui()
    if node_by_id(n, "fab") is None:
        return None
    return n


def _count_text(nodes=None):
    nodes = ui() if nodes is None else nodes
    c = node_by_id(nodes, "entries_shown_count")
    return (c or {}).get("text")


def _issuers(nodes=None):
    """Top-to-bottom list of profile_issuer strings currently shown."""
    nodes = ui() if nodes is None else nodes
    rows = [(x["_bounds"][1], x.get("text", ""))
            for x in nodes
            if x.get("resource-id", "").rsplit("/", 1)[-1] == "profile_issuer"
            and "_bounds" in x]
    return [t for _y, t in sorted(rows)]


def and_enter_editor():
    """Main -> FAB menu -> Enter manually -> EditEntryActivity. Backs depth via
    the and_enter_* NAME + an and_enter() call once the surface changes."""
    n = ui()
    fab = node_by_id(n, "fab")
    if fab is None or not tap_node(fab):
        return False
    n = ui()
    enter = node_by_id(n, "fab_menu_item_enter")
    if enter is None or not tap_node(enter):
        return False
    settle("tap")
    if not get_current_activity().endswith("EditEntryActivity"):
        return False
    and_enter("editor")
    return True


def and_create_entry(name, issuer, secret):
    """FAB -> Enter manually -> fill name/issuer/secret -> SAVE. Returns True only
    when we land back on Main with the new issuer visible. Robust: re-dumps after
    every field, lowers the keyboard between fields (secret sits below it), and
    handles the discard/error dialogs."""
    if not and_enter_editor():
        return False
    n = ui()
    nm = node_by_id(n, "text_name")
    if nm is None or not type_text(nm, name):
        return False
    _kb_off()
    n = ui()
    iss = node_by_id(n, "text_issuer")
    if iss is None or not type_text(iss, issuer):
        return False
    _kb_off()
    n = ui()
    sec = node_by_id(n, "text_secret")
    if sec is None or not type_text(sec, secret):
        return False
    _kb_off()
    n = ui()
    save = node_by_id(n, "action_save")
    if save is None or not tap_node(save):
        return False
    n = ui()
    if find_node_ci(n, "Error saving profile"):
        return False
    if find_node_ci(n, "Your changes have not been saved"):
        sv = find_node(n, text="Save")
        if sv:
            tap_node(sv)
            n = ui()
    if not get_current_activity().endswith("MainActivity"):
        return False
    return find_node_ci(ui(), issuer) is not None


def and_open_action_mode(issuer=None):
    """Long-press a row (the one with `issuer`, else the first) to enter the
    contextual action mode. Returns True once action_mode_close_button appears."""
    n = ui()
    row = None
    if issuer:
        for x in n:
            if (x.get("resource-id", "").rsplit("/", 1)[-1] == "profile_issuer"
                    and x.get("text") == issuer):
                row = x
                break
    if row is None:
        row = node_by_id(n, "profile_issuer")
    if row is None or not long_press(row):
        return False
    settle("tap")
    if node_by_id(ui(), "action_mode_close_button") is None:
        return False
    and_enter("action_mode")
    return True


def _exit_action_mode():
    n = ui()
    done = node_by_id(n, "action_mode_close_button")
    if done:
        tap_node(done)


def _clear_and_type(node, rid, val):
    """Clear an EditText (select-to-end + delete) then type `val`. No BACK."""
    if not tap_node(node):
        return False
    settle("keyboard")
    press_key("KEYCODE_MOVE_END")
    for _ in range(24):
        press_key("KEYCODE_DEL")
    settle("text")
    fresh = node_by_id(ui(), rid)
    if fresh is None:
        return False
    return type_text(fresh, val)


# ══════════════════════════════════════════════════════════════════════════════
# 1. Create entry -> count increments AND issuer appears
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_create_entry",))
def test_create_entry():
    if and_enter_main(clear=True) is None:
        record("interaction_create_entry", False,
               "setup_failed: could not reach MainActivity",
               depth=1, jump_kind="value", expect="Showing 1 entry + issuer 'iCreate'")
        return
    absent = find_node_ci(ui(), "iCreate") is None and _count_text() is None
    if not and_create_entry("nCreate", "iCreate", SEC_A):
        record("interaction_create_entry", False,
               "feature_missing: could not create an entry via FAB/Enter-manually",
               depth=1, jump_kind="value", expect="Showing 1 entry + issuer 'iCreate'")
        return
    n = ui()
    present = find_node_ci(n, "iCreate") is not None
    cnt = _count_text(n)
    ok = absent and present and cnt == "Showing 1 entry"
    record("interaction_create_entry", ok,
           "" if ok else f"behavior_wrong: after create count={cnt!r} "
                         f"issuer_present={present} (expected 'Showing 1 entry')",
           depth=1, jump_kind="value", expect="Showing 1 entry + issuer 'iCreate'")


# ══════════════════════════════════════════════════════════════════════════════
# 2. Create then read back -> count flips absent -> present (transition)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_create_absent_then_present",))
def test_create_absent_then_present():
    if and_enter_main(clear=True) is None:
        record("interaction_create_absent_then_present", False,
               "setup_failed: could not reach MainActivity",
               depth=1, jump_kind="transition", expect="issuer 'iFlip' absent->present")
        return
    before = find_node_ci(ui(), "iFlip") is not None
    if not and_create_entry("nFlip", "iFlip", SEC_A):
        record("interaction_create_absent_then_present", False,
               "feature_missing: could not create an entry",
               depth=1, jump_kind="transition", expect="issuer 'iFlip' absent->present")
        return
    after = find_node_ci(ui(), "iFlip") is not None
    ok = (not before) and after
    record("interaction_create_absent_then_present", ok,
           "" if ok else f"behavior_wrong: iFlip before={before} after={after}",
           depth=1, jump_kind="transition", expect="issuer 'iFlip' absent->present")


# ══════════════════════════════════════════════════════════════════════════════
# 3. Multi-record integrity: create 2 -> both present AND "Showing 2 entries"
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_multi_two_entries",))
def test_multi_two_entries():
    if and_enter_main(clear=True) is None:
        record("interaction_multi_two_entries", False,
               "setup_failed: could not reach MainActivity",
               depth=1, jump_kind="value", expect="Showing 2 entries + iMultiA + iMultiB")
        return
    if not and_create_entry("nMultiA", "iMultiA", SEC_A):
        record("interaction_multi_two_entries", False,
               "feature_missing: could not create the first entry",
               depth=1, jump_kind="value", expect="Showing 2 entries + iMultiA + iMultiB")
        return
    if not and_create_entry("nMultiB", "iMultiB", SEC_A):
        record("interaction_multi_two_entries", False,
               "behavior_wrong: could not create the second entry",
               depth=1, jump_kind="value", expect="Showing 2 entries + iMultiA + iMultiB")
        return
    n = ui()
    both = find_node_ci(n, "iMultiA") is not None and find_node_ci(n, "iMultiB") is not None
    cnt = _count_text(n)
    ok = both and cnt == "Showing 2 entries"
    record("interaction_multi_two_entries", ok,
           "" if ok else f"behavior_wrong: both_present={both} count={cnt!r} "
                         f"(expected 'Showing 2 entries')",
           depth=1, jump_kind="value", expect="Showing 2 entries + iMultiA + iMultiB")


# ══════════════════════════════════════════════════════════════════════════════
# 4. Multi-record integrity across an EDIT of the middle row (recreation killer:
#    an app that rebuilds the whole list keeping one row fails here)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_edit_middle_keeps_others",))
def test_edit_middle_keeps_others():
    if and_enter_main(clear=True) is None:
        record("interaction_edit_middle_keeps_others", False,
               "setup_failed: could not reach MainActivity",
               depth=2, jump_kind="value", expect="rows [iOne, iTwoEDIT, iThree]")
        return
    for nm, iss in (("n1", "iOne"), ("n2", "iTwo"), ("n3", "iThree")):
        if not and_create_entry(nm, iss, SEC_A):
            record("interaction_edit_middle_keeps_others", False,
                   f"feature_missing: could not create {iss}",
                   depth=2, jump_kind="value", expect="rows [iOne, iTwoEDIT, iThree]")
            return
    # Edit the middle row (iTwo) -> issuer iTwoEDIT.
    if not and_open_action_mode("iTwo"):
        record("interaction_edit_middle_keeps_others", False,
               "feature_missing: long-press did not open action mode on iTwo",
               depth=2, jump_kind="value", expect="rows [iOne, iTwoEDIT, iThree]")
        return
    n = ui()
    ed = node_by_id(n, "action_edit")
    if ed is None or not tap_node(ed):
        record("interaction_edit_middle_keeps_others", False,
               "feature_missing: no Edit control in action mode",
               depth=2, jump_kind="value", expect="rows [iOne, iTwoEDIT, iThree]")
        return
    and_enter("editor")
    n = ui()
    iss = node_by_id(n, "text_issuer")
    if iss is None or not _clear_and_type(iss, "text_issuer", "iTwoEDIT"):
        record("interaction_edit_middle_keeps_others", False,
               "behavior_wrong: could not change the issuer field",
               depth=2, jump_kind="value", expect="rows [iOne, iTwoEDIT, iThree]")
        return
    n = ui()
    save = node_by_id(n, "action_save")
    tap_node(save)
    n = ui()
    if find_node_ci(n, "Your changes have not been saved"):
        tap_node(find_node(n, text="Save"))
        n = ui()
    isr = _issuers(n)
    ok = ("iOne" in isr and "iThree" in isr and "iTwoEDIT" in isr
          and "iTwo" not in isr and len(isr) == 3)
    record("interaction_edit_middle_keeps_others", ok,
           "" if ok else f"behavior_wrong: rows after middle edit = {isr!r} "
                         f"(expected iOne, iTwoEDIT, iThree)",
           depth=2, jump_kind="value", expect="rows [iOne, iTwoEDIT, iThree]")


# ══════════════════════════════════════════════════════════════════════════════
# 5. Long-press -> contextual ACTION MODE controls appear (transition)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_longpress_action_mode",))
def test_longpress_action_mode():
    if and_enter_main(clear=True) is None or not and_create_entry("nLP", "iLP", SEC_A):
        record("interaction_longpress_action_mode", False,
               "setup_failed: could not create an entry to long-press",
               depth=1, jump_kind="transition",
               expect="Done/Copy/Edit/Favorite appear (absent before)")
        return
    n = ui()
    # Before: none of the action-mode controls present.
    before = all(node_by_id(n, r) is None for r in
                 ("action_mode_close_button", "action_copy", "action_edit",
                  "action_toggle_favorite"))
    if not and_open_action_mode("iLP"):
        record("interaction_longpress_action_mode", False,
               "feature_missing: long-press did not open action mode",
               depth=1, jump_kind="transition",
               expect="Done/Copy/Edit/Favorite appear (absent before)")
        return
    n = ui()
    got = [r for r in ("action_mode_close_button", "action_copy", "action_edit",
                       "action_toggle_favorite", "action_share_qr")
           if node_by_id(n, r) is not None]
    ok = before and len(got) >= 4
    _exit_action_mode()
    record("interaction_longpress_action_mode", ok,
           "" if ok else f"behavior_wrong: action-mode controls before_absent={before} "
                         f"present_now={got}",
           depth=1, jump_kind="transition",
           expect="Done/Copy/Edit/Favorite appear (absent before)")


# VLM #1: long-press selection highlight (color)
@and_test(expects=("interaction_longpress_highlight_vlm",))
def test_longpress_highlight_vlm():
    if and_enter_main(clear=True) is None or not and_create_entry("nHL", "iHL", SEC_A):
        record("interaction_longpress_highlight_vlm", False,
               "setup_failed: could not create an entry to long-press",
               depth=1, jump_kind="transition", tag="color")
        return
    if not and_open_action_mode("iHL"):
        record("interaction_longpress_highlight_vlm", False,
               "feature_missing: long-press did not open action mode",
               depth=1, jump_kind="transition", tag="color")
        return
    vlm_assert("interaction_longpress_highlight",
               "A single entry row in this authenticator list is long-press "
               "selected. Is exactly one list row visually highlighted with a "
               "different (tinted/darker) background colour than the rest of the "
               "screen?",
               RESULTS_DIR, expect="YES", depth=1, jump_kind="transition", tag="color")
    _exit_action_mode()


# ══════════════════════════════════════════════════════════════════════════════
# 6. Action-mode overflow -> Select all / Assign to group / Delete appear (reach)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_context_more_menu",))
def test_context_more_menu():
    if and_enter_main(clear=True) is None or not and_create_entry("nCM", "iCM", SEC_A):
        record("interaction_context_more_menu", False,
               "setup_failed: could not create an entry",
               depth=2, jump_kind="reach",
               expect="menu 'Select all'/'Assign to group'/'Delete'")
        return
    if not and_open_action_mode("iCM"):
        record("interaction_context_more_menu", False,
               "feature_missing: long-press did not open action mode",
               depth=2, jump_kind="reach",
               expect="menu 'Select all'/'Assign to group'/'Delete'")
        return
    n = ui()
    mo = find_node(n, content_desc="More options")
    before = and_showing(n)
    if mo is None or not tap_node(mo):
        record("interaction_context_more_menu", False,
               "feature_missing: no More-options overflow in action mode",
               depth=2, jump_kind="reach",
               expect="menu 'Select all'/'Assign to group'/'Delete'")
        return
    and_enter("context_menu")
    n = ui()
    after = and_showing(n)
    items = [t for t in ("Select all", "Assign to group", "Delete")
             if find_node_ci(n, t) is not None]
    reached = and_reach(before, after, "Select all")
    ok = reached and len(items) >= 2 and "Delete" in items
    # Close the menu without tapping any destructive item.
    back()
    _exit_action_mode()
    record("interaction_context_more_menu", ok,
           "" if ok else f"behavior_wrong: overflow items={items} reached={reached}",
           depth=2, jump_kind="reach",
           expect="menu 'Select all'/'Assign to group'/'Delete'")


# ══════════════════════════════════════════════════════════════════════════════
# 7. Edit entry: prefilled -> change name -> SAVE -> row shows NEW name, old gone
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_edit_prefilled",))
def test_edit_prefilled():
    if and_enter_main(clear=True) is None or not and_create_entry("nEd", "iEdOLD", SEC_A):
        record("interaction_edit_prefilled", False,
               "setup_failed: could not create an entry to edit",
               depth=2, jump_kind="value", expect="editor prefilled issuer 'iEdOLD'")
        return
    if not and_open_action_mode("iEdOLD"):
        record("interaction_edit_prefilled", False,
               "feature_missing: long-press did not open action mode",
               depth=2, jump_kind="value", expect="editor prefilled issuer 'iEdOLD'")
        return
    n = ui()
    ed = node_by_id(n, "action_edit")
    if ed is None or not tap_node(ed):
        record("interaction_edit_prefilled", False,
               "feature_missing: no Edit control in action mode",
               depth=2, jump_kind="value", expect="editor prefilled issuer 'iEdOLD'")
        return
    and_enter("editor")
    n = ui()
    # Prefilled check: the editor's issuer field equals what we created.
    prefilled_iss = (node_by_id(n, "text_issuer") or {}).get("text")
    prefilled_nm = (node_by_id(n, "text_name") or {}).get("text")
    ok = prefilled_iss == "iEdOLD" and prefilled_nm == "nEd"
    record("interaction_edit_prefilled", ok,
           "" if ok else f"behavior_wrong: editor prefilled issuer={prefilled_iss!r} "
                         f"name={prefilled_nm!r} (expected 'iEdOLD'/'nEd')",
           depth=2, jump_kind="value", expect="editor prefilled issuer 'iEdOLD'")


@and_test(expects=("interaction_edit_saves_new_name",))
def test_edit_saves_new_name():
    if and_enter_main(clear=True) is None or not and_create_entry("nEd2", "iEdA", SEC_A):
        record("interaction_edit_saves_new_name", False,
               "setup_failed: could not create an entry to edit",
               depth=2, jump_kind="value", expect="row issuer 'iEdB' present, 'iEdA' gone")
        return
    if not and_open_action_mode("iEdA"):
        record("interaction_edit_saves_new_name", False,
               "feature_missing: long-press did not open action mode",
               depth=2, jump_kind="value", expect="row issuer 'iEdB' present, 'iEdA' gone")
        return
    n = ui()
    ed = node_by_id(n, "action_edit")
    if ed is None or not tap_node(ed):
        record("interaction_edit_saves_new_name", False,
               "feature_missing: no Edit control in action mode",
               depth=2, jump_kind="value", expect="row issuer 'iEdB' present, 'iEdA' gone")
        return
    and_enter("editor")
    n = ui()
    iss = node_by_id(n, "text_issuer")
    if iss is None or not _clear_and_type(iss, "text_issuer", "iEdB"):
        record("interaction_edit_saves_new_name", False,
               "behavior_wrong: could not change the issuer field",
               depth=2, jump_kind="value", expect="row issuer 'iEdB' present, 'iEdA' gone")
        return
    n = ui()
    tap_node(node_by_id(n, "action_save"))
    n = ui()
    if find_node_ci(n, "Your changes have not been saved"):
        tap_node(find_node(n, text="Save"))
        n = ui()
    new_present = find_node_ci(n, "iEdB") is not None
    old_gone = find_node_ci(n, "iEdA") is None
    ok = new_present and old_gone and get_current_activity().endswith("MainActivity")
    record("interaction_edit_saves_new_name", ok,
           "" if ok else f"behavior_wrong: iEdB_present={new_present} iEdA_gone={old_gone}",
           depth=2, jump_kind="value", expect="row issuer 'iEdB' present, 'iEdA' gone")


# ══════════════════════════════════════════════════════════════════════════════
# 8. Favorite toggle: favoriting the BOTTOM entry pins it to the TOP (value)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_favorite_pins_top",))
def test_favorite_pins_top():
    if and_enter_main(clear=True) is None:
        record("interaction_favorite_pins_top", False,
               "setup_failed: could not reach MainActivity",
               depth=1, jump_kind="value", expect="favorited iFavC becomes first row")
        return
    for nm, iss in (("na", "iFavA"), ("nb", "iFavB"), ("nc", "iFavC")):
        if not and_create_entry(nm, iss, SEC_A):
            record("interaction_favorite_pins_top", False,
                   f"feature_missing: could not create {iss}",
                   depth=1, jump_kind="value", expect="favorited iFavC becomes first row")
            return
    order0 = _issuers()
    if not order0 or order0[0] == "iFavC":
        # Need iFavC NOT already first for the pin to be observable.
        record("interaction_favorite_pins_top", False,
               f"setup_failed: unexpected initial order {order0!r}",
               depth=1, jump_kind="value", expect="favorited iFavC becomes first row")
        return
    if not and_open_action_mode("iFavC"):
        record("interaction_favorite_pins_top", False,
               "feature_missing: long-press did not open action mode",
               depth=1, jump_kind="value", expect="favorited iFavC becomes first row")
        return
    n = ui()
    fav = node_by_id(n, "action_toggle_favorite")
    if fav is None or not tap_node(fav):
        record("interaction_favorite_pins_top", False,
               "feature_missing: no Favorite toggle in action mode",
               depth=1, jump_kind="value", expect="favorited iFavC becomes first row")
        return
    _exit_action_mode()
    order1 = _issuers()
    ok = bool(order1) and order1[0] == "iFavC" and set(order1) == set(order0)
    record("interaction_favorite_pins_top", ok,
           "" if ok else f"behavior_wrong: order before={order0!r} after favorite={order1!r} "
                         f"(expected iFavC first)",
           depth=1, jump_kind="value", expect="favorited iFavC becomes first row")


# VLM #2: favorite star/indicator rendering (shape)
@and_test(expects=("interaction_favorite_marker_vlm",))
def test_favorite_marker_vlm():
    if and_enter_main(clear=True) is None or not and_create_entry("nfm", "iFavM", SEC_A):
        record("interaction_favorite_marker_vlm", False,
               "setup_failed: could not create an entry to favorite",
               depth=1, jump_kind="transition", tag="shape")
        return
    if not and_open_action_mode("iFavM"):
        record("interaction_favorite_marker_vlm", False,
               "feature_missing: long-press did not open action mode",
               depth=1, jump_kind="transition", tag="shape")
        return
    n = ui()
    fav = node_by_id(n, "action_toggle_favorite")
    if fav is None or not tap_node(fav):
        record("interaction_favorite_marker_vlm", False,
               "feature_missing: no Favorite toggle in action mode",
               depth=1, jump_kind="transition", tag="shape")
        return
    _exit_action_mode()
    vlm_assert("interaction_favorite_marker",
               "One entry in this authenticator list was just marked as a "
               "favorite. Is there a small star-shaped indicator (a star icon or "
               "a coloured vertical bar) marking one of the entry rows as "
               "favorited?",
               RESULTS_DIR, expect="YES", depth=1, jump_kind="transition", tag="shape")


# ══════════════════════════════════════════════════════════════════════════════
# 9. PERSISTENCE across process death — the key in-memory-shell killer (value)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_persist_single",))
def test_persist_single():
    if and_enter_main(clear=True) is None or not and_create_entry("nPersist", "iPersist", SEC_A):
        record("interaction_persist_single", False,
               "setup_failed: could not create an entry to persist",
               depth=0, jump_kind="value", expect="issuer 'iPersist' + Showing 1 entry after relaunch")
        return
    cnt_before = _count_text()
    force_stop_and_relaunch()
    wait_for_foreground()
    n = ui()
    # rb_none means no unlock; data persisted means no onboarding either.
    present = find_node_ci(n, "iPersist") is not None
    cnt_after = _count_text(n)
    ok = present and cnt_after == "Showing 1 entry" and cnt_before == cnt_after
    record("interaction_persist_single", ok,
           "" if ok else f"behavior_wrong: after process death issuer_present={present} "
                         f"count={cnt_after!r} (expected 'Showing 1 entry')",
           depth=0, jump_kind="value",
           expect="issuer 'iPersist' + Showing 1 entry after relaunch")


@and_test(expects=("interaction_persist_multi_integrity",))
def test_persist_multi_integrity():
    if and_enter_main(clear=True) is None:
        record("interaction_persist_multi_integrity", False,
               "setup_failed: could not reach MainActivity",
               depth=0, jump_kind="value",
               expect="rows [iPa, iPb, iPc] + Showing 3 entries after relaunch")
        return
    for nm, iss in (("npa", "iPa"), ("npb", "iPb"), ("npc", "iPc")):
        if not and_create_entry(nm, iss, SEC_A):
            record("interaction_persist_multi_integrity", False,
                   f"feature_missing: could not create {iss}",
                   depth=0, jump_kind="value",
                   expect="rows [iPa, iPb, iPc] + Showing 3 entries after relaunch")
            return
    force_stop_and_relaunch()
    wait_for_foreground()
    n = ui()
    isr = set(_issuers(n))
    cnt = _count_text(n)
    ok = {"iPa", "iPb", "iPc"} <= isr and cnt == "Showing 3 entries"
    record("interaction_persist_multi_integrity", ok,
           "" if ok else f"behavior_wrong: after death issuers={sorted(isr)} count={cnt!r} "
                         f"(expected iPa/iPb/iPc + 'Showing 3 entries')",
           depth=0, jump_kind="value",
           expect="rows [iPa, iPb, iPc] + Showing 3 entries after relaunch")


@and_test(expects=("interaction_edit_persists",))
def test_edit_persists():
    """An edit must survive process death, not just live in memory."""
    if and_enter_main(clear=True) is None or not and_create_entry("nep", "iEpOLD", SEC_A):
        record("interaction_edit_persists", False,
               "setup_failed: could not create an entry to edit",
               depth=0, jump_kind="value", expect="issuer 'iEpNEW' after relaunch, 'iEpOLD' gone")
        return
    if not and_open_action_mode("iEpOLD"):
        record("interaction_edit_persists", False,
               "feature_missing: long-press did not open action mode",
               depth=0, jump_kind="value", expect="issuer 'iEpNEW' after relaunch, 'iEpOLD' gone")
        return
    n = ui()
    ed = node_by_id(n, "action_edit")
    if ed is None or not tap_node(ed):
        record("interaction_edit_persists", False,
               "feature_missing: no Edit control in action mode",
               depth=0, jump_kind="value", expect="issuer 'iEpNEW' after relaunch, 'iEpOLD' gone")
        return
    n = ui()
    iss = node_by_id(n, "text_issuer")
    if iss is None or not _clear_and_type(iss, "text_issuer", "iEpNEW"):
        record("interaction_edit_persists", False,
               "behavior_wrong: could not change the issuer field",
               depth=0, jump_kind="value", expect="issuer 'iEpNEW' after relaunch, 'iEpOLD' gone")
        return
    n = ui()
    tap_node(node_by_id(n, "action_save"))
    n = ui()
    if find_node_ci(n, "Your changes have not been saved"):
        tap_node(find_node(n, text="Save"))
    force_stop_and_relaunch()
    wait_for_foreground()
    n = ui()
    new_present = find_node_ci(n, "iEpNEW") is not None
    old_gone = find_node_ci(n, "iEpOLD") is None
    ok = new_present and old_gone
    record("interaction_edit_persists", ok,
           "" if ok else f"behavior_wrong: after death iEpNEW_present={new_present} "
                         f"iEpOLD_gone={old_gone}",
           depth=0, jump_kind="value", expect="issuer 'iEpNEW' after relaunch, 'iEpOLD' gone")


# ══════════════════════════════════════════════════════════════════════════════
# 10. Cancel / discard create -> no phantom row, count unchanged (transition)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_cancel_create_no_phantom",))
def test_cancel_create_no_phantom():
    if and_enter_main(clear=True) is None or not and_create_entry("nseed", "iSeed", SEC_A):
        record("interaction_cancel_create_no_phantom", False,
               "setup_failed: could not seed one entry",
               depth=1, jump_kind="transition", expect="count stays 'Showing 1 entry', no iPhantom")
        return
    cnt0 = _count_text()
    if not and_enter_editor():
        record("interaction_cancel_create_no_phantom", False,
               "feature_missing: could not open the create form",
               depth=1, jump_kind="transition", expect="count stays 'Showing 1 entry', no iPhantom")
        return
    n = ui()
    type_text(node_by_id(n, "text_issuer"), "iPhantom")
    _kb_off()
    # BACK without saving -> discard dialog -> Discard.
    back()
    n = ui()
    if find_node_ci(n, "Your changes have not been saved"):
        d = find_node(n, text="Discard")
        if d:
            tap_node(d)
            n = ui()
    cnt1 = _count_text(n)
    phantom = find_node_ci(ui(), "iPhantom") is not None
    ok = (cnt0 == cnt1 == "Showing 1 entry") and not phantom \
        and get_current_activity().endswith("MainActivity")
    record("interaction_cancel_create_no_phantom", ok,
           "" if ok else f"behavior_wrong: count {cnt0!r}->{cnt1!r} phantom_present={phantom}",
           depth=1, jump_kind="transition", expect="count stays 'Showing 1 entry', no iPhantom")


# ══════════════════════════════════════════════════════════════════════════════
# 11. Long-press action mode dismisses cleanly via Done (transition)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_action_mode_done_exits",))
def test_action_mode_done_exits():
    if and_enter_main(clear=True) is None or not and_create_entry("ndn", "iDone", SEC_A):
        record("interaction_action_mode_done_exits", False,
               "setup_failed: could not create an entry",
               depth=1, jump_kind="transition", expect="action mode -> Done -> back to list")
        return
    if not and_open_action_mode("iDone"):
        record("interaction_action_mode_done_exits", False,
               "feature_missing: long-press did not open action mode",
               depth=1, jump_kind="transition", expect="action mode -> Done -> back to list")
        return
    before = and_showing()
    n = ui()
    done = node_by_id(n, "action_mode_close_button")
    if done is None or not tap_node(done):
        record("interaction_action_mode_done_exits", False,
               "feature_missing: no Done control to leave action mode",
               depth=1, jump_kind="transition", expect="action mode -> Done -> back to list")
        return
    after = and_showing()
    # Done DISAPPEARED and the FAB (plain-list affordance) is back.
    gone = node_by_id(ui(), "action_mode_close_button") is None
    fab_back = node_by_id(ui(), "fab") is not None
    ok = gone and fab_back and surface_changed(before, after)
    record("interaction_action_mode_done_exits", ok,
           "" if ok else f"behavior_wrong: done_gone={gone} fab_back={fab_back}",
           depth=1, jump_kind="transition", expect="action mode -> Done -> back to list")


# ══════════════════════════════════════════════════════════════════════════════
# ── VLM cluster: rendered per-row / per-surface properties (distinct fine tags) ─
# All questions were authored from screenshots captured on the running original.
# ══════════════════════════════════════════════════════════════════════════════

# VLM #3 — avatar tile is a circle (shape)
@and_test(expects=("interaction_row_avatar_vlm",))
def test_row_avatar_vlm():
    if and_enter_main(clear=True) is None or not and_create_entry("nAv", "Zebra", SEC_A):
        record("interaction_row_avatar_vlm", False,
               "setup_failed: could not create an entry",
               depth=0, jump_kind="none", tag="shape")
        return
    vlm_assert("interaction_row_avatar",
               "In this authenticator list, does the entry whose issuer is "
               "'Zebra' have a round circular avatar tile on its left side "
               "(a coloured circle, typically showing a letter)?",
               RESULTS_DIR, expect="YES", depth=0, jump_kind="none", tag="shape")


# VLM #4 — avatar shows the issuer's first letter (content)
@and_test(expects=("interaction_row_avatar_letter_vlm",))
def test_row_avatar_letter_vlm():
    if and_enter_main(clear=True) is None or not and_create_entry("nQ", "Quartz", SEC_A):
        record("interaction_row_avatar_letter_vlm", False,
               "setup_failed: could not create an entry",
               depth=0, jump_kind="none", tag="content")
        return
    vlm_assert("interaction_row_avatar_letter",
               "The single entry in this authenticator list has issuer 'Quartz'. "
               "Does its round avatar tile on the left contain the capital letter "
               "'Q' (the first letter of the issuer)?",
               RESULTS_DIR, expect="YES", depth=0, jump_kind="none", tag="content")


# VLM #5 — each entry sits inside its own rounded card (shape)
@and_test(expects=("interaction_row_card_shape_vlm",))
def test_row_card_shape_vlm():
    if and_enter_main(clear=True) is None or not and_create_entry("nCard", "iCard", SEC_A):
        record("interaction_row_card_shape_vlm", False,
               "setup_failed: could not create an entry",
               depth=0, jump_kind="none", tag="shape")
        return
    vlm_assert("interaction_row_card_shape",
               "In this authenticator list, is the single entry drawn inside its "
               "own rounded-corner rectangular card/tile whose fill colour differs "
               "from the plain page background around it?",
               RESULTS_DIR, expect="YES", depth=0, jump_kind="none", tag="shape")


# VLM #6 — TOTP code digits are a solid accent colour (color)
@and_test(expects=("interaction_row_code_color_vlm",))
def test_row_code_color_vlm():
    if and_enter_main(clear=True) is None or not and_create_entry("nCol", "iCol", SEC_A):
        record("interaction_row_code_color_vlm", False,
               "setup_failed: could not create an entry",
               depth=0, jump_kind="none", tag="color")
        return
    vlm_assert("interaction_row_code_color",
               "Look at the large TOTP code digits on the entry row. Are the code "
               "digits rendered in a single solid colour (a coloured accent such "
               "as red/green/blue) rather than plain black or grey body text?",
               RESULTS_DIR, expect="YES", depth=0, jump_kind="none", tag="color")


# VLM #7 — FAB menu options stack above the FAB (position)
@and_test(expects=("interaction_fab_menu_layout_vlm",))
def test_fab_menu_layout_vlm():
    if and_enter_main(clear=True) is None:
        record("interaction_fab_menu_layout_vlm", False,
               "setup_failed: could not reach MainActivity",
               depth=1, jump_kind="transition", tag="position")
        return
    n = ui()
    fab = node_by_id(n, "fab")
    if fab is None or not tap_node(fab):
        record("interaction_fab_menu_layout_vlm", False,
               "feature_missing: FAB not tappable",
               depth=1, jump_kind="transition", tag="position")
        return
    and_enter("fab_menu")
    # confirm the menu opened before asking the VLM
    if node_by_id(ui(), "fab_menu_item_enter") is None:
        record("interaction_fab_menu_layout_vlm", False,
               "feature_missing: FAB menu did not expand",
               depth=1, jump_kind="transition", tag="position")
        return
    vlm_assert("interaction_fab_menu_layout",
               "The add-entry menu is open. Are its options stacked vertically as "
               "a column of labelled items positioned above the floating action "
               "button in the bottom-right area of the screen?",
               RESULTS_DIR, expect="YES", depth=1, jump_kind="transition", tag="position")
    back()


# VLM #8 — action bar shows a horizontal row of icons (layout)
@and_test(expects=("interaction_action_toolbar_layout_vlm",))
def test_action_toolbar_layout_vlm():
    if and_enter_main(clear=True) is None or not and_create_entry("nTb", "iTb", SEC_A):
        record("interaction_action_toolbar_layout_vlm", False,
               "setup_failed: could not create an entry",
               depth=1, jump_kind="transition", tag="layout")
        return
    if not and_open_action_mode("iTb"):
        record("interaction_action_toolbar_layout_vlm", False,
               "feature_missing: long-press did not open action mode",
               depth=1, jump_kind="transition", tag="layout")
        return
    # NOTE: the vlm_assert name MUST equal the declared expects (minus the _vlm
    # suffix the kit appends) or the record drifts the denominator.
    vlm_assert("interaction_action_toolbar_layout",
               "The contextual action bar is showing at the top after a "
               "long-press. Does the top bar display a horizontal row of several "
               "action icons (such as copy, edit, favourite, share/QR)?",
               RESULTS_DIR, expect="YES", depth=1, jump_kind="transition", tag="layout")
    _exit_action_mode()


# VLM #9 — after process death, list is NOT in selection mode (color)
@and_test(expects=("interaction_persist_highlight_gone_vlm",))
def test_persist_highlight_gone_vlm():
    """After process death the list is NOT in selection mode: no row highlighted.
    A rendered-state check that complements the rule persistence tests."""
    if and_enter_main(clear=True) is None or not and_create_entry("nph", "iPH", SEC_A):
        record("interaction_persist_highlight_gone_vlm", False,
               "setup_failed: could not create an entry",
               depth=0, jump_kind="value", tag="color")
        return
    force_stop_and_relaunch()
    wait_for_foreground()
    if node_by_id(ui(), "fab") is None:
        record("interaction_persist_highlight_gone_vlm", False,
               "behavior_wrong: not on the entry list after relaunch",
               depth=0, jump_kind="value", tag="color")
        return
    vlm_assert("interaction_persist_highlight_gone",
               "This authenticator list was just relaunched from a killed "
               "process. Is the list in its normal state with NO row highlighted "
               "or selected (i.e. every row shares the same background colour)?",
               RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="color")


TESTS = [
    test_create_entry,
    test_create_absent_then_present,
    test_multi_two_entries,
    test_edit_middle_keeps_others,
    test_longpress_action_mode,
    test_longpress_highlight_vlm,
    test_context_more_menu,
    test_edit_prefilled,
    test_edit_saves_new_name,
    test_favorite_pins_top,
    test_favorite_marker_vlm,
    test_persist_single,
    test_persist_multi_integrity,
    test_edit_persists,
    test_cancel_create_no_phantom,
    test_action_mode_done_exits,
    test_row_avatar_vlm,
    test_row_avatar_letter_vlm,
    test_row_card_shape_vlm,
    test_row_code_color_vlm,
    test_fab_menu_layout_vlm,
    test_action_toolbar_layout_vlm,
    test_persist_highlight_gone_vlm,
]

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