File size: 42,377 Bytes
3fbbdd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
"""test_ax_states.py — CodeEdit AX STATE lane.

Owns CHECKED / ENABLED / SELECTED state and focus.  Every fact asserted here was
observed live on the official app under fresh-launch pytest conditions and is
recorded in recon.md `## STATE` (pristine profile — conftest wipes the app's
defaults before every launch, so the recorded values ARE the shipped defaults).

Contract: pytest methods on Test* classes taking the `ax` fixture, plain asserts,
every test declaring @pytest.mark.rb(depth=, jump_kind=, expect=) and backing a
`transition` with kit.rb_flip(...) / a `value` with kit.rb_value(...).
"""

# ── PRIMITIVES (verbatim from recon.md) ──────────────────────────────────────
import json
import os
import shutil
import subprocess
import time

import pytest

import rb_testgen_kit as kit
import verifier_helpers as helpers

RESULTS_DIR = os.environ.get("RESULTS_DIR", os.path.join(os.path.dirname(__file__), "results"))
FIXTURES_DIR = os.environ.get("FIXTURES_DIR") or os.path.join(os.path.dirname(__file__), "fixtures")


def screenshot_assert(test_name, description, results_dir=None):
    results_dir = results_dir or RESULTS_DIR
    ss_dir = os.path.join(results_dir, "screenshots")
    os.makedirs(ss_dir, exist_ok=True)
    ss_path = os.path.join(ss_dir, f"{test_name}.png")
    try:
        subprocess.run(["screencapture", "-x", ss_path], timeout=5)
    except Exception:
        pass
    af = os.path.join(ss_dir, "assertions.json")
    data = {}
    if os.path.exists(af):
        try:
            with open(af) as f:
                data = json.load(f)
        except Exception:
            data = {}
    data[f"{test_name}.png"] = description
    with open(af, "w") as f:
        json.dump(data, f, indent=2)


def win_id(ax, w):
    return ax.get(w.id, ["AXIdentifier"]).get("AXIdentifier")


def all_windows(ax):
    return ax.find(role="window", max_depth=1, max_results=20)


def find_window(ax, ident=None, title=None, timeout=8.0):
    end = time.time() + timeout
    while True:
        for w in all_windows(ax):
            if ident is not None and win_id(ax, w) == ident:
                return w
            if title is not None and (w.name or "") == title:
                return w
        if time.time() >= end:
            return None
        time.sleep(0.25)


def close_window(ax, w):
    if w is None:
        return False
    for b in ax.find(role="button", root_id=w.id, max_results=200, max_depth=3):
        if ax.get(b.id, ["AXSubrole"]).get("AXSubrole") == "AXCloseButton":
            ax.action(b.id, "AXPress")
            time.sleep(0.8)
            return True
    return False


def values_in(ax, root_id, max_results=400, max_depth=18):
    """Every non-empty AXValue string under root (labels, fields, popups)."""
    out = []
    for e in ax.find(root_id=root_id, max_results=max_results, max_depth=max_depth):
        v = ax.get(e.id, ["AXValue"]).get("AXValue")
        if isinstance(v, str) and v.strip():
            out.append(v)
    return out


def names_in(ax, root_id, role=None, max_results=400, max_depth=18):
    return [e.name for e in ax.find(role=role, root_id=root_id,
                                    max_results=max_results, max_depth=max_depth) if e.name]


def buttons_named(ax, root_id, name):
    return [b for b in ax.find(role="button", root_id=root_id, max_results=300, max_depth=16)
            if (b.name or "") == name]


def menu_item(ax, *path):
    mbi = [m for m in ax.find(role="menu_bar_item", max_results=20, max_depth=3)
           if (m.name or "") == path[0]]
    if not mbi:
        return None
    cur = mbi[0].id
    for label in path[1:]:
        items = ax.find(role="menu_item", root_id=cur, max_results=300, max_depth=2)
        hit = [i for i in items if (i.name or "") == label]
        if not hit:
            return None
        cur = hit[0].id
    return cur


def menu_items(ax, *path):
    """Item NAMES directly under a menu-bar item (or a submenu item)."""
    root = menu_item(ax, *path) if len(path) > 1 else None
    if root is None:
        mbi = [m for m in ax.find(role="menu_bar_item", max_results=20, max_depth=3)
               if (m.name or "") == path[0]]
        if not mbi:
            return []
        menus = ax.find(role="menu", root_id=mbi[0].id, max_results=2, max_depth=1)
        if not menus:
            return []
        root = menus[0].id
    else:
        menus = ax.find(role="menu", root_id=root, max_results=2, max_depth=1)
        if not menus:
            return []
        root = menus[0].id
    return [i.name for i in ax.find(role="menu_item", root_id=root, max_results=100, max_depth=1)
            if (i.name or "")]


def rb_enter_menu_item(ax, *path, wait=1.6):
    mid = menu_item(ax, *path)
    if mid is None:
        return False
    ax.action(mid, "AXPress")
    time.sleep(wait)
    return True


def rb_enter_welcome(ax):
    w = find_window(ax, ident="welcome", timeout=3)
    if w is None:
        rb_enter_menu_item(ax, "Window", "Welcome to CodeEdit")
        w = find_window(ax, ident="welcome", timeout=6)
    return w


