File size: 34,367 Bytes
41dfd8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
#!/usr/bin/env python3
"""NAVIGATION lane — Urik Keyboard (com.urik.keyboard).

Owns surface REACHABILITY + back-stack integrity: this lane is the sole owner of
jump_kind="reach" and of the depth>=2 chains. Every forward jump is proven with
and_reach(before, after, target, source): the TARGET surface's discriminating
element APPEARED and the SOURCE surface's DISAPPEARED. A screen that was already
in the tree was never reached. Every test opens its own entry point (the S0
launcher, via open_launcher()) and navigates FORWARD from there; back-navigation
is exercised as its own short forward-then-BACK test (nested cross-surface back()
chains are flaky).

Relaunching is only ever how a test re-establishes its S0 entry point — it is
NEVER the mechanism that reaches a destination. The reach is always a forward tap
proven by and_reach*, so restart lives in open_launcher()/open_settings(), one
level below the reach call.

Ground truth for every target/source string below was observed live on the
original app before the assertion was written (see recon.md + recon_shots/).

Two source-collision hazards were found live and encoded here:
  * The Privacy screen contains the summary "Save keyboard settings and custom
    key mappings...", so the substring "Keyboard Settings" does NOT vanish on the
    S2->Privacy jump — the source for that jump is a distinctive list row instead.
  * Several destination TOOLBAR titles equal their originating list-row text
    (Open Source Licenses / Dictionary Data / Customize Keys / Reset to Defaults),
    so those jumps assert a destination-only element (a content view id or a
    unique button/message), never the colliding title.
"""
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 helpers ──────────────────────────────────────────────────────────────

def open_launcher():
    """Re-establish this test's S0 (MainActivity launcher) entry point and return
    its fresh node list. Relaunch is the ISOLATION mechanism (kit contract: each
    test owns its entry point), never the navigation under test."""
    restart_app()
    wait_for_foreground()
    return ui()


def open_settings():
    """S0 -> SettingsActivity. Returns the fresh Settings node list, or None."""
    nodes = open_launcher()
    trig = find_node(nodes, text="Open Settings") or find_node_ci(nodes, "Open Settings")
    if not trig or not tap_node(trig):
        return None
    after = ui()
    # Confirm we are on the Settings list before any test navigates further.
    if find_node(after, text="Keyboard Settings") is None:
        return None
    return after


def theme_name_tv(nodes):
    """The dynamic theme-name TextView on S0 (reads 'Default'/'Abyss'/...). It is
    the only short TextView that is neither the app title nor a button label, so
    locate it structurally rather than by a value that persists across runs."""
    known = {"urik keyboard", "enable", "open settings", "about"}
    btnlabels = {b.get("text", "").strip().lower() for b in find_by_class(nodes, "Button")}
    for n in nodes:
        if not n.get("class", "").endswith("TextView"):
            continue
        t = n.get("text", "").strip()
        if t and t.lower() not in known and t.lower() not in btnlabels and len(t) < 20:
            return n
    return None


def tap_up(nodes):
    """Tap the toolbar up-affordance (ImageButton content-desc 'Navigate up') and
    settle for the surface transition. This IS the back action under test, so it
    presses BACK exactly once — callers must NOT also call and_back()."""
    up = find_node(nodes, content_desc="Navigate up")
    if not up or not tap_node(up):
        return False
    settle("tap")  # a fragment/activity pop can outlast the default tap settle
    return True


# Depth-family helpers. The and_enter_*/and_reach_* NAME is what the depth audit
# looks for; the implementation is ours. Each proves ONE surface crossing.

def and_enter_settings():
    """S0 -> Settings, proven (Keyboard Settings appeared, Open Settings gone)."""
    trig = find_node(open_launcher(), text="Open Settings")
    return bool(trig) and and_reach_surface(trig, "Keyboard Settings", "Open Settings")


def and_reach_appearance():
    """Settings -> Appearance, proven."""
    nodes = open_settings()
    if not nodes:
        return False
    row = find_node(nodes, text="Appearance")
    return bool(row) and and_reach_surface(row, "Key Press Highlight", "Keyboard Settings")


def and_reach_layout_input():
    """Settings -> Layout & Input, proven (row text is literally 'Layout &amp; Input')."""
    nodes = open_settings()
    if not nodes:
        return False
    row = find_node(nodes, text="Layout &amp; Input")
    return bool(row) and and_reach_surface(row, "Keyboard Layout", "Keyboard Settings")


