File size: 36,412 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
#!/usr/bin/env python3
"""COMPUTATION lane — Simple Time Tracker.

INPUT -> OUTPUT: this lane owns jump_kind="value". The app's core transform is the
manual add-record / edit-record screen, where the preview card's DURATION is
recomputed from the Start/End time-adjust chips (-30 -5 -1 +1 +5 +30). That preview
duration `tvRecordItemDuration` is DUMP-READABLE (unlike the running-timer card,
which is canvas-only). A second derived surface is the Statistics tab: with exactly
one record, the sole activity's percent is "100%" and the "Total tracked" duration
equals that record's duration.

GROUND TRUTH established live on the running original (v1.58 debug):
  - Records tab exposes btnRecordsContainerAdd only once a record EXISTS (empty
    Records reports the Timers page — a ViewPager quirk). So every test seeds one
    real start->stop record first, then opens manual-add / edit.
  - The time-adjust chips repeat TWICE: the FIRST row (LOWER y) is Start, the
    SECOND row (HIGHER y) is End. Verified:
      * End +5  -> +5 min      (0m->5m->10m)
      * End +30 -> +30 min
      * End -5  -> -5 min ;  End -30 -> -30 min   (only when there is headroom)
      * Start +5 -> -5 min (moves start later, interval SHRINKS)
      * Start -5 -> +5 min ;  Start -30 -> +30 min
      * combos compose (End+30 twice -> +60, "1h 0m"->"2h 0m")
  - *** The duration CLAMPS at 0 *** and the manual-add INITIAL duration is
    NON-DETERMINISTIC (observed both "0m" and "1h 0m" on fresh opens). So NO test
    asserts an absolute start value; every value test reads the BEFORE duration,
    applies chips, reads the AFTER duration, parses both to minutes and asserts the
    signed DELTA. Any test that DECREASES the duration first raises it with End +30
    (`prep`) so the change has room to move (a decrease from 0m would be swallowed
    by the clamp — a real, observed behaviour, not a test bug).
  - Manual-add SAVE (no activity chosen) persists an "Untracked" row whose
    tvRecordItemDuration equals the value that was set (End+5x2 -> "10m" row).
  - Edit a record row: same screen pre-filled; End+5 turns the preview 0m->5m and,
    after Save, the row itself 0m->5m.
  - Statistics (one record of "Stat1"): tvStatisticsItemPercent="100%",
    tvStatisticsItemDuration matches the record, plus a "Total tracked" row whose
    duration equals it. TWO records edited to ~30m each split the pie ~51%/49% into
    two differently-coloured donut halves.

DUMPS ARE SLOW on this emulator, so every test minimises ui() calls, opens its OWN
entry point (clear_data + launch), seeds its own data inline, and any test that
starts a timer stops it. Nothing depends on a previous test's leftovers.
"""
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="computation", package=PACKAGE, results_dir=RESULTS_DIR)


# ── local recipes (from recon; 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 goto_tab(desc):
    t = tab_trigger(ui(), desc)
    if t:
        tap_node(t)
        settle("nav")
        settle("nav")
    return ui()


def open_fresh():
    """Clean ENTRY POINT: a virgin DB + a fresh launch. Only setup — every value
    below is driven by a real in-app tap and read from a fresh dump."""
    clear_data()
    launch_app()
    wait_for_foreground()
    settle("launch")
    return ui()


def create_activity(name):
    """From the Timers tab: Add tile -> type name -> SAVE. Leaves you on Timers."""
    tap_node(tile(ui(), "Add"))
    settle("nav")
    type_text(node_by_id(ui(), "etChangeRecordTypeName"), name)
    hide_keyboard()
    tap_node(node_by_id(ui(), "btnChangeRecordTypeSave"))
    settle("nav")
    return ui()


def start_timer(name):
    t = tile(ui(), name)
    if not t:
        return False
    tap_node(t)
    settle("nav")
    return True


