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

This lane owns jump_kind="value": a deterministic INPUT fed through the user path,
then the exact OUTPUT read back out of a fresh ui() and asserted equal to what was
OBSERVED on the running original. The app's "computation" is GLSL source -> live GL
render, but the render is an opaque GL surface (id ending /preview, an
android.view.View) whose pixels NEVER reach the view tree. So the VALUE tests assert
the DETERMINISTIC EDITOR-TEXT deltas that each core operation produces, and the 3
VLM assertions are reserved for the rendered GL result (the only thing not readable
from the dump).

Ground truth (ALL verified live on the running original, package
de.markusfisch...debug — re-derived, not read from source):
  * Default editor source is 716 chars and contains 'uniform float time' exactly
    once and 'void main(void)'; it does NOT contain battery/date/light/frame/daytime.
  * Add uniform preset (menu -> Add uniform/texture -> tap a NON-sampler row) INSERTS
    an exact declaration and finishes the activity, growing the editor text:
        battery (float) -> 'uniform float battery'   716 -> 743
        date (vec4)     -> 'uniform vec4 date'       716 -> 739
        light (float)   -> 'uniform float light'     716 -> 741
        frame (int)     -> 'uniform int frame'       716 -> 739
        daytime (vec3)  -> 'uniform vec3 daytime'    716 -> 742
        time (float)    -> 'uniform float time' count 1 -> 2  716 -> 740
  * Extra-key row (appears when the editor is focused) has six /btn buttons
    { } ( ) [ ]; tapping '{' inserts exactly +1 char and one more '{'; '(' the same.
  * insert_tab (Button, content-desc 'Insert tab') inserts a tab, which uiautomator
    emits as the un-decoded entity '	' (4 chars) -> parsed text length grows by
    EXACTLY 4 (so this variant asserts LENGTH +4, never a literal char).
  * Load sample (menu -> Load sample -> tap a row) REPLACES the editor source with a
    different non-empty program: Circles 716 -> 489, Swirl 716 -> 874.
  * Quality spinner (id /quality, child /text1) offers 1/32 1/16 1/8 1/4 1/2 1/1 2/1
    with 1/1 checked; selecting 2/1 changes the spinner label 1/1 -> 2/1.
  * Undo (menu -> Undo, content-desc 'Undo') reverts the last edit: after a '{' insert
    (716 -> 717) an Undo reverts the text back to the pre-edit 716 (brace count 3 -> 2).
    The overflow popup stays OPEN after Undo, so the popup is dismissed with BACK
    (which returns to the editor, NOT out of the app) before reading the reverted text.
  * toggle_code (the "eye" Button, id /toggle_code, empty content-desc) hides
    editor_container/editor and shows the fullscreen preview (a GL surface, no code).

NOTE on the parsed editor text: uiautomator emits the EditText value with HTML
entities un-decoded (newline -> '&#10;', tab -> '&#9;', '<' -> '&lt;'). Every asserted
substring below ('uniform float battery', 'uniform vec4 date', 'uniform float light',
'uniform int frame', 'uniform vec3 daytime', 'uniform float time', '{', '(') is
entity-free, so it appears literally; no assertion spans a newline/tab.

    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


# ── Portable launch: land on MainActivity, NOT LeakCanary's leak list ────────────
# The debug build ships LeakCanary, which registers a SECOND MAIN/LAUNCHER activity,
# so the kit's launch_app()/restart_app() land on the wrong screen. Resolve the app's
# own non-leakcanary LAUNCHER activity at runtime (works for the recreation too, which
# has no LeakCanary — the filter is then a no-op), verify the editor toolbar appeared,
# and retry. Uses only PACKAGE, so it is fully portable.
def launch_editor():
    out = adb_shell("cmd", "package", "query-activities", "--brief",
                    "-a", "android.intent.action.MAIN",
                    "-c", "android.intent.category.LAUNCHER", PACKAGE)
    comp = next((ln.strip() for ln in out.splitlines()
                 if ln.strip().startswith(PACKAGE + "/")
                 and "leakcanary" not in ln.lower()), "")
    for _ in range(4):
        force_stop()
        if comp:
            adb_shell("am", "start", "-n", comp)
        else:
            launch_app()               # recreation: no explicit launcher listing
        settle("launch")
        wait_for_foreground()
        if node_by_id(ui(), "menu_btn") or node_by_id(ui(), "editor"):
            return True
        back()
        settle("tap")                  # dismiss whatever we landed on, then retry
    return False