# ══════════════════════════════════════════════════════════════════════════════
# (A) S0 top-level destinations — depth 1, reach
# ══════════════════════════════════════════════════════════════════════════════

@test
@and_test(expects=("nav_reach_settings", "nav_reach_settings_vlm"))
def test_reach_settings():
    nodes = open_launcher()
    trig = find_node(nodes, text="Open Settings") or find_node_ci(nodes, "Open Settings")
    ok = trig is not None and and_reach_surface(trig, "Keyboard Settings", "Open Settings")
    record("nav_reach_settings", ok,
           "" if ok else "feature_missing: Settings surface not reachable from 'Open Settings'",
           depth=1, jump_kind="reach",
           expect="'Keyboard Settings' title appeared; launcher 'Open Settings' button gone")
    vlm_assert("nav_reach_settings",
               "Is a settings screen showing a top toolbar with a left-pointing back "
               "arrow at the top-left and a vertical list of labelled rows below it?",
               RESULTS_DIR, tag="position")


@test
@and_test(expects=("nav_reach_about", "nav_reach_about_vlm"))
def test_reach_about():
    nodes = open_launcher()
    trig = find_node(nodes, text="About") or find_node_ci(nodes, "About")
    # Discriminator = About page text substring ('GNU GPL v3.0'), which is unique to
    # the About screen; the toolbar title 'About' collides with the launcher button.
    ok = trig is not None and and_reach_surface(trig, "GNU GPL v3.0", "Open Settings")
    record("nav_reach_about", ok,
           "" if ok else "feature_missing: About surface not reachable from 'About' button",
           depth=1, jump_kind="reach",
           expect="About text ('...GNU GPL v3.0...') appeared; launcher 'Open Settings' gone")
    vlm_assert("nav_reach_about",
               "Is this an 'About' text page: a screen filled mostly with lines of text "
               "(version, copyright, links) and NO keyboard preview or list of toggle rows?",
               RESULTS_DIR, tag="layout")


@test
@and_test(expects=("nav_reach_themepicker", "nav_reach_themepicker_vlm"))
def test_reach_themepicker():
    nodes = open_launcher()
    trig = theme_name_tv(nodes)
    ok = trig is not None and and_reach_surface(trig, "Keyboard Theme", "Open Settings")
    record("nav_reach_themepicker", ok,
           "" if ok else "feature_missing: ThemePicker not reachable from the theme-name card",
           depth=1, jump_kind="reach",
           expect="'Keyboard Theme' title appeared; launcher 'Open Settings' gone")
    vlm_assert("nav_reach_themepicker",
               "Does this screen show a vertical list of keyboard theme previews rendered "
               "in several DIFFERENT colors (e.g. a dark one, a white/light one, a black one)?",
               RESULTS_DIR, tag="color")


@test
@and_test(expects=("nav_reach_features_sheet", "nav_reach_features_sheet_vlm"))
def test_reach_features_sheet():
    nodes = open_launcher()
    fabs = find_by_class(nodes, "FloatingActionButton")
    trig = fabs[0] if fabs else None
    # The sheet slides over the launcher, so 'Open Settings' is covered (disappears)
    # while a tip string ('Learning Words') appears.
    ok = trig is not None and and_reach_surface(trig, "Learning Words", "Open Settings")
    record("nav_reach_features_sheet", ok,
           "" if ok else "feature_missing: Features bottom sheet not reachable from the FAB",
           depth=1, jump_kind="reach",
           expect="Features tip 'Learning Words' appeared; launcher 'Open Settings' covered/gone")
    vlm_assert("nav_reach_features_sheet",
               "Is a bottom sheet panel covering the lower portion of the screen, showing a "
               "list of tip titles with descriptions, while the top of the screen is dimmed?",
               RESULTS_DIR, tag="position")


# ══════════════════════════════════════════════════════════════════════════════
# (B) Settings -> each of the 8 rows — depth 2, reach (this lane's depth>=2 core)
# ══════════════════════════════════════════════════════════════════════════════

