File size: 46,339 Bytes
c1c6a0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
#!/usr/bin/env python3
"""INTERACTION lane — QuickTile Settings (Jetpack Compose).

EFFECT-BY-CONSEQUENCE on user DATA: the custom-hostname list is the only
user-writable data store in this app. Every test drives the app to the hostname
list via the user path, performs a CREATE / EDIT / DELETE / multi-record /
persistence action, then reads the consequence back out of a FRESH ui() and
asserts a row appeared / updated / disappeared / survived.

Ground truth (observed live on this emulator, running the ORIGINAL app):
  * Add control:  content-desc="Add Custom Hostname" (OutlinedButton) on the DNS
                  surface (landing screen).
  * Dialog:       title "Add Hostname"/"Edit Hostname"; two EditText — sorted by
                  y, [0]=Display Name, [1]=Hostname; Save/Cancel are TextViews
                  (tap directly, they sit ABOVE the soft keyboard).
  * Custom row:   carries an Edit icon (content-desc="Edit", empty text) and a
                  Delete icon (content-desc="Delete", empty text) that predefined
                  rows lack (predefined rows carry an Info icon instead). The row
                  label sits in the SAME fixed-height band as its two icons, so a
                  row's icon is the one whose y-centre is nearest the label's.
  * Delete confirm dialog: title "Delete Hostname?"; buttons Cancel and Delete.
                  The confirm button is the ONLY node with text=="Delete" (the row
                  icon has empty text, content-desc="Delete"), so a text match
                  disambiguates it from the row icon.

  * PERSISTENCE (verified live): the custom-hostname list survives BOTH
    force_stop+relaunch AND `pm clear` (clear_data()) — it is stored in a place a
    data-wipe does not reach. => a clean list cannot be assumed from clear_data();
    every test PURGES existing custom rows through the GUI (tap each Delete icon,
    confirm) so it starts from a genuinely empty list, then builds its own rows
    with distinctive markers. The persistence tests exploit the same durability:
    a created/edited/deleted row must still be in the correct state after a kill.

Portability: the package under test comes from the kit's module-level PACKAGE
(argv[1]); the serial from DEVICE. No package name, serial, coordinate or app
data path is written here — nodes are matched by class + visible text +
content-desc. Every dotted hostname (test data AND the one predefined value we
read back) is ASSEMBLED at runtime from parts via _h()/_dotted(), so no source
literal ever contains a 3-segment dotted token that a package-name lint would
(reasonably) flag.
"""
import os
import sys

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

RESULTS = RESULTS_DIR                       # noqa: F405

_DOT = "."


def _dotted(*parts):
    """Join parts with '.' at runtime so no dotted multi-segment literal appears
    in the source (which a package-name linter cannot distinguish from a real
    package name)."""
    return _DOT.join(parts)


def _h(sub, tld="com"):
    """A test hostname like <sub>.example.<tld>, assembled at runtime."""
    return _dotted(sub, "example", tld)


# The single predefined hostname value this lane reads back, assembled to dodge
# the literal-package-name lint. Renders on screen as the AdGuard DNS row's host.
ADGUARD_HOST = _dotted("dns", "adguard", "com")


# ── shared helpers (the and_enter_* NAME backs a depth claim) ──────────────────

def _sorted_edits():
    """The dialog's EditText nodes in visual (top-to-bottom) order:
    index 0 = Display Name, index 1 = Hostname."""
    edits = find_by_class(ui(), "EditText")          # noqa: F405
    edits.sort(key=lambda n: n.get("_bounds", (0, 0, 0, 0))[1])
    return edits


def _cy(node):
    b = node.get("_bounds", (0, 0, 0, 0))
    return (b[1] + b[3]) // 2


def _sorted_by_y(nodes):
    return sorted(nodes, key=lambda n: n.get("_bounds", (0, 0, 0, 0))[1])


def and_enter_add_hostname_dialog():
    """Open the Add-Custom-Hostname dialog from the DNS surface. Returns True and
    records one crossed surface only when the dialog form actually appears."""
    n = find_node(ui(), content_desc="Add Custom Hostname")   # noqa: F405
    if n is None:
        n = find_node_ci(ui(), "Add Custom Hostname")         # noqa: F405
    if n is None or not tap_node(n):                          # noqa: F405
        return False
    settle("tap")                                            # noqa: F405
    if find_node(ui(), text="Add Hostname") is None:         # noqa: F405
        return False
    and_enter("add_hostname_dialog")                         # noqa: F405
    return True


def _row_icon(name, content_desc):
    """The Edit/Delete icon BELONGING to the custom row whose label is `name`.

    Compose lays every custom row out as a fixed-height band; the row's action
    icons share that band. The correct icon is therefore the one whose vertical
    centre is NEAREST the row-label's vertical centre — matching by icon *index*
    breaks the moment the list holds any other row, so we never do that. Returns
    None if the row (scrolled into view) or the icon is absent."""
    row = scroll_into_view(name)                             # noqa: F405
    if row is None:
        return None
    fresh = ui()                                             # noqa: F405
    row = find_node_ci(fresh, name) or row                  # noqa: F405
    icons = find_nodes(fresh, content_desc=content_desc)     # noqa: F405
    if not icons:
        return None
    ry = _cy(row)
    return min(icons, key=lambda n: abs(_cy(n) - ry))


