File size: 32,711 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
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
#!/usr/bin/env python3
"""INTERACTION lane — EFFECT-BY-CONSEQUENCE on user DATA for TimePlanner.

Owns: CRUD lifecycle, 3+ step sequences, multi-record integrity, DATA
persistence across process death (force_stop_and_relaunch), long-press/context
menus. Every test drives the app to the surface via the real user path, performs
the action, then reads the consequence back out of a FRESH ui() and asserts it
against what was observed on the original.

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

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

require_kit(1)

# The category we create/read back. All are real built-in categories (verified in
# recon: Absent/Shopping/Health/Study/Sleep/Work), so the golden create flow
# (Plan now -> Editor -> Category sheet -> row -> Select -> Save) yields a card
# whose category we read straight out of the Home schedule dump. "Study" never
# accidentally matches an empty schedule.
CAT_A = "Study"
CAT_B = "Health"     # the edit target — a DIFFERENT built-in category
NOTE_TEXT = "kitreadchapter"   # ASCII, no spaces => input-text path is reliable

# Every built-in category name that renders as a task-card icon desc. Used to
# count DISTINCT task cards on the schedule.
_CATEGORY_NAMES = ("Study", "Health", "Shopping", "Sleep", "Work", "Absent")


# ══════════════════════════════════════════════════════════════════════════════
# Trap handling — LeakCanary launcher alias + onboarding permission dialog.
#   * LeakCanary: the .debug build bundles a SECOND launcher activity in the same
#     package; monkey non-deterministically opens leakcanary.internal.activity.
#     LeakActivity, and wait_for_foreground()/is_app_foreground() then LIE (same
#     package). We detect it by the ABSENCE of a Home surface and force-stop +
#     relaunch to shake it off. We never press HOME (that lands on the system
#     launcher, whose TimePlanner ICON also fools the package check).
#   * onboarding: the notification-permission dialog after clear_data(), dismissed
#     at the top of the loop.
# ══════════════════════════════════════════════════════════════════════════════

def dismiss_onboarding(nodes=None):
    """Tap the notification-permission dialog's button if present. Returns True
    if it dismissed one (so the caller re-loops)."""
    nodes = nodes if nodes is not None else ui()
    btn = next((n for n in nodes
                if (n.get("text") or "") in ("Allow", "Don't allow", "Don’t allow")),
               None)
    if btn is None:
        return False
    tap_node(btn)
    return True


def _home_ready(nodes):
    """Home's own surface — the top-bar title, the empty-state prompt, or the
    'Plan now' control. Any means the REAL app (not LeakCanary, not the launcher)
    is on screen."""
    return (find_node_ci(nodes, "Schedule") is not None
            or find_node_ci(nodes, "Plan now") is not None
            or find_node_ci(nodes, "Nothing planned yet") is not None)


def ensure_home(max_tries=20):
    for _ in range(max_tries):
        nodes = ui()
        if dismiss_onboarding(nodes):
            settle("tap")
            continue
        if _home_ready(nodes):
            settle("launch")                 # confirm a mid-launch frame settled
            if _home_ready(ui()):
                return True
            continue
        force_stop(); settle("key")
        launch_app(); settle("launch")
    return _home_ready(ui())


def start_home_clean():
    """Virgin-database entry point: clear data, relaunch, dismiss onboarding,
    settle on the empty Home. Every CRUD/persistence test starts here."""
    clear_data()
    launch_app()
    return ensure_home()


# ══════════════════════════════════════════════════════════════════════════════
# Compose tap helpers — leaves report clickable="false"; tap the clickable
# ancestor whose bounds enclose the label's centre.
# ══════════════════════════════════════════════════════════════════════════════

def _clickable_ancestor(nodes, anchor):
    """Tightest clickable node whose bounds contain `anchor`'s centre."""
    if not anchor or "_center" not in anchor:
        return None
    cx, cy = anchor["_center"]
    cands = [n for n in nodes
             if n.get("clickable") == "true" and "_bounds" in n
             and n["_bounds"][0] <= cx <= n["_bounds"][2]
             and n["_bounds"][1] <= cy <= n["_bounds"][3]]
    cands.sort(key=lambda n: (n["_bounds"][2] - n["_bounds"][0])
               * (n["_bounds"][3] - n["_bounds"][1]))
    return cands[0] if cands else None