@test
@and_test(expects=("nav_settings_to_autocorrect",))
def test_settings_to_autocorrect():
    nodes = open_settings()
    if nodes is None:
        record("nav_settings_to_autocorrect", False,
               "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
               expect="Auto-Correct fragment after tapping its row")
        return
    and_enter("Settings")  # crossed S0 -> Settings
    row = find_node(nodes, text="Auto-Correct Settings")
    ok = row is not None and and_reach_surface(row, "Spell Check", "Keyboard Settings")
    record("nav_settings_to_autocorrect", ok,
           "" if ok else "feature_missing: Auto-Correct fragment not reachable from its row",
           depth=2, jump_kind="reach",
           expect="'Spell Check' row appeared; 'Keyboard Settings' title gone")


@test
@and_test(expects=("nav_settings_to_languages",))
def test_settings_to_languages():
    nodes = open_settings()
    if nodes is None:
        record("nav_settings_to_languages", False,
               "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
               expect="Languages fragment after tapping its row")
        return
    and_enter("Settings")
    row = find_node(nodes, text="Language Settings")
    ok = row is not None and and_reach_surface(row, "Merged Dictionaries", "Keyboard Settings")
    record("nav_settings_to_languages", ok,
           "" if ok else "feature_missing: Languages fragment not reachable from its row",
           depth=2, jump_kind="reach",
           expect="'Merged Dictionaries' row appeared; 'Keyboard Settings' title gone")


@test
@and_test(expects=("nav_settings_to_typing",))
def test_settings_to_typing():
    nodes = open_settings()
    if nodes is None:
        record("nav_settings_to_typing", False,
               "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
               expect="Typing Behavior fragment after tapping its row")
        return
    and_enter("Settings")
    row = find_node(nodes, text="Typing Behavior Settings")
    ok = row is not None and and_reach_surface(row, "Double-Space Period", "Keyboard Settings")
    record("nav_settings_to_typing", ok,
           "" if ok else "feature_missing: Typing Behavior fragment not reachable from its row",
           depth=2, jump_kind="reach",
           expect="'Double-Space Period' row appeared; 'Keyboard Settings' title gone")


@test
@and_test(expects=("nav_settings_to_layout",))
def test_settings_to_layout():
    nodes = open_settings()
    if nodes is None:
        record("nav_settings_to_layout", False,
               "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
               expect="Layout & Input fragment after tapping its row")
        return
    and_enter("Settings")
    # The dump keeps '&' un-unescaped: the row text is literally 'Layout &amp; Input'.
    row = find_node(nodes, text="Layout &amp; Input")
    ok = row is not None and and_reach_surface(row, "Keyboard Layout", "Keyboard Settings")
    record("nav_settings_to_layout", ok,
           "" if ok else "feature_missing: Layout & Input fragment not reachable from its row",
           depth=2, jump_kind="reach",
           expect="'Keyboard Layout' row appeared; 'Keyboard Settings' title gone")


@test
@and_test(expects=("nav_settings_to_appearance",))
def test_settings_to_appearance():
    nodes = open_settings()
    if nodes is None:
        record("nav_settings_to_appearance", False,
               "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
               expect="Appearance fragment after tapping its row")
        return
    and_enter("Settings")
    row = find_node(nodes, text="Appearance")
    ok = row is not None and and_reach_surface(row, "Key Press Highlight", "Keyboard Settings")
    record("nav_settings_to_appearance", ok,
           "" if ok else "feature_missing: Appearance fragment not reachable from its row",
           depth=2, jump_kind="reach",
           expect="'Key Press Highlight' row appeared; 'Keyboard Settings' title gone")


@test
@and_test(expects=("nav_settings_to_privacy",))
def test_settings_to_privacy():
    nodes = open_settings()
    if nodes is None:
        record("nav_settings_to_privacy", False,
               "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
               expect="Privacy & Data fragment after tapping its row")
        return
    and_enter("Settings")
    row = find_node(nodes, text="Privacy &amp; Data")
    # SOURCE note: the Privacy screen itself contains the Export-Settings summary
    # "Save keyboard settings and custom key mappings...", so the substring
    # "Keyboard Settings" SURVIVES the jump. Use a distinctive Settings-list row
    # ("Dictionary Data") that genuinely vanishes and has no substring collision.
    ok = row is not None and and_reach_surface(row, "Clipboard History", "Dictionary Data")
    record("nav_settings_to_privacy", ok,
           "" if ok else "feature_missing: Privacy & Data fragment not reachable from its row",
           depth=2, jump_kind="reach",
           expect="'Clipboard History' row appeared; Settings-list 'Dictionary Data' row gone")