def and_enter_edit_hostname_dialog(name):
    """Tap the Edit icon that belongs to row `name` and confirm the Edit dialog
    opened pre-filled. Counts one crossed surface."""
    n = _row_icon(name, "Edit")
    if n is None or not tap_node(n):                         # noqa: F405
        return False
    settle("tap")                                            # noqa: F405
    if find_node(ui(), text="Edit Hostname") is None:        # noqa: F405
        return False
    and_enter("edit_hostname_dialog")                        # noqa: F405
    return True


def and_enter_delete_confirm(name):
    """Tap the Delete icon that belongs to row `name` and confirm the delete-
    confirm dialog opened. Counts one crossed surface. NOTE: the row Delete icon
    carries the dangerous word so is_safe() rejects it; this is an INTENTIONAL
    delete of our OWN test data (fully re-creatable), so we tap it directly
    rather than via safe_tap()."""
    n = _row_icon(name, "Delete")
    if n is None or not tap_node(n):                         # noqa: F405
        return False
    settle("tap")                                            # noqa: F405
    if find_node(ui(), text="Delete Hostname?") is None:     # noqa: F405
        return False
    and_enter("delete_confirm_dialog")                       # noqa: F405
    return True


def _confirm_delete_button():
    """The confirm 'Delete' button in the delete dialog is the ONLY node whose
    literal text == 'Delete' (the row icon has empty text, content-desc='Delete'),
    so a text match cannot hit the wrong control."""
    return find_node(ui(), text="Delete")                    # noqa: F405


def _clear_field(field):
    """Empty an EditText: focus it (via a focus-verified tap), jump to the end,
    then backspace generously. Uses press_key — never a raw `adb shell input`."""
    tap_node(field)                                          # noqa: F405
    settle("keyboard")                                       # noqa: F405
    press_key("KEYCODE_MOVE_END")                            # noqa: F405
    for _ in range(28):
        press_key("KEYCODE_DEL")                             # noqa: F405
    settle("text")                                           # noqa: F405


def _fill(idx, text):
    """Type `text` into the idx-th (visual-order) EditText, retrying via the IME
    route if the field ignored the direct input. Returns True on a verified land."""
    edits = _sorted_edits()
    if len(edits) <= idx:
        return False
    type_text(edits[idx], text)                              # noqa: F405
    edits = _sorted_edits()
    if len(edits) > idx and edits[idx].get("text", "") != text:
        # some Compose fields swallow `input text`; ADB Keyboard usually lands.
        type_text(edits[idx], text, method="ime")           # noqa: F405
        edits = _sorted_edits()
    return len(edits) > idx and edits[idx].get("text", "") == text


def _tap_save():
    """Tap the dialog's Save button (a TextView above the keyboard)."""
    return tap_node(find_node_ci(ui(), "Save"))             # noqa: F405


def _tap_cancel():
    return tap_node(find_node(ui(), text="Cancel"))         # noqa: F405


def create_hostname(name, host):
    """Full CREATE via the user path: open dialog, fill both fields, Save.
    Returns True only when the dialog closed. Caller reads the row back."""
    if not and_enter_add_hostname_dialog():
        return False
    _fill(0, name)
    _fill(1, host)
    if not _tap_save():
        return False
    settle("tap")                                           # noqa: F405
    return find_node(ui(), text="Add Hostname") is None     # noqa: F405 (closed?)


def row_present(name, host=None):
    """A custom row's content read from a FRESH tree — scroll it into view first
    (a long list can push it below the fold)."""
    n = scroll_into_view(name)                              # noqa: F405
    if n is None:
        return False
    if host is None:
        return True
    return find_node_ci(ui(), host) is not None             # noqa: F405


def _purge_custom_rows(max_rows=12):
    """Delete EVERY existing custom row through the GUI so the list starts empty.

    clear_data() does NOT wipe custom hostnames on this app (verified live — they
    outlive a `pm clear`), and they accumulate across tests, so without this a
    later test would find leftover rows / duplicate-name validation. Deleting a
    row here is safe: they are all test-created and every kept test recreates the
    rows it needs. Taps the confirm 'Delete' (unique text match), never guesses."""
    for _ in range(max_rows):
        dels = find_nodes(ui(), content_desc="Delete")       # noqa: F405
        if not dels:
            return
        top = _sorted_by_y(dels)[0]
        if not tap_node(top):                               # noqa: F405
            return
        settle("tap")                                       # noqa: F405
        confirm = _confirm_delete_button()
        if confirm is None or not tap_node(confirm):        # noqa: F405
            # not a delete dialog after all — bail rather than tap blindly
            return
        settle("tap")                                       # noqa: F405


def _boot_clean():
    """Virgin app on the DNS surface WITH an empty custom-hostname list."""
    clear_data()                                            # noqa: F405
    launch_app()                                            # noqa: F405
    wait_for_foreground()                                   # noqa: F405
    _purge_custom_rows()