def stop_timer():
    """Tap the CANVAS running card at the top of rvRunningRecordsList to STOP."""
    rv = node_by_id(ui(), "rvRunningRecordsList")
    if not rv:
        return False
    s = get_screen_info()
    tap(s["center_x"], rv["_bounds"][1] + 90)
    settle("nav")
    settle("nav")
    return True


def seed_record(name):
    """Create `name`, then start+stop once so a completed record exists AND the
    Records tab's tree materialises."""
    create_activity(name)
    if not start_timer(name):
        return False
    return stop_timer()


def duration_text(nodes=None):
    """The preview / row duration string, e.g. '3m', '1h 5m', '2h 0m'."""
    nodes = ui() if nodes is None else nodes
    return next((n.get("text") for n in nodes
                 if (n.get("resource-id") or "").endswith("tvRecordItemDuration")), None)


def dur_to_min(s):
    """Parse 'Xh Ym' / 'Xh' / 'Xh 0m' / 'Ym' / '45m' (stray whitespace ok) into
    integer minutes. Returns None if nothing parseable."""
    if not s:
        return None
    s = s.strip().lower()
    total = 0
    seen = False
    h = re.search(r"(\d+)\s*h", s)
    if h:
        total += int(h.group(1)) * 60
        seen = True
    m = re.search(r"(\d+)\s*m", s)
    if m:
        total += int(m.group(1))
        seen = True
    if not seen:                      # bare number (rare) -> minutes
        b = re.search(r"(\d+)", s)
        if b:
            return int(b.group(1))
        return None
    return total


def _chip(txt, which):
    """Return the Start (which='start', FIRST/lower-y row) or End (which='end',
    SECOND/higher-y row) time-adjust chip with the given label, from a FRESH dump."""
    xs = sorted([n for n in ui()
                 if n.get("text") == txt
                 and (n.get("resource-id") or "").endswith("tvTimeAdjustmentItem")],
                key=lambda z: z["_bounds"][1])
    if len(xs) < 2:
        return None
    return xs[0] if which == "start" else xs[-1]


def tap_chip(txt, which):
    c = _chip(txt, which)
    if not c:
        return False
    tap_node(c)
    settle("nav")
    return True


def record_row_by_name(name):
    """The clickable viewRecordItem row whose enclosed tvRecordItemName == name."""
    nodes = ui()
    nm = next((n for n in nodes
               if (n.get("resource-id") or "").endswith("tvRecordItemName")
               and n.get("text") == name), None)
    if not nm:
        return None
    nb = nm["_bounds"]
    for n in nodes:
        if (n.get("resource-id") or "").endswith("viewRecordItem"):
            b = n["_bounds"]
            if b[1] <= nb[1] and b[3] >= nb[3]:
                return n
    return None


# ── depth-backing entry points (NAME backs the depth claim) ────────────────────
def and_reach_records():
    """Timers -> Records tab; confirm the jump via the Records-only anchor
    btnRecordsContainerAdd. Records' tree exists only after a record does."""
    t = tab_trigger(ui(), "Records")
    if not t:
        return False
    tap_node(t)
    settle("nav")
    settle("nav")
    and_enter("records")
    return node_by_id(ui(), "btnRecordsContainerAdd") is not None


def and_enter_manual_add_record():
    """Records tab -> manual add-record screen via btnRecordsContainerAdd. NAME
    backs the depth; confirms the preview duration + Save landed on the new
    surface. Returns the BEFORE duration string, or None if unreachable."""
    add = node_by_id(ui(), "btnRecordsContainerAdd")
    if not add or not tap_node(add):
        return None
    settle("nav")
    and_enter("manual_add_record")
    if node_by_id(ui(), "btnChangeRecordSave") is None:
        return None
    return duration_text()