@test
@and_test(expects=("nav_settings_to_licenses",))
def test_settings_to_licenses():
    nodes = open_settings()
    if nodes is None:
        record("nav_settings_to_licenses", False,
               "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
               expect="Open Source Licenses screen after tapping its row")
        return
    and_enter("Settings")
    row = find_node(nodes, text="Open Source Licenses")
    # The toolbar title equals the row text (same node_key), so use the licenses
    # content view (resource-id 'oss_licenses_text'), unique to the destination.
    ok = row is not None and and_reach_surface(row, "oss_licenses_text", "Dictionary Data")
    record("nav_settings_to_licenses", ok,
           "" if ok else "feature_missing: Open Source Licenses screen not reachable from its row",
           depth=2, jump_kind="reach",
           expect="licenses text view appeared; 'Dictionary Data' row gone")


@test
@and_test(expects=("nav_settings_to_dictionary",))
def test_settings_to_dictionary():
    nodes = open_settings()
    if nodes is None:
        record("nav_settings_to_dictionary", False,
               "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
               expect="Dictionary Data screen after tapping its row")
        return
    and_enter("Settings")
    row = find_node(nodes, text="Dictionary Data")
    # Title collides with the row; the attribution body text is unique to the screen.
    ok = row is not None and and_reach_surface(row, "DICTIONARY DATA ATTRIBUTION",
                                               "Open Source Licenses")
    record("nav_settings_to_dictionary", ok,
           "" if ok else "feature_missing: Dictionary Data screen not reachable from its row",
           depth=2, jump_kind="reach",
           expect="attribution text appeared; 'Open Source Licenses' row gone")


# ══════════════════════════════════════════════════════════════════════════════
# (C) Deep chains — and_enter per surface, prove the final reach
# ══════════════════════════════════════════════════════════════════════════════

@test
@and_test(expects=("nav_chain_appearance_themepicker", "nav_chain_appearance_themepicker_vlm"))
def test_chain_appearance_themepicker():
    """S0 -> Settings -> Appearance -> ThemePicker (depth 2 chain)."""
    nodes = open_settings()
    if nodes is None:
        record("nav_chain_appearance_themepicker", False,
               "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
               expect="ThemePicker after Settings->Appearance->Theme")
        vlm_assert("nav_chain_appearance_themepicker",
                   "Does this screen show a vertical list of keyboard theme previews in "
                   "several different colors?", RESULTS_DIR, tag="color")
        return
    and_enter("Settings")  # S0 -> Settings
    appr = find_node(nodes, text="Appearance")
    hop1 = appr is not None and and_reach_surface(appr, "Key Press Highlight", "Keyboard Settings")
    hop2 = False
    if hop1:
        theme_row = find_node(ui(), text="Theme")
        hop2 = theme_row is not None and and_reach_surface(theme_row, "Keyboard Theme",
                                                           "Key Press Highlight")
    ok = hop1 and hop2
    record("nav_chain_appearance_themepicker", ok,
           "" if ok else "behavior_wrong: Appearance->Theme did not reach the ThemePicker",
           depth=2, jump_kind="reach",
           expect="'Keyboard Theme' appeared after the Appearance 'Theme' row; "
                  "'Key Press Highlight' gone")
    vlm_assert("nav_chain_appearance_themepicker",
               "Does this screen show a vertical list of keyboard theme previews rendered "
               "in several DIFFERENT colors (dark, light/white, black, etc.)?",
               RESULTS_DIR, tag="color")


@test
@and_test(expects=("nav_chain_layout_mapper", "nav_chain_layout_mapper_vlm"))
def test_chain_layout_mapper():
    """S0 -> Settings -> Layout & Input -> LayoutMapper (depth 3 chain)."""
    nodes = open_settings()
    if nodes is None:
        record("nav_chain_layout_mapper", False,
               "setup_failed: could not reach the Settings list", depth=3, jump_kind="reach",
               expect="LayoutMapper after Settings->Layout->Customize Keys")
        vlm_assert("nav_chain_layout_mapper",
                   "Does this screen show a full rendered QWERTY keyboard (rows of letter "
                   "keys) with a button below it?", RESULTS_DIR, tag="layout")
        return
    and_enter("Settings")  # S0 -> Settings
    li = find_node(nodes, text="Layout &amp; Input")
    hop1 = li is not None and and_reach_surface(li, "Keyboard Layout", "Keyboard Settings")
    hop2 = False
    if hop1:
        ck = find_node(ui(), text="Customize Keys")
        # LayoutMapper title 'Customize Keys' collides with the row; 'Reset All'
        # (a button unique to the mapper) is the discriminator.
        hop2 = ck is not None and and_reach_surface(ck, "Reset All", "Keyboard Layout")
    ok = hop1 and hop2
    record("nav_chain_layout_mapper", ok,
           "" if ok else "behavior_wrong: Layout->Customize Keys did not reach the LayoutMapper",
           depth=3, jump_kind="reach",
           expect="'Reset All' appeared after the 'Customize Keys' row; 'Keyboard Layout' gone")
    vlm_assert("nav_chain_layout_mapper",
               "Is a full keyboard laid out as horizontal rows of keys (number row, then "
               "letter rows Q-P, A-L, Z-M) rendered in the center of this screen?",
               RESULTS_DIR, tag="layout")