def rb_enter_settings_window(ax):
    w = find_window(ax, ident="settings", timeout=1)
    if w is None:
        rb_enter_menu_item(ax, "CodeEdit", "Settings...", wait=2.0)
        w = find_window(ax, ident="settings", timeout=8)
    return w


def rb_reach_settings_pane(ax, pane):
    """Select a Settings sidebar pane. MUST be a CG click (AXPress does NOT select)."""
    w = rb_enter_settings_window(ax)
    if w is None:
        return None
    bs = buttons_named(ax, w.id, pane)
    if not bs:
        return None
    ax.click_element_cg(bs[-1].id)
    time.sleep(1.0)
    return find_window(ax, ident="settings", timeout=3)


def rb_enter_about_window(ax):
    rb_enter_menu_item(ax, "CodeEdit", "About CodeEdit", wait=2.0)
    return find_window(ax, ident="about", timeout=6)


def rb_enter_extensions_window(ax):
    rb_enter_menu_item(ax, "Extensions", "Open Extensions Window", wait=2.0)
    return find_window(ax, ident="extensions", timeout=6)


def rb_enter_clone_sheet(ax):
    w = rb_enter_welcome(ax)
    bs = buttons_named(ax, w.id, "Clone Git Repository...")
    if not bs:
        return None
    ax.action(bs[0].id, "AXPress")
    end = time.time() + 6
    while time.time() < end:
        s = ax.find(role="sheet", max_results=3, max_depth=6)
        if s:
            return s[0]
        time.sleep(0.25)
    return None


def rb_enter_save_panel(ax):
    w = rb_enter_welcome(ax)
    bs = buttons_named(ax, w.id, "Create New File...")
    if bs:
        ax.action(bs[0].id, "AXPress")
    return find_window(ax, title="Save", timeout=8)


def rb_enter_open_panel(ax):
    w = rb_enter_welcome(ax)
    bs = buttons_named(ax, w.id, "Open File or Folder...")
    if bs:
        ax.action(bs[0].id, "AXPress")
    return find_window(ax, title="Open Workspace or File", timeout=8)


def dismiss_panel_or_sheet(ax):
    """Escape does not work here — press the panel/sheet's own Cancel button."""
    for b in ax.find(role="button", max_results=120, max_depth=10):
        if (b.name or "") == "Cancel":
            ax.action(b.id, "AXPress")
            time.sleep(1.0)
            return True
    return False


def rb_enter_workspace(ax, folder_name="sample_project", timeout=20.0):
    """Open the fixture folder as a workspace the way Finder does: hand the folder to the
    RUNNING app's own bundle (discovered from its pid at runtime — portable)."""
    from AppKit import NSWorkspace, NSRunningApplication, NSWorkspaceOpenConfiguration
    from Foundation import NSURL
    src = os.path.join(FIXTURES_DIR, folder_name)
    base = os.path.join("/tmp", "rb_codeedit_ws")
    dst = os.path.join(base, folder_name)
    if os.path.isdir(base):
        shutil.rmtree(base, ignore_errors=True)
    os.makedirs(base, exist_ok=True)
    shutil.copytree(src, dst)
    ra = NSRunningApplication.runningApplicationWithProcessIdentifier_(int(ax._pid))
    cfg = NSWorkspaceOpenConfiguration.configuration()
    cfg.setActivates_(True)
    NSWorkspace.sharedWorkspace().openURLs_withApplicationAtURL_configuration_completionHandler_(
        [NSURL.fileURLWithPath_(dst)], ra.bundleURL(), cfg, None)
    return find_window(ax, ident="workspace", timeout=timeout)


def project_navigator(ax, ws):
    for o in ax.find(role="outline", root_id=ws.id, max_results=10, max_depth=14):
        if (o.name or "") == "Project Navigator":
            return o
    return None


def navigator_rows(ax, ws):
    nav = project_navigator(ax, ws)
    if nav is None:
        return []
    return [ax.get(t.id, ["AXValue"]).get("AXValue")
            for t in ax.find(role="text_field", root_id=nav.id, max_results=60, max_depth=8)]


def rb_reach_editor(ax, ws, filename):
    """Click a file row in the Project Navigator; returns the editor AXTextArea (or None)."""
    nav = project_navigator(ax, ws)
    if nav is None:
        return None
    rows = ax.find(role="text_field", root_id=nav.id, max_results=60, max_depth=8)
    tgt = [t for t in rows if ax.get(t.id, ["AXValue"]).get("AXValue") == filename]
    if not tgt:
        return None
    ax.click_element_cg(tgt[0].id)
    end = time.time() + 8
    while time.time() < end:
        ta = ax.find(role="text_area", root_id=ws.id, max_results=5, max_depth=18)
        if ta:
            return ta[0]
        time.sleep(0.3)
    return None


def rb_enter_command_palette(ax, ws):
    """Command Palette / Open Quickly only exist while a WORKSPACE window is open."""
    ax.action(ws.id, "AXRaise")
    time.sleep(0.5)
    rb_enter_menu_item(ax, "View", "Show Command Palette", wait=1.6)
    return _overlay_window(ax)


def rb_enter_open_quickly(ax, ws):
    ax.action(ws.id, "AXRaise")
    time.sleep(0.5)
    rb_enter_menu_item(ax, "File", "Open Quickly", wait=1.6)
    return _overlay_window(ax)