def _tap_anchor(nodes, anchor):
    """Tap `anchor`'s clickable ancestor (or the anchor itself, which hits the
    same ancestor by coordinate)."""
    if anchor is None:
        return False
    anc = _clickable_ancestor(nodes, anchor)
    return tap_node(anc) if anc else tap_node(anchor)


def _card_anchor(nodes, cat):
    """The task-card / category leaf for `cat` (icon desc or label text)."""
    return find_node(nodes, content_desc=cat) or find_node(nodes, text=cat)


def _task_card_names(nodes):
    """Distinct category names rendered as task cards on the schedule. Each card
    carries its category as an icon leaf desc=<category> exactly once."""
    return sorted(n.get("content-desc", "") for n in nodes
                  if n.get("content-desc", "") in _CATEGORY_NAMES)


def _count_category(nodes, cat):
    """How many nodes carry `cat` as text or content-desc (>=1 => a card exists)."""
    return sum(1 for n in nodes
              if n.get("content-desc") == cat or n.get("text") == cat)


# ══════════════════════════════════════════════════════════════════════════════
# The core create flow, decomposed so depth is backed by NAMED and_enter_* /
# and_reach_* helpers. Each takes the app one surface deeper and calls and_enter.
# ══════════════════════════════════════════════════════════════════════════════

def and_reach_free_row():
    """Home empty -> tap 'Plan now' (CREATES the day's schedule) -> the free-time
    'Unassigned' row appears. Stays on Home, so counts NO surface."""
    n = find_node_ci(ui(), "Plan now")
    if n is not None:
        tap_node(n)
        settle("tap")
    return find_node_ci(ui(), "Unassigned") or find_node_ci(ui(), "Add a task")


def and_enter_editor():
    """Home -> free/add row -> Editor (title 'Editor', 'Category', 'Save').
    Counts ONE surface. Returns True on success."""
    row = and_reach_free_row()
    if row is None:
        return False
    nodes = ui()
    before = and_showing(nodes)
    if not _tap_anchor(nodes, row):
        return False
    after = and_showing()
    if not and_reach(before, after, "Category", "Schedule"):
        return False
    and_enter("editor")
    return True


def and_enter_editor_via_card(cat):
    """Home (task exists) -> tap the task card for `cat` -> Editor. A RUNNING card
    first expands inline (Add-time/Reduce/Edit); if so, tap its 'Edit' control to
    reach the Editor. Counts ONE surface. Returns True on success."""
    nodes = ui()
    anchor = _card_anchor(nodes, cat)
    if anchor is None:
        return False
    before = and_showing(nodes)
    if not _tap_anchor(nodes, anchor):
        return False
    if find_node_ci(ui(), "Category") is None:      # expanded, not yet in Editor
        edit = find_node(ui(), content_desc="Edit")
        if edit is not None:
            _tap_anchor(ui(), edit)
    after = and_showing()
    if not and_reach(before, after, "Category", "Schedule"):
        return False
    and_enter("editor")
    return True


def and_reach_category_sheet():
    """Editor -> tap the Category card -> Category bottom sheet ('Select' confirm;
    the Editor has 'Save', not 'Select'). Counts ONE surface. True on success."""
    nodes = ui()
    card = _clickable_ancestor(nodes, find_node(nodes, text="Category"))
    if card is None:
        return False
    before = and_showing(nodes)
    if not tap_node(card):
        return False
    after = and_showing()
    if not and_reach(before, after, "Select", "Save"):
        return False
    and_enter("category_sheet")
    return True