# ══════════════════════════════════════════════════════════════════════════════
# (D) Dialog reachability + dismissal (a dialog is a surface)
# ══════════════════════════════════════════════════════════════════════════════

@test
@and_test(expects=("nav_reset_dialog_reach", "nav_reset_dialog_reach_vlm"))
def test_reset_dialog_reach():
    """Privacy -> Reset to Defaults -> the confirm dialog appears (SAFE: never tap OK)."""
    nodes = open_settings()
    if nodes is None:
        record("nav_reset_dialog_reach", False,
               "setup_failed: could not reach the Settings list", depth=3, jump_kind="reach",
               expect="Reset confirm dialog after tapping 'Reset to Defaults'")
        vlm_assert("nav_reset_dialog_reach",
                   "Is a small modal dialog box centered over a dimmed screen, with two text "
                   "buttons in its bottom-right?", RESULTS_DIR, tag="position")
        return
    and_enter("Settings")
    pv = find_node(nodes, text="Privacy &amp; Data")
    # Privacy hop source: distinctive list row (see nav_settings_to_privacy note).
    hop1 = pv is not None and and_reach_surface(pv, "Clipboard History", "Dictionary Data")
    hop2 = False
    if hop1:
        reset = find_node(ui(), text="Reset to Defaults")
        # Title 'Reset to Defaults' collides with the row; the dialog MESSAGE is unique.
        hop2 = reset is not None and and_reach_surface(reset, "Reset all settings to defaults?",
                                                       "Clipboard History")
    ok = hop1 and hop2
    record("nav_reset_dialog_reach", ok,
           "" if ok else "behavior_wrong: 'Reset to Defaults' did not raise a confirm dialog",
           depth=3, jump_kind="reach",
           expect="dialog message 'Reset all settings to defaults?' appeared; "
                  "'Clipboard History' row covered/gone")
    vlm_assert("nav_reset_dialog_reach",
               "Is a small modal dialog box centered on the screen (with a title, a short "
               "message, and Cancel/OK buttons) over a dimmed background?",
               RESULTS_DIR, tag="position")


@test
@and_test(expects=("nav_reset_dialog_cancel",))
def test_reset_dialog_cancel():
    """Reset dialog -> Cancel -> dialog gone, back on Privacy (SAFE)."""
    nodes = open_settings()
    if nodes is None:
        record("nav_reset_dialog_cancel", False,
               "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
               expect="Privacy screen restored after Cancel")
        return
    and_enter("Settings")
    pv = find_node(nodes, text="Privacy &amp; Data")
    ok_pv = pv is not None and and_reach_surface(pv, "Clipboard History", "Dictionary Data")
    dismissed = False
    if ok_pv:
        reset = find_node(ui(), text="Reset to Defaults")
        if reset and and_reach_surface(reset, "Reset all settings to defaults?", "Clipboard History"):
            dlg = ui()
            cancel = find_node(dlg, text="Cancel")  # SAFETY: only ever Cancel, never OK
            before = and_showing(dlg)
            if cancel and tap_node(cancel):
                settle("tap")
                dismissed = and_reach(before, and_showing(),
                                      "Clipboard History", "Reset all settings to defaults?")
    record("nav_reset_dialog_cancel", ok_pv and dismissed,
           "" if (ok_pv and dismissed) else
           "behavior_wrong: Cancel did not dismiss the reset dialog back to Privacy",
           depth=2, jump_kind="reach",
           expect="after Cancel: dialog message gone, 'Clipboard History' row restored")