def _overlay_window(ax):
    """The palette/quick-open overlay is a borderless AXWindow: no title, no AXIdentifier."""
    for w in all_windows(ax):
        if win_id(ax, w) is None and not (w.name or ""):
            return w
    return None


def overlay_rows(ax, pal):
    return [v for v in (ax.get(t.id, ["AXValue"]).get("AXValue")
                        for t in ax.find(role="label", root_id=pal.id,
                                         max_results=60, max_depth=14)) if v]


def overlay_type(ax, pal, text):
    tf = ax.find(role="text_field", root_id=pal.id, max_results=5, max_depth=8)
    if not tf:
        return False
    ax.set_value(tf[0].id, text)
    time.sleep(1.3)
    return True


def switch_for_label(ax, root_id, label):
    """The AXCheckBox(AXSwitch) that follows the AXStaticText whose AXValue == label."""
    seq = ax.find(root_id=root_id, max_results=400, max_depth=18)
    idx = None
    for i, e in enumerate(seq):
        if e.role == "label" and ax.get(e.id, ["AXValue"]).get("AXValue") == label:
            idx = i
            break
    if idx is None:
        return None
    for e in seq[idx + 1:idx + 4]:
        if e.role == "checkbox":
            return e
    return None


def popup_for_label(ax, root_id, label):
    seq = ax.find(root_id=root_id, max_results=400, max_depth=18)
    idx = None
    for i, e in enumerate(seq):
        if e.role == "label" and ax.get(e.id, ["AXValue"]).get("AXValue") == label:
            idx = i
            break
    if idx is None:
        return None
    for e in seq[idx + 1:idx + 4]:
        if e.role == "popup":
            return e
    return None


def popup_options(ax, popup):
    ax.action(popup.id, "AXPress")
    time.sleep(0.8)
    menus = ax.find(role="menu", root_id=popup.id, max_results=3, max_depth=2)
    out = []
    if menus:
        for i in ax.find(role="menu_item", root_id=menus[0].id, max_results=40, max_depth=2):
            out.append(i.name or ax.get(i.id, ["AXValue"]).get("AXValue"))
        ax.action(menus[0].id, "AXCancel")
        time.sleep(0.4)
    return [o for o in out if o]


def popup_pick(ax, popup, option):
    ax.action(popup.id, "AXPress")
    time.sleep(0.8)
    menus = ax.find(role="menu", root_id=popup.id, max_results=3, max_depth=2)
    if not menus:
        return False
    for i in ax.find(role="menu_item", root_id=menus[0].id, max_results=40, max_depth=2):
        if (i.name or ax.get(i.id, ["AXValue"]).get("AXValue")) == option:
            ax.action(i.id, "AXPick")
            time.sleep(1.0)
            return True
    ax.action(menus[0].id, "AXCancel")
    return False
# ── end PRIMITIVES ───────────────────────────────────────────────────────────


# ── STATE-lane locators (semantic: visible label + role, never child index) ───

SETTLE = 0.9          # after a CG click on a SwiftUI switch/radio/segment
PANE_WALK = dict(max_results=400, max_depth=18)


def _norm(s):
    """Curly-quote / ellipsis tolerant, whitespace-trimmed label text."""
    return (str(s).replace("“", '"').replace("”", '"')
            .replace("‘", "'").replace("’", "'")
            .replace("…", "...").strip())


def _flag(v):
    """AXValue of a switch / radio / segment normalised to 1, 0 or None."""
    if v is None:
        return None
    if isinstance(v, bool):
        return int(v)
    if isinstance(v, (int, float)):
        return int(v)
    s = str(v).strip().lower()
    if s in ("1", "true", "yes", "on"):
        return 1
    if s in ("0", "false", "no", "off"):
        return 0
    return None


def _axval(ax, el):
    """Live AXValue of an element (None when the element was not found)."""
    if el is None:
        return None
    return ax.get(el.id, ["AXValue"]).get("AXValue")


def _boolish(v):
    """AXEnabled / AXFocused / AXSelected normalised to a real bool (None stays None).
    The AX bridge may hand back 1/0 or True/False depending on the toolkit."""
    if v is None:
        return None
    if isinstance(v, bool):
        return v
    if isinstance(v, (int, float)):
        return bool(v)
    s = str(v).strip().lower()
    if s in ("1", "true", "yes"):
        return True
    if s in ("0", "false", "no"):
        return False
    return None


def _texts(ax, e):
    """Every visible-text candidate for an element: AXValue then AXTitle/AXDescription."""
    out = []
    v = e.value
    if isinstance(v, str) and v:
        out.append(v)
    if e.name:
        out.append(str(e.name))
    if not out:
        v2 = ax.get(e.id, ["AXValue"]).get("AXValue")
        if isinstance(v2, str) and v2:
            out.append(v2)
    return out


def _pane_seq(ax, root_id):
    """Pre-order element sequence of a settings pane (one tree walk per read)."""
    return ax.find(root_id=root_id, **PANE_WALK)