# ── Domain helpers (plain helpers; the and_enter_* NAMES below back the depth) ─────

def editor_text(nodes=None):
    """Current editor EditText value ('' if not on screen). Re-dumps a few times if
    the editor node is transiently absent (right after the keyboard opens/closes or a
    popup dismisses, the node can drop out of one dump)."""
    for _ in range(4):
        nds = ui() if nodes is None else nodes
        ed = node_by_id(nds, "editor")
        if ed is not None:
            return ed.get("text", "")
        nodes = None
        settle("tap")
    return ""


def quality_label(nodes=None):
    """The quality spinner's current label (its child /text1 TextView)."""
    nds = ui() if nodes is None else nodes
    t1 = node_by_id(nds, "text1")
    return t1.get("text", "") if t1 else ""


def _menu_open(nodes=None):
    """True when the overflow popup is showing (one of its rows is present)."""
    nds = ui() if nodes is None else nodes
    return (node_by_id(nds, "add_uniform") is not None
            or node_by_id(nds, "load_sample") is not None
            or node_by_id(nds, "undo") is not None)


def open_menu():
    """Editor -> overflow popup (menu_btn). True once a known menu row is visible.
    Retries the tap, re-dumping each time: the very FIRST menu tap right after a
    launch can land while the toolbar is still settling and miss the popup, and a
    keyboard/soft-input transition can swallow one tap."""
    for _ in range(4):
        if _menu_open():
            return True
        mb = node_by_id(ui(), "menu_btn")
        if mb is None or not tap_node(mb):
            settle("tap")
            continue
        settle("tap")
        if _menu_open():
            return True
        settle("tap")
    return _menu_open()


def and_enter_add_uniform():
    """Editor -> menu -> AddUniformActivity (crosses the menu popup, THEN the
    activity). Two surfaces, each named with and_enter, so depth=2 is backed."""
    if not open_menu():
        return False
    and_enter("menu")
    au = node_by_id(ui(), "add_uniform")
    if au is None or not tap_node(au):
        return False
    settle("launch")
    wait_for_foreground()
    if find_node_ci(ui(), "Add uniform/texture") is None:
        return False
    and_enter("add_uniform_activity")
    return True


def and_enter_load_sample():
    """Editor -> menu -> LoadSampleActivity (two surfaces, both named)."""
    if not open_menu():
        return False
    and_enter("menu")
    ls = node_by_id(ui(), "load_sample")
    if ls is None or not tap_node(ls):
        return False
    settle("launch")
    wait_for_foreground()
    if find_node_ci(ui(), "Load sample") is None:
        return False
    and_enter("load_sample_activity")
    return True


def _quality_dropdown_open(nodes=None):
    """True when the quality dropdown popup is showing (>=2 selectable /text1)."""
    nds = ui() if nodes is None else nodes
    return len([n for n in nds if n.get("resource-id", "").endswith("/text1")]) >= 2


def and_enter_quality_dropdown():
    """Editor -> tap the quality Spinner -> its dropdown popup of CheckedTextViews.
    One surface; named so a depth=1 value claim is backed. Retries the spinner tap
    (the collapsed spinner shows exactly one /text1, the open dropdown shows all
    seven, so a >=2 count is the open-state signal). Returns True once open."""
    for _ in range(3):
        if _quality_dropdown_open():
            and_enter("quality_dropdown")
            return True
        q = node_by_id(ui(), "quality")
        if q is None or not tap_node(q):
            settle("tap")
            continue
        settle("tap")
    if _quality_dropdown_open():
        and_enter("quality_dropdown")
        return True
    return False