@test
@and_test(expects=("nav_suggestion_dialog_reach", "nav_suggestion_dialog_reach_vlm"))
def test_suggestion_dialog_reach():
    """Auto-Correct -> Suggestion Count -> the list dialog appears."""
    nodes = open_settings()
    if nodes is None:
        record("nav_suggestion_dialog_reach", False,
               "setup_failed: could not reach the Settings list", depth=3, jump_kind="reach",
               expect="Suggestion Count list dialog")
        vlm_assert("nav_suggestion_dialog_reach",
                   "Is a modal dialog showing a short vertical list of selectable options "
                   "each with a round radio button on its left?", RESULTS_DIR, tag="shape")
        return
    and_enter("Settings")
    ac = find_node(nodes, text="Auto-Correct Settings")
    hop1 = ac is not None and and_reach_surface(ac, "Spell Check", "Keyboard Settings")
    hop2 = False
    if hop1:
        sc = find_node(ui(), text="Suggestion Count")
        # The list dialog adds a select list; 'Learn New Words' (a row below in the
        # fragment) is covered by the dialog.
        hop2 = sc is not None and and_reach_surface(sc, "select_dialog_listview", "Learn New Words")
    ok = hop1 and hop2
    record("nav_suggestion_dialog_reach", ok,
           "" if ok else "behavior_wrong: 'Suggestion Count' did not open a list dialog",
           depth=3, jump_kind="reach",
           expect="dialog list ('select_dialog_listview') appeared; 'Learn New Words' covered/gone")
    vlm_assert("nav_suggestion_dialog_reach",
               "Is a modal dialog showing a short vertical list of numeric options, each with "
               "a round radio-button circle to its left, and a Cancel button?",
               RESULTS_DIR, tag="shape")


@test
@and_test(expects=("nav_suggestion_dialog_cancel",))
def test_suggestion_dialog_cancel():
    """Suggestion Count dialog -> Cancel -> back on the Auto-Correct fragment."""
    nodes = open_settings()
    if nodes is None:
        record("nav_suggestion_dialog_cancel", False,
               "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
               expect="Auto-Correct fragment restored after Cancel")
        return
    and_enter("Settings")
    ac = find_node(nodes, text="Auto-Correct Settings")
    ok_ac = ac is not None and and_reach_surface(ac, "Spell Check", "Keyboard Settings")
    dismissed = False
    if ok_ac:
        sc = find_node(ui(), text="Suggestion Count")
        if sc and and_reach_surface(sc, "select_dialog_listview", "Learn New Words"):
            dlg = ui()
            cancel = find_node(dlg, text="Cancel")
            before = and_showing(dlg)
            if cancel and tap_node(cancel):
                settle("tap")
                dismissed = and_reach(before, and_showing(),
                                      "Learn New Words", "select_dialog_listview")
    record("nav_suggestion_dialog_cancel", ok_ac and dismissed,
           "" if (ok_ac and dismissed) else
           "behavior_wrong: Cancel did not dismiss the Suggestion Count dialog",
           depth=2, jump_kind="reach",
           expect="after Cancel: dialog list gone, 'Learn New Words' row restored")


# ══════════════════════════════════════════════════════════════════════════════
# (E) Back-stack integrity — forward-then-BACK, proven in reverse with and_reach.
# The trigger under test (up-affordance / BACK) presses BACK exactly ONCE; these
# tests never double-pop.
# ══════════════════════════════════════════════════════════════════════════════

@test
@and_test(expects=("nav_backstack_up_autocorrect", "nav_backstack_up_autocorrect_vlm"))
def test_backstack_up_autocorrect():
    """Settings -> Auto-Correct, then the toolbar up-affordance returns to the list."""
    nodes = open_settings()
    if nodes is None:
        record("nav_backstack_up_autocorrect", False,
               "setup_failed: could not reach the Settings list", depth=1, jump_kind="reach",
               expect="Settings list restored after Navigate up")
        vlm_assert("nav_backstack_up_autocorrect",
                   "Does the toolbar at the top of this screen show a left-pointing back "
                   "arrow (up affordance) at its far left?", RESULTS_DIR, tag="shape")
        return
    and_enter("Settings")
    ac = find_node(nodes, text="Auto-Correct Settings")
    forward = ac is not None and and_reach_surface(ac, "Spell Check", "Keyboard Settings")
    sub = ui() if forward else []
    # VLM on the SUB-fragment: the up affordance must be present there. Captured
    # BEFORE we pop so the screenshot is of the sub-screen toolbar.
    vlm_assert("nav_backstack_up_autocorrect",
               "Does the toolbar at the very top of this screen show a left-pointing back "
               "arrow at its far left, next to the screen title?",
               RESULTS_DIR, tag="shape")
    returned = False
    if forward:
        before = and_showing(sub)
        if tap_up(sub):  # the up-affordance IS the back action; single BACK
            returned = and_reach(before, and_showing(), "Keyboard Settings", "Spell Check")
    record("nav_backstack_up_autocorrect", forward and returned,
           "" if (forward and returned) else
           "behavior_wrong: the up-affordance did not return to the Settings list",
           depth=1, jump_kind="reach",
           expect="'Keyboard Settings' title reappeared; 'Spell Check' row gone")