def _label_index(ax, seq, label):
    """Index of the static text carrying `label` — exact, then trimmed, then
    curly-quote-normalised (a recreation may use straight quotes / trim spaces)."""
    cands = [(i, _texts(ax, e)) for i, e in enumerate(seq) if e.role == "label"]
    for i, ts in cands:
        if any(t == label for t in ts):
            return i
    for i, ts in cands:
        if any(t.strip() == label.strip() for t in ts):
            return i
    tgt = _norm(label)
    for i, ts in cands:
        if any(_norm(t) == tgt for t in ts):
            return i
    return None


def _control_after(ax, seq, label, role, window=4):
    """The control of `role` that immediately follows the row label (SwiftUI Form order)."""
    i = _label_index(ax, seq, label)
    if i is None:
        return None
    for e in seq[i + 1:i + 1 + window]:
        if e.role == role:
            return e
    return None


def _switch_in(ax, seq, label, root_id=None):
    """AXCheckBox/AXSwitch for a row label; falls back to the PRIMITIVES locator."""
    el = _control_after(ax, seq, label, "checkbox")
    if el is None and root_id is not None:
        el = switch_for_label(ax, root_id, label)
    return el


def _popup_in(ax, seq, label, root_id=None):
    """AXPopUpButton for a row label; falls back to the PRIMITIVES locator."""
    el = _control_after(ax, seq, label, "popup")
    if el is None and root_id is not None:
        el = popup_for_label(ax, root_id, label)
    return el


def _field_in(ax, seq, label):
    return _control_after(ax, seq, label, "text_field")


def _switch_flags(ax, seq, labels, root_id=None):
    return {lbl: _flag(_axval(ax, _switch_in(ax, seq, lbl, root_id))) for lbl in labels}


def _popup_values(ax, seq, labels, root_id=None):
    out = {}
    for lbl in labels:
        v = _axval(ax, _popup_in(ax, seq, lbl, root_id))
        out[lbl] = str(v) if isinstance(v, str) else v
    return out


def _field_values(ax, seq, labels):
    out = {}
    for lbl in labels:
        v = _axval(ax, _field_in(ax, seq, lbl))
        out[lbl] = str(v) if v is not None else None
    return out


def _radios(ax, root_id):
    """name -> first AXRadioButton/segment with that name under root."""
    out = {}
    for r in ax.find(role="radio", root_id=root_id, max_results=60, max_depth=18):
        nm = (r.name or "").strip()
        if nm and nm not in out:
            out[nm] = r
    return out


def _radio_flags(ax, root_id, names):
    rs = _radios(ax, root_id)
    return {n: _flag(_axval(ax, rs.get(n))) for n in names}


def _group_with(ax, root_id, names):
    """The AXRadioGroup / segmented control under root whose radios carry ALL `names`.
    Scoping every read to that group keeps a same-named element elsewhere in the window
    (e.g. the sidebar's 'General' pane row) out of the measurement."""
    want = {n.strip() for n in names}
    for g in ax.find(role="radiogroup", root_id=root_id, max_results=20, max_depth=18):
        got = {(r.name or "").strip()
               for r in ax.find(role="radio", root_id=g.id, max_results=12, max_depth=4)}
        if want <= got:
            return g
    return None


def _radio_group_for(ax, seq, label, member_names):
    """The AXRadioGroup belonging to `label`.

    Both `Navigator Tab Bar Position` and `Inspector Tab Bar Position` own a Top/Side
    pair, so member names alone are ambiguous. Pick, among the groups that DO carry
    `member_names`, the one nearest the row label in tree order (a recreation may emit
    the group just before or just after its label); recon records the Navigator group
    first, so fall back to first-vs-last if no label is found at all."""
    want = {n.strip() for n in member_names}
    cands = []
    for i, e in enumerate(seq):
        if e.role != "radiogroup":
            continue
        got = {(r.name or "").strip()
               for r in ax.find(role="radio", root_id=e.id, max_results=10, max_depth=4)}
        if want <= got:
            cands.append((i, e))
    if not cands:
        return None
    li = _label_index(ax, seq, label)
    if li is None:
        return cands[0][1] if "Navigator" in label else cands[-1][1]
    after = [(i, e) for i, e in cands if i >= li]
    if after:
        return min(after, key=lambda p: p[0] - li)[1]
    return min(cands, key=lambda p: abs(p[0] - li))[1]


def _has_text(ax, seq, needle):
    n = _norm(needle).lower()
    for e in seq:
        for t in _texts(ax, e):
            if n in _norm(t).lower():
                return True
    return False


def _selected_rows(ax, w):
    """Visible-text blob of every sidebar row currently AXSelected.

    recon: the selected pane's AXRow/AXCell carries AXSelected == True. Rows are
    tried first; only if NO row reports the selection do we fall back to cells, so a
    selected row plus its selected cell can never be counted twice."""
    def _sel(role):
        out = []
        for r in ax.find(role=role, root_id=w, max_results=80, max_depth=16):
            if _boolish(ax.get(r.id, ["AXSelected"]).get("AXSelected")) is True:
                parts = []
                for e in ax.find(root_id=r.id, max_results=20, max_depth=6):
                    ts = _texts(ax, e)
                    if ts:
                        parts.append(ts[0])
                out.append(" ".join(parts).strip())
        return out

    return _sel("row") or _sel("cell")