def and_enter_edit_record(name=None):
    """Records tab -> record-edit screen. If `name` is given, open THAT record's row;
    otherwise the first viewRecordItem. NAME backs the depth; confirms Save landed.
    Returns the BEFORE preview duration, or None if unreachable."""
    row = record_row_by_name(name) if name else node_by_id(ui(), "viewRecordItem")
    if not row or not tap_node(row):
        return None
    settle("nav")
    and_enter("edit_record")
    if node_by_id(ui(), "btnChangeRecordSave") is None:
        return None
    return duration_text()


def bump_record_end30(name):
    """From the Records tab: open `name`'s row, apply End +30, Save. Returns True on
    success. Used to give a record a non-trivial, comparable duration."""
    if not and_reach_records():
        return False
    if and_enter_edit_record(name) is None:
        return False
    if not tap_chip("+30", "end"):
        return False
    save = node_by_id(ui(), "btnChangeRecordSave")
    if not save or not tap_node(save):
        return False
    settle("nav")
    settle("nav")
    return True


def _delta_via_chips(chips, prep=None):
    """Shared driver: seed a record, open manual-add, optionally apply `prep` chips
    FIRST (to build headroom — the app CLAMPS duration at 0, so a decrease from a
    non-deterministic '0m' start would be swallowed), read the BEFORE duration, then
    apply `chips` in order and read AFTER. Returns
    (ok_setup, before_str, after_str, before_min, after_min). ok_setup is False if
    setup was unreachable, None if a feature/chip was missing, True on success."""
    prep = prep or []
    if not seed_record("Kc" + str(abs(hash(tuple(chips) + tuple(prep))) % 9999)):
        return (False, None, None, None, None)
    if not and_reach_records():
        return (False, None, None, None, None)
    if and_enter_manual_add_record() is None:
        return (None, None, None, None, None)   # feature_missing sentinel
    # Build headroom BEFORE measuring the baseline, so a decrease has room to move.
    for (label, which) in prep:
        if not tap_chip(label, which):
            return (None, None, None, None, None)
    before = duration_text()
    bmin = dur_to_min(before)
    for (label, which) in chips:
        if not tap_chip(label, which):
            return (None, before, None, bmin, None)
    after = duration_text()
    return (True, before, after, bmin, dur_to_min(after))


def _assert_delta(name, chips, expected_delta, expect_desc, prep=None):
    """Author a value test that applies `chips` on the manual-add screen (after an
    optional `prep` to build headroom) and asserts after_min - before_min ==
    expected_delta (a parsed minute delta measured from the post-prep baseline)."""
    ok_setup, before, after, bmin, amin = _delta_via_chips(chips, prep=prep)
    if ok_setup is False:
        record(name, False,
               "setup_failed: could not seed a record / reach the Records add screen",
               depth=1, jump_kind="value", expect=expect_desc)
        return
    if ok_setup is None:
        record(name, False,
               "feature_missing: manual add-record screen or a required time chip "
               "was not present",
               depth=1, jump_kind="value", expect=expect_desc)
        return
    if bmin is None or amin is None:
        record(name, False,
               f"behavior_wrong: could not parse duration (before={before!r}, "
               f"after={after!r})",
               depth=1, jump_kind="value", expect=expect_desc)
        return
    delta = amin - bmin
    ok = delta == expected_delta
    record(name, ok,
           "" if ok else f"behavior_wrong: duration delta was {delta:+d} min "
           f"(before={before!r}->{bmin}, after={after!r}->{amin}), expected "
           f"{expected_delta:+d}",
           depth=1, jump_kind="value",
           expect=f"{expect_desc} (before={before!r}/{bmin}m -> after={after!r}/"
                  f"{amin}m, delta={expected_delta:+d}m)")


# ══════════════════════════════════════════════════════════════════════════════
# 1. End +5 once -> +5 min
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_end_plus5",))
def test_end_plus5():
    open_fresh()
    _assert_delta("computation_end_plus5", [("+5", "end")], +5,
                  "End +5 raises the preview duration by 5 minutes")


