File size: 45,200 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
#!/usr/bin/env python3
"""COMPUTATION lane — the app's CORE FUNCTION (input -> output) for the Aegis
Authenticator (TOTP/HOTP 2FA). Sole owner of jump_kind="value".

The core transform is TOTP code generation. Absolute code values are NOT asserted
against wall-clock time — there is a ~30 s clock skew between adb and the app, so
an absolute code is flaky. Every value test here is DETERMINISTIC and
clock-independent:

  * same secret        -> identical code          (RFC-6238 is a pure function)
  * different secret   -> (almost surely) differ
  * digits setting     -> code length             (6 default, 8 configured)
  * code format        -> digits + spaces only, len(strip) == configured digits
  * search filter      -> "Showing N entries" + which issuers remain visible

All expected values were OBSERVED on the running original, never computed here.

Nothing is keyed on package / paths / coordinates: the same file scores a
from-scratch recreation at a different package name.

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

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

# Distinctive markers + valid base32 secrets (from recon; verified live).
SEC_A = "JBSWY3DPEHPK3PXP"
SEC_B = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"


# ── shared plumbing (own copies — NOT imported from the interaction lane) ────────

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

    The kit's hide_keyboard() can fall back to BACK, and on EditEntryActivity BACK
    raises the "changes have not been saved" discard dialog which corrupts a
    multi-field fill. KEYCODE_ESCAPE lowers the IME with no navigation (verified).
    """
    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 _code_for(issuer, nodes=None):
    """profile_code of the row whose profile_issuer == `issuer` (space-stripped).

    Matches by y-band: the issuer label and its code sit on the same row, so the
    code is the profile_code node closest below the issuer's top edge. Returns ""
    when not found.
    """
    nodes = ui() if nodes is None else nodes
    iss_y = None
    for x in nodes:
        if (x.get("resource-id", "").rsplit("/", 1)[-1] == "profile_issuer"
                and x.get("text") == issuer and "_bounds" in x):
            iss_y = x["_bounds"][1]
            break
    if iss_y is None:
        return ""
    best, best_dy = "", 10 ** 9
    for x in nodes:
        if (x.get("resource-id", "").rsplit("/", 1)[-1] == "profile_code"
                and "_bounds" in x):
            dy = abs(x["_bounds"][1] - iss_y)
            if dy < best_dy:
                best, best_dy = x.get("text", ""), dy
    # Only accept a code on the same row (rows are ~300px tall on this device).
    return best.replace(" ", "") if best_dy < 260 else ""


def _all_codes(nodes=None):
    """Every profile_code on screen (space-stripped), top-to-bottom."""
    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_code"
            and "_bounds" in x]
    return [t.replace(" ", "") for _y, t in sorted(rows)]


def _raw_code_text(issuer, nodes=None):
    """The profile_code text WITH spaces (to check the grouping format)."""
    nodes = ui() if nodes is None else nodes
    iss_y = None
    for x in nodes:
        if (x.get("resource-id", "").rsplit("/", 1)[-1] == "profile_issuer"
                and x.get("text") == issuer and "_bounds" in x):
            iss_y = x["_bounds"][1]
            break
    if iss_y is None:
        return ""
    best, best_dy = "", 10 ** 9
    for x in nodes:
        if (x.get("resource-id", "").rsplit("/", 1)[-1] == "profile_code"
                and "_bounds" in x):
            dy = abs(x["_bounds"][1] - iss_y)
            if dy < best_dy:
                best, best_dy = x.get("text", ""), dy
    return best if best_dy < 260 else ""


def _row_node(issuer, nodes=None):
    """The profile_issuer node with text == issuer, from a fresh/given dump."""
    nodes = ui() if nodes is None else nodes
    for x in nodes:
        if (x.get("resource-id", "").rsplit("/", 1)[-1] == "profile_issuer"
                and x.get("text") == issuer):
            return x
    return None


