File size: 27,473 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
#!/usr/bin/env python3
"""STRUCTURE lane — Aegis Authenticator.

Owns exactly two things:
  1. The GATE: MainActivity is in the foreground and its top-level surfaces
     (toolbar host with search/sort/overflow, FAB, root container) exist.
     These are jump_kind="none" existence checks — the only place existence
     is allowed.
  2. Tree-SHAPE deltas: an interaction that changes the tree's shape (a menu
     that adds a class of card, a dialog that adds a window layer, an
     empty->populated list, a contextual action-mode toolbar). Recorded as
     jump_kind="transition" with the observed delta, reversed where the app
     reverses it.

Every expected shape below was OBSERVED on the running original app.
Never asserts content strings/values — those belong to other lanes.
"""
import os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from android_testgen_kit import *  # noqa: F403

TESTS = []


def test(fn):
    TESTS.append(fn)
    return fn


# ── Shared entry points ──────────────────────────────────────────────────────

def _robust_id(rid_suffix, tries=4):
    """node_by_id with a re-dump retry. A dump taken right after a keyboard
    dismissal can come back partial (missing nodes); retrying absorbs that."""
    for _ in range(tries):
        n = node_by_id(ui(), rid_suffix)
        if n:
            return n
        settle("dump")
    return None


def _dismiss_kb_on_form():
    """Dismiss the soft keyboard on EditEntryActivity WITHOUT leaving it, so the
    lower form fields (text_issuer/text_secret) and the toolbar SAVE button
    return to the uiautomator dump. A raw BACK here collapses the IME but keeps
    the activity; we re-press once if the IME lags, and bail if we somehow left
    the form. (The kit's generic hide_keyboard() taps an inert strip that on this
    form re-shows the IME, leaving those fields below the fold.)"""
    for _ in range(2):
        if not keyboard_visible():
            return True
        if "EditEntryActivity" not in get_current_activity():
            return False
        press_key("KEYCODE_BACK")
        settle("keyboard")
    return "EditEntryActivity" in get_current_activity()


def and_enter_main():
    """Clean MainActivity: force-stop + clear data (-> onboarding), then skip the
    IntroActivity by resource-id if it is showing (portable). Choosing rb_none
    means the vault opens directly on every launch (no unlock screen)."""
    force_stop()
    clear_data()
    launch_app()
    wait_for_foreground()
    nodes = ui()
    if node_by_id(nodes, "btnNext"):
        tap_node(node_by_id(nodes, "btnNext"))          # Welcome -> Security
        rb = node_by_id(ui(), "rb_none")
        if rb:
            tap_node(rb)                                 # choose "None"
        b = node_by_id(ui(), "btnNext")
        if b:
            tap_node(b)                                  # Security -> Setup completed
        b = node_by_id(ui(), "btnNext")
        if b:
            tap_node(b)                                  # -> MainActivity
    return ui()


def and_enter_edit_entry():
    """Navigate Main -> FAB menu -> "Enter manually" -> EditEntryActivity.
    Counts one surface (backs a depth>=1 declaration)."""
    tap_node(node_by_id(ui(), "fab"))
    settle("tap")
    item = node_by_id(ui(), "fab_menu_item_enter")
    if not item:
        return None
    tap_node(item)
    settle("launch")
    and_enter("EditEntryActivity")
    return ui()


def and_enter_settings():
    """Navigate Main -> overflow ("More options") -> Settings ->
    PreferencesActivity. Counts one surface."""
    ov = find_node(ui(), content_desc="More options")
    if not ov:
        return None
    tap_node(ov)
    settle("tap")
    st = find_node_ci(ui(), "Settings")
    if not st:
        return None
    tap_node(st)
    settle("launch")
    and_enter("PreferencesActivity")
    return ui()