def _menu_enabled(ax, menu_name, item_names):
    """{item -> AXEnabled} for items directly under a menu-bar menu (None if absent)."""
    mbi = [m for m in ax.find(role="menu_bar_item", max_results=20, max_depth=3)
           if (m.name or "") == menu_name]
    if not mbi:
        return {n: None for n in item_names}
    by_name = {}
    for i in ax.find(role="menu_item", root_id=mbi[0].id, max_results=300, max_depth=2):
        nm = (i.name or "").strip()
        if nm and nm not in by_name:
            by_name[nm] = i
    out = {}
    for n in item_names:
        el = by_name.get(n)
        out[n] = None if el is None else _boolish(
            ax.get(el.id, ["AXEnabled"]).get("AXEnabled"))
    return out


def rb_enter_popup_options(ax, popup):
    """Open a popup button's MENU — a new AX surface — and read its option list."""
    return popup_options(ax, popup)


# ── recorded shipped defaults (recon ## STATE, pristine profile) ─────────────

GENERAL_SWITCH_DEFAULTS = {
    "Show Path Bar": 1,
    "Dim editors without focus": 0,
    "Show Live Issues": 1,
    "Automatically save changes to disk": 1,
    "Automatically reveal in project navigator": 0,
    # curly quotes in the shipped label
    "Show “Open With CodeEdit” option in Finder": 1,
    "Automatically check for app updates": 0,
}

GENERAL_POPUP_DEFAULTS = {
    "Appearance": "System",
    "Show Issues": "Show Inline",
    "Reopen Behavior": "Welcome Screen",
    "After the last window is closed": "Do nothing",
    "File Extensions": "Show all",
    "Project Navigator Size": "Medium",
    "Find Navigator Detail": "Up to 3 lines",
}

FIND_MENU_ITEMS = ["Find...", "Find and Replace...", "Find Next", "Find Previous",
                   "Use Selection for Find", "Jump to Selection"]

SOURCE_CONTROL_MENU_ITEMS = ["Commit...", "Push...", "Pull...", "Fetch Changes",
                             "Stage All Changes", "Unstage All Changes", "Cherry-Pick...",
                             "Stash Changes...", "Discard All Changes...",
                             "Add Exisiting Remote..."]


# ── General pane: shipped defaults (value) ───────────────────────────────────

class TestGeneralPaneDefaults:

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Settings>General switches on a pristine profile: Show Path Bar=1, "
                           "Dim editors without focus=0, Show Live Issues=1, Automatically save "
                           "changes to disk=1, Automatically reveal in project navigator=0, "
                           "Show “Open With CodeEdit” option in Finder=1, "
                           "Automatically check for app updates=0")
    def test_general_pane_switch_defaults(self, ax):
        w = rb_reach_settings_pane(ax, "General")
        assert w is not None, "Settings window / General pane not reachable"
        seq = _pane_seq(ax, w.id)
        observed = _switch_flags(ax, seq, list(GENERAL_SWITCH_DEFAULTS), w.id)
        assert kit.rb_value(observed, GENERAL_SWITCH_DEFAULTS), (
            f"General switch defaults mismatch: observed={observed} "
            f"expected={GENERAL_SWITCH_DEFAULTS}")

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Settings>General popups default to Appearance=System, Show Issues="
                           "Show Inline, Reopen Behavior=Welcome Screen, After the last window "
                           "is closed=Do nothing, File Extensions=Show all, Project Navigator "
                           "Size=Medium, Find Navigator Detail=Up to 3 lines")
    def test_general_pane_popup_defaults(self, ax):
        w = rb_reach_settings_pane(ax, "General")
        assert w is not None, "Settings window / General pane not reachable"
        seq = _pane_seq(ax, w.id)
        observed = _popup_values(ax, seq, list(GENERAL_POPUP_DEFAULTS), w.id)
        assert kit.rb_value(observed, GENERAL_POPUP_DEFAULTS), (
            f"General popup defaults mismatch: observed={observed} "
            f"expected={GENERAL_POPUP_DEFAULTS}")


# ── Switch flips: read → CG click → read (transition) ────────────────────────