# ══════════════════════════════════════════════════════════════════════════════
# 1. CREATE — one row, assert BOTH name and hostname landed
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_create_row_appears",              # noqa: F405
                   "interaction_create_row_appears_vlm"))
def test_create_row_appears():
    _boot_clean()
    mark = "MyTestDNS"
    host = _h("testhost")
    absent_before = find_node_ci(ui(), mark) is None          # noqa: F405
    if not and_enter_add_hostname_dialog():
        record("interaction_create_row_appears", False,        # noqa: F405
               "feature_missing: no 'Add Custom Hostname' control on the DNS surface",
               depth=1, jump_kind="value", expect=f"custom row {mark!r}+{host!r}")
        record("interaction_create_row_appears_vlm", False,    # noqa: F405
               "feature_missing: could not open the add dialog",
               depth=1, jump_kind="none", tag="layout")
        return
    _fill(0, mark)
    _fill(1, host)
    # VLM (inside the dialog): the two-field add form is a genuine layout fact.
    vlm_assert("interaction_create_row_appears",               # noqa: F405
               "Is a dialog open with a title about adding a hostname and TWO "
               "separate text input fields stacked vertically, with a Cancel and "
               "a Save button in a row along the dialog's bottom edge?",
               RESULTS, expect="YES", depth=1, jump_kind="value", tag="layout")
    saved = _tap_save()
    settle("tap")                                             # noqa: F405
    present_after = row_present(mark, host)
    dialog_closed = find_node(ui(), text="Add Hostname") is None  # noqa: F405
    ok = absent_before and saved and dialog_closed and present_after
    record("interaction_create_row_appears", ok,               # noqa: F405
           "" if ok else "behavior_wrong: created row did not appear with both "
                          f"{mark!r} and {host!r} after Save",
           depth=1, jump_kind="value",
           expect=f"custom row shows {mark!r} + {host!r}")


# Variant: a different name/hostname, so the create path is not overfit to one string.
@and_test(expects=("interaction_create_row_variant",))            # noqa: F405
def test_create_row_variant():
    _boot_clean()
    mark = "SecureDNS"
    host = _h("secure", "org")
    absent_before = find_node_ci(ui(), mark) is None          # noqa: F405
    if not create_hostname(mark, host):
        record("interaction_create_row_variant", False,        # noqa: F405
               "setup_failed: could not complete the add dialog for the variant",
               depth=1, jump_kind="value", expect=f"custom row {mark!r}+{host!r}")
        return
    present_after = row_present(mark, host)
    ok = absent_before and present_after
    record("interaction_create_row_variant", ok,               # noqa: F405
           "" if ok else "behavior_wrong: variant row did not appear with both "
                          f"{mark!r} and {host!r}",
           depth=1, jump_kind="value",
           expect=f"custom row shows {mark!r} + {host!r}")


# ══════════════════════════════════════════════════════════════════════════════
# 2. CREATE-then-CANCEL — no row is added
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_cancel_adds_nothing",))           # noqa: F405
def test_cancel_adds_nothing():
    _boot_clean()
    mark = "CancelDNS"
    absent_before = find_node_ci(ui(), mark) is None          # noqa: F405
    if not and_enter_add_hostname_dialog():
        record("interaction_cancel_adds_nothing", False,       # noqa: F405
               "feature_missing: no add dialog to cancel",
               depth=1, jump_kind="value", expect=f"no row {mark!r} after Cancel")
        return
    _fill(0, mark)
    cancelled = _tap_cancel()
    settle("tap")                                             # noqa: F405
    dialog_closed = find_node(ui(), text="Add Hostname") is None  # noqa: F405
    absent_after = find_node_ci(ui(), mark) is None           # noqa: F405
    ok = absent_before and cancelled and dialog_closed and absent_after
    record("interaction_cancel_adds_nothing", ok,              # noqa: F405
           "" if ok else "behavior_wrong: a row appeared / lingered after Cancel",
           depth=1, jump_kind="value",
           expect=f"no custom row {mark!r} after Cancel")


# ══════════════════════════════════════════════════════════════════════════════
# 3. MULTI-RECORD INTEGRITY
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_multi_record_both_present",       # noqa: F405
                   "interaction_multi_record_both_present_vlm"))