def and_enter_undo_menu():
    """Editor -> overflow popup that holds the Undo control. One surface (the popup);
    named so a depth=1 value claim is backed. Returns True once Undo is present."""
    if not open_menu():
        return False
    if node_by_id(ui(), "undo") is None:
        return False
    and_enter("menu")
    return True


def tap_uniform_row(text):
    """Tap a uniform preset row by its /name text, re-dumping until it is laid out
    (has _center) AND scrolling the list — the AddUniform rows report no bounds for a
    beat after the activity opens, and lower presets need a scroll to appear."""
    for _ in range(10):
        settle("tap")
        cand = find_node(ui(), text=text)
        if cand and "_center" in cand:
            return tap_node(cand)
        scroll_down(0.5)
    return False


def tap_sample_row(text):
    """Tap a Load-sample row by its visible text, re-dumping and scrolling until laid
    out (Swirl and other lower samples need a scroll)."""
    for _ in range(10):
        settle("tap")
        cand = find_node(ui(), text=text)
        if cand and "_center" in cand:
            return tap_node(cand)
        scroll_down(0.5)
    return False


def extra_key_btn(nodes, ch):
    """The extra-keys-row Button (id ending /btn) whose text is exactly `ch`."""
    for n in nodes:
        if n.get("resource-id", "").endswith("/btn") and n.get("text", "") == ch:
            return n
    return None


def focus_editor_extra_keys():
    """Focus the editor so the soft keyboard + extra-keys row appear; move the caret
    to the very end. Returns the pre-edit editor text, or None if it could not focus.
    """
    ed = node_by_id(ui(), "editor")
    if ed is None or not tap_node(ed):
        return None
    settle("keyboard")
    press_key("KEYCODE_MOVE_END")
    return editor_text()


def show_fullscreen_preview():
    """Tap the 'eye' toggle_code so the code editor hides and the fullscreen GL
    preview is shown. Retries once. True iff the editor is gone afterwards."""
    for _ in range(2):
        tc = node_by_id(ui(), "toggle_code")
        if tc is None or not tap_node(tc):
            return False
        settle("tap")
        settle("tap")
        if node_by_id(ui(), "editor") is None:
            return True
    return node_by_id(ui(), "editor") is None


# ══════════════════════════════════════════════════════════════════════════════
# 1) FLAGSHIP value: Add uniform inserts the EXACT declaration into the source
# ══════════════════════════════════════════════════════════════════════════════
def _add_uniform_case(name, row_text, substring, expect_str):
    """Shared body: default source lacks `substring`; after inserting `row_text` the
    editor CONTAINS `substring` and is longer. depth=2 (menu popup + activity)."""
    clear_data()
    if not launch_editor():
        record(name, False, "setup_failed: could not reach the editor",
               depth=2, jump_kind="value", expect=expect_str)
        return
    before = editor_text()
    absent_before = substring not in before
    if not and_enter_add_uniform():
        record(name, False, "feature_missing: no Add uniform/texture path",
               depth=2, jump_kind="value", expect=expect_str)
        return
    if not tap_uniform_row(row_text):
        record(name, False, f"feature_missing: no '{row_text}' preset row",
               depth=2, jump_kind="value", expect=expect_str)
        return
    wait_for_foreground()
    after = editor_text()
    ok = absent_before and substring in after and len(after) > len(before)
    record(name, ok,
           "" if ok else f"behavior_wrong: '{substring}' not inserted "
           f"(present_before={not absent_before}, in_after={substring in after}, "
           f"len {len(before)} -> {len(after)})",
           depth=2, jump_kind="value", expect=expect_str)


@and_test(expects=("computation_add_uniform_battery",))
def test_add_uniform_battery():
    _add_uniform_case("computation_add_uniform_battery", "battery (float)",
                      "uniform float battery",
                      "editor text contains 'uniform float battery' after inserting "
                      "the battery preset")