def _create_entry(name="TestIssuer", secret="GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"):
    """Fill and SAVE one manual entry from Main. Returns the Main tree after save,
    or None if the flow did not land back on MainActivity.

    Per field: tap-type (type_text focuses the field first) then hide the
    keyboard so the next field's tap is not intercepted. Every element lookup
    goes through _robust_id because the post-keyboard dump is occasionally
    partial on this form."""
    if and_enter_edit_entry() is None:
        return None
    nm = _robust_id("text_name")
    if nm:
        type_text(nm, name)
        _dismiss_kb_on_form()
    iss = _robust_id("text_issuer")
    if iss:
        type_text(iss, name)
        _dismiss_kb_on_form()
    sec = _robust_id("text_secret")
    if sec:
        type_text(sec, secret)
        _dismiss_kb_on_form()
    save = _robust_id("action_save")
    if not save:
        return None
    tap_node(save)
    settle("launch")
    # SAVE itself pops EditEntryActivity back to Main (no extra BACK — a BACK on
    # Main would exit the app). Reset the surface counter to reflect that.
    and_reset_depth()
    if "MainActivity" not in get_current_activity():
        return None
    return ui()


def _count_by_id(nodes, rid_suffix):
    """How many nodes carry this resource-id last segment (for row counting)."""
    return len([n for n in (nodes or [])
                if n.get("resource-id", "").rsplit("/", 1)[-1] == rid_suffix])


# ══════════════════════════════════════════════════════════════════════════════
# GATE — existence only (jump_kind="none"). Kept to <=30% of tests.
# ══════════════════════════════════════════════════════════════════════════════

@test
@and_test(expects=("structure_gate_launch",))
def test_gate_launch():
    nodes = and_enter_main()
    fg = wait_for_foreground()
    root = bool(find_by_class(nodes, "FrameLayout")) and bool(find_by_class(nodes, "ViewGroup"))
    ok = fg and root and "MainActivity" in get_current_activity()
    record("structure_gate_launch", bool(ok),
           "" if ok else "setup_failed: app did not reach MainActivity with a root container",
           depth=0, jump_kind="none")


@test
@and_test(expects=("structure_gate_toolbar",))
def test_gate_toolbar():
    nodes = and_enter_main()
    # Toolbar host by id + its three action affordances by content-desc/id.
    host = node_by_id(nodes, "toolbar") is not None or node_by_id(nodes, "app_bar_layout") is not None
    search = node_by_id(nodes, "search_button") is not None
    sort = node_by_id(nodes, "action_sort") is not None
    overflow = find_node(nodes, content_desc="More options") is not None
    ok = host and search and sort and overflow
    record("structure_gate_toolbar", bool(ok),
           "" if ok else "feature_missing: toolbar host with search/sort/overflow not all present",
           depth=0, jump_kind="none")


@test
@and_test(expects=("structure_gate_fab",))
def test_gate_fab():
    nodes = and_enter_main()
    fab = node_by_id(nodes, "fab") is not None
    add_desc = find_node(nodes, content_desc="Add new entry") is not None
    ok = fab and add_desc
    record("structure_gate_fab", bool(ok),
           "" if ok else "feature_missing: FAB ('Add new entry') not present on MainActivity",
           depth=0, jump_kind="none")


# ══════════════════════════════════════════════════════════════════════════════
# SHAPE deltas — jump_kind="transition". Each observed the delta on the original.
# ══════════════════════════════════════════════════════════════════════════════

@test
@and_test(expects=("structure_fab_menu_shape",
                   "structure_fab_menu_shape_vlm"))
def test_fab_menu_shape():
    """FAB tap -> tree gains the 3 CardView menu items (Scan QR / Scan image /
    Enter manually) that were absent before. Observed: 0 -> 3 cards."""
    nodes = and_enter_main()
    cards_before = len(find_by_class(nodes, "CardView"))
    before = and_showing(nodes)
    ok_tap = tap_node(node_by_id(nodes, "fab"))
    settle("tap")
    after_nodes = ui()
    cards_after = len(find_by_class(after_nodes, "CardView"))
    after = and_showing(after_nodes)
    menu_item = node_by_id(after_nodes, "fab_menu_item_enter") is not None
    ok = (ok_tap and menu_item and cards_after == cards_before + 3
          and surface_changed(before, after))
    record("structure_fab_menu_shape", bool(ok),
           "" if ok else f"behavior_wrong: fab menu did not add 3 cards "
                         f"({cards_before}->{cards_after})",
           depth=0, jump_kind="transition",
           expect="FAB menu subtree appears: CardView 0->3 + fab_menu_item_enter")
    # VLM: the expanded menu is a vertical stack of cards ABOVE the FAB.
    vlm_assert("structure_fab_menu_shape",
               "Is there a vertical stack of menu item cards positioned above the "
               "circular floating action button in the lower-right area?",
               RESULTS_DIR, tag="layout", depth=0, jump_kind="transition")