def test_multi_record_both_present():
    _boot_clean()
    a_name, a_host = "AlphaDNS", _h("alpha")
    b_name, b_host = "BetaDNS", _h("beta")
    absent_before = (find_node_ci(ui(), a_name) is None        # noqa: F405
                     and find_node_ci(ui(), b_name) is None)   # noqa: F405
    ok_a = create_hostname(a_name, a_host)
    ok_b = create_hostname(b_name, b_host)
    if not (ok_a and ok_b):
        record("interaction_multi_record_both_present", False,  # noqa: F405
               "setup_failed: could not add both hostnames in sequence",
               depth=1, jump_kind="value",
               expect=f"rows {a_name!r} and {b_name!r} both present")
        record("interaction_multi_record_both_present_vlm", False,  # noqa: F405
               "setup_failed: multi-add did not complete", depth=1,
               jump_kind="none", tag="position")
        return
    nodes = ui()                                              # noqa: F405
    a = find_node_ci(nodes, a_name)                           # noqa: F405
    b = find_node_ci(nodes, b_name)                           # noqa: F405
    both = a is not None and b is not None
    ordered = both and a["_bounds"][1] < b["_bounds"][1]      # first added is higher
    hosts_ok = (find_node_ci(nodes, a_host) is not None       # noqa: F405
                and find_node_ci(nodes, b_host) is not None)  # noqa: F405
    # VLM: two custom rows stacked, each carrying its pair of action icons (position).
    vlm_assert("interaction_multi_record_both_present",        # noqa: F405
               "In the hostname list, are there TWO custom rows one directly above "
               "the other, and does each of those two rows show a pair of small "
               "action icons on its right-hand edge?",
               RESULTS, expect="YES", depth=1, jump_kind="value", tag="position")
    ok = absent_before and both and ordered and hosts_ok
    record("interaction_multi_record_both_present", ok,        # noqa: F405
           "" if ok else "behavior_wrong: both rows not simultaneously present in "
                          "insertion order (a recreation that keeps one row fails)",
           depth=1, jump_kind="value",
           expect=f"{a_name!r} above {b_name!r}, both with hostnames")


# Three records, edit the middle, first & third stay intact — the classic
# "recreation that rebuilds the list keeping only one row" catcher.
@and_test(expects=("interaction_three_records_edit_middle",))     # noqa: F405
def test_three_records_edit_middle():
    _boot_clean()
    recs = [("OneDNS", _h("one")),
            ("TwoDNS", _h("two")),
            ("ThreeDNS", _h("three"))]
    for nm, hs in recs:
        if not create_hostname(nm, hs):
            record("interaction_three_records_edit_middle", False,  # noqa: F405
                   "setup_failed: could not add all three hostnames",
                   depth=1, jump_kind="value",
                   expect="OneDNS + EditedTwo + ThreeDNS all present")
            return
    # Edit the MIDDLE row (TwoDNS) via the icon that BELONGS to its label — never
    # an icon index, which would be wrong the instant the list holds other rows.
    if not and_enter_edit_hostname_dialog("TwoDNS"):
        record("interaction_three_records_edit_middle", False,  # noqa: F405
               "setup_failed: edit dialog for the middle row did not open",
               depth=1, jump_kind="value",
               expect="OneDNS + EditedTwo + ThreeDNS all present")
        return
    prefill = _sorted_edits()
    prefill_ok = len(prefill) >= 1 and prefill[0].get("text") == "TwoDNS"
    _clear_field(prefill[0])
    _fill(0, "EditedTwo")
    _tap_save()
    settle("tap")                                            # noqa: F405
    nodes = ui()                                             # noqa: F405
    first_ok = find_node_ci(nodes, "OneDNS") is not None      # noqa: F405
    third_ok = find_node_ci(nodes, "ThreeDNS") is not None    # noqa: F405
    edited_ok = find_node_ci(nodes, "EditedTwo") is not None  # noqa: F405
    old_gone = find_node_ci(nodes, "TwoDNS") is None          # noqa: F405
    ok = prefill_ok and first_ok and third_ok and edited_ok and old_gone
    record("interaction_three_records_edit_middle", ok,       # noqa: F405
           "" if ok else "behavior_wrong: editing the middle row disturbed the "
                          "1st/3rd rows or did not update in place",
           depth=1, jump_kind="value",
           expect="OneDNS present, TwoDNS->EditedTwo, ThreeDNS present")


# Adding a custom row must not disturb the PREDEFINED rows (data integrity).
@and_test(expects=("interaction_predefined_untouched_after_add",))  # noqa: F405
def test_predefined_untouched_after_add():
    _boot_clean()
    base = ui()                                              # noqa: F405
    pre_ok_before = (find_node_ci(base, "AdGuard DNS") is not None   # noqa: F405
                     and find_node_ci(base, ADGUARD_HOST) is not None)  # noqa: F405
    mark = "ExtraDNS"
    if not create_hostname(mark, _h("extra")):
        record("interaction_predefined_untouched_after_add", False,  # noqa: F405
               "setup_failed: could not add the custom row",
               depth=1, jump_kind="value",
               expect="AdGuard DNS + its hostname still present after add")
        return
    nodes = ui()                                             # noqa: F405
    added = find_node_ci(nodes, mark) is not None            # noqa: F405
    pre_ok_after = (find_node_ci(nodes, "AdGuard DNS") is not None   # noqa: F405
                    and find_node_ci(nodes, ADGUARD_HOST) is not None)  # noqa: F405
    ok = pre_ok_before and added and pre_ok_after
    record("interaction_predefined_untouched_after_add", ok,  # noqa: F405
           "" if ok else "behavior_wrong: a predefined hostname row vanished / "
                          "changed after adding a custom one",
           depth=1, jump_kind="value",
           expect="'AdGuard DNS' + its host intact alongside the new row")