@and_test(expects=("computation_add_uniform_date",))
def test_add_uniform_date():
    _add_uniform_case("computation_add_uniform_date", "date (vec4)",
                      "uniform vec4 date",
                      "editor text contains 'uniform vec4 date' after inserting the "
                      "date preset")


@and_test(expects=("computation_add_uniform_light",))
def test_add_uniform_light():
    _add_uniform_case("computation_add_uniform_light", "light (float)",
                      "uniform float light",
                      "editor text contains 'uniform float light' after inserting the "
                      "light preset")


@and_test(expects=("computation_add_uniform_frame",))
def test_add_uniform_frame():
    _add_uniform_case("computation_add_uniform_frame", "frame (int)",
                      "uniform int frame",
                      "editor text contains 'uniform int frame' after inserting the "
                      "frame preset")


@and_test(expects=("computation_add_uniform_daytime",))
def test_add_uniform_daytime():
    _add_uniform_case("computation_add_uniform_daytime", "daytime (vec3)",
                      "uniform vec3 daytime",
                      "editor text contains 'uniform vec3 daytime' after inserting the "
                      "daytime preset")


# The default source ALREADY declares 'uniform float time' once, so this variant
# asserts the COUNT increments 1 -> 2 (a second declaration is appended) rather than
# absence->presence. This discriminates a recreation that ignores the tapped preset.
@and_test(expects=("computation_add_uniform_time_count",))
def test_add_uniform_time_count():
    name = "computation_add_uniform_time_count"
    expect_str = ("editor's 'uniform float time' count goes 1 -> 2 after inserting "
                  "the time preset")
    clear_data()
    if not launch_editor():
        record(name, False, "setup_failed: could not reach the editor",
               depth=2, jump_kind="value", expect=expect_str)
        return
    before = editor_text()
    n_before = before.count("uniform float time")
    if not and_enter_add_uniform():
        record(name, False, "feature_missing: no Add uniform/texture path",
               depth=2, jump_kind="value", expect=expect_str)
        return
    if not tap_uniform_row("time (float)"):
        record(name, False, "feature_missing: no 'time (float)' preset row",
               depth=2, jump_kind="value", expect=expect_str)
        return
    wait_for_foreground()
    after = editor_text()
    n_after = after.count("uniform float time")
    ok = n_before == 1 and n_after == 2 and len(after) > len(before)
    record(name, ok,
           "" if ok else "behavior_wrong: 'uniform float time' count did not go "
           f"1 -> 2 (before={n_before}, after={n_after}, "
           f"len {len(before)} -> {len(after)})",
           depth=2, jump_kind="value", expect=expect_str)


# ══════════════════════════════════════════════════════════════════════════════
# 2) Extra-key bracket buttons insert EXACTLY one char at the caret (depth=0)
# ══════════════════════════════════════════════════════════════════════════════
def _extra_key_char_case(name, ch, expect_str):
    clear_data()
    if not launch_editor():
        record(name, False, "setup_failed: could not reach the editor",
               depth=0, jump_kind="value", expect=expect_str)
        return
    before = focus_editor_extra_keys()
    if before is None:
        record(name, False, "setup_failed: could not focus the editor",
               depth=0, jump_kind="value", expect=expect_str)
        return
    btn = extra_key_btn(ui(), ch)
    if btn is None:
        record(name, False, f"feature_missing: no '{ch}' extra-key button",
               depth=0, jump_kind="value", expect=expect_str)
        return
    tap_node(btn)
    settle("tap")
    after = editor_text()
    ok = (len(after) == len(before) + 1
          and after.count(ch) == before.count(ch) + 1)
    record(name, ok,
           "" if ok else f"behavior_wrong: '{ch}' did not insert exactly one char "
           f"(len {len(before)} -> {len(after)}, "
           f"'{ch}' count {before.count(ch)} -> {after.count(ch)})",
           depth=0, jump_kind="value", expect=expect_str)