def _select_category_in_sheet(cat):
    """From an OPEN category sheet: choose `cat`, confirm with 'Select', then land
    back on the Editor. The sheet opens scrolled to the CURRENTLY selected
    category, so the wanted row may be off screen; rather than scroll the recycler
    (which can overshoot), type `cat` into the sheet's search field to FILTER the
    list down to it. Returns True if it ran the sequence."""
    row = _card_anchor(ui(), cat)
    if row is None:
        # filter via the search field (the sole EditText on the sheet)
        fields = find_by_class(ui(), "EditText")
        if fields:
            type_text(fields[0], cat)
            settle("tap")
        row = _card_anchor(ui(), cat)
    if row is None:
        return False
    # Tapping the row both selects it AND dismisses the search keyboard.
    _tap_anchor(ui(), row)
    settle("tap")
    sel = find_node_ci(ui(), "Select")
    if sel is None or not safe_tap(sel):
        return False
    # Tapping 'Select' DISMISSES the sheet by itself and lands back on the Editor
    # (verified: Save reappears, Select is gone). Do NOT press BACK here — that
    # would pop the Editor and discard the task.
    settle("tap")
    return True


def _pick_category_and_save(cat):
    """From an open Editor: open the Category sheet, choose `cat`, Select, Save.
    Returns True if it ran the full sequence."""
    if not and_reach_category_sheet():
        return False
    if not _select_category_in_sheet(cat):
        return False
    save = find_node_ci(ui(), "Save")
    if save is None or not safe_tap(save):
        return False
    settle("tap")
    return True


# KEYCODE_MOVE_END / KEYCODE_DEL — used only to clear the time-picker hour field
# via the kit's press_key (never a raw `input`).
_KEY_MOVE_END = 123
_KEY_DEL = 67


def _set_end_time_earlier(hour_str="6", ampm="AM"):
    """From an open Editor, shrink the task by moving its End earlier via the
    Material time picker (hour -> `hour_str`, meridiem -> `ampm`). Leaves a real
    free block after the task so a SECOND task can be created. Returns True if the
    Editor's duration text changed (the edit landed)."""
    e = ui()
    end = find_node(e, content_desc="End")
    if end is None:
        return False
    dur_before = [n.get("text") for n in e
                  if (n.get("text") or "").endswith("m") and "h" in (n.get("text") or "")]
    if not _tap_anchor(e, end):
        return False
    settle("tap")
    fields = find_by_class(ui(), "EditText")           # the hour input
    if not fields:
        return False
    hour = fields[0]
    if not tap_node(hour):
        return False
    settle("keyboard")
    press_key(_KEY_MOVE_END)
    for _ in range(3):
        press_key(_KEY_DEL)
    settle("text")
    type_text(hour, hour_str, verify_focus=False)
    m = find_node_ci(ui(), ampm)
    if m is not None:
        _tap_anchor(ui(), m)
        settle("tap")
    ok = find_node_ci(ui(), "OK")
    if ok is None or not safe_tap(ok):
        return False
    settle("tap")
    after = ui()
    dur_after = [n.get("text") for n in after
                 if (n.get("text") or "").endswith("m") and "h" in (n.get("text") or "")]
    return dur_after != dur_before


def _create_task(cat):
    """Full golden create: from empty Home, Plan now -> Editor -> set category
    `cat` -> Save. Leaves the app on Home. Returns True iff the card is present."""
    if not and_enter_editor():
        return False
    if not _pick_category_and_save(cat):
        return False
    settle("tap")
    return _count_category(ui(), cat) >= 1


# ══════════════════════════════════════════════════════════════════════════════
# TESTS
# ══════════════════════════════════════════════════════════════════════════════

# 1) CREATE a task (golden path) + VLM on the rendered card.
@and_test(expects=("interaction_create_task",
                   "interaction_create_task_running_vlm",
                   "interaction_create_task_icon_vlm"))