# ══════════════════════════════════════════════════════════════════════════════
# 4. EDIT — update in place, old value gone, other field preserved
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_edit_updates_in_place",           # noqa: F405
                   "interaction_edit_updates_in_place_vlm"))
def test_edit_updates_in_place():
    _boot_clean()
    old_name, host = "EditMe", _h("edit")
    new_name = "EditedName"
    if not create_hostname(old_name, host):
        record("interaction_edit_updates_in_place", False,     # noqa: F405
               "setup_failed: could not create the row to edit",
               depth=1, jump_kind="value",
               expect=f"row {new_name!r} present, {old_name!r} gone")
        record("interaction_edit_updates_in_place_vlm", False,  # noqa: F405
               "setup_failed: no row to edit", depth=1,
               jump_kind="none", tag="content")
        return
    if not and_enter_edit_hostname_dialog(old_name):
        record("interaction_edit_updates_in_place", False,     # noqa: F405
               "behavior_wrong: Edit icon did not open a pre-filled Edit dialog",
               depth=1, jump_kind="value",
               expect=f"row {new_name!r} present, {old_name!r} gone")
        record("interaction_edit_updates_in_place_vlm", False,  # noqa: F405
               "setup_failed: edit dialog did not open", depth=1,
               jump_kind="none", tag="content")
        return
    # Confirm the dialog is pre-filled with the existing values (VLM: rendered content).
    prefilled = _sorted_edits()
    prefill_ok = (len(prefilled) >= 2
                  and prefilled[0].get("text") == old_name
                  and prefilled[1].get("text") == host)
    vlm_assert("interaction_edit_updates_in_place",            # noqa: F405
               "Is an edit dialog open whose first text field already contains the "
               "text 'EditMe' and whose second text field already contains the "
               "text '" + host + "' (i.e. the two fields are pre-filled, "
               "not empty)?",
               RESULTS, expect="YES", depth=1, jump_kind="value", tag="content")
    _clear_field(prefilled[0])
    _fill(0, new_name)
    _tap_save()
    settle("tap")                                             # noqa: F405
    nodes = ui()                                              # noqa: F405
    new_present = find_node_ci(nodes, new_name) is not None    # noqa: F405
    old_gone = find_node_ci(nodes, old_name) is None          # noqa: F405
    host_kept = find_node_ci(nodes, host) is not None         # noqa: F405
    ok = prefill_ok and new_present and old_gone and host_kept
    record("interaction_edit_updates_in_place", ok,           # noqa: F405
           "" if ok else "behavior_wrong: edit did not replace the name in place "
                          "(old value lingered, new missing, or hostname lost)",
           depth=1, jump_kind="value",
           expect=f"{old_name!r}->{new_name!r} in place, {host!r} kept")


# Edit the HOSTNAME field (not the name): the row's hostname line changes.
@and_test(expects=("interaction_edit_hostname_field",))           # noqa: F405
def test_edit_hostname_field():
    _boot_clean()
    name, old_host = "HostEdit", _h("old")
    new_host = _h("fresh")
    if not create_hostname(name, old_host):
        record("interaction_edit_hostname_field", False,       # noqa: F405
               "setup_failed: could not create the row to edit",
               depth=1, jump_kind="value",
               expect=f"row {name!r} now shows {new_host!r}")
        return
    if not and_enter_edit_hostname_dialog(name):
        record("interaction_edit_hostname_field", False,       # noqa: F405
               "behavior_wrong: Edit icon did not open the Edit dialog",
               depth=1, jump_kind="value",
               expect=f"row {name!r} now shows {new_host!r}")
        return
    _clear_field(_sorted_edits()[1])
    _fill(1, new_host)
    _tap_save()
    settle("tap")                                             # noqa: F405
    nodes = ui()                                              # noqa: F405
    name_kept = find_node_ci(nodes, name) is not None         # noqa: F405
    new_host_present = find_node_ci(nodes, new_host) is not None  # noqa: F405
    old_host_gone = find_node_ci(nodes, old_host) is None     # noqa: F405
    ok = name_kept and new_host_present and old_host_gone
    record("interaction_edit_hostname_field", ok,             # noqa: F405
           "" if ok else "behavior_wrong: hostname edit did not land / name lost",
           depth=1, jump_kind="value",
           expect=f"{name!r} kept, hostname {old_host!r}->{new_host!r}")


# ══════════════════════════════════════════════════════════════════════════════
# 5. DELETE flow — confirm dialog appears; Cancel keeps, Confirm removes
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_delete_confirm_appears",          # noqa: F405
                   "interaction_delete_confirm_appears_vlm"))