@and_test(expects=("computation_extra_key_brace",))
def test_extra_key_brace():
    _extra_key_char_case("computation_extra_key_brace", "{",
                         "editor text length +1 and gains one '{' after tapping the "
                         "{ extra-key")


@and_test(expects=("computation_extra_key_paren",))
def test_extra_key_paren():
    _extra_key_char_case("computation_extra_key_paren", "(",
                         "editor text length +1 and gains one '(' after tapping the "
                         "( extra-key")


# insert_tab inserts a tab; uiautomator emits it as the un-decoded entity '&#9;'
# (4 chars), so assert the parsed length grows by EXACTLY 4 (never a literal char).
@and_test(expects=("computation_insert_tab",))
def test_insert_tab():
    name = "computation_insert_tab"
    expect_str = ("editor text length grows by exactly 4 (un-decoded &#9;) after "
                  "tapping Insert tab")
    clear_data()
    if not launch_editor():
        record(name, False, "setup_failed: could not reach the editor",
               depth=0, jump_kind="value", expect=expect_str)
        return
    before = focus_editor_extra_keys()
    if before is None:
        record(name, False, "setup_failed: could not focus the editor",
               depth=0, jump_kind="value", expect=expect_str)
        return
    it = node_by_id(ui(), "insert_tab")
    if it is None:
        it = find_node(ui(), content_desc="Insert tab")
    if it is None or not tap_node(it):
        record(name, False, "feature_missing: no 'Insert tab' button",
               depth=0, jump_kind="value", expect=expect_str)
        return
    settle("tap")
    after = editor_text()
    ok = len(after) == len(before) + 4
    record(name, ok,
           "" if ok else "behavior_wrong: Insert tab did not grow the parsed text by "
           f"exactly 4 (len {len(before)} -> {len(after)})",
           depth=0, jump_kind="value", expect=expect_str)


# ══════════════════════════════════════════════════════════════════════════════
# 3) Load sample REPLACES the editor source with a different non-empty program
# ══════════════════════════════════════════════════════════════════════════════
def _load_sample_case(name, sample_text, expect_str):
    clear_data()
    if not launch_editor():
        record(name, False, "setup_failed: could not reach the editor",
               depth=2, jump_kind="value", expect=expect_str)
        return
    before = editor_text()
    if not and_enter_load_sample():
        record(name, False, "feature_missing: no Load sample path",
               depth=2, jump_kind="value", expect=expect_str)
        return
    if not tap_sample_row(sample_text):
        record(name, False, f"feature_missing: no '{sample_text}' sample row",
               depth=2, jump_kind="value", expect=expect_str)
        return
    wait_for_foreground()
    after = editor_text()
    ok = after != before and len(after) > 0
    record(name, ok,
           "" if ok else f"behavior_wrong: loading '{sample_text}' did not replace "
           f"the editor source (changed={after != before}, after_len={len(after)})",
           depth=2, jump_kind="value", expect=expect_str)


@and_test(expects=("computation_load_sample_circles",
                   "computation_load_sample_circles_vlm"))
def test_load_sample_circles():
    name = "computation_load_sample_circles"
    expect_str = "editor source differs from the default after loading Circles"
    circ_q = ("In this fullscreen preview, are concentric circular rings (a ripple / "
              "bullseye pattern) rendered around the centre of the screen, with NO "
              "source-code text visible?")
    clear_data()
    if not launch_editor():
        record(name, False, "setup_failed: could not reach the editor",
               depth=2, jump_kind="value", expect=expect_str)
        vlm_assert(name, circ_q, depth=2, jump_kind="value", tag="shape")
        return
    before = editor_text()
    if not and_enter_load_sample():
        record(name, False, "feature_missing: no Load sample path",
               depth=2, jump_kind="value", expect=expect_str)
        vlm_assert(name, circ_q, depth=2, jump_kind="value", tag="shape")
        return
    if not tap_sample_row("Circles"):
        record(name, False, "feature_missing: no 'Circles' sample row",
               depth=2, jump_kind="value", expect=expect_str)
        vlm_assert(name, circ_q, depth=2, jump_kind="value", tag="shape")
        return
    wait_for_foreground()
    after = editor_text()
    ok = after != before and len(after) > 0
    record(name, ok,
           "" if ok else "behavior_wrong: loading 'Circles' did not replace the "
           f"editor source (changed={after != before}, after_len={len(after)})",
           depth=2, jump_kind="value", expect=expect_str)
    # VLM: toggle to the fullscreen GL preview and confirm the RENDERED Circles output
    # (concentric rings). The GL surface never reaches the view tree, so this is a
    # legitimate visual-only check.
    show_fullscreen_preview()
    vlm_assert(name, circ_q, depth=2, jump_kind="value", tag="shape")