class TestSwitchFlips:

    @pytest.mark.rb(depth=1, jump_kind="transition",
                    expect="'Dim editors without focus' AXValue flips 0 -> 1 after a CG click "
                           "on its switch in Settings>General")
    def test_dim_editors_without_focus_switch_turns_on(self, ax):
        label = "Dim editors without focus"
        w = rb_reach_settings_pane(ax, "General")
        assert w is not None, "Settings window / General pane not reachable"
        sw = _switch_in(ax, _pane_seq(ax, w.id), label, w.id)
        assert sw is not None, f"no AXCheckBox/AXSwitch found for label {label!r}"
        before = _flag(_axval(ax, sw))
        ax.click_element_cg(sw.id)
        time.sleep(SETTLE)
        after = _flag(_axval(ax, _switch_in(ax, _pane_seq(ax, w.id), label, w.id)))
        screenshot_assert(
            "state_test_dim_editors_switch_on",
            "CodeEdit Settings window, General pane. The 'Dim editors without focus' toggle "
            "switch is now ON (knob slid to the right, track filled with the blue accent "
            "colour); the 'Show Path Bar' switch directly above it is still ON and every other "
            "row (Appearance popup showing 'System', the Color/Monochrome File Icon Style "
            "radio pair with Color selected) is unchanged.")
        assert kit.rb_flip(before, after) and before == 0 and after == 1, (
            f"'{label}' switch did not flip 0->1: before={before} after={after}")

    @pytest.mark.rb(depth=1, jump_kind="transition",
                    expect="'Show Path Bar' AXValue flips 1 -> 0 after a CG click on its switch "
                           "in Settings>General")
    def test_show_path_bar_switch_turns_off(self, ax):
        label = "Show Path Bar"
        w = rb_reach_settings_pane(ax, "General")
        assert w is not None, "Settings window / General pane not reachable"
        sw = _switch_in(ax, _pane_seq(ax, w.id), label, w.id)
        assert sw is not None, f"no AXCheckBox/AXSwitch found for label {label!r}"
        before = _flag(_axval(ax, sw))
        ax.click_element_cg(sw.id)
        time.sleep(SETTLE)
        after = _flag(_axval(ax, _switch_in(ax, _pane_seq(ax, w.id), label, w.id)))
        assert kit.rb_flip(before, after) and before == 1 and after == 0, (
            f"'{label}' switch did not flip 1->0: before={before} after={after}")

    @pytest.mark.rb(depth=1, jump_kind="transition",
                    expect="'Show Live Issues' AXValue flips 1 -> 0 after a CG click on its "
                           "switch in Settings>General")
    def test_show_live_issues_switch_turns_off(self, ax):
        label = "Show Live Issues"
        w = rb_reach_settings_pane(ax, "General")
        assert w is not None, "Settings window / General pane not reachable"
        sw = _switch_in(ax, _pane_seq(ax, w.id), label, w.id)
        assert sw is not None, f"no AXCheckBox/AXSwitch found for label {label!r}"
        before = _flag(_axval(ax, sw))
        ax.click_element_cg(sw.id)
        time.sleep(SETTLE)
        after = _flag(_axval(ax, _switch_in(ax, _pane_seq(ax, w.id), label, w.id)))
        assert kit.rb_flip(before, after) and before == 1 and after == 0, (
            f"'{label}' switch did not flip 1->0: before={before} after={after}")


# ── Radio groups: exactly one member checked, and it moves (transition) ──────

class TestRadioGroups:

    @pytest.mark.rb(depth=1, jump_kind="transition",
                    expect="File Icon Style radio selection moves: Color 1/Monochrome 0 -> "
                           "Color 0/Monochrome 1 (exactly one selected before and after)")
    def test_file_icon_style_radio_moves_to_monochrome(self, ax):
        w = rb_reach_settings_pane(ax, "General")
        assert w is not None, "Settings window / General pane not reachable"
        rs = _radios(ax, w.id)
        assert "Color" in rs and "Monochrome" in rs, (
            f"File Icon Style radios not found; radios present: {sorted(rs)}")
        before = (_flag(_axval(ax, rs["Color"])), _flag(_axval(ax, rs["Monochrome"])))
        ax.click_element_cg(rs["Monochrome"].id)
        time.sleep(SETTLE)
        after = tuple(_radio_flags(ax, w.id, ["Color", "Monochrome"]).values())
        screenshot_assert(
            "state_test_file_icon_style_monochrome",
            "CodeEdit Settings window, General pane. In the 'File Icon Style' radio pair the "
            "'Monochrome' radio button is now filled/selected and 'Color' is empty, so the "
            "file icons render in a single grey tone. The Appearance popup above still reads "
            "'System' and the Navigator Tab Bar Position pair below still has 'Top' selected.")
        assert kit.rb_flip(before, after) and before == (1, 0) and after == (0, 1), (
            f"File Icon Style selection did not move Color->Monochrome: "
            f"before={before} after={after}")

    @pytest.mark.rb(depth=1, jump_kind="transition",
                    expect="Navigator Tab Bar Position radio selection moves Top 1/Side 0 -> "
                           "Top 0/Side 1 after a CG click on 'Side'")
    def test_navigator_tab_bar_position_radio_moves_to_side(self, ax):
        w = rb_reach_settings_pane(ax, "General")
        assert w is not None, "Settings window / General pane not reachable"
        grp = _radio_group_for(ax, _pane_seq(ax, w.id),
                               "Navigator Tab Bar Position", ["Top", "Side"])
        assert grp is not None, "Navigator Tab Bar Position radio group not found"
        before = tuple(_radio_flags(ax, grp.id, ["Top", "Side"]).values())
        side = _radios(ax, grp.id).get("Side")
        assert side is not None, "no 'Side' radio inside the Navigator Tab Bar Position group"
        ax.click_element_cg(side.id)
        time.sleep(SETTLE)
        after = tuple(_radio_flags(ax, grp.id, ["Top", "Side"]).values())
        assert kit.rb_flip(before, after) and before == (1, 0) and after == (0, 1), (
            f"Navigator Tab Bar Position did not move Top->Side: before={before} after={after}")


# ── Popup buttons: selected value + option list ──────────────────────────────