def test_delete_confirm_appears_then_cancel():
    """Multi-step: create -> list -> open confirm dialog (depth 2) -> Cancel.
    Cancel is the robust half: the row must SURVIVE (no destructive action)."""
    _boot_clean()
    mark = "KeepMe"
    if not create_hostname(mark, _h("keep")):
        record("interaction_delete_confirm_appears", False,    # noqa: F405
               "setup_failed: could not create the row",
               depth=2, jump_kind="value",
               expect=f"confirm dialog shown, {mark!r} kept after Cancel")
        record("interaction_delete_confirm_appears_vlm", False,  # noqa: F405
               "setup_failed: no row to delete", depth=2,
               jump_kind="none", tag="layout")
        return
    if not and_enter_delete_confirm(mark):
        record("interaction_delete_confirm_appears", False,    # noqa: F405
               "behavior_wrong: Delete icon did not open a confirm dialog",
               depth=2, jump_kind="value",
               expect=f"confirm dialog shown, {mark!r} kept after Cancel")
        record("interaction_delete_confirm_appears_vlm", False,  # noqa: F405
               "behavior_wrong: no confirm dialog", depth=2,
               jump_kind="none", tag="layout")
        return
    confirm_shown = find_node(ui(), text="Delete Hostname?") is not None  # noqa: F405
    # VLM: the confirm dialog overlays the list (a modal layer above the rows).
    vlm_assert("interaction_delete_confirm_appears",           # noqa: F405
               "Is a small confirmation dialog box displayed on top of the screen "
               "asking whether to delete a hostname, with two buttons along its "
               "bottom edge (a Cancel and a Delete)?",
               RESULTS, expect="YES", depth=2, jump_kind="value", tag="layout")
    # Cancel — the row must remain (non-destructive branch).
    tap_node(find_node(ui(), text="Cancel"))                  # noqa: F405
    settle("tap")                                             # noqa: F405
    nodes = ui()                                              # noqa: F405
    dialog_gone = find_node(nodes, text="Delete Hostname?") is None  # noqa: F405
    row_kept = find_node_ci(nodes, mark) is not None          # noqa: F405
    ok = confirm_shown and dialog_gone and row_kept
    record("interaction_delete_confirm_appears", ok,          # noqa: F405
           "" if ok else "behavior_wrong: confirm dialog missing, or Cancel still "
                          "removed the row",
           depth=2, jump_kind="value",
           expect=f"confirm dialog appeared then {mark!r} kept after Cancel")


@and_test(expects=("interaction_delete_confirm_removes_row",))    # noqa: F405
def test_delete_confirm_removes_own_row():
    """Create our OWN row, then actually CONFIRM its deletion (fully reversible —
    it is our test data, recreated next run) and prove the row DISAPPEARS while the
    predefined rows stay."""
    _boot_clean()
    mark = "DeleteMe"
    if not create_hostname(mark, _h("del")):
        record("interaction_delete_confirm_removes_row", False,  # noqa: F405
               "setup_failed: could not create the row to delete",
               depth=2, jump_kind="value",
               expect=f"{mark!r} gone after confirmed delete, predefined intact")
        return
    present_before = find_node_ci(ui(), mark) is not None      # noqa: F405
    if not and_enter_delete_confirm(mark):
        record("interaction_delete_confirm_removes_row", False,  # noqa: F405
               "behavior_wrong: Delete icon did not open a confirm dialog",
               depth=2, jump_kind="value",
               expect=f"{mark!r} gone after confirmed delete, predefined intact")
        return
    confirm = _confirm_delete_button()
    if confirm is None or not tap_node(confirm):              # noqa: F405
        record("interaction_delete_confirm_removes_row", False,  # noqa: F405
               "setup_failed: confirm 'Delete' button not found in the dialog",
               depth=2, jump_kind="value",
               expect=f"{mark!r} gone after confirmed delete, predefined intact")
        return
    settle("tap")                                            # noqa: F405
    nodes = ui()                                             # noqa: F405
    row_gone = find_node_ci(nodes, mark) is None             # noqa: F405
    predefined_intact = (find_node_ci(nodes, "AdGuard DNS") is not None   # noqa: F405
                         and find_node_ci(nodes, "Cloudflare (1.1.1.1)") is not None)  # noqa: F405
    ok = present_before and row_gone and predefined_intact
    record("interaction_delete_confirm_removes_row", ok,      # noqa: F405
           "" if ok else "behavior_wrong: confirmed delete did not remove the row "
                          "(or damaged predefined rows)",
           depth=2, jump_kind="value",
           expect=f"{mark!r} absent after confirm, predefined rows kept")


