File size: 31,500 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
#!/usr/bin/env python3
"""COMPUTATION lane — CORE FUNCTION input->output for TimePlanner.

Owns jump_kind="value": apply a specific INPUT (Start/End times, a category, a
task count) then assert the SPECIFIC computed OUTPUT string the RUNNING original
produced. Every expected value here was OBSERVED live on the original app, never
derived from source or from arithmetic — the app is the ground truth.

The two computations this planner actually performs:
  * Editor duration = End - Start, formatted "Xh Ym" (recomputed live as the
    Material time picker changes End). Independent of the wall clock, so stable.
  * Analytics category proportion: with a single categorized task the donut/legend
    show that category at "100%" and every other at "0%"; the donut CENTER shows
    the summed total time. Stable for a controlled single-task input.

Wall-clock-dependent values (a running task's ELAPSED time, "today") are NEVER
asserted — only schedule geometry (End-Start) and controlled proportions.

Run:
  python3 test_android_computation.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 for the Analytics proportion. A real built-in
# (verified in recon: Absent/Shopping/Health/Study/Sleep/Work), so the golden
# create flow yields a legend row we can read straight out of the dump. "Study"
# never accidentally matches an empty analytics page.
CAT = "Study"

# 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


# ══════════════════════════════════════════════════════════════════════════════
# Trap handling — copied verbatim from the interaction lane's proven pattern.
#   (A) LeakCanary launcher alias: the .debug build bundles a SECOND launcher
#       activity in the SAME package; monkey LAUNCHER non-deterministically opens
#       it 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.
#   (B) Onboarding: after clear_data() a notification-permission dialog appears
#       ("Allow"/"Don't allow", curly apostrophe); ui() sees it, so dismiss it.
# ══════════════════════════════════════════════════════════════════════════════

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")
            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. Tests that need a KNOWN empty schedule start 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. (Pattern reused from the
# interaction lane; not imported, so this file stands alone.)
# ══════════════════════════════════════════════════════════════════════════════

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)


# ── Reading the computed outputs out of a fresh tree ────────────────────────────

def _duration_text(nodes):
    """The Editor's duration string — the sole TextView shaped like 'Xh Ym'
    (ends in 'm', contains 'h'). Returns "" when none is present."""
    for n in nodes:
        t = (n.get("text") or "").strip()
        if t.endswith("m") and "h" in t:
            return t
    return ""


def _norm(s):
    """Normalise a duration/time string for comparison: collapse whitespace."""
    return " ".join((s or "").split())


def _time_field(nodes, desc):
    """The clock value shown in the Start/End field. The field node carries
    content-desc=`desc` ('Start'/'End'); its value is the 'H:MM AM/PM' TextView
    horizontally closest to that field's centre (Start sits left of End, so a
    nearest-centre match disambiguates the two clock labels even when neither
    centre falls exactly inside the field's reported bounds)."""
    field = find_node(nodes, content_desc=desc)
    if field is None or "_center" not in field:
        return ""
    fcx, fcy = field["_center"]
    clocks = [n for n in nodes
              if "_center" in n
              and (n.get("text") or "").strip().count(":") == 1
              and ("AM" in (n.get("text") or "") or "PM" in (n.get("text") or ""))]
    if not clocks:
        return ""
    # prefer clocks on the same row (|dy| small), then nearest in x
    clocks.sort(key=lambda n: (abs(n["_center"][1] - fcy) > 80,
                               abs(n["_center"][0] - fcx)))
    return (clocks[0].get("text") or "").strip()


def _pct_for_category(nodes, cat):
    """The percentage string on the Analytics legend row for `cat`. The legend
    renders the category name and its '%' value on the SAME row (same y-band), so
    pair `cat`'s TextView with the nearest '%' TextView at the same vertical
    centre. Returns "" when not found."""
    name = None
    for n in nodes:
        if (n.get("text") or "").strip() == cat and "_center" in n:
            name = n
            break
    if name is None:
        return ""
    ny = name["_center"][1]
    best, best_dy = "", 10 ** 9
    for n in nodes:
        t = (n.get("text") or "").strip()
        if t.endswith("%") and "_center" in n:
            dy = abs(n["_center"][1] - ny)
            if dy < best_dy and dy <= 40:      # same row (rows are ~85px apart)
                best, best_dy = t, dy
    return best


def _donut_center_total(nodes):
    """The time total rendered in the donut centre — a 'Xh Ym' TextView. With a
    single full-day task this equals that task's duration. (Dump-readable here, so
    asserted as a rule value, not via the VLM.)"""
    return _duration_text(nodes)