def and_enter_editor():
    """Main -> FAB menu -> Enter manually -> EditEntryActivity. Backs a depth>=1
    claim 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 _clear_field(node, rid):
    """Select-to-end + delete an EditText, then return the fresh node."""
    if not tap_node(node):
        return None
    settle("keyboard")
    press_key("KEYCODE_MOVE_END")
    for _ in range(14):
        press_key("KEYCODE_DEL")
    settle("text")
    return node_by_id(ui(), rid)


def and_expand_advanced():
    """On EditEntryActivity, expand the Advanced accordion so text_digits /
    dropdown_type become visible. Counts as crossing into that section."""
    n = ui()
    if node_by_id(n, "text_digits") is not None:
        return True                       # already expanded
    hdr = node_by_id(n, "accordian_header") or find_node_ci(n, "Advanced")
    if hdr is None or not tap_node(hdr):
        return False
    settle("tap")
    if node_by_id(ui(), "text_digits") is None:
        return False
    and_enter("advanced")
    return True


def and_create_entry(name, issuer, secret, *, digits=None, type_name=None):
    """FAB -> Enter manually -> fill name/issuer/secret (+ optional Advanced
    digits / type) -> SAVE. Returns True only when we land on Main with the new
    issuer visible."""
    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()
    if digits is not None or type_name is not None:
        if not and_expand_advanced():
            return False
        if type_name is not None:
            n = ui()
            dd = node_by_id(n, "dropdown_type")
            if dd is None or not tap_node(dd):
                return False
            settle("tap")
            opt = find_node_ci(ui(), type_name)
            if opt is None or not tap_node(opt):
                return False
            settle("tap")
            _kb_off()
        if digits is not None:
            n = ui()
            dg = node_by_id(n, "text_digits")
            dg = _clear_field(dg, "text_digits")
            if dg is None or not type_text(dg, str(digits)):
                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_search():
    """Main -> Search icon -> in-toolbar SearchView. Counts one surface."""
    n = ui()
    sb = node_by_id(n, "search_button")
    if sb is None or not tap_node(sb):
        return False
    settle("tap")
    if node_by_id(ui(), "search_src_text") is None:
        return False
    and_enter("search")
    return True


def _type_search(query):
    """Clear the search field then type `query`. Returns the visible field text."""
    st = node_by_id(ui(), "search_src_text")
    if st is None:
        return None
    tap_node(st)
    settle("keyboard")
    press_key("KEYCODE_MOVE_END")
    for _ in range(16):
        press_key("KEYCODE_DEL")
    settle("text")
    st = node_by_id(ui(), "search_src_text")
    if st is None or not type_text(st, query):
        return None
    return (node_by_id(ui(), "search_src_text") or {}).get("text")


# ══════════════════════════════════════════════════════════════════════════════
# 1. PRIMARY value test — same secret -> IDENTICAL code (RFC-6238 is a function)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_same_secret_same_code",))
def test_same_secret_same_code():
    if and_enter_main(clear=True) is None:
        record("computation_same_secret_same_code", False,
               "setup_failed: could not reach MainActivity",
               depth=0, jump_kind="value", expect="iSameA code == iSameB code")
        return
    if not (and_create_entry("nSameA", "iSameA", SEC_B)
            and and_create_entry("nSameB", "iSameB", SEC_B)):
        record("computation_same_secret_same_code", False,
               "feature_missing: could not create two entries",
               depth=0, jump_kind="value", expect="iSameA code == iSameB code")
        return
    n = ui()
    ca, cb = _code_for("iSameA", n), _code_for("iSameB", n)
    ok = bool(ca) and bool(cb) and ca == cb
    record("computation_same_secret_same_code", ok,
           "" if ok else f"behavior_wrong: identical secret gave codes "
                         f"{ca!r} vs {cb!r} (must be equal)",
           depth=0, jump_kind="value", expect="iSameA code == iSameB code")


# ══════════════════════════════════════════════════════════════════════════════
# 2. Different secrets -> different codes (almost surely)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_diff_secret_diff_code",))
def test_diff_secret_diff_code():
    if and_enter_main(clear=True) is None:
        record("computation_diff_secret_diff_code", False,
               "setup_failed: could not reach MainActivity",
               depth=0, jump_kind="value", expect="iDiffA code != iDiffB code")
        return
    if not (and_create_entry("nDiffA", "iDiffA", SEC_A)
            and and_create_entry("nDiffB", "iDiffB", SEC_B)):
        record("computation_diff_secret_diff_code", False,
               "feature_missing: could not create two entries",
               depth=0, jump_kind="value", expect="iDiffA code != iDiffB code")
        return
    n = ui()
    ca, cb = _code_for("iDiffA", n), _code_for("iDiffB", n)
    ok = bool(ca) and bool(cb) and ca != cb
    record("computation_diff_secret_diff_code", ok,
           "" if ok else f"behavior_wrong: different secrets gave equal code "
                         f"{ca!r} == {cb!r}",
           depth=0, jump_kind="value", expect="iDiffA code != iDiffB code")


# ══════════════════════════════════════════════════════════════════════════════
# 3. Default code length == 6 digits (format "XXX XXX")
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_default_six_digits",))
def test_default_six_digits():
    if and_enter_main(clear=True) is None or not and_create_entry("n6", "iSix", SEC_A):
        record("computation_default_six_digits", False,
               "setup_failed: could not create a default entry",
               depth=0, jump_kind="value", expect="code has exactly 6 digits")
        return
    n = ui()
    code = _code_for("iSix", n)
    ok = bool(code) and len(code) == 6 and code.isdigit()
    record("computation_default_six_digits", ok,
           "" if ok else f"behavior_wrong: default code {code!r} has "
                         f"{len(code)} digits (expected 6)",
           depth=0, jump_kind="value", expect="code has exactly 6 digits")


# ══════════════════════════════════════════════════════════════════════════════
# 4. Default grouping format is exactly "XXX XXX"
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_default_grouping_format",))
def test_default_grouping_format():
    if and_enter_main(clear=True) is None or not and_create_entry("ng", "iGrp", SEC_A):
        record("computation_default_grouping_format", False,
               "setup_failed: could not create a default entry",
               depth=0, jump_kind="value", expect="code text matches 'DDD DDD'")
        return
    raw = _raw_code_text("iGrp", ui())
    ok = bool(re.fullmatch(r"\d{3} \d{3}", raw))
    record("computation_default_grouping_format", ok,
           "" if ok else f"behavior_wrong: code text {raw!r} is not 'DDD DDD'",
           depth=0, jump_kind="value", expect="code text matches 'DDD DDD'")


# ══════════════════════════════════════════════════════════════════════════════
# 5. Digits setting -> code length == 8 (Advanced accordion; depth>=1)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_digits_eight",))
def test_digits_eight():
    if and_enter_main(clear=True) is None:
        record("computation_digits_eight", False,
               "setup_failed: could not reach MainActivity",
               depth=1, jump_kind="value", expect="code has exactly 8 digits")
        return
    if not and_create_entry("n8", "iEight", SEC_A, digits=8):
        record("computation_digits_eight", False,
               "feature_missing: could not set Advanced digits=8 and save",
               depth=1, jump_kind="value", expect="code has exactly 8 digits")
        return
    code = _code_for("iEight", ui())
    ok = bool(code) and len(code) == 8 and code.isdigit()
    record("computation_digits_eight", ok,
           "" if ok else f"behavior_wrong: digits=8 gave code {code!r} with "
                         f"{len(code)} digits (expected 8)",
           depth=1, jump_kind="value", expect="code has exactly 8 digits")


# ══════════════════════════════════════════════════════════════════════════════
# 6. 8-digit grouping format is exactly "XXX XXX XX"
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_eight_grouping_format",))
def test_eight_grouping_format():
    if and_enter_main(clear=True) is None:
        record("computation_eight_grouping_format", False,
               "setup_failed: could not reach MainActivity",
               depth=1, jump_kind="value", expect="code text matches 'DDD DDD DD'")
        return
    if not and_create_entry("n8g", "iEightG", SEC_A, digits=8):
        record("computation_eight_grouping_format", False,
               "feature_missing: could not set Advanced digits=8 and save",
               depth=1, jump_kind="value", expect="code text matches 'DDD DDD DD'")
        return
    raw = _raw_code_text("iEightG", ui())
    ok = bool(re.fullmatch(r"\d{3} \d{3} \d{2}", raw))
    record("computation_eight_grouping_format", ok,
           "" if ok else f"behavior_wrong: 8-digit code text {raw!r} is not "
                         f"'DDD DDD DD'",
           depth=1, jump_kind="value", expect="code text matches 'DDD DDD DD'")


# ══════════════════════════════════════════════════════════════════════════════
# 7. Digits contrast: a 6-digit row and an 8-digit row coexist with the right lens
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_digits_contrast",))
def test_digits_contrast():
    if and_enter_main(clear=True) is None:
        record("computation_digits_contrast", False,
               "setup_failed: could not reach MainActivity",
               depth=1, jump_kind="value", expect="iC6->6 digits, iC8->8 digits")
        return
    if not (and_create_entry("nc6", "iC6", SEC_A)
            and and_create_entry("nc8", "iC8", SEC_A, digits=8)):
        record("computation_digits_contrast", False,
               "feature_missing: could not create a 6- and an 8-digit entry",
               depth=1, jump_kind="value", expect="iC6->6 digits, iC8->8 digits")
        return
    n = ui()
    c6, c8 = _code_for("iC6", n), _code_for("iC8", n)
    ok = (bool(c6) and bool(c8) and len(c6) == 6 and len(c8) == 8
          and c6.isdigit() and c8.isdigit())
    record("computation_digits_contrast", ok,
           "" if ok else f"behavior_wrong: iC6={c6!r}({len(c6)}) iC8={c8!r}"
                         f"({len(c8)}) (expected 6 and 8)",
           depth=1, jump_kind="value", expect="iC6->6 digits, iC8->8 digits")


# ══════════════════════════════════════════════════════════════════════════════
# 8. Code format: only digits + spaces, and len(strip) == configured digits (6)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_code_charset",))
def test_code_charset():
    if and_enter_main(clear=True) is None or not and_create_entry("ncs", "iCharset", SEC_B):
        record("computation_code_charset", False,
               "setup_failed: could not create an entry",
               depth=0, jump_kind="value", expect="code is /^[0-9 ]+$/ with 6 digits")
        return
    raw = _raw_code_text("iCharset", ui())
    only_digits_spaces = bool(raw) and bool(re.fullmatch(r"[0-9 ]+", raw))
    ndig = len(raw.replace(" ", ""))
    ok = only_digits_spaces and ndig == 6
    record("computation_code_charset", ok,
           "" if ok else f"behavior_wrong: code text {raw!r} not digits+spaces "
                         f"or digit-count {ndig} != 6",
           depth=0, jump_kind="value", expect="code is /^[0-9 ]+$/ with 6 digits")


# ══════════════════════════════════════════════════════════════════════════════
# 9. Code is STABLE within a 30 s period (two close reads must match)
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_code_stable_in_period",))
def test_code_stable_in_period():
    if and_enter_main(clear=True) is None or not and_create_entry("nst", "iStable", SEC_B):
        record("computation_code_stable_in_period", False,
               "setup_failed: could not create an entry",
               depth=0, jump_kind="value", expect="two close reads give the same code")
        return
    c1 = _code_for("iStable", ui())
    c2 = _code_for("iStable", ui())      # a fresh dump, only ~1 s later
    ok = bool(c1) and c1 == c2
    record("computation_code_stable_in_period", ok,
           "" if ok else f"behavior_wrong: code changed within one read pair "
                         f"{c1!r} -> {c2!r}",
           depth=0, jump_kind="value", expect="two close reads give the same code")


# ══════════════════════════════════════════════════════════════════════════════
# 10. Copy code -> the clipboard holds the code that was displayed AT COPY TIME.
#     We read the clipboard THROUGH the app: copy, then paste into the search
#     field and read its text back. depth>=1 (action mode + search surface).
#
#     The copy + navigate-to-search sequence can straddle a 30 s TOTP period
#     boundary, so a single displayed-code snapshot goes stale. We therefore
#     accept the clipboard iff it equals a code the app ACTUALLY showed for this
#     row during the copy window (the read right before AND the read right after
#     the copy tap). This stays strict — the clipboard must match an OBSERVED
#     displayed code, never an arbitrary 6-digit string — while tolerating the
#     one boundary the slow navigation can cross.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_copy_matches_display",))
def test_copy_matches_display():
    if and_enter_main(clear=True) is None or not and_create_entry("ncp", "iCopy", SEC_A):
        record("computation_copy_matches_display", False,
               "setup_failed: could not create an entry to copy",
               depth=1, jump_kind="value", expect="clipboard digits == a displayed code")
        return
    # Read the code and locate the row from the SAME dump, so the copy happens
    # immediately after the snapshot.
    n = ui()
    disp_before = _code_for("iCopy", n)
    row = _row_node("iCopy", n)
    if not disp_before or row is None:
        record("computation_copy_matches_display", False,
               "setup_failed: could not read the displayed code / row",
               depth=1, jump_kind="value", expect="clipboard digits == a displayed code")
        return
    # Long-press the row -> action mode -> Copy.
    if not long_press(row):
        record("computation_copy_matches_display", False,
               "feature_missing: long-press did not open action mode",
               depth=1, jump_kind="value", expect="clipboard digits == a displayed code")
        return
    and_enter("action_mode")
    cp = node_by_id(ui(), "action_copy")
    if cp is None or not tap_node(cp):
        record("computation_copy_matches_display", False,
               "feature_missing: no Copy control in action mode",
               depth=1, jump_kind="value", expect="clipboard digits == a displayed code")
        return
    settle("tap")
    # Leave action mode if still up, then read the code AGAIN from Main — this
    # brackets the copy so a boundary crossing is captured either side.
    done = node_by_id(ui(), "action_mode_close_button")
    if done:
        tap_node(done)
        settle("tap")
    disp_after = _code_for("iCopy", ui())
    valid_codes = {c for c in (disp_before, disp_after) if c}
    # Paste the clipboard into the search field and read it back.
    if not and_open_search():
        record("computation_copy_matches_display", False,
               "setup_failed: could not open search to read the clipboard back",
               depth=1, jump_kind="value", expect="clipboard digits == a displayed code")
        return
    st = node_by_id(ui(), "search_src_text")
    tap_node(st)
    settle("keyboard")
    press_key(279)                       # KEYCODE_PASTE
    settle("text")
    pasted = (node_by_id(ui(), "search_src_text") or {}).get("text", "") or ""
    clip_digits = re.sub(r"\D", "", pasted)
    ok = bool(clip_digits) and clip_digits in valid_codes
    record("computation_copy_matches_display", ok,
           "" if ok else f"behavior_wrong: pasted clipboard {pasted!r} "
                         f"(digits {clip_digits!r}) not in displayed codes "
                         f"{sorted(valid_codes)}",
           depth=1, jump_kind="value", expect="clipboard digits == a displayed code")


# ══════════════════════════════════════════════════════════════════════════════
# 11. Search filter: exact issuer query -> "Showing 1 entry" + only that issuer
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_search_matches_one",))
def test_search_matches_one():
    if and_enter_main(clear=True) is None:
        record("computation_search_matches_one", False,
               "setup_failed: could not reach MainActivity",
               depth=1, jump_kind="value", expect="Showing 1 entry + only AppleCorp")
        return
    if not (and_create_entry("na", "AppleCorp", SEC_A)
            and and_create_entry("nb", "BananaInc", SEC_B)):
        record("computation_search_matches_one", False,
               "feature_missing: could not create two entries",
               depth=1, jump_kind="value", expect="Showing 1 entry + only AppleCorp")
        return
    if not and_open_search():
        record("computation_search_matches_one", False,
               "feature_missing: could not open Search",
               depth=1, jump_kind="value", expect="Showing 1 entry + only AppleCorp")
        return
    _type_search("Apple")
    n = ui()
    cnt = _count_text(n)
    iss = _issuers(n)
    ok = cnt == "Showing 1 entry" and iss == ["AppleCorp"]
    record("computation_search_matches_one", ok,
           "" if ok else f"behavior_wrong: query 'Apple' -> count {cnt!r} "
                         f"issuers {iss!r} (expected 'Showing 1 entry' + ['AppleCorp'])",
           depth=1, jump_kind="value", expect="Showing 1 entry + only AppleCorp")


# ══════════════════════════════════════════════════════════════════════════════
# 12. Search filter: no-match query -> "Showing 0 entries", no rows
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_search_matches_none",))
def test_search_matches_none():
    if and_enter_main(clear=True) is None:
        record("computation_search_matches_none", False,
               "setup_failed: could not reach MainActivity",
               depth=1, jump_kind="value", expect="Showing 0 entries + no rows")
        return
    if not (and_create_entry("na", "AppleCorp", SEC_A)
            and and_create_entry("nb", "BananaInc", SEC_B)):
        record("computation_search_matches_none", False,
               "feature_missing: could not create two entries",
               depth=1, jump_kind="value", expect="Showing 0 entries + no rows")
        return
    if not and_open_search():
        record("computation_search_matches_none", False,
               "feature_missing: could not open Search",
               depth=1, jump_kind="value", expect="Showing 0 entries + no rows")
        return
    _type_search("ZZZQQ")
    n = ui()
    cnt = _count_text(n)
    iss = _issuers(n)
    ok = cnt == "Showing 0 entries" and iss == []
    record("computation_search_matches_none", ok,
           "" if ok else f"behavior_wrong: query 'ZZZQQ' -> count {cnt!r} "
                         f"issuers {iss!r} (expected 'Showing 0 entries' + [])",
           depth=1, jump_kind="value", expect="Showing 0 entries + no rows")


# ══════════════════════════════════════════════════════════════════════════════
# 13. Search is case-insensitive substring: lowercase query still matches issuer
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_search_case_insensitive",))
def test_search_case_insensitive():
    if and_enter_main(clear=True) is None:
        record("computation_search_case_insensitive", False,
               "setup_failed: could not reach MainActivity",
               depth=1, jump_kind="value", expect="'banana' -> Showing 1 entry + BananaInc")
        return
    if not (and_create_entry("na", "AppleCorp", SEC_A)
            and and_create_entry("nb", "BananaInc", SEC_B)):
        record("computation_search_case_insensitive", False,
               "feature_missing: could not create two entries",
               depth=1, jump_kind="value", expect="'banana' -> Showing 1 entry + BananaInc")
        return
    if not and_open_search():
        record("computation_search_case_insensitive", False,
               "feature_missing: could not open Search",
               depth=1, jump_kind="value", expect="'banana' -> Showing 1 entry + BananaInc")
        return
    _type_search("banana")               # lowercase substring of "BananaInc"
    n = ui()
    cnt = _count_text(n)
    iss = _issuers(n)
    ok = cnt == "Showing 1 entry" and iss == ["BananaInc"]
    record("computation_search_case_insensitive", ok,
           "" if ok else f"behavior_wrong: query 'banana' -> count {cnt!r} "
                         f"issuers {iss!r} (expected 'Showing 1 entry' + ['BananaInc'])",
           depth=1, jump_kind="value", expect="'banana' -> Showing 1 entry + BananaInc")


# ══════════════════════════════════════════════════════════════════════════════
# 14. Search transition: a matching row is PRESENT, then a no-match query makes
#     it ABSENT — the discriminator's positive/negative pairing.
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_search_present_then_absent",))
def test_search_present_then_absent():
    if and_enter_main(clear=True) is None or not and_create_entry("nsp", "SoloIssuer", SEC_A):
        record("computation_search_present_then_absent", False,
               "setup_failed: could not create an entry",
               depth=1, jump_kind="transition", expect="SoloIssuer present->absent on no-match")
        return
    if not and_open_search():
        record("computation_search_present_then_absent", False,
               "feature_missing: could not open Search",
               depth=1, jump_kind="transition", expect="SoloIssuer present->absent on no-match")
        return
    _type_search("Solo")
    present = find_node_ci(ui(), "SoloIssuer") is not None
    _type_search("ZZZQQ")
    absent = find_node_ci(ui(), "SoloIssuer") is None
    ok = present and absent
    record("computation_search_present_then_absent", ok,
           "" if ok else f"behavior_wrong: SoloIssuer present_on_match={present} "
                         f"absent_on_nomatch={absent}",
           depth=1, jump_kind="transition", expect="SoloIssuer present->absent on no-match")


# ══════════════════════════════════════════════════════════════════════════════
# 15. TOTP type default is "TOTP" (Advanced spinner default) — value in editor
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_type_default_totp",))
def test_type_default_totp():
    if and_enter_main(clear=True) is None or not and_enter_editor():
        record("computation_type_default_totp", False,
               "setup_failed: could not open the editor",
               depth=2, jump_kind="value", expect="dropdown_type == 'TOTP'")
        return
    if not and_expand_advanced():
        record("computation_type_default_totp", False,
               "feature_missing: could not expand Advanced",
               depth=2, jump_kind="value", expect="dropdown_type == 'TOTP'")
        return
    dd = node_by_id(ui(), "dropdown_type")
    got = (dd or {}).get("text")
    ok = got == "TOTP"
    record("computation_type_default_totp", ok,
           "" if ok else f"behavior_wrong: default type spinner is {got!r} "
                         f"(expected 'TOTP')",
           depth=2, jump_kind="value", expect="dropdown_type == 'TOTP'")


# ══════════════════════════════════════════════════════════════════════════════
# 16. Default digits field default is "6" (Advanced) — value in editor
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_digits_field_default_six",))
def test_digits_field_default_six():
    if and_enter_main(clear=True) is None or not and_enter_editor():
        record("computation_digits_field_default_six", False,
               "setup_failed: could not open the editor",
               depth=2, jump_kind="value", expect="text_digits == '6'")
        return
    if not and_expand_advanced():
        record("computation_digits_field_default_six", False,
               "feature_missing: could not expand Advanced",
               depth=2, jump_kind="value", expect="text_digits == '6'")
        return
    dg = node_by_id(ui(), "text_digits")
    got = (dg or {}).get("text")
    ok = got == "6"
    record("computation_digits_field_default_six", ok,
           "" if ok else f"behavior_wrong: default digits field is {got!r} "
                         f"(expected '6')",
           depth=2, jump_kind="value", expect="text_digits == '6'")


# ══════════════════════════════════════════════════════════════════════════════
# 17. Period field default is "30" (Advanced) — value in editor
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("computation_period_field_default_thirty",))
def test_period_field_default_thirty():
    if and_enter_main(clear=True) is None or not and_enter_editor():
        record("computation_period_field_default_thirty", False,
               "setup_failed: could not open the editor",
               depth=2, jump_kind="value", expect="text_period_counter == '30'")
        return
    if not and_expand_advanced():
        record("computation_period_field_default_thirty", False,
               "feature_missing: could not expand Advanced",
               depth=2, jump_kind="value", expect="text_period_counter == '30'")
        return
    pc = node_by_id(ui(), "text_period_counter")
    got = (pc or {}).get("text")
    ok = got == "30"
    record("computation_period_field_default_thirty", ok,
           "" if ok else f"behavior_wrong: default period field is {got!r} "
                         f"(expected '30')",
           depth=2, jump_kind="value", expect="text_period_counter == '30'")


# ══════════════════════════════════════════════════════════════════════════════
# ── VLM cluster (exactly 4): genuinely RENDERED code properties ─────────────────
# All questions authored from screenshots captured on the running original.
# Fine tags used: color, size, position, size (>= 2 distinct fine tags).
# NOTE observed on the original: this build shows NO per-row countdown pie/ring,
# so that property is deliberately NOT asserted (it would fail on the ground
# truth). Instead VLM #1 asserts the code's distinct accent colour, which IS
# rendered (the code sits in a clear blue, unlike the black issuer text).
# ══════════════════════════════════════════════════════════════════════════════

# VLM #1 — the generated code digits are rendered in a distinct ACCENT COLOUR.
@and_test(expects=("computation_code_accent_color_vlm",))
def test_code_accent_color_vlm():
    if and_enter_main(clear=True) is None or not and_create_entry("nac", "iAccent", SEC_B):
        record("computation_code_accent_color_vlm", False,
               "setup_failed: could not create an entry",
               depth=0, jump_kind="value", tag="color")
        return
    vlm_assert("computation_code_accent_color",
               "On the single authenticator entry row, are the large numeric TOTP "
               "code digits rendered in a distinct coloured accent (for example a "
               "blue/teal tint) that is clearly DIFFERENT from the plain black/dark "
               "issuer and account-name text on the same row?",
               RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="color")


# VLM #2 — the TOTP code digits are rendered large (prominent size).
@and_test(expects=("computation_code_large_font_vlm",))
def test_code_large_font_vlm():
    if and_enter_main(clear=True) is None or not and_create_entry("nlf", "iLargeFont", SEC_B):
        record("computation_code_large_font_vlm", False,
               "setup_failed: could not create an entry",
               depth=0, jump_kind="value", tag="size")
        return
    vlm_assert("computation_code_large_font",
               "On the single authenticator entry row, are the numeric TOTP code "
               "digits rendered in a noticeably LARGER font than the smaller "
               "issuer/account-name text on the same row (i.e. the code is the "
               "most prominent text)?",
               RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="size")


# VLM #3 — the 6-digit code is split into two space-separated groups of 3.
@and_test(expects=("computation_code_grouped_vlm",))
def test_code_grouped_vlm():
    if and_enter_main(clear=True) is None or not and_create_entry("ngp", "iGrouped", SEC_A):
        record("computation_code_grouped_vlm", False,
               "setup_failed: could not create an entry",
               depth=0, jump_kind="value", tag="position")
        return
    vlm_assert("computation_code_grouped",
               "Look at the six-digit TOTP code on the entry row. Is it displayed "
               "as TWO groups of three digits separated by a visible gap/space "
               "(for example '123 456'), rather than six digits with no gap?",
               RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="position")


# VLM #4 — an 8-digit code is visibly WIDER than a 6-digit code on the same list.
@and_test(expects=("computation_eight_wider_than_six_vlm",))
def test_eight_wider_than_six_vlm():
    if and_enter_main(clear=True) is None:
        record("computation_eight_wider_than_six_vlm", False,
               "setup_failed: could not reach MainActivity",
               depth=1, jump_kind="value", tag="size")
        return
    # Name them so their alphabetical relation makes the 6-digit row sit above.
    if not (and_create_entry("na", "Alpha6", SEC_A)
            and and_create_entry("nz", "Zulu8", SEC_A, digits=8)):
        record("computation_eight_wider_than_six_vlm", False,
               "feature_missing: could not create a 6- and an 8-digit entry",
               depth=1, jump_kind="value", tag="size")
        return
    vlm_assert("computation_eight_wider_than_six",
               "This authenticator list has two entries. One shows a six-digit "
               "code and the other shows an eight-digit code. Is the eight-digit "
               "code visibly WIDER (occupies more horizontal space) than the "
               "six-digit code?",
               RESULTS_DIR, expect="YES", depth=1, jump_kind="value", tag="size")


TESTS = [
    test_same_secret_same_code,
    test_diff_secret_diff_code,
    test_default_six_digits,
    test_default_grouping_format,
    test_digits_eight,
    test_eight_grouping_format,
    test_digits_contrast,
    test_code_charset,
    test_code_stable_in_period,
    test_copy_matches_display,
    test_search_matches_one,
    test_search_matches_none,
    test_search_case_insensitive,
    test_search_present_then_absent,
    test_type_default_totp,
    test_digits_field_default_six,
    test_period_field_default_thirty,
    test_code_accent_color_vlm,
    test_code_large_font_vlm,
    test_code_grouped_vlm,
    test_eight_wider_than_six_vlm,
]

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