@and_test(expects=("computation_load_sample_swirl",))
def test_load_sample_swirl():
    _load_sample_case("computation_load_sample_swirl", "Swirl",
                      "editor source differs from the default after loading Swirl")


# ══════════════════════════════════════════════════════════════════════════════
# 4) Quality spinner selection changes the displayed value 1/1 -> 2/1 (depth=1)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_quality_spinner_2to1",))
def test_quality_spinner_2to1():
    name = "computation_quality_spinner_2to1"
    expect_str = "quality spinner label 1/1 -> 2/1 after selecting 2/1"
    clear_data()
    if not launch_editor():
        record(name, False, "setup_failed: could not reach the editor",
               depth=1, jump_kind="value", expect=expect_str)
        return
    before = quality_label()
    if not and_enter_quality_dropdown():
        record(name, False, "feature_missing: no quality spinner dropdown",
               depth=1, jump_kind="value", expect=expect_str)
        return
    row = None
    for n in ui():
        if n.get("resource-id", "").endswith("/text1") and n.get("text") == "2/1":
            row = n
            break
    if row is None or not tap_node(row):
        record(name, False, "feature_missing: no '2/1' option in the quality dropdown",
               depth=1, jump_kind="value", expect=expect_str)
        return
    settle("tap")
    after = quality_label()
    ok = before == "1/1" and after == "2/1"
    record(name, ok,
           "" if ok else f"behavior_wrong: quality label did not change 1/1 -> 2/1 "
           f"(before={before!r}, after={after!r})",
           depth=1, jump_kind="value", expect=expect_str)


# ══════════════════════════════════════════════════════════════════════════════
# 5) Undo reverts the last editor edit (depth=1: the Undo lives in the popup)
# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_undo_reverts_edit",))
def test_undo_reverts_edit():
    name = "computation_undo_reverts_edit"
    expect_str = ("editor text reverts to the pre-edit content (len and '{' count) "
                  "after Undo")
    clear_data()
    if not launch_editor():
        record(name, False, "setup_failed: could not reach the editor",
               depth=1, jump_kind="value", expect=expect_str)
        return
    before = focus_editor_extra_keys()
    if before is None:
        record(name, False, "setup_failed: could not focus the editor",
               depth=1, jump_kind="value", expect=expect_str)
        return
    brace = extra_key_btn(ui(), "{")
    if brace is None:
        record(name, False, "feature_missing: no '{' extra-key button",
               depth=1, jump_kind="value", expect=expect_str)
        return
    tap_node(brace)
    settle("tap")
    edited = editor_text()
    if not (len(edited) == len(before) + 1
            and edited.count("{") == before.count("{") + 1):
        record(name, False, "setup_failed: the '{' edit did not register "
               f"(len {len(before)} -> {len(edited)})",
               depth=1, jump_kind="value", expect=expect_str)
        return
    # Undo lives in the overflow popup; the popup stays OPEN after tapping Undo.
    if not and_enter_undo_menu():
        record(name, False, "feature_missing: no Undo control in the menu",
               depth=1, jump_kind="value", expect=expect_str)
        return
    undo = node_by_id(ui(), "undo")
    if undo is None or not tap_node(undo):
        record(name, False, "feature_missing: Undo not tappable",
               depth=1, jump_kind="value", expect=expect_str)
        return
    settle("tap")
    # Dismiss the still-open popup with BACK (returns to the editor, NOT out of the
    # app), guarded so we only press BACK while the popup is actually showing.
    if _menu_open():
        back()
        settle("tap")
    reverted = editor_text()
    ok = (reverted == before
          and len(reverted) == len(before)
          and reverted.count("{") == before.count("{"))
    record(name, ok,
           "" if ok else "behavior_wrong: Undo did not revert the edit "
           f"(before_len={len(before)}, edited_len={len(edited)}, "
           f"reverted_len={len(reverted)}, "
           f"braces before={before.count('{')} reverted={reverted.count('{')})",
           depth=1, jump_kind="value", expect=expect_str)