def test_create_task():
    if not start_home_clean():
        record("interaction_create_task", False,
               "setup_failed: could not reach empty Home",
               depth=2, jump_kind="transition",
               expect=f"a {CAT_A!r} task card appears on the schedule")
        return
    before = ui()
    absent = (_count_category(before, CAT_A) == 0
              and find_node_ci(before, "Nothing planned yet") is not None)
    if not and_enter_editor():
        record("interaction_create_task", False,
               "feature_missing: no create path (Plan now -> free row -> Editor)",
               depth=1, jump_kind="transition",
               expect="Editor opens for a new task")
        return
    ran = _pick_category_and_save(CAT_A)
    settle("tap")
    after = ui()
    present = _count_category(after, CAT_A) >= 1
    ok = absent and ran and present
    record("interaction_create_task", ok,
           "" if ok else
           (f"behavior_wrong: created task did not appear as a {CAT_A!r} card "
            "on the schedule"),
           depth=2, jump_kind="transition",
           expect=f"{CAT_A!r} task card present on Home (was 'Nothing planned yet')")

    # VLM: the default 12:00 AM-11:59 PM task spans NOW, so it renders as a
    # running task highlighted with a distinct tinted background.
    vlm_assert("interaction_create_task_running",
               "There is a task row on the schedule (not the empty 'Nothing planned "
               "yet' state). Is that task row visually highlighted with a distinct "
               "coloured/tinted background different from the plain page background?",
               RESULTS_DIR, expect="YES", depth=2, jump_kind="transition",
               tag="color")
    # VLM: the card carries a coloured category glyph beside the name.
    vlm_assert("interaction_create_task_icon",
               "Does the task row on the schedule show a small coloured category "
               "icon/symbol (a glyph such as a graduation cap) positioned to the "
               "left of the category name text?",
               RESULTS_DIR, expect="YES", depth=2, jump_kind="transition",
               tag="shape")


# 2) CREATE persists across process death (marquee).
@and_test(expects=("interaction_create_persists",))
def test_create_survives_process_death():
    if not start_home_clean():
        record("interaction_create_persists", False,
               "setup_failed: could not reach empty Home",
               depth=2, jump_kind="transition",
               expect=f"{CAT_A!r} task survives process kill")
        return
    absent_before = _count_category(ui(), CAT_A) == 0
    if not _create_task(CAT_A):
        record("interaction_create_persists", False,
               "feature_missing: could not create a task to test persistence",
               depth=2, jump_kind="transition",
               expect=f"{CAT_A!r} task survives process kill")
        return
    # THE probe: kill the process and relaunch. In-memory-only recreations fail.
    force_stop_and_relaunch()
    ensure_home()                      # LeakCanary alias can still intercept
    present_after = _count_category(ui(), CAT_A) >= 1
    ok = absent_before and present_after
    record("interaction_create_persists", ok,
           "" if ok else
           f"behavior_wrong: {CAT_A!r} task did not survive process death",
           depth=2, jump_kind="transition",
           expect=f"{CAT_A!r} task card still on Home after force_stop_and_relaunch")


# 3) EDIT a task: change category Study -> Health, verify the card updated.
@and_test(expects=("interaction_edit_category",
                   "interaction_edit_icon_vlm"))
def test_edit_task_category():
    if not start_home_clean():
        record("interaction_edit_category", False,
               "setup_failed: could not reach empty Home",
               depth=2, jump_kind="transition",
               expect=f"task category updates {CAT_A}->{CAT_B}")
        return
    if not _create_task(CAT_A):
        record("interaction_edit_category", False,
               "feature_missing: could not create the initial task to edit",
               depth=2, jump_kind="transition",
               expect=f"task category updates {CAT_A}->{CAT_B}")
        return
    had_study = _count_category(ui(), CAT_A) >= 1
    if not and_enter_editor_via_card(CAT_A):
        record("interaction_edit_category", False,
               "setup_failed: could not reopen the task in the Editor",
               depth=2, jump_kind="transition",
               expect=f"task category updates {CAT_A}->{CAT_B}")
        return
    changed = _pick_category_and_save(CAT_B)
    settle("tap")
    after = ui()
    now_health = _count_category(after, CAT_B) >= 1
    no_more_study = _count_category(after, CAT_A) == 0
    ok = had_study and changed and now_health and no_more_study
    record("interaction_edit_category", ok,
           "" if ok else
           (f"behavior_wrong: editing {CAT_A}->{CAT_B} did not update the card "
            f"(health={now_health}, study_gone={no_more_study})"),
           depth=2, jump_kind="transition",
           expect=f"schedule shows {CAT_B!r} card and no {CAT_A!r} card")

    # VLM: the icon changed to a health (cross/heart) glyph.
    vlm_assert("interaction_edit_icon",
               "The schedule shows one task row. Does its category icon look like a "
               "health/medical symbol (a cross or heart) rather than an academic "
               "graduation-cap symbol?",
               RESULTS_DIR, expect="YES", depth=2, jump_kind="transition",
               tag="shape")