# ══════════════════════════════════════════════════════════════════════════════
# NAMED navigation helpers — these BACK every depth>=1 claim (the depth audit
# looks for an and_enter*/and_reach* call, directly or in a helper a test calls).
# ══════════════════════════════════════════════════════════════════════════════

def and_reach_free_row():
    """Home empty -> tap 'Plan now' (CREATES the day's schedule) -> the free-time
    'Unassigned' add 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_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 and_reach_analytics():
    """Any root -> tap the 'Analytics' bottom tab -> the Analytics screen (the
    'Time'/'Workload' tabs and 'Category stats' appear; the Home schedule leaves).
    Counts ONE surface. Ensures the 'Time' tab is selected so the donut + legend
    are visible. True on success."""
    nodes = ui()
    tab = find_node(nodes, content_desc="Analytics") or find_node(nodes, text="Analytics")
    if tab is None:
        return False
    before = and_showing(nodes)
    if not _tap_anchor(nodes, tab):
        return False
    settle("launch")
    after_nodes = ui()
    after = and_showing(after_nodes)
    reached = (and_reach(before, after, "Category stats")
               or find_node(after_nodes, content_desc="Time") is not None
               or find_node_ci(after_nodes, "Category stats") is not None)
    if not reached:
        return False
    and_enter("analytics")
    # make sure the Time tab (donut + legend) is showing
    t = find_node(ui(), content_desc="Time")
    if t is not None:
        _tap_anchor(ui(), t)
        settle("tap")
    return True


def _open_end_picker():
    """From an open Editor, open the End time picker. Returns the hour EditText
    node (the sole EditText in the Material 'Enter time' dialog), or None."""
    e = ui()
    end = find_node(e, content_desc="End")
    if end is None:
        return None
    if not _tap_anchor(e, end):
        return None
    settle("tap")
    fields = find_by_class(ui(), "EditText")
    return fields[0] if fields else None


def _set_end_hour(hour_str, ampm="AM"):
    """From an open Editor, set End's hour to `hour_str` at `ampm` via the Material
    time picker (keyboard-entry mode). Leaves the original minute (:59) untouched,
    matching the proven mechanic. Returns True if the picker was driven to OK."""
    hour = _open_end_picker()
    if hour is None:
        return False
    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")
    return True


def _select_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
    row = find_node(ui(), content_desc=cat) or find_node(ui(), text=cat)
    if row is None:
        fields = find_by_class(ui(), "EditText")     # filter via the search field
        if fields:
            type_text(fields[0], cat)
            settle("tap")
        row = find_node(ui(), content_desc=cat) or find_node(ui(), text=cat)
    if row is None:
        return False
    _tap_anchor(ui(), row)
    settle("tap")
    sel = find_node_ci(ui(), "Select")
    if sel is None or not safe_tap(sel):
        return False
    settle("tap")
    save = find_node_ci(ui(), "Save")
    if save is None or not safe_tap(save):
        return False
    settle("tap")
    return True


def _create_fullday_task(cat):
    """Golden create with DEFAULT times (12:00 AM -> 11:59 PM => full day): empty
    Home -> Plan now -> Editor -> set category `cat` -> Save. Leaves the app on
    Home with one full-day categorized task. Returns True on success."""
    if not and_enter_editor():
        return False
    return _select_category_and_save(cat)


# ══════════════════════════════════════════════════════════════════════════════
# TESTS — every assertion jump_kind="value" with an exact observed `expect`.
# ══════════════════════════════════════════════════════════════════════════════

# 1) Default duration: a fresh day's free slot spans 12:00 AM -> 11:59 PM, and the
#    Editor computes the duration "23h 59m".
@and_test(expects=("computation_default_duration",
                   "computation_duration_layout_vlm"))
def test_default_duration():
    if not start_home_clean():
        record("computation_default_duration", False,
               "setup_failed: could not reach empty Home",
               depth=2, jump_kind="value", expect="duration '23h 59m'")
        vlm_assert("computation_duration_layout",
                   "In this task editor, is there a duration label of the form "
                   "'<number>h <number>m' displayed on the same horizontal row as, "
                   "and to the right of, the Start and End time fields?",
                   RESULTS_DIR, expect="YES", depth=2, jump_kind="none",
                   tag="position")
        return
    if not and_enter_editor():
        record("computation_default_duration", False,
               "feature_missing: no create path (Plan now -> free row -> Editor)",
               depth=2, jump_kind="value", expect="duration '23h 59m'")
        vlm_assert("computation_duration_layout",
                   "In this task editor, is there a duration label of the form "
                   "'<number>h <number>m' displayed on the same horizontal row as, "
                   "and to the right of, the Start and End time fields?",
                   RESULTS_DIR, expect="YES", depth=2, jump_kind="none",
                   tag="position")
        return
    got = _duration_text(ui())
    ok = _norm(got) == "23h 59m"
    record("computation_default_duration", ok,
           "" if ok else f"behavior_wrong: duration shows {got!r}, expected '23h 59m'",
           depth=2, jump_kind="value", expect="duration '23h 59m'")

    # VLM: the duration is RENDERED as text positioned beside the time fields (a
    # layout property the tree confirms but this checks visually as rendered).
    vlm_assert("computation_duration_layout",
               "In this task editor, is there a duration label of the form "
               "'<number>h <number>m' displayed on the same horizontal row as, and "
               "to the right of, the Start and End time fields?",
               RESULTS_DIR, expect="YES", depth=2, jump_kind="none",
               tag="position")


# 2) Duration recompute: setting End -> 6:00 AM makes End read "6:59 AM" (minute
#    preserved) and the duration recompute to "6h 59m" (12:00 AM -> 6:59 AM). One
#    record asserts BOTH computed outputs.
@and_test(expects=("computation_end_6am",))
def test_end_6am_duration():
    if not start_home_clean():
        record("computation_end_6am", False,
               "setup_failed: could not reach empty Home",
               depth=2, jump_kind="value",
               expect="End '6:59 AM' and duration '6h 59m'")
        return
    if not and_enter_editor():
        record("computation_end_6am", False,
               "feature_missing: could not open the Editor",
               depth=2, jump_kind="value",
               expect="End '6:59 AM' and duration '6h 59m'")
        return
    if not _set_end_hour("6", "AM"):
        record("computation_end_6am", False,
               "setup_failed: could not drive the End time picker to 6 AM",
               depth=2, jump_kind="value",
               expect="End '6:59 AM' and duration '6h 59m'")
        return
    after = ui()
    dur = _norm(_duration_text(after))
    end = _norm(_time_field(after, "End"))
    ok = dur == "6h 59m" and end == "6:59 AM"
    record("computation_end_6am", ok,
           "" if ok else
           (f"behavior_wrong: after End->6 AM got End={end!r} duration={dur!r}, "
            "expected End '6:59 AM' duration '6h 59m'"),
           depth=2, jump_kind="value",
           expect="End '6:59 AM' and duration '6h 59m'")


# 3) Second distinct input: End -> 3:00 AM => End "3:59 AM", duration "3h 59m".
#    A different operand proves the duration is COMPUTED, not a fixed string.
@and_test(expects=("computation_end_3am",))
def test_end_3am_duration():
    if not start_home_clean():
        record("computation_end_3am", False,
               "setup_failed: could not reach empty Home",
               depth=2, jump_kind="value",
               expect="End '3:59 AM' and duration '3h 59m'")
        return
    if not and_enter_editor():
        record("computation_end_3am", False,
               "feature_missing: could not open the Editor",
               depth=2, jump_kind="value",
               expect="End '3:59 AM' and duration '3h 59m'")
        return
    if not _set_end_hour("3", "AM"):
        record("computation_end_3am", False,
               "setup_failed: could not drive the End time picker to 3 AM",
               depth=2, jump_kind="value",
               expect="End '3:59 AM' and duration '3h 59m'")
        return
    after = ui()
    dur = _norm(_duration_text(after))
    end = _norm(_time_field(after, "End"))
    ok = dur == "3h 59m" and end == "3:59 AM"
    record("computation_end_3am", ok,
           "" if ok else
           (f"behavior_wrong: after End->3 AM got End={end!r} duration={dur!r}, "
            "expected End '3:59 AM' duration '3h 59m'"),
           depth=2, jump_kind="value",
           expect="End '3:59 AM' and duration '3h 59m'")


# 4) Differential: capture the duration at the default End, change End to 6 AM,
#    assert the duration is NOW "6h 59m" AND DIFFERENT from the "23h 59m" before —
#    proves the value tracks the input rather than being static.
@and_test(expects=("computation_duration_differential",
                   "computation_duration_shrinks_vlm"))
def test_duration_differential():
    if not start_home_clean():
        record("computation_duration_differential", False,
               "setup_failed: could not reach empty Home",
               depth=2, jump_kind="value",
               expect="duration goes 23h 59m -> 6h 59m")
        vlm_assert("computation_duration_shrinks",
                   "Does this task editor show a duration label of the form "
                   "'<number>h <number>m' next to the Start/End time fields?",
                   RESULTS_DIR, expect="YES", depth=2, jump_kind="none",
                   tag="content")
        return
    if not and_enter_editor():
        record("computation_duration_differential", False,
               "feature_missing: could not open the Editor",
               depth=2, jump_kind="value",
               expect="duration goes 23h 59m -> 6h 59m")
        vlm_assert("computation_duration_shrinks",
                   "Does this task editor show a duration label of the form "
                   "'<number>h <number>m' next to the Start/End time fields?",
                   RESULTS_DIR, expect="YES", depth=2, jump_kind="none",
                   tag="content")
        return
    before = _norm(_duration_text(ui()))
    changed = _set_end_hour("6", "AM")
    after = _norm(_duration_text(ui()))
    ok = (before == "23h 59m" and changed and after == "6h 59m" and after != before)
    record("computation_duration_differential", ok,
           "" if ok else
           (f"behavior_wrong: expected duration 23h 59m -> 6h 59m, "
            f"got {before!r} -> {after!r}"),
           depth=2, jump_kind="value",
           expect="duration goes 23h 59m -> 6h 59m")

    # VLM: the duration text is rendered smaller after shrinking End (a rendered
    # value now visible in the editor). Verifies the recomputed label draws.
    vlm_assert("computation_duration_shrinks",
               "Does this task editor show a duration label of the form "
               "'<number>h <number>m' next to the Start/End time fields?",
               RESULTS_DIR, expect="YES", depth=2, jump_kind="none",
               tag="content")


# 5) Analytics proportion: with exactly ONE full-day Study task, the Category
#    stats legend shows "Study" = "100%".
@and_test(expects=("computation_analytics_study_pct",
                   "computation_donut_full_vlm",
                   "computation_legend_layout_vlm"))
def test_analytics_study_percent():
    if not start_home_clean():
        record("computation_analytics_study_pct", False,
               "setup_failed: could not reach empty Home",
               depth=1, jump_kind="value", expect="Study 100%")
        _analytics_vlms_fail()
        return
    if not _create_fullday_task(CAT):
        record("computation_analytics_study_pct", False,
               f"feature_missing: could not create a full-day {CAT!r} task",
               depth=1, jump_kind="value", expect="Study 100%")
        _analytics_vlms_fail()
        return
    if not and_reach_analytics():
        record("computation_analytics_study_pct", False,
               "setup_failed: could not reach the Analytics Time tab",
               depth=1, jump_kind="value", expect="Study 100%")
        _analytics_vlms_fail()
        return
    a = ui()
    pct = _norm(_pct_for_category(a, CAT))
    ok = pct == "100%"
    record("computation_analytics_study_pct", ok,
           "" if ok else
           f"behavior_wrong: {CAT!r} legend shows {pct!r}, expected '100%'",
           depth=1, jump_kind="value", expect="Study 100%")

    # VLM: the donut is a single filled ring (one 100% category fills it entirely).
    vlm_assert("computation_donut_full",
               "There is a ring/doughnut chart. Is the MAJORITY of the ring taken up "
               "by a single large arc of one dominant colour (one segment covering "
               "most of the circle), rather than the ring being divided into several "
               "roughly equal wedges?",
               RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="shape")
    # VLM: the legend renders one row with a filled value and the rest at zero,
    # each with a coloured dot marker.
    vlm_assert("computation_legend_layout",
               "Below the ring chart is a legend of category rows, each with a "
               "small coloured dot to the left of its name. Is exactly ONE row "
               "showing a non-zero percentage while the other rows show 0%?",
               RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="layout")


def _analytics_vlms_fail():
    """Emit the two Analytics VLM records as failures on a setup abort, keeping the
    denominator fixed."""
    vlm_assert("computation_donut_full",
               "There is a ring/doughnut chart. Is the MAJORITY of the ring taken up "
               "by a single large arc of one dominant colour (one segment covering "
               "most of the circle), rather than the ring being divided into several "
               "roughly equal wedges?",
               RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="shape")
    vlm_assert("computation_legend_layout",
               "Below the ring chart is a legend of category rows, each with a "
               "small coloured dot to the left of its name. Is exactly ONE row "
               "showing a non-zero percentage while the other rows show 0%?",
               RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="layout")


# 6) Analytics complement: the OTHER categories all read "0%" (the proportion is
#    exclusive — a genuine computed distribution, not just a lone label).
@and_test(expects=("computation_analytics_others_zero",))
def test_analytics_others_zero():
    if not start_home_clean():
        record("computation_analytics_others_zero", False,
               "setup_failed: could not reach empty Home",
               depth=1, jump_kind="value", expect="every other category 0%")
        return
    if not _create_fullday_task(CAT):
        record("computation_analytics_others_zero", False,
               f"feature_missing: could not create a full-day {CAT!r} task",
               depth=1, jump_kind="value", expect="every other category 0%")
        return
    if not and_reach_analytics():
        record("computation_analytics_others_zero", False,
               "setup_failed: could not reach the Analytics Time tab",
               depth=1, jump_kind="value", expect="every other category 0%")
        return
    a = ui()
    pcts = [( (n.get("text") or "").strip()) for n in a
            if (n.get("text") or "").strip().endswith("%")]
    hundred = pcts.count("100%")
    zeros = pcts.count("0%")
    # exactly one 100% row and at least one 0% row, and no other non-zero value
    others_nonzero = [p for p in pcts if p not in ("0%", "100%")]
    ok = hundred == 1 and zeros >= 1 and not others_nonzero
    record("computation_analytics_others_zero", ok,
           "" if ok else
           (f"behavior_wrong: legend percentages were {sorted(set(pcts))}, expected "
            "exactly one '100%' and the rest '0%'"),
           depth=1, jump_kind="value",
           expect="one 100% row, every other category 0%")


# 7) Analytics donut centre total: with the single full-day task the ring centre
#    shows the summed time "23h 59m" (dump-readable here => a rule value test).
@and_test(expects=("computation_donut_center_total",
                   "computation_workload_bars_vlm"))
def test_donut_center_total():
    if not start_home_clean():
        record("computation_donut_center_total", False,
               "setup_failed: could not reach empty Home",
               depth=1, jump_kind="value", expect="donut centre '23h 59m'")
        _workload_vlm_fail()
        return
    if not _create_fullday_task(CAT):
        record("computation_donut_center_total", False,
               f"feature_missing: could not create a full-day {CAT!r} task",
               depth=1, jump_kind="value", expect="donut centre '23h 59m'")
        _workload_vlm_fail()
        return
    if not and_reach_analytics():
        record("computation_donut_center_total", False,
               "setup_failed: could not reach the Analytics Time tab",
               depth=1, jump_kind="value", expect="donut centre '23h 59m'")
        _workload_vlm_fail()
        return
    a = ui()
    total = _norm(_donut_center_total(a))
    ok = total == "23h 59m"
    record("computation_donut_center_total", ok,
           "" if ok else
           f"behavior_wrong: donut centre total shows {total!r}, expected '23h 59m'",
           depth=1, jump_kind="value", expect="donut centre '23h 59m'")

    # VLM: switch to the Workload tab and confirm it renders a bar chart (bars of
    # differing heights) — a genuinely non-dump-readable graphical property.
    w = find_node(ui(), content_desc="Workload")
    if w is not None:
        _tap_anchor(ui(), w)
        settle("tap")
    vlm_assert("computation_workload_bars",
               "In the 'Workload stats' bar chart, is there a single tall coloured "
               "vertical bar that rises well above the chart baseline, while the "
               "other x-axis positions have no visible bar?",
               RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="shape")


def _workload_vlm_fail():
    vlm_assert("computation_workload_bars",
               "In the 'Workload stats' bar chart, is there a single tall coloured "
               "vertical bar that rises well above the chart baseline, while the "
               "other x-axis positions have no visible bar?",
               RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="shape")


# 8) Analytics category-dot colour: the legend rows each carry a distinct coloured
#    dot marker (a rendered colour property the tree cannot express).
@and_test(expects=("computation_legend_dots_vlm",))
def test_legend_dots_vlm():
    if not start_home_clean():
        record("computation_legend_dots_vlm", False,
               "setup_failed: could not reach empty Home",
               depth=1, jump_kind="none", tag="color")
        return
    if not (_create_fullday_task(CAT) and and_reach_analytics()):
        record("computation_legend_dots_vlm", False,
               "setup_failed: could not reach the Analytics Time tab",
               depth=1, jump_kind="none", tag="color")
        return
    vlm_assert("computation_legend_dots",
               "In the category legend under the ring chart, does each category "
               "name have a small round COLOURED dot marker beside it (the dots are "
               "coloured, not grey/black bullets)?",
               RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="color")


TESTS = [
    test_default_duration,
    test_end_6am_duration,
    test_end_3am_duration,
    test_duration_differential,
    test_analytics_study_percent,
    test_analytics_others_zero,
    test_donut_center_total,
    test_legend_dots_vlm,
]


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