# ══════════════════════════════════════════════════════════════════════════════
# 2. End +5 twice -> +10 min
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_end_plus5_twice",))
def test_end_plus5_twice():
    open_fresh()
    _assert_delta("computation_end_plus5_twice", [("+5", "end"), ("+5", "end")], +10,
                  "End +5 applied twice raises the duration by 10 minutes")


# ══════════════════════════════════════════════════════════════════════════════
# 3. End +30 -> +30 min
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_end_plus30",))
def test_end_plus30():
    open_fresh()
    _assert_delta("computation_end_plus30", [("+30", "end")], +30,
                  "End +30 raises the duration by 30 minutes")


# ══════════════════════════════════════════════════════════════════════════════
# 4. End -5 -> -5 min  (after raising with End +30 for headroom; app clamps at 0)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_end_minus5",))
def test_end_minus5():
    open_fresh()
    _assert_delta("computation_end_minus5", [("-5", "end")], -5,
                  "End -5 lowers the duration by 5 minutes",
                  prep=[("+30", "end")])


# ══════════════════════════════════════════════════════════════════════════════
# 5. End -30 -> -30 min  (headroom = End +30 twice)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_end_minus30",))
def test_end_minus30():
    open_fresh()
    _assert_delta("computation_end_minus30", [("-30", "end")], -30,
                  "End -30 lowers the duration by 30 minutes",
                  prep=[("+30", "end"), ("+30", "end")])


# ══════════════════════════════════════════════════════════════════════════════
# 6. Start +5 -> -5 min  (moving Start later SHRINKS the interval; headroom needed)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_start_plus5_shrinks",))
def test_start_plus5():
    open_fresh()
    _assert_delta("computation_start_plus5_shrinks", [("+5", "start")], -5,
                  "Start +5 moves the start later so the duration DROPS by 5 minutes",
                  prep=[("+30", "end")])


# ══════════════════════════════════════════════════════════════════════════════
# 7. Start -5 -> +5 min  (moving Start earlier LENGTHENS the interval)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_start_minus5_grows",))
def test_start_minus5():
    open_fresh()
    _assert_delta("computation_start_minus5_grows", [("-5", "start")], +5,
                  "Start -5 moves the start earlier so the duration GROWS by 5 minutes")


# ══════════════════════════════════════════════════════════════════════════════
# 8. Start -30 -> +30 min
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_start_minus30_grows",))
def test_start_minus30():
    open_fresh()
    _assert_delta("computation_start_minus30_grows", [("-30", "start")], +30,
                  "Start -30 grows the duration by 30 minutes")


# ══════════════════════════════════════════════════════════════════════════════
# 9. Combo: End +30 then End -5 -> +25 min  (chips compose)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_combo_end_plus30_minus5",))
def test_combo_end_plus30_minus5():
    open_fresh()
    _assert_delta("computation_combo_end_plus30_minus5",
                  [("+30", "end"), ("-5", "end")], +25,
                  "End +30 then End -5 composes to a +25 minute net change")


# ══════════════════════════════════════════════════════════════════════════════
# 10. Combo: End +5 then Start +5 -> 0 net  (equal & opposite -> unchanged)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_combo_net_zero",))
def test_combo_net_zero():
    open_fresh()
    _assert_delta("computation_combo_net_zero",
                  [("+5", "end"), ("+5", "start")], 0,
                  "End +5 then Start +5 cancel to a net 0 minute change")