# 4) Multi-step schedule build: after saving task #1 the list grows to show the
#    task PLUS a new 'Add a task' free-slot add row.
@and_test(expects=("interaction_schedule_grows",
                   "interaction_schedule_grows_vlm"))
def test_schedule_build_grows():
    if not start_home_clean():
        record("interaction_schedule_grows", False,
               "setup_failed: could not reach empty Home",
               depth=2, jump_kind="transition",
               expect="after saving, list shows the task AND a new add row")
        return
    b = ui()
    was_empty = (find_node_ci(b, "Nothing planned yet") is not None
                 and find_node_ci(b, "Add a task") is None)
    if not _create_task(CAT_A):
        record("interaction_schedule_grows", False,
               "feature_missing: could not create the first task",
               depth=2, jump_kind="transition",
               expect="after saving, list shows the task AND a new add row")
        return
    after = ui()
    has_task = _count_category(after, CAT_A) >= 1
    has_add_row = (find_node_ci(after, "Add a task") is not None
                   or find_node_ci(after, "Unassigned") is not None)
    ok = was_empty and has_task and has_add_row
    record("interaction_schedule_grows", ok,
           "" if ok else
           ("behavior_wrong: after saving, expected both the task card and a new "
            "add row on the schedule"),
           depth=2, jump_kind="transition",
           expect=f"schedule shows a {CAT_A!r} card AND an 'Add a task' add row")

    # VLM: timeline shows a task block followed by an add row below it.
    vlm_assert("interaction_schedule_grows",
               "On the schedule/timeline, is there a filled task block near the top "
               "and, directly below it, a separate row containing a plus (+) 'add' "
               "control (i.e. the list has grown to two stacked rows)?",
               RESULTS_DIR, expect="YES", depth=2, jump_kind="transition",
               tag="layout")


# 5) Add a SECOND task -> two distinct task cards on the schedule.
@and_test(expects=("interaction_second_task",
                   "interaction_two_tasks_vlm"))
def test_add_second_task():
    if not start_home_clean():
        record("interaction_second_task", False,
               "setup_failed: could not reach empty Home",
               depth=2, jump_kind="transition",
               expect="two task cards on the schedule")
        return
    # Task #1 must NOT span the whole day, or the only free slot left is a
    # zero-length one (Start==End) whose save REPLACES the first task instead of
    # adding a second. So build task #1 with an earlier End, leaving a real free
    # block for task #2.
    if not and_enter_editor():
        record("interaction_second_task", False,
               "feature_missing: could not open the Editor for the first task",
               depth=2, jump_kind="transition",
               expect="two task cards on the schedule")
        return
    _set_end_time_earlier("6", "AM")            # Study now ~12:00 AM-6:59 AM
    settle("tap")
    if not _pick_category_and_save(CAT_A):
        record("interaction_second_task", False,
               "feature_missing: could not save the first task",
               depth=2, jump_kind="transition",
               expect="two task cards on the schedule")
        return
    one = len(_task_card_names(ui()))
    if not and_enter_editor():                  # opens the Editor on the free slot
        record("interaction_second_task", False,
               "setup_failed: could not open the Editor for the second task",
               depth=2, jump_kind="transition",
               expect="two task cards on the schedule")
        return
    ran = _pick_category_and_save(CAT_B)
    settle("tap")
    after = ui()
    two = len(_task_card_names(after))
    ok = ran and one >= 1 and two >= 2 and two > one
    record("interaction_second_task", ok,
           "" if ok else
           (f"behavior_wrong: expected the schedule to grow to >=2 task cards "
            f"(had {one}, now {two})"),
           depth=2, jump_kind="transition",
           expect=f"task-card count rises from {one} to >=2")

    # VLM: two distinct task blocks, one positioned ABOVE the other on the
    # timeline (a positional property — the second card sits below the first).
    vlm_assert("interaction_two_tasks",
               "There are two separate coloured task blocks on the schedule, each "
               "with its own category name. Is one task block positioned directly "
               "ABOVE the other (they are stacked vertically, not overlapping and "
               "not side by side)?",
               RESULTS_DIR, expect="YES", depth=2, jump_kind="transition",
               tag="position")