@test
@and_test(expects=("structure_fab_menu_reverse",))
def test_fab_menu_reverse():
    """FAB menu is reversible: BACK collapses it -> the 3 cards disappear and the
    tree shape restores to the pre-open surface."""
    nodes = and_enter_main()
    base = and_showing(nodes)
    tap_node(node_by_id(nodes, "fab"))
    settle("tap")
    opened = ui()
    open_has = node_by_id(opened, "fab_menu_item_enter") is not None
    back()  # scrim/back collapses the menu (observed: cards removed)
    settle("tap")
    closed = ui()
    close_gone = node_by_id(closed, "fab_menu_item_enter") is None
    cards_gone = len(find_by_class(closed, "CardView")) == 0
    restored = not surface_changed(base, and_showing(closed))
    ok = open_has and close_gone and cards_gone and restored
    record("structure_fab_menu_reverse", bool(ok),
           "" if ok else "behavior_wrong: fab menu did not collapse/restore on back",
           depth=0, jump_kind="transition",
           expect="FAB menu cards removed on back; surface restored to base")


@test
@and_test(expects=("structure_search_shape",
                   "structure_search_shape_vlm"))
def test_search_shape():
    """Search tap -> toolbar swaps to a SearchView subtree: search_src_text +
    search_close_btn appear where the search_button was."""
    nodes = and_enter_main()
    before = and_showing(nodes)
    ok_tap = tap_node(node_by_id(nodes, "search_button"))
    settle("tap")
    after_nodes = ui()
    after = and_showing(after_nodes)
    src = node_by_id(after_nodes, "search_src_text") is not None
    close_btn = node_by_id(after_nodes, "search_close_btn") is not None
    btn_gone = node_by_id(after_nodes, "search_button") is None
    ok = ok_tap and src and close_btn and btn_gone and surface_changed(before, after)
    record("structure_search_shape", bool(ok),
           "" if ok else "behavior_wrong: search did not swap toolbar to a SearchView subtree",
           depth=0, jump_kind="transition",
           expect="Toolbar -> SearchView: search_src_text/search_close_btn appear, search_button gone")
    # VLM: an in-toolbar search field appears — magnifier + "Search" hint on the
    # left, an X clear button on the right (observed layout).
    vlm_assert("structure_search_shape",
               "Is there a search input field across the top with a magnifier icon "
               "on the left and an X (clear) icon on the right?",
               RESULTS_DIR, tag="position", depth=0, jump_kind="transition")


@test
@and_test(expects=("structure_search_reverse",))
def test_search_reverse():
    """Search is reversible: tapping the SearchView close button collapses it ->
    search_src_text disappears and the normal search_button returns."""
    nodes = and_enter_main()
    tap_node(node_by_id(nodes, "search_button"))
    settle("tap")
    opened = ui()
    open_src = node_by_id(opened, "search_src_text") is not None
    cb = node_by_id(opened, "search_close_btn")
    tap_node(cb)
    settle("tap")
    closed = ui()
    src_gone = node_by_id(closed, "search_src_text") is None
    btn_back = node_by_id(closed, "search_button") is not None
    fab_back = node_by_id(closed, "fab") is not None
    ok = open_src and src_gone and btn_back and fab_back
    record("structure_search_reverse", bool(ok),
           "" if ok else "behavior_wrong: search did not collapse back to the normal toolbar",
           depth=0, jump_kind="transition",
           expect="SearchView collapses: search_src_text gone, search_button+fab restored")


@test
@and_test(expects=("structure_sort_popup_shape",))
def test_sort_popup_shape():
    """Sort tap -> a popup subtree layers over Main: RadioButtons + the sort
    option rows appear (none of which were in the tree before)."""
    nodes = and_enter_main()
    radios_before = len(find_by_class(nodes, "RadioButton"))
    before = and_showing(nodes)
    trigger = node_by_id(nodes, "action_sort") or find_node(nodes, content_desc="Sort")
    ok_tap = tap_node(trigger)
    settle("tap")
    after_nodes = ui()
    after = and_showing(after_nodes)
    radios_after = len(find_by_class(after_nodes, "RadioButton"))
    ok = ok_tap and radios_after > radios_before and surface_changed(before, after)
    record("structure_sort_popup_shape", bool(ok),
           "" if ok else f"behavior_wrong: sort popup added no radio subtree "
                         f"({radios_before}->{radios_after})",
           depth=0, jump_kind="transition",
           expect="Sort popup subtree appears: RadioButton count increases (0->>0)")