# ══════════════════════════════════════════════════════════════════════════════
# 11. Combo: End +30 twice -> +60 min  (crosses into the 'Xh Ym' hour formatting)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_combo_plus60_hour_format",))
def test_combo_plus60():
    open_fresh()
    ok_setup, before, after, bmin, amin = _delta_via_chips(
        [("+30", "end"), ("+30", "end")])
    exp = "End +30 twice adds 60 minutes and the duration crosses into 'Xh' format"
    if ok_setup is False:
        record("computation_combo_plus60_hour_format", False,
               "setup_failed: could not seed a record / reach the Records add screen",
               depth=1, jump_kind="value", expect=exp)
        return
    if ok_setup is None:
        record("computation_combo_plus60_hour_format", False,
               "feature_missing: manual add-record screen or End +30 chip missing",
               depth=1, jump_kind="value", expect=exp)
        return
    if bmin is None or amin is None:
        record("computation_combo_plus60_hour_format", False,
               f"behavior_wrong: unparseable duration (before={before!r}, after={after!r})",
               depth=1, jump_kind="value", expect=exp)
        return
    delta_ok = (amin - bmin) == 60
    # after MUST render an hour component ('h'): +60 min from a non-negative base
    # always tips the total to >= 1h.
    hour_ok = "h" in (after or "").lower()
    ok = delta_ok and hour_ok
    record("computation_combo_plus60_hour_format", ok,
           "" if ok else f"behavior_wrong: +60 combo gave delta {amin - bmin:+d} min "
           f"(before={before!r}->{bmin}, after={after!r}->{amin}), hour_format={hour_ok}",
           depth=1, jump_kind="value",
           expect=f"{exp} (before={before!r}/{bmin}m -> after={after!r}/{amin}m)")


# ══════════════════════════════════════════════════════════════════════════════
# 12. Combo: End +30 then Start +30 -> 0 net (30-min chips cancel across rows)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_combo_30_net_zero",))
def test_combo_30_net_zero():
    open_fresh()
    _assert_delta("computation_combo_30_net_zero",
                  [("+30", "end"), ("+30", "start")], 0,
                  "End +30 then Start +30 cancel to a net 0 minute change")


# ══════════════════════════════════════════════════════════════════════════════
# 13. Manual-add SAVE round-trip: set End+5x2 -> Save -> the saved 'Untracked' row's
#     duration equals the value that was set (delta +10 vs the pre-save preview).
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_manual_save_roundtrip",))
def test_manual_save_roundtrip():
    open_fresh()
    exp = "the saved record row duration equals the End+5x2 preview value"
    if not seed_record("KcSave"):
        record("computation_manual_save_roundtrip", False,
               "setup_failed: could not seed a record to make Records render",
               depth=1, jump_kind="value", expect=exp)
        return
    if not and_reach_records():
        record("computation_manual_save_roundtrip", False,
               "setup_failed: Records tab did not expose the manual-add button",
               depth=1, jump_kind="value", expect=exp)
        return
    before = and_enter_manual_add_record()
    if before is None:
        record("computation_manual_save_roundtrip", False,
               "feature_missing: manual add-record screen has no Save/preview",
               depth=1, jump_kind="value", expect=exp)
        return
    bmin = dur_to_min(before)
    if not (tap_chip("+5", "end") and tap_chip("+5", "end")):
        record("computation_manual_save_roundtrip", False,
               "feature_missing: End +5 time chip missing on manual-add",
               depth=1, jump_kind="value", expect=exp)
        return
    preview = duration_text()
    pmin = dur_to_min(preview)
    # SAVE and read the new row back on the Records list.
    tap_node(node_by_id(ui(), "btnChangeRecordSave"))
    settle("nav")
    settle("nav")
    nodes = ui()
    rows = [n for n in nodes if (n.get("resource-id") or "").endswith("tvRecordItemDuration")]
    saved_min = None
    for r in rows:
        if dur_to_min(r.get("text")) == pmin:
            saved_min = pmin
            break
    ok = (pmin is not None and bmin is not None and (pmin - bmin) == 10
          and saved_min == pmin)
    record("computation_manual_save_roundtrip", ok,
           "" if ok else "behavior_wrong: saved row duration did not match the set "
           f"preview (before={before!r}/{bmin}, preview={preview!r}/{pmin}, "
           f"saved_row_min={saved_min}, row_durs={[r.get('text') for r in rows]})",
           depth=1, jump_kind="value",
           expect=f"{exp} (preview={preview!r}/{pmin}m persisted as a row of {pmin}m)")