class TestPopupState:

    @pytest.mark.rb(depth=1, jump_kind="transition",
                    expect="'Project Navigator Size' popup value flips Medium -> Large after "
                           "AXPress + AXPick on the 'Large' menu item")
    def test_project_navigator_size_popup_picks_large(self, ax):
        label = "Project Navigator Size"
        w = rb_reach_settings_pane(ax, "General")
        assert w is not None, "Settings window / General pane not reachable"
        pu = _popup_in(ax, _pane_seq(ax, w.id), label, w.id)
        assert pu is not None, f"no AXPopUpButton found for label {label!r}"
        before = _axval(ax, pu)
        assert popup_pick(ax, pu, "Large"), "'Large' option not offered by the popup menu"
        after = _axval(ax, _popup_in(ax, _pane_seq(ax, w.id), label, w.id))
        assert kit.rb_flip(before, after) and before == "Medium" and after == "Large", (
            f"'{label}' popup did not change Medium->Large: before={before!r} after={after!r}")

    @pytest.mark.rb(depth=1, jump_kind="transition",
                    expect="'Appearance' popup value flips System -> Dark after AXPress + "
                           "AXPick on the 'Dark' menu item")
    def test_appearance_popup_picks_dark(self, ax):
        label = "Appearance"
        w = rb_reach_settings_pane(ax, "General")
        assert w is not None, "Settings window / General pane not reachable"
        pu = _popup_in(ax, _pane_seq(ax, w.id), label, w.id)
        assert pu is not None, f"no AXPopUpButton found for label {label!r}"
        before = _axval(ax, pu)
        assert popup_pick(ax, pu, "Dark"), "'Dark' option not offered by the Appearance popup"
        after = _axval(ax, _popup_in(ax, _pane_seq(ax, w.id), label, w.id))
        assert kit.rb_flip(before, after) and before == "System" and after == "Dark", (
            f"'{label}' popup did not change System->Dark: before={before!r} after={after!r}")

    @pytest.mark.rb(depth=2, jump_kind="value",
                    expect="the Appearance popup's own menu (a second surface) lists exactly "
                           "System, Light, Dark")
    def test_appearance_popup_option_list(self, ax):
        w = rb_reach_settings_pane(ax, "General")
        assert w is not None, "Settings window / General pane not reachable"
        pu = _popup_in(ax, _pane_seq(ax, w.id), "Appearance", w.id)
        assert pu is not None, "no AXPopUpButton found for label 'Appearance'"
        observed = [str(o) for o in rb_enter_popup_options(ax, pu)]
        assert kit.rb_value(observed, ["System", "Light", "Dark"]), (
            f"Appearance popup options mismatch: observed={observed} "
            f"expected=['System', 'Light', 'Dark']")


# ── Segmented controls (AXRadioGroup of AXSegments) ──────────────────────────

class TestSegmentedControls:

    @pytest.mark.rb(depth=1, jump_kind="transition",
                    expect="Source Control segmented control flips General 1/Git 0 -> General "
                           "0/Git 1 and the pane content swaps in the Git fields (Author Name / "
                           "Author Email)")
    def test_source_control_segment_switches_to_git(self, ax):
        w = rb_reach_settings_pane(ax, "Source Control")
        assert w is not None, "Settings window / Source Control pane not reachable"
        seq = _pane_seq(ax, w.id)
        rs = _radios(ax, w.id)
        assert "General" in rs and "Git" in rs, (
            f"Source Control segments not found; radios present: {sorted(rs)}")
        before = (_flag(_axval(ax, rs["General"])), _flag(_axval(ax, rs["Git"])),
                  _has_text(ax, seq, "Author Name"))
        ax.click_element_cg(rs["Git"].id)
        time.sleep(SETTLE + 0.4)
        seq2 = _pane_seq(ax, w.id)
        flags = _radio_flags(ax, w.id, ["General", "Git"])
        after = (flags["General"], flags["Git"],
                 _has_text(ax, seq2, "Author Name") and _has_text(ax, seq2, "Author Email"))
        assert kit.rb_flip(before, after) and before == (1, 0, False) and after == (0, 1, True), (
            f"Source Control segment did not switch to Git: before={before} after={after}")



# ── Per-pane shipped default state (value) ───────────────────────────────────