@test
@and_test(expects=("structure_overflow_menu_shape",
                   "structure_overflow_menu_shape_vlm"))
def test_overflow_menu_shape():
    """More-options tap -> an options popup subtree layers over Main (Settings /
    About rows appear that were not in the tree before)."""
    nodes = and_enter_main()
    before = and_showing(nodes)
    ov = find_node(nodes, content_desc="More options")
    ok_tap = tap_node(ov)
    settle("tap")
    after_nodes = ui()
    after = and_showing(after_nodes)
    settings = find_node_ci(after_nodes, "Settings") is not None
    about = find_node_ci(after_nodes, "About") is not None
    ok = ok_tap and settings and about and surface_changed(before, after)
    record("structure_overflow_menu_shape", bool(ok),
           "" if ok else "behavior_wrong: overflow did not add a popup menu subtree",
           depth=0, jump_kind="transition",
           expect="Overflow popup subtree appears with Settings + About rows")
    # VLM: overflow menu is a small popup anchored to the top-right corner.
    vlm_assert("structure_overflow_menu_shape",
               "Is there a small popup menu of text options anchored near the "
               "top-right corner of the screen?",
               RESULTS_DIR, tag="position", depth=0, jump_kind="transition")


@test
@and_test(expects=("structure_editentry_form_shape",))
def test_editentry_form_shape():
    """EditEntryActivity presents the add-entry form cluster: the text fields
    (name/issuer/secret) and the collapsed Advanced accordion header + SAVE —
    a distinct shape from Main's list. depth>=1 (backed by and_enter_edit_entry)."""
    and_enter_main()
    nodes = and_enter_edit_entry()
    if nodes is None:
        record("structure_editentry_form_shape", False,
               "setup_failed: could not reach EditEntryActivity",
               depth=1, jump_kind="transition",
               expect="EditEntryActivity form fields present")
        return
    edits = len(find_by_class(nodes, "EditText"))
    have = all(node_by_id(nodes, i) is not None
               for i in ("text_name", "text_issuer", "text_secret",
                         "accordian_header", "action_save"))
    on_edit = "EditEntryActivity" in get_current_activity()
    ok = on_edit and have and edits >= 4
    record("structure_editentry_form_shape", bool(ok),
           "" if ok else f"behavior_wrong: edit-entry form cluster incomplete "
                         f"(EditText={edits})",
           depth=1, jump_kind="transition",
           expect="EditEntryActivity: >=4 EditText + accordian_header + action_save")


@test
@and_test(expects=("structure_accordion_expand",
                   "structure_accordion_expand_vlm"))
def test_accordion_expand():
    """Advanced accordion in EditEntryActivity: tapping the header expands the
    subtree, adding the advanced controls (dropdown_type, dropdown_algo,
    text_digits) and increasing the node count. Observed: 50 -> 75 nodes.
    depth>=1 (backed by and_enter_edit_entry)."""
    and_enter_main()
    nodes = and_enter_edit_entry()
    if nodes is None:
        record("structure_accordion_expand", False,
               "setup_failed: could not reach EditEntryActivity",
               depth=1, jump_kind="transition",
               expect="Advanced accordion expands to add dropdown_type/text_digits")
        record("structure_accordion_expand_vlm", False,
               "setup_failed: could not reach EditEntryActivity",
               depth=1, jump_kind="transition", tag="position",
               expect="two dropdowns side by side after Advanced expands")
        return
    n_before = len(nodes)
    adv_before = node_by_id(nodes, "dropdown_type") is not None
    before = and_showing(nodes)
    ok_tap = tap_node(node_by_id(nodes, "accordian_header"))
    settle("tap")
    after_nodes = ui()
    n_after = len(after_nodes)
    after = and_showing(after_nodes)
    adv_after = all(node_by_id(after_nodes, i) is not None
                    for i in ("dropdown_type", "dropdown_algo", "text_digits"))
    ok = (ok_tap and not adv_before and adv_after and n_after > n_before
          and surface_changed(before, after))
    record("structure_accordion_expand", bool(ok),
           "" if ok else f"behavior_wrong: accordion did not expand advanced subtree "
                         f"(nodes {n_before}->{n_after})",
           depth=1, jump_kind="transition",
           expect="Accordion expands: dropdown_type/dropdown_algo/text_digits appear, node count grows")
    # VLM: expanded Advanced shows the type + algorithm dropdowns SIDE BY SIDE.
    vlm_assert("structure_accordion_expand",
               "In the expanded Advanced section, are there two dropdown/spinner "
               "controls placed side by side on the same row?",
               RESULTS_DIR, tag="position", depth=1, jump_kind="transition")