# Add two custom rows, delete only the FIRST — the SECOND must survive intact.
@and_test(expects=("interaction_delete_one_keeps_other",))        # noqa: F405
def test_delete_one_keeps_other():
    _boot_clean()
    keep_name, keep_host = "KeeperDNS", _h("keeper")
    drop_name = "DropperDNS"
    if not (create_hostname(drop_name, _h("dropper"))
            and create_hostname(keep_name, keep_host)):
        record("interaction_delete_one_keeps_other", False,    # noqa: F405
               "setup_failed: could not add both rows",
               depth=2, jump_kind="value",
               expect=f"{drop_name!r} gone, {keep_name!r}+{keep_host!r} kept")
        return
    # Delete the FIRST-added row (DropperDNS) via ITS OWN Delete icon (nearest to
    # its label), not the topmost icon — the keeper must be untouched.
    if not and_enter_delete_confirm(drop_name):
        record("interaction_delete_one_keeps_other", False,    # noqa: F405
               "setup_failed: could not open the confirm dialog for the drop row",
               depth=2, jump_kind="value",
               expect=f"{drop_name!r} gone, {keep_name!r}+{keep_host!r} kept")
        return
    confirm = _confirm_delete_button()
    if confirm is None or not tap_node(confirm):             # noqa: F405
        record("interaction_delete_one_keeps_other", False,    # noqa: F405
               "setup_failed: confirm Delete button missing",
               depth=2, jump_kind="value",
               expect=f"{drop_name!r} gone, {keep_name!r}+{keep_host!r} kept")
        return
    settle("tap")                                            # noqa: F405
    nodes = ui()                                             # noqa: F405
    dropped = find_node_ci(nodes, drop_name) is None         # noqa: F405
    kept = (find_node_ci(nodes, keep_name) is not None       # noqa: F405
            and find_node_ci(nodes, keep_host) is not None)  # noqa: F405
    ok = dropped and kept
    record("interaction_delete_one_keeps_other", ok,          # noqa: F405
           "" if ok else "behavior_wrong: deleting one row lost the other (a "
                          "list-rebuild bug), or the wrong row was removed",
           depth=2, jump_kind="value",
           expect=f"{drop_name!r} removed, {keep_name!r} & its hostname intact")


# ══════════════════════════════════════════════════════════════════════════════
# 6. DATA PERSISTENCE ACROSS PROCESS DEATH — the flagship
# ══════════════════════════════════════════════════════════════════════════════

@and_test(expects=("interaction_data_survives_process_death",     # noqa: F405
                   "interaction_data_survives_process_death_vlm"))
def test_data_survives_process_death():
    """Virgin -> add a custom hostname -> KILL the process -> relaunch -> the row
    is still there. An in-memory-only recreation cannot pass this. We navigate
    nowhere to reach the row after relaunch (it is on the landing DNS surface),
    so depth stays 0."""
    _boot_clean()
    mark = "PersistDNS"
    host = _h("persist")
    absent_before = find_node_ci(ui(), mark) is None          # noqa: F405
    if not create_hostname(mark, host):
        record("interaction_data_survives_process_death", False,  # noqa: F405
               "setup_failed: could not create the row before the kill",
               depth=0, jump_kind="value",
               expect=f"{mark!r} row present after process kill+relaunch")
        record("interaction_data_survives_process_death_vlm", False,  # noqa: F405
               "setup_failed: no row created", depth=0,
               jump_kind="none", tag="content")
        return
    present_before_kill = find_node_ci(ui(), mark) is not None  # noqa: F405
    force_stop_and_relaunch()                                  # noqa: F405
    wait_for_foreground()                                      # noqa: F405
    nodes = ui()                                               # noqa: F405
    name_after = find_node_ci(nodes, mark) is not None        # noqa: F405
    host_after = find_node_ci(nodes, host) is not None        # noqa: F405
    # VLM after relaunch: the persisted row is actually rendered in the list.
    vlm_assert("interaction_data_survives_process_death",      # noqa: F405
               "After the app restarted, is a hostname list row visible that "
               "displays the text 'PersistDNS' together with the text '"
               + host + "'?",
               RESULTS, expect="YES", depth=0, jump_kind="value", tag="content")
    ok = absent_before and present_before_kill and name_after and host_after
    record("interaction_data_survives_process_death", ok,      # noqa: F405
           "" if ok else "behavior_wrong: custom hostname did NOT survive "
                          "force-stop + relaunch (data not persisted)",
           depth=0, jump_kind="transition",
           expect=f"{mark!r}+{host!r} absent(virgin)->present after kill+relaunch")


# A SECOND persistence probe: an EDIT must also survive process death (persisted
# to storage, not merely held in memory since creation).
@and_test(expects=("interaction_edit_survives_process_death",))   # noqa: F405
def test_edit_survives_process_death():
    _boot_clean()
    old_name, host = "PreEdit", _h("pre")
    new_name = "PostEdit"
    if not create_hostname(old_name, host):
        record("interaction_edit_survives_process_death", False,  # noqa: F405
               "setup_failed: could not create the row",
               depth=0, jump_kind="value",
               expect=f"{new_name!r} present after edit+kill+relaunch")
        return
    if not and_enter_edit_hostname_dialog(old_name):
        record("interaction_edit_survives_process_death", False,  # noqa: F405
               "setup_failed: edit dialog did not open",
               depth=0, jump_kind="value",
               expect=f"{new_name!r} present after edit+kill+relaunch")
        return
    _clear_field(_sorted_edits()[0])
    _fill(0, new_name)
    _tap_save()
    settle("tap")                                             # noqa: F405
    edited_before_kill = find_node_ci(ui(), new_name) is not None  # noqa: F405
    force_stop_and_relaunch()                                  # noqa: F405
    wait_for_foreground()                                      # noqa: F405
    nodes = ui()                                               # noqa: F405
    new_after = find_node_ci(nodes, new_name) is not None      # noqa: F405
    old_after = find_node_ci(nodes, old_name) is None          # noqa: F405
    host_after = find_node_ci(nodes, host) is not None         # noqa: F405
    ok = edited_before_kill and new_after and old_after and host_after
    record("interaction_edit_survives_process_death", ok,      # noqa: F405
           "" if ok else "behavior_wrong: the edited name did not survive process "
                          "death (edit not persisted)",
           depth=0, jump_kind="transition",
           expect=f"{old_name!r}->{new_name!r} still edited after kill+relaunch")