class TestPaneDefaultState:

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Settings>Themes switches default to Automatically change theme "
                           "based on system appearance=1, Always use dark terminal "
                           "appearance=0, Use theme background=1")
    def test_themes_pane_switch_defaults(self, ax):
        w = rb_reach_settings_pane(ax, "Themes")
        assert w is not None, "Settings window / Themes pane not reachable"
        seq = _pane_seq(ax, w.id)
        expected = {
            "Automatically change theme based on system appearance": 1,
            "Always use dark terminal appearance": 0,
            # shipped label carries a trailing space — matched trim-tolerantly
            "Use theme background": 1,
        }
        observed = _switch_flags(ax, seq, list(expected), w.id)
        assert kit.rb_value(observed, expected), (
            f"Themes switch defaults mismatch: observed={observed} expected={expected}")

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Settings>Terminal defaults: Shell=System Default, Terminal Cursor "
                           "Style=Block, Use \"Option\" key as \"Meta\"=0, Use text editor "
                           "font=1, Blink Cursor=0, Shell Integration=1, Use Login Shell=1")
    def test_terminal_pane_control_defaults(self, ax):
        w = rb_reach_settings_pane(ax, "Terminal")
        assert w is not None, "Settings window / Terminal pane not reachable"
        seq = _pane_seq(ax, w.id)
        expected_sw = {
            "Use \"Option\" key as \"Meta\"": 0,
            "Use text editor font": 1,
            "Blink Cursor": 0,
            "Shell Integration": 1,
            "Use Login Shell": 1,
        }
        expected_pu = {"Shell": "System Default", "Terminal Cursor Style": "Block"}
        observed = dict(_switch_flags(ax, seq, list(expected_sw), w.id))
        observed.update(_popup_values(ax, seq, list(expected_pu), w.id))
        expected = dict(expected_sw)
        expected.update(expected_pu)
        assert kit.rb_value(observed, expected), (
            f"Terminal pane defaults mismatch: observed={observed} expected={expected}")


    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Settings>Source Control (General segment) defaults: Enable source "
                           "control=1, Show source control changes=1, the four automatic "
                           "switches=0, Include upstream changes=0 and Default branch name=main")
    def test_source_control_general_defaults(self, ax):
        w = rb_reach_settings_pane(ax, "Source Control")
        assert w is not None, "Settings window / Source Control pane not reachable"
        seq = _pane_seq(ax, w.id)
        expected_sw = {
            "Enable source control": 1,
            "Refresh local status automatically": 0,
            "Fetch and refresh server status automatically": 0,
            "Add and remove files automatically": 0,
            "Select files to commit automatically": 0,
            "Show source control changes": 1,
            "Include upstream changes": 0,
        }
        expected_pu = {"Comparison view": "Local Revision on Left Side",
                       "Source control navigator": "Sort by Name"}
        expected_fl = {"Default branch name": "main"}
        observed = dict(_switch_flags(ax, seq, list(expected_sw), w.id))
        observed.update(_popup_values(ax, seq, list(expected_pu), w.id))
        observed.update(_field_values(ax, seq, list(expected_fl)))
        expected = dict(expected_sw)
        expected.update(expected_pu)
        expected.update(expected_fl)
        assert kit.rb_value(observed, expected), (
            f"Source Control General defaults mismatch: observed={observed} "
            f"expected={expected}")


# ── Sidebar selection state (exactly one row AXSelected) ─────────────────────

class TestSelectionState:

    @pytest.mark.rb(depth=1, jump_kind="transition",
                    expect="Settings sidebar selection moves General -> Themes: exactly one "
                           "AXRow/AXCell is AXSelected at a time and the window title equals "
                           "the selected pane name")
    def test_settings_sidebar_selection_follows_pane(self, ax):
        w1 = rb_reach_settings_pane(ax, "General")
        assert w1 is not None, "Settings window / General pane not reachable"
        sel1 = _selected_rows(ax, w1.id)
        before = ((w1.name or ""), tuple(sel1))
        w2 = rb_reach_settings_pane(ax, "Themes")
        assert w2 is not None, "Settings window lost after selecting the Themes pane"
        sel2 = _selected_rows(ax, w2.id)
        after = ((w2.name or ""), tuple(sel2))
        ok_shape = (len(sel1) == 1 and len(sel2) == 1
                    and "General" in sel1[0] and "Themes" in sel2[0]
                    and (w1.name or "") == "General" and (w2.name or "") == "Themes")
        assert kit.rb_flip(before, after) and ok_shape, (
            f"Settings sidebar selection did not move General->Themes: "
            f"before={before} after={after}")


# ── Menu enabled-state at fresh launch (value, depth 0) ─────────────────────

class TestMenuEnabledState:

    @pytest.mark.rb(depth=0, jump_kind="value",
                    expect="at fresh launch all 6 Find menu items and all 10 Source Control "
                           "menu items report AXEnabled == False (no workspace / no repository)")
    def test_find_and_source_control_menu_items_disabled(self, ax):
        observed = {}
        for k, v in _menu_enabled(ax, "Find", FIND_MENU_ITEMS).items():
            observed[f"Find > {k}"] = v
        for k, v in _menu_enabled(ax, "Source Control", SOURCE_CONTROL_MENU_ITEMS).items():
            observed[f"Source Control > {k}"] = v
        expected = {k: False for k in observed}
        expected_full = {f"Find > {n}": False for n in FIND_MENU_ITEMS}
        expected_full.update({f"Source Control > {n}": False
                              for n in SOURCE_CONTROL_MENU_ITEMS})
        assert kit.rb_value(observed, expected_full), (
            f"fresh-launch disabled set mismatch: observed={observed} "
            f"expected={expected_full} (keys seen: {sorted(expected)})")

    @pytest.mark.rb(depth=0, jump_kind="value",
                    expect="File menu at fresh launch: Close Workspace and Workspace Settings "
                           "are AXEnabled False while New, Open... and Save are enabled")
    def test_file_menu_workspace_items_disabled_but_new_enabled(self, ax):
        items = ["New", "Open...", "Save", "Close Workspace", "Workspace Settings"]
        observed = _menu_enabled(ax, "File", items)
        expected = {"New": True, "Open...": True, "Save": True,
                    "Close Workspace": False, "Workspace Settings": False}
        assert kit.rb_value(observed, expected), (
            f"File menu enabled-state mismatch: observed={observed} expected={expected}")


# ── Focus + context-sensitive enablement behind a workspace (depth 2) ────────