@test
@and_test(expects=("structure_settings_list_shape",
                   "structure_settings_list_shape_vlm"))
def test_settings_list_shape():
    """Settings root (PreferencesActivity) is a scrollable RecyclerView list of
    category rows — a distinct shape from Main. depth>=1 (and_enter_settings)."""
    and_enter_main()
    nodes = and_enter_settings()
    if nodes is None:
        record("structure_settings_list_shape", False,
               "setup_failed: could not reach Settings",
               depth=1, jump_kind="transition",
               expect="PreferencesActivity RecyclerView list of category rows")
        record("structure_settings_list_shape_vlm", False,
               "setup_failed: could not reach Settings",
               depth=1, jump_kind="transition", tag="layout",
               expect="single vertical column of settings category rows")
        return
    on_prefs = "PreferencesActivity" in get_current_activity()
    has_list = len(find_by_class(nodes, "RecyclerView")) >= 1
    # Several category rows are visible (each a TextView label in the list).
    rows = sum(1 for lbl in ("Appearance", "Behavior", "Security", "Backups")
               if find_node_ci(nodes, lbl) is not None)
    ok = on_prefs and has_list and rows >= 3
    record("structure_settings_list_shape", bool(ok),
           "" if ok else f"behavior_wrong: settings not a category list "
                         f"(recycler={has_list}, rows={rows})",
           depth=1, jump_kind="transition",
           expect="PreferencesActivity: RecyclerView with >=3 category rows")
    # VLM: settings is a single-column vertical list of category rows.
    vlm_assert("structure_settings_list_shape",
               "Is the settings screen a single vertical column of stacked category "
               "rows, each with a title and a short description line?",
               RESULTS_DIR, tag="layout", depth=1, jump_kind="transition")


@test
@and_test(expects=("structure_create_populates_list",
                   "structure_create_populates_list_vlm"))
def test_create_populates_list():
    """Creating an entry flips the list shape: the empty-state placeholder
    (textView5) is replaced by a populated list containing a profile_code row,
    and the header gains entries_shown_count. depth 0 but a real shape delta."""
    nodes = and_enter_main()
    empty_before = node_by_id(nodes, "textView5") is not None
    code_before = node_by_id(nodes, "profile_code") is not None
    after = _create_entry()
    if after is None:
        record("structure_create_populates_list", False,
               "setup_failed: entry creation flow did not complete",
               depth=0, jump_kind="transition",
               expect="empty-state -> populated list with a profile_code row")
        record("structure_create_populates_list_vlm", False,
               "setup_failed: entry creation flow did not complete",
               depth=0, jump_kind="transition", tag="layout",
               expect="entry row: circular avatar left, two text lines right")
        return
    code_after = node_by_id(after, "profile_code") is not None
    empty_gone = node_by_id(after, "textView5") is None
    count_row = node_by_id(after, "entries_shown_count") is not None
    ok = (empty_before and not code_before and code_after and empty_gone and count_row)
    record("structure_create_populates_list", bool(ok),
           "" if ok else "behavior_wrong: list shape did not change from empty to populated",
           depth=0, jump_kind="transition",
           expect="empty textView5 removed; profile_code row + entries_shown_count appear")
    # VLM: an entry row = circular avatar tile on the left, text stacked to its right.
    vlm_assert("structure_create_populates_list",
               "Does the list now show an entry row with a circular avatar tile on "
               "the left and two lines of text stacked to its right?",
               RESULTS_DIR, tag="layout", depth=0, jump_kind="transition")


