File size: 43,457 Bytes
c1c6a0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""STATE CHANGE lane — Simple Time Tracker.

Sole owner of `checked` and `focused`. Every case is a BEFORE->AFTER flip PAIRED
with the app-authored consequence — a bare `checked` flip a framework widget can
do with zero app code is worthless, so each toggle is tied to what it makes appear,
disappear, or re-read.

GROUND TRUTH established live on the running original (v1.58 debug):
  SETTINGS tab (reachable via the 'Settings' bottom-tab content-desc):
    * 'Allow multitasking' is a CheckBox `checkboxItemSettings`, `checked` dump-
      readable, DEFAULT checked=true. Toggling it flips checked AND the subtitle
      'If disabled, starting new timer will automatically stop other activities.'
      stays; the discriminating consequence is the checked attr re-reading after a
      relaunch (persistence).
    * 'Dark mode' is the FIRST `spinnerItemSettings` (y above 'Language'); its value
      TextView `tvItemSettingsValue` reads 'System' by default. The dropdown options
      are EXACTLY System / Enabled / Disabled. Choosing 'Enabled' re-themes the app
      to a near-black background with light text (VLM) and the value reads 'Enabled'.
    * 'Language' is the SECOND `spinnerItemSettings`; its dropdown lists System /
      English / ... . Opening it is a depth-1 surface; we DISMISS with back(), never
      switch the language.
    * Collapse header 'Display settings' (`tvItemSettingsCollapseTitle`) needs a
      scroll to reach; tapping it reveals sub-items incl. 'Show untracked time in
      records' (a `tvItemSettingsTitle`) that were absent before the expand.
  ADD-ACTIVITY screen (Timers tab -> 'Add' tile):
    * `etChangeRecordTypeName` is auto-focused (focused=true) on entry — the FOCUS
      target this lane owns.
    * 'More'/'Less' toggler `tvChangeRecordTypeMoreFieldsText` flips More->Less AND
      reveals the Note editor `etChangeRecordTypeNote` (+ Category/Goal).
    * Tapping the Note field flips ITS focused false->true (focus moves off the name).
    * Color field expands a grid; exactly one `viewColorItemSelected` marker sits in
      the currently-selected cell. Tapping a different cell MOVES that marker's bounds.
    * Icon field expands a picker with `btnButtonsRowView` mode buttons ICON/TEXT/
      EMOJI. TEXT reveals `etIconSelectionText`; EMOJI changes the category header
      `tvIconSelectionCategoryInfoItem` from 'Maps' to 'Smileys & Emotion' (the XML
      entity is stored raw as 'Smileys & Emotion' by the kit parser, so match on
      the substring 'Smileys').