@test
@and_test(expects=("nav_backstack_about_to_home",))
def test_backstack_about_to_home():
    """S0 -> About, then BACK returns to the launcher."""
    trig = find_node(open_launcher(), text="About")
    forward = trig is not None and and_reach_surface(trig, "GNU GPL v3.0", "Open Settings")
    returned = False
    if forward:
        before = and_showing()
        and_back()  # BACK pops the About activity (single press)
        settle("tap")
        returned = and_reach(before, and_showing(), "Open Settings", "GNU GPL v3.0")
    record("nav_backstack_about_to_home", forward and returned,
           "" if (forward and returned) else
           "behavior_wrong: BACK from About did not return to the launcher",
           depth=1, jump_kind="reach",
           expect="launcher 'Open Settings' button restored; About text ('GNU GPL v3.0') gone")


@test
@and_test(expects=("nav_backstack_themepicker_to_home",))
def test_backstack_themepicker_to_home():
    """S0 -> ThemePicker (card), then BACK returns to the launcher."""
    trig = theme_name_tv(open_launcher())
    forward = trig is not None and and_reach_surface(trig, "Keyboard Theme", "Open Settings")
    returned = False
    if forward:
        before = and_showing()
        and_back()  # BACK pops the ThemePicker activity (single press)
        settle("tap")
        returned = and_reach(before, and_showing(), "Open Settings", "Keyboard Theme")
    record("nav_backstack_themepicker_to_home", forward and returned,
           "" if (forward and returned) else
           "behavior_wrong: BACK from ThemePicker did not return to the launcher",
           depth=1, jump_kind="reach",
           expect="launcher 'Open Settings' button restored; 'Keyboard Theme' title gone")


@test
@and_test(expects=("nav_backstack_2hop_unwind",))
def test_backstack_2hop_unwind():
    """Depth-2 chain unwound hop by hop: S0->Settings->Appearance->ThemePicker,
    then the up-affordance TWICE, asserting the expected surface after each pop."""
    nodes = open_settings()
    if nodes is None:
        record("nav_backstack_2hop_unwind", False,
               "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
               expect="Settings restored after unwinding ThemePicker->Appearance->Settings")
        return
    and_enter("Settings")  # S0 -> Settings
    appr = find_node(nodes, text="Appearance")
    hop1 = appr is not None and and_reach_surface(appr, "Key Press Highlight", "Keyboard Settings")
    hop2 = False
    if hop1:
        theme_row = find_node(ui(), text="Theme")
        hop2 = theme_row is not None and and_reach_surface(theme_row, "Keyboard Theme",
                                                           "Key Press Highlight")
    pop1 = pop2 = False
    if hop2:
        tp = ui()
        b_tp = and_showing(tp)
        if tap_up(tp):  # pop ThemePicker -> Appearance (single BACK)
            pop1 = and_reach(b_tp, and_showing(), "Key Press Highlight", "Keyboard Theme")
        if pop1:
            appr_now = ui()
            b_appr = and_showing(appr_now)
            if tap_up(appr_now):  # pop Appearance -> Settings (single BACK)
                pop2 = and_reach(b_appr, and_showing(), "Keyboard Settings", "Key Press Highlight")
    ok = hop1 and hop2 and pop1 and pop2
    record("nav_backstack_2hop_unwind", ok,
           "" if ok else "behavior_wrong: BACK did not unwind ThemePicker->Appearance->Settings hop by hop",
           depth=2, jump_kind="reach",
           expect="pop1 -> Appearance ('Key Press Highlight'), pop2 -> Settings ('Keyboard Settings')")


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