@test
@and_test(expects=("structure_longpress_action_mode",
                   "structure_longpress_action_mode_vlm"))
def test_longpress_action_mode():
    """Long-press an entry -> the normal toolbar is replaced by a contextual
    action-mode bar: action_mode_close_button + Copy/Edit action buttons appear.
    depth>=1 (backed by and_enter_edit_entry inside the create helper)."""
    and_enter_main()
    nodes = _create_entry()
    if nodes is None or node_by_id(nodes, "profile_code") is None:
        record("structure_longpress_action_mode", False,
               "setup_failed: no entry to long-press",
               depth=1, jump_kind="transition",
               expect="contextual action-mode toolbar appears on long-press")
        record("structure_longpress_action_mode_vlm", False,
               "setup_failed: no entry to long-press",
               depth=1, jump_kind="transition", tag="layout",
               expect="row of action icons across the top bar")
        return
    row = node_by_id(nodes, "profile_code")
    before = and_showing(nodes)
    long_press(row)
    settle("tap")
    after_nodes = ui()
    after = and_showing(after_nodes)
    close_btn = node_by_id(after_nodes, "action_mode_close_button") is not None
    copy = node_by_id(after_nodes, "action_copy") is not None
    edit = node_by_id(after_nodes, "action_edit") is not None
    ok = close_btn and copy and edit and surface_changed(before, after)
    record("structure_longpress_action_mode", bool(ok),
           "" if ok else "behavior_wrong: long-press did not open the contextual action mode",
           depth=1, jump_kind="transition",
           expect="action-mode bar: action_mode_close_button + action_copy + action_edit appear")
    # VLM: the action-mode bar is a row of action icons across the top, with a
    # back/close affordance at the far left (observed: back arrow + star/copy/
    # edit/QR icons).
    vlm_assert("structure_longpress_action_mode",
               "Is the top bar a row of several action icons (such as star, copy, "
               "edit) with a back or close arrow icon at the far left?",
               RESULTS_DIR, tag="layout", depth=1, jump_kind="transition")


@test
@and_test(expects=("structure_multi_entry_shape",))
def test_multi_entry_shape():
    """Creating a second entry grows the list shape: the number of profile_code
    rows increases from 1 to 2 (each row is one entry). depth 0 shape delta."""
    and_enter_main()
    one = _create_entry(name="AlphaOne")
    if one is None:
        record("structure_multi_entry_shape", False,
               "setup_failed: first entry not created",
               depth=0, jump_kind="transition",
               expect="profile_code row count 1 -> 2 after a second create")
        return
    rows_one = _count_by_id(one, "profile_code")
    two = _create_entry(name="BravoTwo")
    rows_two = _count_by_id(two, "profile_code")
    ok = rows_one == 1 and rows_two == 2
    record("structure_multi_entry_shape", bool(ok),
           "" if ok else f"behavior_wrong: profile_code row count not 1->2 "
                         f"({rows_one}->{rows_two})",
           depth=0, jump_kind="transition",
           expect="profile_code rows: 1 -> 2 after second create")


@test
@and_test(expects=("structure_main_overview_vlm",))
def test_main_overview_vlm():
    """Whole-screen layout of Main with one entry: a single-column list with a
    floating action button in the bottom-right. VLM-only (spatial)."""
    and_enter_main()
    nodes = _create_entry()
    ok_setup = nodes is not None and node_by_id(nodes, "profile_code") is not None
    if not ok_setup:
        record("structure_main_overview_vlm", False,
               "setup_failed: could not populate Main for the overview shot",
               depth=0, jump_kind="transition", tag="position",
               expect="single-column list with a FAB bottom-right")
        return
    vlm_assert("structure_main_overview",
               "Is the main screen a single-column list of entries with a round "
               "floating action button in the bottom-right corner?",
               RESULTS_DIR, tag="position", depth=0, jump_kind="transition")


if __name__ == "__main__":
    if not device_online():
        print("setup_failed: device offline — the adb tunnel may have dropped")
        sys.exit(1)
    run_suite(TESTS, "structure")