Every test opens its OWN entry point (clear_data / restart) and reads a FRESH ui()
after each change; a node located in an old dump is re-found with find_closest_match
before its new state is read. Dumps are ~11s on this emulator, so ui() calls are
minimised. No fixtures (this app opens no external files).
"""
import os
import sys

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

PACKAGE = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("PACKAGE", "")
RESULTS_DIR = (sys.argv[2] if len(sys.argv) > 2
               else os.environ.get("RESULTS_DIR", os.path.dirname(os.path.abspath(__file__))))
init(module="states", package=PACKAGE, results_dir=RESULTS_DIR)


# ── local recipes (kit-only, nothing hardcoded) ────────────────────────────────
def tile(nodes, label):
    """The clickable tile CONTAINER whose bounds enclose the name TextView."""
    name = next((n for n in nodes if (n.get("text") or "") == label
                 and (n.get("resource-id") or "").endswith("tvRecordTypeItemName")), None)
    if not name:
        return None
    nb = name["_bounds"]
    for n in nodes:
        if (n.get("resource-id") or "").endswith("viewRecordTypeItem") \
                and n.get("clickable") == "true":
            b = n["_bounds"]
            if b[0] <= nb[0] and b[2] >= nb[2] and b[1] <= nb[1] and b[3] >= nb[3]:
                return n
    return None


def tab_trigger(nodes, desc):
    return next((n for n in nodes if (n.get("content-desc") or "") == desc), None)


def fresh_launch():
    """Clean ENTRY POINT: a virgin database + a fresh launch."""
    clear_data()
    launch_app()
    wait_for_foreground()
    settle("launch")
    return ui()


def relaunch_keep_data():
    """Relaunch WITHOUT wiping data — the persistence entry point."""
    force_stop_and_relaunch()
    wait_for_foreground()
    settle("launch")
    return ui()


def spinner_value_texts(nodes=None):
    nodes = ui() if nodes is None else nodes
    return [n.get("text") for n in nodes
            if (n.get("resource-id") or "").endswith("tvItemSettingsValue")]


def settings_titles(nodes=None):
    nodes = ui() if nodes is None else nodes
    return [n.get("text") for n in nodes
            if (n.get("resource-id") or "").endswith("tvItemSettingsTitle")]


# ── depth-family helpers (NAME backs any depth>=1 claim) ───────────────────────
def and_enter_settings():
    """Switch to the Settings tab (a real surface hop). NAME backs the depth."""
    t = tab_trigger(ui(), "Settings")
    if not t or not tap_node(t):
        return False
    settle("nav")
    and_enter("settings")
    return find_node_ci(ui(), "Allow multitasking") is not None


def and_enter_add():
    """Timers tab -> Add-activity screen. NAME backs the depth; confirms the name
    field is present on the new surface."""
    add = tile(ui(), "Add")
    if not add or not tap_node(add):
        return False
    settle("nav")
    and_enter("add_activity")
    return node_by_id(ui(), "etChangeRecordTypeName") is not None


def and_enter_icon_picker():
    """Add screen -> icon picker expander (tap the Icon field). NAME backs depth;
    confirms the ICON/TEXT/EMOJI mode buttons appeared."""
    fld = next((n for n in ui()
                if (n.get("resource-id") or "").endswith("fieldChangeRecordTypeIcon")
                and n.get("clickable") in ("true", None)), None)
    # the field container itself is the tap target (focusable frame)
    fld = fld or node_by_id(ui(), "fieldChangeRecordTypeIcon")
    if not fld or not tap_node(fld):
        return False
    settle("nav")
    and_enter("icon_picker")
    return any((n.get("text") or "") in ("ICON", "TEXT", "EMOJI") for n in ui())


def and_enter_color_picker():
    """Add screen -> color picker expander (tap the Color field). NAME backs depth;
    confirms the selected-swatch marker is present."""
    fld = node_by_id(ui(), "fieldChangeRecordTypeColor")
    if not fld or not tap_node(fld):
        return False
    settle("nav")
    and_enter("color_picker")
    return node_by_id(ui(), "viewColorItemSelected") is not None


def mode_button(nodes, label):
    """The ICON/TEXT/EMOJI selector button by its visible text."""
    return next((n for n in nodes if (n.get("text") or "") == label
                 and (n.get("resource-id") or "").endswith("btnButtonsRowView")), None)


def icon_category_headers(nodes=None):
    nodes = ui() if nodes is None else nodes
    return [n.get("text") or "" for n in nodes
            if (n.get("resource-id") or "").endswith("tvIconSelectionCategoryInfoItem")]


# ══════════════════════════════════════════════════════════════════════════════
# 1. 'Allow multitasking' CheckBox flips checked true->false (+ re-reads)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_multitasking_toggle",))
def test_multitasking_toggle():
    fresh_launch()
    if not and_enter_settings():
        record("states_multitasking_toggle", False,
               "setup_failed: Settings tab did not expose 'Allow multitasking'",
               depth=1, jump_kind="transition",
               expect="checked true->false; value re-reads flipped")
        return
    cb = node_by_id(ui(), "checkboxItemSettings")
    if cb is None:
        record("states_multitasking_toggle", False,
               "feature_missing: no 'Allow multitasking' checkbox on Settings",
               depth=1, jump_kind="transition",
               expect="checked true->false; value re-reads flipped")
        return
    before = cb.get("checked")
    tap_node(cb)
    settle("tap")
    after = (find_closest_match(ui(), cb) or {}).get("checked")
    # restore to the original observed state so the device stays clean
    cb2 = node_by_id(ui(), "checkboxItemSettings")
    if cb2 and cb2.get("checked") != before:
        tap_node(cb2)
        settle("tap")
    ok = before in ("true", "false") and after in ("true", "false") and after != before
    record("states_multitasking_toggle", ok,
           "" if ok else "behavior_wrong: 'Allow multitasking' checkbox did not flip "
           f"its checked state (before={before!r}, after={after!r})",
           depth=1, jump_kind="transition",
           expect=f"checkboxItemSettings checked flips {before!r}->not-{before!r} on tap")


# ══════════════════════════════════════════════════════════════════════════════
# 2. 'Allow multitasking' state PERSISTS across process death (the strong probe)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_multitasking_persists",))
def test_multitasking_persists():
    fresh_launch()
    if not and_enter_settings():
        record("states_multitasking_persists", False,
               "setup_failed: Settings tab did not render",
               depth=1, jump_kind="value", expect="checked=false survives relaunch")
        return
    cb = node_by_id(ui(), "checkboxItemSettings")
    if cb is None:
        record("states_multitasking_persists", False,
               "feature_missing: no 'Allow multitasking' checkbox",
               depth=1, jump_kind="value", expect="checked=false survives relaunch")
        return
    orig = cb.get("checked")
    # flip it OFF (to the non-default) so the persisted value is unambiguous
    if orig != "false":
        tap_node(cb)
        settle("tap")
    set_state = (find_closest_match(ui(), cb) or {}).get("checked")
    relaunch_keep_data()
    if not and_enter_settings():
        record("states_multitasking_persists", False,
               "setup_failed: Settings tab did not render after relaunch",
               depth=1, jump_kind="value", expect="checked=false survives relaunch")
        return
    survived = (node_by_id(ui(), "checkboxItemSettings") or {}).get("checked")
    ok = set_state == "false" and survived == "false"
    # restore to original observed default so the device stays clean
    cb3 = node_by_id(ui(), "checkboxItemSettings")
    if cb3 and cb3.get("checked") != orig:
        tap_node(cb3)
        settle("tap")
    record("states_multitasking_persists", ok,
           "" if ok else "behavior_wrong: 'Allow multitasking'=false did not survive "
           f"process death (set={set_state!r}, after_relaunch={survived!r}) — an "
           "in-memory-only recreation fails this",
           depth=1, jump_kind="value",
           expect="checkboxItemSettings checked=false still set after force_stop_and_relaunch")


# ══════════════════════════════════════════════════════════════════════════════
# 3. Dark-mode spinner value System -> 'Enabled'  (+ VLM: dark theme applied)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_darkmode_enabled",
                   "states_darkmode_applied_vlm",
                   "states_darkmode_settings_vlm"))
def test_darkmode_enabled():
    fresh_launch()
    if not and_enter_settings():
        record("states_darkmode_enabled", False,
               "setup_failed: Settings tab did not render",
               depth=1, jump_kind="value", expect="dark-mode value System->'Enabled'")
        vlm_assert("states_darkmode_applied", "unreachable", RESULTS_DIR,
                   expect="YES", depth=1, jump_kind="none", tag="color")
        vlm_assert("states_darkmode_settings", "unreachable", RESULTS_DIR,
                   expect="YES", depth=1, jump_kind="none", tag="color")
        return
    spinners = [n for n in ui()
                if (n.get("resource-id") or "").endswith("spinnerItemSettings")]
    if len(spinners) < 1:
        record("states_darkmode_enabled", False,
               "feature_missing: no dark-mode spinner on Settings",
               depth=1, jump_kind="value", expect="dark-mode value System->'Enabled'")
        vlm_assert("states_darkmode_applied", "unreachable", RESULTS_DIR,
                   expect="YES", depth=1, jump_kind="none", tag="color")
        vlm_assert("states_darkmode_settings", "unreachable", RESULTS_DIR,
                   expect="YES", depth=1, jump_kind="none", tag="color")
        return
    before_vals = spinner_value_texts()
    dark_before = "System" in (before_vals[0] if before_vals else "")
    tap_node(spinners[0])          # open the dark-mode dropdown
    settle("nav")
    en = find_node_ci(ui(), "Enabled")
    if en is None or not tap_node(en):
        record("states_darkmode_enabled", False,
               "feature_missing: dark-mode dropdown had no 'Enabled' option",
               depth=1, jump_kind="value", expect="dark-mode value System->'Enabled'")
        vlm_assert("states_darkmode_applied", "unreachable", RESULTS_DIR,
                   expect="YES", depth=1, jump_kind="none", tag="color")
        vlm_assert("states_darkmode_settings", "unreachable", RESULTS_DIR,
                   expect="YES", depth=1, jump_kind="none", tag="color")
        return
    settle("nav")
    settle("nav")
    after_vals = spinner_value_texts()
    dark_after = "Enabled" in (after_vals[0] if after_vals else "")
    ok = dark_before and dark_after
    record("states_darkmode_enabled", ok,
           "" if ok else "behavior_wrong: dark-mode value did not change System->'Enabled' "
           f"(before={before_vals}, after={after_vals})",
           depth=1, jump_kind="value",
           expect="first tvItemSettingsValue 'System'->'Enabled' after choosing Enabled")
    # VLM: the theme actually re-rendered dark (near-black bg + light text).
    vlm_assert("states_darkmode_applied",
               "Is this screen's background very dark (near-black / very dark grey) "
               "with light/white text, indicating a dark theme is applied?",
               RESULTS_DIR, expect="YES", depth=1, jump_kind="value", tag="color")
    vlm_assert("states_darkmode_settings",
               "On this Settings list, is the overall page background dark (black/very "
               "dark grey) while the setting titles are rendered in light/white text?",
               RESULTS_DIR, expect="YES", depth=1, jump_kind="value", tag="color")
    # restore to System via the GUI so the device stays at the default theme
    spinners = [n for n in ui()
                if (n.get("resource-id") or "").endswith("spinnerItemSettings")]
    if spinners:
        tap_node(spinners[0])
        settle("nav")
        sysopt = find_node_ci(ui(), "System")
        if sysopt:
            tap_node(sysopt)
            settle("nav")


# ══════════════════════════════════════════════════════════════════════════════
# 4. Dark-mode 'Enabled' PERSISTS across process death
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_darkmode_persists",))
def test_darkmode_persists():
    fresh_launch()
    if not and_enter_settings():
        record("states_darkmode_persists", False,
               "setup_failed: Settings tab did not render",
               depth=1, jump_kind="value", expect="dark-mode 'Enabled' survives relaunch")
        return
    spinners = [n for n in ui()
                if (n.get("resource-id") or "").endswith("spinnerItemSettings")]
    if not spinners:
        record("states_darkmode_persists", False,
               "feature_missing: no dark-mode spinner",
               depth=1, jump_kind="value", expect="dark-mode 'Enabled' survives relaunch")
        return
    tap_node(spinners[0])
    settle("nav")
    en = find_node_ci(ui(), "Enabled")
    if en is None or not tap_node(en):
        record("states_darkmode_persists", False,
               "feature_missing: dark-mode dropdown had no 'Enabled' option",
               depth=1, jump_kind="value", expect="dark-mode 'Enabled' survives relaunch")
        return
    settle("nav")
    settle("nav")
    set_val = (spinner_value_texts() or [""])[0]
    relaunch_keep_data()
    survived = ""
    if and_enter_settings():
        survived = (spinner_value_texts() or [""])[0]
    ok = set_val == "Enabled" and survived == "Enabled"
    # restore to System
    spinners = [n for n in ui()
                if (n.get("resource-id") or "").endswith("spinnerItemSettings")]
    if spinners:
        tap_node(spinners[0])
        settle("nav")
        sysopt = find_node_ci(ui(), "System")
        if sysopt:
            tap_node(sysopt)
            settle("nav")
    record("states_darkmode_persists", ok,
           "" if ok else "behavior_wrong: dark-mode 'Enabled' did not survive process "
           f"death (set={set_val!r}, after_relaunch={survived!r})",
           depth=1, jump_kind="value",
           expect="dark-mode value still 'Enabled' after force_stop_and_relaunch")


# ══════════════════════════════════════════════════════════════════════════════
# 5. 'More'->'Less' toggler flips label AND reveals the Note editor
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_more_less_toggle",))
def test_more_less_toggle():
    fresh_launch()
    if not and_enter_add():
        record("states_more_less_toggle", False,
               "setup_failed: could not open the Add-activity screen",
               depth=1, jump_kind="transition",
               expect="More->Less; Note field appears")
        return
    toggler = node_by_id(ui(), "tvChangeRecordTypeMoreFieldsText")
    if toggler is None:
        record("states_more_less_toggle", False,
               "feature_missing: no More/Less toggler on the Add screen",
               depth=1, jump_kind="transition",
               expect="More->Less; Note field appears")
        return
    label_before = toggler.get("text")
    note_before = node_by_id(ui(), "etChangeRecordTypeNote") is not None
    tap_node(toggler)
    settle("nav")
    fresh = ui()
    label_after = (node_by_id(fresh, "tvChangeRecordTypeMoreFieldsText") or {}).get("text")
    note_after = node_by_id(fresh, "etChangeRecordTypeNote") is not None
    ok = (label_before == "More" and label_after == "Less"
          and (not note_before) and note_after)
    record("states_more_less_toggle", ok,
           "" if ok else "behavior_wrong: More/Less did not flip the label AND reveal the "
           f"Note field (label {label_before!r}->{label_after!r}, note {note_before}->{note_after})",
           depth=1, jump_kind="transition",
           expect="toggler text 'More'->'Less' AND etChangeRecordTypeNote absent->present")


# ══════════════════════════════════════════════════════════════════════════════
# 6. Expand 'Display settings' -> a sub-setting appears (absent -> present)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_display_collapse_expand",))
def test_display_collapse_expand():
    fresh_launch()
    SUB = "Show untracked time in records"
    if not and_enter_settings():
        record("states_display_collapse_expand", False,
               "setup_failed: Settings tab did not render",
               depth=1, jump_kind="transition",
               expect=f"'{SUB}' absent->present after expanding Display settings")
        return
    # 'Display settings' lives lower on the list — scroll it into view first.
    header = scroll_into_view("Display settings", max_swipes=6)
    if header is None:
        record("states_display_collapse_expand", False,
               "feature_missing: no 'Display settings' collapse header",
               depth=1, jump_kind="transition",
               expect=f"'{SUB}' absent->present after expanding Display settings")
        return
    absent_before = find_node_ci(ui(), SUB) is None
    tap_node(header)
    settle("nav")
    # the revealed sub-item may sit just below — pull it into view to read it
    present_after = (find_node_ci(ui(), SUB) is not None
                     or scroll_into_view(SUB, max_swipes=3) is not None)
    ok = absent_before and present_after
    record("states_display_collapse_expand", ok,
           "" if ok else "behavior_wrong: expanding 'Display settings' did not reveal "
           f"the '{SUB}' sub-item (absent_before={absent_before}, present_after={present_after})",
           depth=1, jump_kind="transition",
           expect=f"'{SUB}' sub-item absent before expand, present after tapping the header")


# ══════════════════════════════════════════════════════════════════════════════
# 7. Icon-mode ICON->TEXT reveals the text-icon input (+2 VLM: icon vs text grid)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_icon_mode_text",
                   "states_icon_grid_pictographic_vlm",
                   "states_mode_button_highlighted_vlm"))
def test_icon_mode_text():
    fresh_launch()
    if not and_enter_add():
        record("states_icon_mode_text", False,
               "setup_failed: could not open the Add-activity screen",
               depth=2, jump_kind="transition", expect="ICON->TEXT reveals text-icon input")
        vlm_assert("states_icon_grid_pictographic", "unreachable", RESULTS_DIR,
                   expect="YES", depth=2, jump_kind="none", tag="shape")
        vlm_assert("states_mode_button_highlighted", "unreachable", RESULTS_DIR,
                   expect="YES", depth=2, jump_kind="none", tag="color")
        return
    if not and_enter_icon_picker():
        record("states_icon_mode_text", False,
               "feature_missing: Icon field did not expose ICON/TEXT/EMOJI mode buttons",
               depth=2, jump_kind="transition", expect="ICON->TEXT reveals text-icon input")
        vlm_assert("states_icon_grid_pictographic", "unreachable", RESULTS_DIR,
                   expect="YES", depth=2, jump_kind="none", tag="shape")
        vlm_assert("states_mode_button_highlighted", "unreachable", RESULTS_DIR,
                   expect="YES", depth=2, jump_kind="none", tag="color")
        return
    # VLM on the ICON grid (default mode): pictographic icon cells + which mode
    # button is highlighted. The grid is a custom RecyclerView of image cells.
    vlm_assert("states_icon_grid_pictographic",
               "Below the ICON / TEXT / EMOJI buttons, is there a grid of small "
               "pictographic icon glyphs (line-drawn symbols such as location pins, "
               "shapes or objects) rather than letters or emoji?",
               RESULTS_DIR, expect="YES", depth=2, jump_kind="transition", tag="shape")
    vlm_assert("states_mode_button_highlighted",
               "Among the three mode buttons labelled ICON, TEXT and EMOJI, is the "
               "'ICON' button visually highlighted (a different/filled background) "
               "compared to the other two?",
               RESULTS_DIR, expect="YES", depth=2, jump_kind="transition", tag="color")
    text_before = node_by_id(ui(), "etIconSelectionText") is not None
    btn = mode_button(ui(), "TEXT")
    if btn is None or not tap_node(btn):
        record("states_icon_mode_text", False,
               "feature_missing: 'TEXT' mode button not tappable",
               depth=2, jump_kind="transition", expect="ICON->TEXT reveals text-icon input")
        return
    settle("nav")
    text_after = node_by_id(ui(), "etIconSelectionText") is not None
    ok = (not text_before) and text_after
    record("states_icon_mode_text", ok,
           "" if ok else "behavior_wrong: switching icon-mode to TEXT did not reveal the "
           f"text-icon input etIconSelectionText (before={text_before}, after={text_after})",
           depth=2, jump_kind="transition",
           expect="etIconSelectionText absent in ICON mode, present after selecting TEXT")


# ══════════════════════════════════════════════════════════════════════════════
# 8. Icon-mode ICON->EMOJI changes the category header (+2 VLM: emoji grid)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_icon_mode_emoji",
                   "states_emoji_grid_glyphs_vlm",))
def test_icon_mode_emoji():
    fresh_launch()
    if not and_enter_add():
        record("states_icon_mode_emoji", False,
               "setup_failed: could not open the Add-activity screen",
               depth=2, jump_kind="transition",
               expect="ICON->EMOJI: category 'Maps'->'Smileys...'")
        vlm_assert("states_emoji_grid_glyphs", "unreachable", RESULTS_DIR,
                   expect="YES", depth=2, jump_kind="none", tag="shape")
        return
    if not and_enter_icon_picker():
        record("states_icon_mode_emoji", False,
               "feature_missing: Icon field did not expose the mode buttons",
               depth=2, jump_kind="transition",
               expect="ICON->EMOJI: category 'Maps'->'Smileys...'")
        vlm_assert("states_emoji_grid_glyphs", "unreachable", RESULTS_DIR,
                   expect="YES", depth=2, jump_kind="none", tag="shape")
        return
    cats_before = icon_category_headers()
    icon_default = any("Maps" in c for c in cats_before)
    btn = mode_button(ui(), "EMOJI")
    if btn is None or not tap_node(btn):
        record("states_icon_mode_emoji", False,
               "feature_missing: 'EMOJI' mode button not tappable",
               depth=2, jump_kind="transition",
               expect="ICON->EMOJI: category 'Maps'->'Smileys...'")
        vlm_assert("states_emoji_grid_glyphs", "unreachable", RESULTS_DIR,
                   expect="YES", depth=2, jump_kind="none", tag="shape")
        return
    settle("nav")
    cats_after = icon_category_headers()
    # the kit parser keeps the raw entity, so match the substring 'Smileys'
    emoji_header = any("Smileys" in c for c in cats_after)
    ok = icon_default and emoji_header and (cats_before != cats_after)
    record("states_icon_mode_emoji", ok,
           "" if ok else "behavior_wrong: switching icon-mode to EMOJI did not change the "
           f"category header from Maps to Smileys (before={cats_before}, after={cats_after})",
           depth=2, jump_kind="transition",
           expect="category header 'Maps' (ICON) -> contains 'Smileys' (EMOJI)")
    # VLM: the EMOJI grid shows coloured emoji glyphs, distinct from line-icons.
    vlm_assert("states_emoji_grid_glyphs",
               "Below the ICON / TEXT / EMOJI buttons, is there a grid of colourful "
               "emoji glyphs (e.g. faces / coloured pictorial emoji) rather than "
               "monochrome line-drawn icons?",
               RESULTS_DIR, expect="YES", depth=2, jump_kind="transition", tag="shape")


# ══════════════════════════════════════════════════════════════════════════════
# 9. Color swatch selection moves the selected-marker (+2 VLM: preview + ring)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_color_swatch_selection",
                   "states_color_preview_vlm",
                   "states_color_selected_ring_vlm"))
def test_color_swatch_selection():
    fresh_launch()
    if not and_enter_add():
        record("states_color_swatch_selection", False,
               "setup_failed: could not open the Add-activity screen",
               depth=2, jump_kind="transition", expect="selected-marker bounds move to tapped cell")
        vlm_assert("states_color_preview", "unreachable", RESULTS_DIR,
                   expect="YES", depth=2, jump_kind="none", tag="color")
        vlm_assert("states_color_selected_ring", "unreachable", RESULTS_DIR,
                   expect="YES", depth=2, jump_kind="none", tag="shape")
        return
    if not and_enter_color_picker():
        record("states_color_swatch_selection", False,
               "feature_missing: Color field did not expose a swatch grid",
               depth=2, jump_kind="transition", expect="selected-marker bounds move to tapped cell")
        vlm_assert("states_color_preview", "unreachable", RESULTS_DIR,
                   expect="YES", depth=2, jump_kind="none", tag="color")
        vlm_assert("states_color_selected_ring", "unreachable", RESULTS_DIR,
                   expect="YES", depth=2, jump_kind="none", tag="shape")
        return
    marker_before = node_by_id(ui(), "viewColorItemSelected")
    cells = [n for n in ui()
             if (n.get("resource-id") or "").endswith("layoutColorItem")
             and n.get("clickable") == "true"]
    if marker_before is None or len(cells) < 2:
        record("states_color_swatch_selection", False,
               "feature_missing: color grid has no selectable swatches / selected marker",
               depth=2, jump_kind="transition", expect="selected-marker bounds move to tapped cell")
        vlm_assert("states_color_preview", "unreachable", RESULTS_DIR,
                   expect="YES", depth=2, jump_kind="none", tag="color")
        vlm_assert("states_color_selected_ring", "unreachable", RESULTS_DIR,
                   expect="YES", depth=2, jump_kind="none", tag="shape")
        return
    mb = marker_before["_bounds"]
    # pick a cell that does NOT currently contain the marker (a different colour)
    target = next((c for c in cells
                   if not (c["_bounds"][0] <= mb[0] and c["_bounds"][2] >= mb[2])),
                  cells[0])
    safe_tap(target)
    settle("nav")
    marker_after = node_by_id(ui(), "viewColorItemSelected")
    ma = marker_after["_bounds"] if marker_after else None
    ok = ma is not None and ma != mb
    record("states_color_swatch_selection", ok,
           "" if ok else "behavior_wrong: selecting a different colour swatch did not move "
           f"the viewColorItemSelected marker (before={mb}, after={ma})",
           depth=2, jump_kind="transition",
           expect=f"viewColorItemSelected marker bounds move from {mb} to the tapped cell")
    # VLM: the preview tile recoloured, and the picked swatch shows a highlight ring.
    vlm_assert("states_color_preview",
               "Near the top of the screen, is there a coloured preview tile (a solid "
               "coloured square, e.g. red/orange) showing the currently selected activity "
               "colour?",
               RESULTS_DIR, expect="YES", depth=2, jump_kind="transition", tag="color")
    vlm_assert("states_color_selected_ring",
               "In the grid of coloured swatches, does exactly one swatch have a "
               "distinguishing selection indicator (an inner ring / checkmark / border) "
               "marking it as the chosen colour?",
               RESULTS_DIR, expect="YES", depth=2, jump_kind="transition", tag="shape")


# ══════════════════════════════════════════════════════════════════════════════
# 10. FOCUS: the name field is auto-focused on the Add screen (this lane owns focus)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_name_field_autofocus",))
def test_name_field_autofocus():
    fresh_launch()
    if not and_enter_add():
        record("states_name_field_autofocus", False,
               "setup_failed: could not open the Add-activity screen",
               depth=1, jump_kind="value", expect="etChangeRecordTypeName focused=true on entry")
        return
    et = node_by_id(ui(), "etChangeRecordTypeName")
    focused = (et or {}).get("focused")
    ok = focused == "true"
    record("states_name_field_autofocus", ok,
           "" if ok else "behavior_wrong: the name field is not auto-focused on the Add "
           f"screen (focused={focused!r})",
           depth=1, jump_kind="value",
           expect="etChangeRecordTypeName focused=true immediately on opening the Add screen")


# ══════════════════════════════════════════════════════════════════════════════
# 11. FOCUS moves: tapping the Note field flips its focused false->true
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_note_field_focus",))
def test_note_field_focus():
    fresh_launch()
    if not and_enter_add():
        record("states_note_field_focus", False,
               "setup_failed: could not open the Add-activity screen",
               depth=1, jump_kind="transition", expect="Note field focused false->true on tap")
        return
    toggler = node_by_id(ui(), "tvChangeRecordTypeMoreFieldsText")
    if toggler is None or not tap_node(toggler):     # expand to reveal the Note field
        record("states_note_field_focus", False,
               "feature_missing: could not reveal the Note field (no More toggler)",
               depth=1, jump_kind="transition", expect="Note field focused false->true on tap")
        return
    settle("nav")
    note = node_by_id(ui(), "etChangeRecordTypeNote")
    if note is None:
        record("states_note_field_focus", False,
               "feature_missing: Note editor did not appear after expanding More",
               depth=1, jump_kind="transition", expect="Note field focused false->true on tap")
        return
    focus_before = note.get("focused")
    tap_node(note)
    settle("keyboard")
    focus_after = (find_closest_match(ui(), note) or {}).get("focused")
    ok = focus_before == "false" and focus_after == "true"
    hide_keyboard()
    record("states_note_field_focus", ok,
           "" if ok else "behavior_wrong: tapping the Note field did not move focus onto it "
           f"(focused {focus_before!r}->{focus_after!r})",
           depth=1, jump_kind="transition",
           expect="etChangeRecordTypeNote focused false->true after tapping it")


# ══════════════════════════════════════════════════════════════════════════════
# 12. Language spinner dropdown OPENS an options list (depth 1); dismiss w/ back()
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_language_dropdown",))
def test_language_dropdown():
    fresh_launch()
    if not and_enter_settings():
        record("states_language_dropdown", False,
               "setup_failed: Settings tab did not render",
               depth=1, jump_kind="transition", expect="language options list appears on open")
        return
    spinners = [n for n in ui()
                if (n.get("resource-id") or "").endswith("spinnerItemSettings")]
    if len(spinners) < 2:
        record("states_language_dropdown", False,
               "feature_missing: no Language spinner on Settings",
               depth=1, jump_kind="transition", expect="language options list appears on open")
        return
    langs_before = sum(1 for n in ui() if (n.get("text") or "") == "English")
    tap_node(spinners[1])          # the Language spinner (second one)
    settle("nav")
    fresh = ui()
    # a real dropdown surfaces multiple language options at once
    has_english = find_node_ci(fresh, "English") is not None
    has_system = find_node_ci(fresh, "System") is not None
    n_options = sum(1 for n in fresh
                    if (n.get("text") or "") in ("English", "Deutsch", "Español",
                                                 "Français", "Italiano", "System"))
    ok = (langs_before == 0) and has_english and has_system and n_options >= 3
    back()                          # dismiss WITHOUT switching the language
    settle("nav")
    record("states_language_dropdown", ok,
           "" if ok else "behavior_wrong: opening the Language spinner did not surface an "
           f"options list (english_before={langs_before}, english_after={has_english}, "
           f"system_after={has_system}, n_options={n_options})",
           depth=1, jump_kind="transition",
           expect="Language dropdown shows System+English (>=3 options) that were absent before opening")


# ══════════════════════════════════════════════════════════════════════════════
# 13. Running state (canvas) — VLM: bright solid card + 'stop tracking' hint
#     (running is invisible to the dump — see recon note 1)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_running_card_vlm",))
def test_running_card_vlm():
    fresh_launch()
    NAME = "RunProbe"
    # create the activity, then TAP its tile to START a running timer
    add = tile(ui(), "Add")
    if add is None or not tap_node(add):
        vlm_assert("states_running_card", "unreachable", RESULTS_DIR,
                   expect="YES", depth=0, jump_kind="none", tag="color")
        record("states_running_card_vlm", False,
               "setup_failed: could not open the Add screen", depth=0, jump_kind="none")
        return
    settle("nav")
    type_text(node_by_id(ui(), "etChangeRecordTypeName"), NAME)
    hide_keyboard()
    tap_node(node_by_id(ui(), "btnChangeRecordTypeSave"))
    settle("nav")
    started = False
    t = tile(ui(), NAME)
    if t and tap_node(t):
        settle("nav")
        started = True
    if not started:
        vlm_assert("states_running_card",
                   "unreachable — timer did not start", RESULTS_DIR,
                   expect="YES", depth=0, jump_kind="none", tag="color")
        return
    # the running card + its hint are CANVAS-drawn (not in the dump) -> VLM only.
    # The card takes the activity's OWN colour, assigned pseudo-randomly at creation
    # (observed pink on one run, slate-blue on another), so the question must NOT pin a
    # hue. The discriminating, always-true rendered property is a wide SOLID-FILLED bar
    # spanning the full width at the very top, ABOVE the small square tile row, with the
    # stop hint beneath it — a canvas view a dead shell cannot fake.
    vlm_assert("states_running_card",
               "At the very top of the screen, is there a wide rectangular bar with a "
               "solid single-colour fill (NOT white/transparent) that spans almost the "
               "full screen width, positioned ABOVE the row of small square tiles, with "
               "the text 'Click on card to stop tracking' shown directly beneath it?",
               RESULTS_DIR, expect="YES", depth=0, jump_kind="transition", tag="position")
    # STOP the timer so no running record is left behind for later tests.
    rv = node_by_id(ui(), "rvRunningRecordsList")
    if rv:
        s = get_screen_info()
        tap(s["center_x"], rv["_bounds"][1] + 90)
        settle("nav")
        settle("nav")


TESTS = [
    test_multitasking_toggle,
    test_multitasking_persists,
    test_darkmode_enabled,
    test_darkmode_persists,
    test_more_less_toggle,
    test_display_collapse_expand,
    test_icon_mode_text,
    test_icon_mode_emoji,
    test_color_swatch_selection,
    test_name_field_autofocus,
    test_note_field_focus,
    test_language_dropdown,
    test_running_card_vlm,
]

if __name__ == "__main__":
    if not device_online():
        print("Device not online — aborting.")
        sys.exit(1)
    run_suite(TESTS, "states")