# ══════════════════════════════════════════════════════════════════════════════
# 14. EDIT record: apply End +5 on the pre-filled screen -> preview delta +5, and
#     after Save the row itself moves by +5. (depth 1: edit_record surface)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_edit_record_end_plus5",))
def test_edit_record_end_plus5():
    open_fresh()
    exp = "editing End +5 raises the record's preview duration and saved row by 5m"
    if not seed_record("KcEdit"):
        record("computation_edit_record_end_plus5", False,
               "setup_failed: could not seed a record to edit",
               depth=1, jump_kind="value", expect=exp)
        return
    if not and_reach_records():
        record("computation_edit_record_end_plus5", False,
               "setup_failed: Records tab did not render",
               depth=1, jump_kind="value", expect=exp)
        return
    row_before = duration_text()
    rbmin = dur_to_min(row_before)
    before = and_enter_edit_record()
    if before is None:
        record("computation_edit_record_end_plus5", False,
               "feature_missing: record row not editable (no Save on edit screen)",
               depth=1, jump_kind="value", expect=exp)
        return
    bmin = dur_to_min(before)
    if not tap_chip("+5", "end"):
        record("computation_edit_record_end_plus5", False,
               "feature_missing: End +5 chip absent on the edit screen",
               depth=1, jump_kind="value", expect=exp)
        return
    preview = duration_text()
    pmin = dur_to_min(preview)
    preview_ok = (bmin is not None and pmin is not None and (pmin - bmin) == 5)
    # Save and confirm the persisted row moved by +5 vs. its pre-edit value.
    tap_node(node_by_id(ui(), "btnChangeRecordSave"))
    settle("nav")
    settle("nav")
    row_after = duration_text()
    ramin = dur_to_min(row_after)
    row_ok = (rbmin is not None and ramin is not None and (ramin - rbmin) == 5)
    ok = preview_ok and row_ok
    record("computation_edit_record_end_plus5", ok,
           "" if ok else "behavior_wrong: End +5 edit did not add 5 min "
           f"(preview {before!r}/{bmin}->{preview!r}/{pmin}; "
           f"row {row_before!r}/{rbmin}->{row_after!r}/{ramin})",
           depth=1, jump_kind="value",
           expect=f"{exp} (preview +5: {before!r}->{preview!r}; "
                  f"row +5: {row_before!r}->{row_after!r})")


# ══════════════════════════════════════════════════════════════════════════════
# 15. STATISTICS derived value: with exactly ONE record, the sole activity's
#     percent == '100%'.  (depth 1: statistics tab surface)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_stats_single_percent_100",))
def test_stats_single_percent():
    open_fresh()
    exp = "the sole activity's statistics percent reads '100%'"
    if not seed_record("KcStatP"):
        record("computation_stats_single_percent_100", False,
               "setup_failed: could not seed the single record",
               depth=1, jump_kind="value", expect=exp)
        return
    goto_tab("Statistics")
    and_enter("statistics")
    percents = [n.get("text") for n in ui()
                if (n.get("resource-id") or "").endswith("tvStatisticsItemPercent")]
    ok = percents == ["100%"]
    record("computation_stats_single_percent_100", ok,
           "" if ok else f"behavior_wrong: single-record percents were {percents!r}, "
           "expected exactly ['100%']",
           depth=1, jump_kind="value",
           expect=f"{exp} (observed percents={percents!r})")


# ══════════════════════════════════════════════════════════════════════════════
# 16. STATISTICS derived value: 'Total tracked' duration EQUALS the sole record's
#     duration (the aggregate equals its only input). [+ VLM pie-chart proportion]
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_stats_total_equals_record",
                   "computation_stats_single_slice_vlm"))