# 6) Running-task expand controls: tapping the running card reveals the inline
#    Add-time / Reduce-the-time / Edit controls that were NOT present collapsed.
#    (Note: the 'Increase' desc also sits on the free 'Add a task' add-row even
#    when collapsed, so the discriminating controls are the 'Add time' /
#    'Reduce the time' / 'Edit' descs, which appear only when the card expands.)
@and_test(expects=("interaction_running_expand",
                   "interaction_running_progress_vlm",
                   "interaction_running_controls_vlm"))
def test_running_task_expand():
    if not start_home_clean():
        record("interaction_running_expand", False,
               "setup_failed: could not reach empty Home",
               depth=1, jump_kind="transition",
               expect="running task expands to Add-time/Reduce controls")
        return
    if not _create_task(CAT_A):
        record("interaction_running_expand", False,
               "feature_missing: could not create a running task",
               depth=1, jump_kind="transition",
               expect="running task expands to Add-time/Reduce controls")
        return
    coll = ui()
    controls_before = (find_node(coll, content_desc="Reduce the time") is not None
                       or find_node(coll, content_desc="Add time") is not None
                       or find_node(coll, content_desc="Edit") is not None)
    anchor = _card_anchor(coll, CAT_A)
    tapped = _tap_anchor(coll, anchor) if anchor else False
    and_enter("expanded_card")
    settle("tap")
    exp = ui()
    add_time = find_node(exp, content_desc="Add time") is not None
    reduce_time = find_node(exp, content_desc="Reduce the time") is not None
    ok = tapped and (not controls_before) and add_time and reduce_time
    record("interaction_running_expand", ok,
           "" if ok else
           ("behavior_wrong: tapping the running task did not reveal both the "
            "Add-time and Reduce-the-time controls"),
           depth=1, jump_kind="transition",
           expect="'Add time' and 'Reduce the time' controls appear after tapping "
                  "the running card")

    # VLM: a partially-filled progress bar spans part-way across the row.
    vlm_assert("interaction_running_progress",
               "The highlighted task row shows a horizontal progress indicator. Is "
               "that progress bar filled only PART of the way across (a partial "
               "fill, not empty and not completely full)?",
               RESULTS_DIR, expect="YES", depth=1, jump_kind="none",
               tag="size")
    # VLM: '+ Increase' and '- Reduce' buttons visible side by side.
    vlm_assert("interaction_running_controls",
               "In the expanded task row, are there two labelled buttons shown side "
               "by side, one reading 'Increase' (with a plus) and one reading "
               "'Reduce' (with a minus)?",
               RESULTS_DIR, expect="YES", depth=1, jump_kind="transition",
               tag="layout")


# 7) Cancel does NOT persist: open the free row's Editor, choose a category, then
#    Cancel -> no new categorized task card was created.
@and_test(expects=("interaction_cancel_no_persist",))
def test_cancel_discards():
    if not start_home_clean():
        record("interaction_cancel_no_persist", False,
               "setup_failed: could not reach empty Home",
               depth=2, jump_kind="transition",
               expect="Cancel discards editor; no new categorized task")
        return
    before = ui()
    no_task_before = len(_task_card_names(before)) == 0
    if not and_enter_editor():
        record("interaction_cancel_no_persist", False,
               "feature_missing: could not open the Editor",
               depth=2, jump_kind="transition",
               expect="Cancel discards editor; no new categorized task")
        return
    # choose a category IN the editor, then Cancel -> should discard
    if and_reach_category_sheet():
        _select_category_in_sheet(CAT_A)
    cancel = find_node_ci(ui(), "Cancel")
    cancelled = cancel is not None and safe_tap(cancel)
    settle("tap")
    ensure_home()
    after = ui()
    no_task_after = len(_task_card_names(after)) == 0
    ok = no_task_before and cancelled and no_task_after
    record("interaction_cancel_no_persist", ok,
           "" if ok else
           ("behavior_wrong: Cancel did not discard — a categorized task card "
            "appeared on the schedule"),
           depth=2, jump_kind="transition",
           expect="no categorized task card on Home after Cancel")