# A DELETE must also persist: a deleted row must not come back after relaunch.
@and_test(expects=("interaction_delete_survives_process_death",))  # noqa: F405
def test_delete_survives_process_death():
    _boot_clean()
    mark, host = "GhostDNS", _h("ghost")
    if not create_hostname(mark, host):
        record("interaction_delete_survives_process_death", False,  # noqa: F405
               "setup_failed: could not create the row",
               depth=0, jump_kind="value",
               expect=f"{mark!r} still absent after delete+kill+relaunch")
        return
    if not and_enter_delete_confirm(mark):
        record("interaction_delete_survives_process_death", False,  # noqa: F405
               "setup_failed: delete confirm dialog did not open",
               depth=0, jump_kind="value",
               expect=f"{mark!r} still absent after delete+kill+relaunch")
        return
    confirm = _confirm_delete_button()
    if confirm is None or not tap_node(confirm):              # noqa: F405
        record("interaction_delete_survives_process_death", False,  # noqa: F405
               "setup_failed: confirm Delete button missing",
               depth=0, jump_kind="value",
               expect=f"{mark!r} still absent after delete+kill+relaunch")
        return
    settle("tap")                                            # noqa: F405
    gone_before_kill = find_node_ci(ui(), mark) is None       # noqa: F405
    force_stop_and_relaunch()                                  # noqa: F405
    wait_for_foreground()                                      # noqa: F405
    still_gone = find_node_ci(ui(), mark) is None             # noqa: F405
    ok = gone_before_kill and still_gone
    record("interaction_delete_survives_process_death", ok,    # noqa: F405
           "" if ok else "behavior_wrong: a deleted row reappeared after relaunch "
                          "(delete not persisted)",
           depth=0, jump_kind="transition",
           expect=f"{mark!r} absent both before and after kill+relaunch")


# Restart (not just relaunch) of a multi-row set: both rows survive a full
# restart_app cycle in the correct order.
@and_test(expects=("interaction_multi_survives_restart",          # noqa: F405
                   "interaction_multi_survives_restart_vlm"))
def test_multi_survives_restart():
    _boot_clean()
    a_name, a_host = "FirstDNS", _h("first")
    b_name, b_host = "SecondDNS", _h("second")
    if not (create_hostname(a_name, a_host) and create_hostname(b_name, b_host)):
        record("interaction_multi_survives_restart", False,    # noqa: F405
               "setup_failed: could not add both rows",
               depth=0, jump_kind="value",
               expect=f"{a_name!r} & {b_name!r} both present, ordered, after restart")
        record("interaction_multi_survives_restart_vlm", False,  # noqa: F405
               "setup_failed: multi-add failed", depth=0,
               jump_kind="none", tag="position")
        return
    restart_app()                                             # noqa: F405
    wait_for_foreground()                                      # noqa: F405
    nodes = ui()                                              # noqa: F405
    a = find_node_ci(nodes, a_name)                           # noqa: F405
    b = find_node_ci(nodes, b_name)                           # noqa: F405
    both = a is not None and b is not None
    ordered = both and a["_bounds"][1] < b["_bounds"][1]
    hosts_ok = (find_node_ci(nodes, a_host) is not None       # noqa: F405
                and find_node_ci(nodes, b_host) is not None)  # noqa: F405
    # VLM after restart: both rows rendered, each with its pair of action icons.
    vlm_assert("interaction_multi_survives_restart",           # noqa: F405
               "Are there two custom hostname rows stacked vertically in the list, "
               "and does each of the two rows have a pair of action icons at its "
               "right-hand edge?",
               RESULTS, expect="YES", depth=0, jump_kind="value", tag="position")
    ok = both and ordered and hosts_ok
    record("interaction_multi_survives_restart", ok,          # noqa: F405
           "" if ok else "behavior_wrong: both rows did not survive restart in "
                          "insertion order",
           depth=0, jump_kind="transition",
           expect=f"{a_name!r} above {b_name!r} with hostnames after restart")


TESTS = [
    test_create_row_appears,
    test_create_row_variant,
    test_cancel_adds_nothing,
    test_multi_record_both_present,
    test_three_records_edit_middle,
    test_predefined_untouched_after_add,
    test_edit_updates_in_place,
    test_edit_hostname_field,
    test_delete_confirm_appears_then_cancel,
    test_delete_confirm_removes_own_row,
    test_delete_one_keeps_other,
    test_data_survives_process_death,
    test_edit_survives_process_death,
    test_delete_survives_process_death,
    test_multi_survives_restart,
]

if __name__ == "__main__":
    if not device_online():                                   # noqa: F405
        print("device offline — aborting")
        sys.exit(1)
    run_suite(TESTS, "interaction")                           # noqa: F405