def test_stats_total_equals_record():
    open_fresh()
    exp = "'Total tracked' duration equals the single activity's duration"
    if not seed_record("KcStatT"):
        record("computation_stats_total_equals_record", False,
               "setup_failed: could not seed the single record",
               depth=1, jump_kind="value", expect=exp)
        vlm_assert("computation_stats_single_slice", "unreachable", RESULTS_DIR,
                   expect="YES", depth=1, jump_kind="none", tag="shape")
        return
    goto_tab("Statistics")
    and_enter("statistics")
    nodes = ui()
    # Both the activity legend row AND the 'Total tracked' row use tvStatisticsItemName;
    # pair each name with its nearest duration by y-order.
    names = [n for n in nodes
             if (n.get("resource-id") or "").endswith("tvStatisticsItemName")]
    durs = [n for n in nodes
            if (n.get("resource-id") or "").endswith("tvStatisticsItemDuration")]
    total_min = activity_min = None
    for nm in names:
        cand = sorted(durs, key=lambda d: abs(d["_bounds"][1] - nm["_bounds"][1]))
        if not cand:
            continue
        val = dur_to_min(cand[0].get("text"))
        if (nm.get("text") or "").strip().lower() == "total tracked":
            total_min = val
        else:
            activity_min = val
    ok = (total_min is not None and activity_min is not None
          and total_min == activity_min)
    record("computation_stats_total_equals_record", ok,
           "" if ok else "behavior_wrong: Total tracked did not equal the sole "
           f"record's duration (total={total_min}m, activity={activity_min}m, "
           f"durs={[d.get('text') for d in durs]})",
           depth=1, jump_kind="value",
           expect=f"{exp} (total={total_min}m == activity={activity_min}m)")
    # VLM: the pie chart is a canvas view (not in the dump). With one record it must
    # render as a single solid slice filling essentially the whole donut ring.
    vlm_assert("computation_stats_single_slice",
               "Does the circular donut chart consist of a SINGLE solid colour "
               "filling the whole ring (one activity at 100%), with NO second "
               "differently-coloured segment?",
               RESULTS_DIR, expect="YES", depth=1, jump_kind="value", tag="color")


# ══════════════════════════════════════════════════════════════════════════════
# 17. STATISTICS with TWO comparable records: the donut splits into two distinct
#     coloured halves. Each seeded record is edited to ~30m so the split is ~51/49
#     (dump-confirmed) — a rendered proportion unreadable from the dump. [VLM]
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_stats_two_slices_vlm",))
def test_stats_two_slices():
    open_fresh()
    create_activity("KcTwoA")
    create_activity("KcTwoB")
    okA = start_timer("KcTwoA") and stop_timer()
    okB = start_timer("KcTwoB") and stop_timer()
    if not (okA and okB):
        vlm_assert("computation_stats_two_slices", "unreachable", RESULTS_DIR,
                   expect="YES", depth=1, jump_kind="none", tag="shape")
        return
    # Give BOTH records a comparable, non-trivial duration (~30m) so neither slice
    # is an invisible sliver — a near-instant start->stop rounds to 0m otherwise.
    okbA = bump_record_end30("KcTwoA")
    okbB = bump_record_end30("KcTwoB")
    if not (okbA and okbB):
        vlm_assert("computation_stats_two_slices", "unreachable", RESULTS_DIR,
                   expect="YES", depth=1, jump_kind="none", tag="shape")
        return
    goto_tab("Statistics")
    and_enter("statistics")
    vlm_assert("computation_stats_two_slices",
               "Is the circular donut chart split into TWO clearly different colours "
               "(two roughly-equal segments for two activities), rather than a single "
               "solid-colour ring?",
               RESULTS_DIR, expect="YES", depth=1, jump_kind="value", tag="color")


TESTS = [
    test_end_plus5,
    test_end_plus5_twice,
    test_end_plus30,
    test_end_minus5,
    test_end_minus30,
    test_start_plus5,
    test_start_minus5,
    test_start_minus30,
    test_combo_end_plus30_minus5,
    test_combo_net_zero,
    test_combo_plus60,
    test_combo_30_net_zero,
    test_manual_save_roundtrip,
    test_edit_record_end_plus5,
    test_stats_single_percent,
    test_stats_total_equals_record,
    test_stats_two_slices,
]

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