# 8) Note text entry round-trips inside the Editor. The Note is a Compose
#    BasicTextField that does NOT expose its content in the accessibility tree,
#    so the observable consequence of a successful entry is the placeholder
#    'Optional' disappearing (shown only while the field is empty). We also read
#    the EditText text back in case a recreation DOES expose it.
@and_test(expects=("interaction_note_roundtrip",))
def test_note_text_roundtrip():
    if not start_home_clean():
        record("interaction_note_roundtrip", False,
               "setup_failed: could not reach empty Home",
               depth=1, jump_kind="transition",
               expect="Note field accepts typed text (placeholder clears)")
        return
    if not and_enter_editor():
        record("interaction_note_roundtrip", False,
               "feature_missing: could not open the Editor",
               depth=1, jump_kind="transition",
               expect="Note field accepts typed text (placeholder clears)")
        return
    e = ui()
    fields = find_by_class(e, "EditText")
    placeholder_before = find_node_ci(e, "Optional") is not None
    if not fields:
        record("interaction_note_roundtrip", False,
               "feature_missing: no Note EditText on the Editor",
               depth=1, jump_kind="transition",
               expect="Note field accepts typed text (placeholder clears)")
        return
    typed = type_text(fields[0], NOTE_TEXT)
    if not typed:
        record("interaction_note_roundtrip", False,
               "setup_failed: could not focus/type into the Note field",
               depth=1, jump_kind="transition",
               expect="Note field accepts typed text (placeholder clears)")
        return
    hide_keyboard()

    def _entered():
        u = ui()
        fresh = find_by_class(u, "EditText")
        got = (fresh[0].get("text") if fresh else "") or ""
        placeholder_gone = find_node_ci(u, "Optional") is None
        return (NOTE_TEXT in got) or placeholder_gone

    if not _entered():
        # custom field may ignore the ascii paste; retry via ADB Keyboard
        type_text(fields[0], NOTE_TEXT, method="ime")
        hide_keyboard()
    entered = _entered()
    ok = placeholder_before and entered
    record("interaction_note_roundtrip", ok,
           "" if ok else
           "behavior_wrong: Note field did not accept typed text "
           "(placeholder did not clear and no text read back)",
           depth=1, jump_kind="transition",
           expect="Note placeholder 'Optional' clears after typing "
                  f"{NOTE_TEXT!r} (data entered)")


# 9) Category bottom sheet: the currently-selected row is highlighted vs others
#    (VLM-only rendered property; the consequence of a selection in the sheet).
@and_test(expects=("interaction_sheet_selected_vlm",))
def test_category_sheet_selection_vlm():
    if not start_home_clean():
        record("interaction_sheet_selected_vlm", False,
               "setup_failed: could not reach empty Home",
               depth=2, jump_kind="none", tag="color")
        return
    if not (and_enter_editor() and and_reach_category_sheet()):
        record("interaction_sheet_selected_vlm", False,
               "setup_failed: could not open the Category sheet",
               depth=2, jump_kind="none", tag="color")
        return
    row = _card_anchor(ui(), CAT_A)          # select 'Study' -> one row selected
    if row is not None:
        _tap_anchor(ui(), row)
        settle("tap")
    vlm_assert("interaction_sheet_selected",
               "This is a category picker list. Is exactly one category row visibly "
               "marked as selected (a filled/checked radio button or a highlighted "
               "background) while the other rows are not?",
               RESULTS_DIR, expect="YES", depth=2, jump_kind="none",
               tag="color")


TESTS = [
    test_create_task,
    test_create_survives_process_death,
    test_edit_task_category,
    test_schedule_build_grows,
    test_add_second_task,
    test_running_task_expand,
    test_cancel_discards,
    test_note_text_roundtrip,
    test_category_sheet_selection_vlm,
]


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