# ══════════════════════════════════════════════════════════════════════════════
# 6) VLM (exactly 3) — the RENDERED GL result, which never reaches the view tree
# ══════════════════════════════════════════════════════════════════════════════
# One of the three (Circles) is issued inside test_load_sample_circles above (a
# render paired with the source-replace value assertion). The remaining two below
# render the DEFAULT gradient and the SWIRL sample fullscreen. All three are tagged
# color/shape (fine-grained): they ask about a specific rendered property.
@and_test(expects=("computation_default_preview_vlm",))
def test_default_preview_render_vlm():
    name = "computation_default_preview"
    clear_data()
    if not launch_editor():
        record(name + "_vlm", False,
               "setup_failed: could not reach the editor",
               depth=1, jump_kind="none", tag="color")
        return
    # toggle_code (the eye) hides the code and shows the fullscreen default preview.
    if not show_fullscreen_preview():
        record(name + "_vlm", False,
               "setup_failed: could not toggle to the fullscreen preview",
               depth=1, jump_kind="none", tag="color")
        return
    and_enter("fullscreen_preview")
    vlm_assert(name,
               "In the area below the top toolbar, is the TOP noticeably brighter "
               "and more vividly GREEN than the darker BOTTOM (a smooth vertical "
               "colour gradient), with NO lines of source code text visible?",
               depth=1, jump_kind="value", tag="color")


@and_test(expects=("computation_swirl_preview_vlm",))
def test_swirl_preview_render_vlm():
    name = "computation_swirl_preview"
    clear_data()
    if not launch_editor():
        record(name + "_vlm", False,
               "setup_failed: could not reach the editor",
               depth=2, jump_kind="none", tag="shape")
        return
    if not and_enter_load_sample() or not tap_sample_row("Swirl"):
        record(name + "_vlm", False,
               "feature_missing: could not load the Swirl sample",
               depth=2, jump_kind="none", tag="shape")
        return
    wait_for_foreground()
    if not show_fullscreen_preview():
        record(name + "_vlm", False,
               "setup_failed: could not toggle to the fullscreen preview",
               depth=2, jump_kind="none", tag="shape")
        return
    vlm_assert(name,
               "Does this fullscreen preview show a rendered graphical image that "
               "fills the screen (colours / a pattern), rather than lines of "
               "source-code text on a plain background?",
               depth=2, jump_kind="value", tag="shape")


TESTS = [
    test_add_uniform_battery,
    test_add_uniform_date,
    test_add_uniform_light,
    test_add_uniform_frame,
    test_add_uniform_daytime,
    test_add_uniform_time_count,
    test_extra_key_brace,
    test_extra_key_paren,
    test_insert_tab,
    test_load_sample_circles,
    test_load_sample_swirl,
    test_quality_spinner_2to1,
    test_undo_reverts_edit,
    test_default_preview_render_vlm,
    test_swirl_preview_render_vlm,
]


if __name__ == "__main__":
    if not device_online():
        print("Device offline — aborting; a whole module of setup_failed usually "
              "means the tunnel died, not that the app is broken.")
        sys.exit(1)
    run_suite(TESTS, "computation")