File size: 46,714 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
#!/usr/bin/env python3
"""AX BUTTON tests for CodeEdit — generated from recon.md ``## BUTTONS``.

Every test drives a real push / toggle button and asserts the CONSEQUENCE recon
recorded for it (a surface appeared, a state flipped, a value changed) — never a bare
"it exists / it did not crash".

The only controls asserted by NAME + enabled-state (never pressed) are the ones recon
marks unsafe: Settings ▸ General ``Install`` / ``Check Now`` /
``Reset "Don't Ask Me" Warnings`` and the 4 Settings ▸ Locations path buttons (they open
Finder).  ``Contributors`` in the About window is network-backed and is never touched.

Interaction rules honoured (recon ▸ ENVIRONMENT CONSTRAINTS):
  * ``AXPress``             → menu items, push buttons, sheet buttons, window close buttons
  * ``ax.click_element_cg`` → Settings sidebar panes, workspace toolbar / tab buttons
  * ``ax.set_value``        → text fields (the clone-URL field)
  * panels & sheets are dismissed with their own Cancel button (Escape is a no-op here)
  * ``AXPress`` on ``Create New File...`` returns **False** while the modal Save panel comes
    up — the return value is ignored and the resulting surface is asserted instead.

Widgets are located by visible label (``AXTitle``/``AXDescription``) + ``AXRole`` scoped to
the owning window — never by child index or tree path — so a recreation that nests the
hierarchy differently still matches.
"""

# ── PRIMITIVES (copied 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


# ── module-local button helpers (semantic locators only) ────────────────────

CLONE_URL = "https://github.com/CodeEditApp/CodeEdit.git"

# The bundled dependency names recon observed in the Acknowledgements view.
ACK_DEPENDENCIES = [
    "AnyCodable", "ConcurrencyPlus", "FSEventsWrapper", "GRDB.swift", "GlobPattern",
    "JSONRPC", "LanguageClient", "LanguageServerProtocol", "LogStream", "ProcessEnv",
    "Queue", "Rearrange", "Semaphore", "Sparkle", "SwiftLintPlugin", "SwiftTerm",
    "SwiftTreeSitter", "SwiftUI-Introspect", "TextFormation", "TextStory",
    "collectionconcurrencykit", "swift-collections", "swift-snapshot-testing",
    "swift-syntax",
]

# Recon ▸ ENVIRONMENT CONSTRAINTS #6 — these must never be pressed.
FORBIDDEN_GENERAL_PANE_BUTTONS = {"Install", "Check Now", 'Reset "Don\'t Ask Me" Warnings'}
FORBIDDEN_TO_PRESS = FORBIDDEN_GENERAL_PANE_BUTTONS | {
    "Contributors", "Quit CodeEdit", "Close Workspace", "Discard All Changes...",
    "Check for updates...",
}


def norm_quotes(s):
    """Curly/straight quote-insensitive text (a recreation may render either form)."""
    if not isinstance(s, str):
        return ""
    return (s.replace("“", '"').replace("”", '"')
             .replace("‘", "'").replace("’", "'"))


def enabled_of(ax, el):
    return bool(ax.get(el.id, ["AXEnabled"]).get("AXEnabled"))


def control_named(ax, root_id, name, roles=("button", "radio", "tab", "checkbox")):
    """Locate a control by its VISIBLE LABEL (AXTitle/AXDescription) + AXRole, scoped to a
    window — never by child index / tree path / internal identifier. ONE tree walk (a role
    filter would not save any AX traffic), role preference honoured afterwards, so a
    recreation that renders a tab as an AXRadioButton still matches."""
    hits = {}
    for e in ax.find(root_id=root_id, max_results=900, max_depth=16):
        if (e.name or "") == name and e.role in roles:
            hits.setdefault(e.role, e)
    for role in roles:
        if role in hits:
            return hits[role]
    return None


def labelled(showing, text):
    """True iff any `role|name` key in a kit.rb_showing() snapshot ends with `|text`
    (role-agnostic: a recreation may host the same label under a different role)."""
    return any(k.endswith("|" + text) for k in showing)


def popup_labels_in(ax, root_id):
    """Title-or-value of every AXPopUpButton under root (popups label themselves either way)."""
    out = []
    for p in ax.find(role="popup", root_id=root_id, max_results=40, max_depth=16):
        out.append((p.name or "") or str(ax.get(p.id, ["AXValue"]).get("AXValue") or ""))
    return out


def rb_reach_acknowledgements(ax, about_win):
    """About window ▸ press `Acknowledgements` — a real second surface (the copyright view
    is replaced by the bundled-dependency list)."""
    bs = buttons_named(ax, about_win.id, "Acknowledgements")
    if not bs:
        return False
    ax.action(bs[0].id, "AXPress")
    time.sleep(1.6)
    return True


def rb_reach_workspace_tab(ax, ws, tab_name, tab=None, wait=1.6):
    """Workspace ▸ switch navigator / utility-area tab. Recon: workspace tab buttons need a
    REAL CG click (AXPress is a no-op for them). `tab` may be pre-located to save a walk."""
    tab = tab if tab is not None else control_named(ax, ws.id, tab_name)
    if tab is None:
        return None
    ax.click_element_cg(tab.id)
    time.sleep(wait)
    return tab


def cg_click(ax, el, wait=1.4):
    ax.click_element_cg(el.id)
    time.sleep(wait)


# ───────────────────────── Welcome window buttons ─────────────────────────

class TestWelcomeWindowButtons:
    """The 4 buttons recon recorded on `AXWindow id='welcome'`."""

    @pytest.mark.rb(depth=1, jump_kind="reach",
                    expect="pressing 'Create New File...' brings up the modal Save panel — a "
                           "window titled 'Save' carrying Save and Cancel buttons")
    def test_create_new_file_opens_save_panel(self, ax):
        w = rb_enter_welcome(ax)
        assert w is not None, "welcome window not present at launch"
        btn = control_named(ax, w.id, "Create New File...")
        assert btn is not None, "no button labelled 'Create New File...' on the welcome window"
        assert btn.name == "Create New File...", "the button must expose its label via AX"
        assert btn.actions, f"'Create New File...' exposes no AX actions: {btn.actions}"
        assert "AXPress" in btn.actions, f"'Create New File...' has no AXPress: {btn.actions}"

        before = kit.rb_showing(ax)
        # AXPress returns False while the modal panel comes up — recon says IGNORE it and
        # assert the resulting surface instead.
        panel = rb_enter_save_panel(ax)
        after = kit.rb_showing(ax)

        assert panel is not None, "no 'Save' panel appeared after pressing 'Create New File...'"
        assert kit.rb_reach(before, after, target="window|Save"), (
            "the Save panel window did not appear in the AX tree")
        panel_buttons = names_in(ax, panel.id, role="button", max_results=200, max_depth=12)
        assert "Save" in panel_buttons, f"Save panel has no Save button: {panel_buttons[:12]}"
        assert "Cancel" in panel_buttons, f"Save panel has no Cancel button: {panel_buttons[:12]}"
        dismiss_panel_or_sheet(ax)

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="the Save panel opened by 'Create New File...' pre-fills its "
                           "'Save As:' text field with exactly 'Untitled'")
    def test_create_new_file_save_panel_default_name(self, ax):
        panel = rb_enter_save_panel(ax)
        assert panel is not None, "'Create New File...' did not open the Save panel"
        fields = ax.find(role="text_field", root_id=panel.id, max_results=10, max_depth=12)
        values = [ax.get(t.id, ["AXValue"]).get("AXValue") for t in fields]
        assert kit.rb_value(values, "Untitled"), (
            f"the Save panel's default file name is not 'Untitled': {values}")
        labels = values_in(ax, panel.id, max_results=160, max_depth=12)
        assert any("Save As" in str(v) for v in labels), (
            f"the Save panel shows no 'Save As:' label: {labels[:14]}")
        dismiss_panel_or_sheet(ax)

    @pytest.mark.rb(depth=1, jump_kind="reach",
                    expect="pressing 'Clone Git Repository...' raises an AXSheet reading "
                           "'Clone a repository' with a URL field, Cancel, and a DISABLED Clone")
    def test_clone_git_repository_opens_sheet(self, ax):
        w = rb_enter_welcome(ax)
        assert w is not None, "welcome window not present at launch"
        btn = control_named(ax, w.id, "Clone Git Repository...")
        assert btn is not None, "no button labelled 'Clone Git Repository...'"
        assert "AXPress" in btn.actions, f"'Clone Git Repository...' has no AXPress: {btn.actions}"

        before = kit.rb_showing(ax)
        sheet = rb_enter_clone_sheet(ax)
        after = kit.rb_showing(ax)

        assert sheet is not None, "no AXSheet appeared after pressing 'Clone Git Repository...'"
        assert kit.rb_reach(before, after, target="Clone a repository"), (
            "the 'Clone a repository' sheet content did not appear")
        sheet_buttons = names_in(ax, sheet.id, role="button", max_results=60, max_depth=12)
        assert "Clone" in sheet_buttons, f"the clone sheet has no Clone button: {sheet_buttons}"
        assert "Cancel" in sheet_buttons, f"the clone sheet has no Cancel button: {sheet_buttons}"
        clone = control_named(ax, sheet.id, "Clone")
        assert clone is not None, "the clone sheet's 'Clone' button is not reachable via AX"
        assert not enabled_of(ax, clone), "Clone must start DISABLED while the URL field is empty"
        screenshot_assert(
            "button_test_clone_sheet",
            "CodeEdit welcome window (centred 740x460 panel, large app icon, 'CodeEdit' and "
            "'Version 0.3.1 (42)') with a modal sheet dropped over it: heading 'Clone a "
            "repository', the prompt 'Enter a git repository URL:', an empty single-line URL "
            "text field, and two buttons at the bottom right — 'Cancel' and a greyed-out "
            "(disabled) 'Clone'.")
        dismiss_panel_or_sheet(ax)

    @pytest.mark.rb(depth=1, jump_kind="reach",
                    expect="pressing 'Open File or Folder...' replaces the welcome window with "
                           "the modal 'Open Workspace or File' panel in the AX window list")
    def test_open_file_or_folder_opens_open_panel(self, ax):
        w = rb_enter_welcome(ax)
        assert w is not None, "welcome window not present at launch"
        btn = control_named(ax, w.id, "Open File or Folder...")
        assert btn is not None, "no button labelled 'Open File or Folder...'"
        assert "AXPress" in btn.actions, f"'Open File or Folder...' has no AXPress: {btn.actions}"

        before = kit.rb_showing(ax)
        panel = rb_enter_open_panel(ax)
        after = kit.rb_showing(ax)

        assert panel is not None, "no 'Open Workspace or File' panel appeared"
        assert kit.rb_reach(before, after,
                            target="window|Open Workspace or File",
                            source="window|Welcome To CodeEdit"), (
            "the open panel did not replace the welcome window in the AX window list")
        panel_buttons = names_in(ax, panel.id, role="button", max_results=200, max_depth=12)
        assert "Open" in panel_buttons, f"the open panel has no Open button: {panel_buttons[:14]}"
        assert "Cancel" in panel_buttons, f"the open panel has no Cancel button: {panel_buttons[:14]}"
        dismiss_panel_or_sheet(ax)

    @pytest.mark.rb(depth=0, jump_kind="transition",
                    expect="pressing the welcome window's 'Close' button removes "
                           "'Welcome To CodeEdit' from the app's AX window list")
    def test_welcome_close_button_removes_window(self, ax):
        w = rb_enter_welcome(ax)
        assert w is not None, "welcome window not present at launch"
        btn = control_named(ax, w.id, "Close")
        assert btn is not None, "the welcome window has no button labelled 'Close'"
        assert "AXPress" in btn.actions, f"'Close' has no AXPress action: {btn.actions}"

        before = sorted(x.name or "" for x in all_windows(ax))
        ax.action(btn.id, "AXPress")
        time.sleep(1.2)
        after = sorted(x.name or "" for x in all_windows(ax))

        assert kit.rb_flip(before, after, "welcome window closed"), (
            f"the window list did not change after pressing Close: {before}")
        assert "Welcome To CodeEdit" in before, f"welcome window missing before Close: {before}"
        assert "Welcome To CodeEdit" not in after, (
            f"the welcome window is still listed after pressing Close: {after}")


# ───────────────────────── Clone sheet buttons (depth 1) ─────────────────────────

class TestCloneSheetButtons:
    """Buttons on the AXSheet raised by the welcome `Clone Git Repository...` button."""

    @pytest.mark.rb(depth=1, jump_kind="transition",
                    expect="the clone sheet's 'Clone' button flips AXEnabled False -> True once "
                           "a git repository URL is entered in the sheet's text field")
    def test_clone_button_enables_once_url_entered(self, ax):
        sheet = rb_enter_clone_sheet(ax)
        assert sheet is not None, "'Clone Git Repository...' did not raise the clone sheet"
        clone = control_named(ax, sheet.id, "Clone")
        assert clone is not None, "the clone sheet has no button labelled 'Clone'"
        assert clone.actions, "'Clone' exposes no AX actions"
        before = enabled_of(ax, clone)

        fields = ax.find(role="text_field", root_id=sheet.id, max_results=5, max_depth=10)
        assert fields, "the clone sheet exposes no AXTextField for the git URL"
        ax.set_value(fields[0].id, CLONE_URL)
        time.sleep(1.2)

        clone_after = control_named(ax, sheet.id, "Clone")
        assert clone_after is not None, "the 'Clone' button vanished after entering the URL"
        after = enabled_of(ax, clone_after)

        assert kit.rb_flip(before, after, "Clone enabled-state"), (
            f"Clone's enabled-state did not change (before={before}, after={after})")
        assert before is False, "Clone must be DISABLED while the URL field is empty"
        assert after is True, "Clone must become ENABLED once a valid git URL is entered"
        dismiss_panel_or_sheet(ax)

    @pytest.mark.rb(depth=1, jump_kind="transition",
                    expect="pressing the clone sheet's 'Cancel' takes the AXSheet count 1 -> 0 "
                           "and the 'Clone a repository' text disappears")
    def test_clone_sheet_cancel_dismisses_sheet(self, ax):
        sheet = rb_enter_clone_sheet(ax)
        assert sheet is not None, "'Clone Git Repository...' did not raise the clone sheet"
        cancel = control_named(ax, sheet.id, "Cancel")
        assert cancel is not None, "the clone sheet has no button labelled 'Cancel'"
        assert "AXPress" in cancel.actions, f"'Cancel' has no AXPress action: {cancel.actions}"

        before = len(ax.find(role="sheet", max_results=5, max_depth=6))
        ax.action(cancel.id, "AXPress")
        time.sleep(1.2)
        after = len(ax.find(role="sheet", max_results=5, max_depth=6))

        assert kit.rb_flip(before, after, "sheet count"), (
            f"the sheet count did not change after Cancel (before={before}, after={after})")
        assert before == 1, f"expected exactly 1 sheet before Cancel, saw {before}"
        assert after == 0, f"the clone sheet is still up after Cancel ({after} sheets)"
        w = find_window(ax, ident="welcome", timeout=4)
        assert w is not None, "the welcome window did not come back after cancelling the sheet"
        assert not any("Clone a repository" in str(v)
                       for v in values_in(ax, w.id, max_results=160, max_depth=12)), (
            "'Clone a repository' text is still present after Cancel")


# ───────────────────────── About window buttons (depth 2) ─────────────────────────

class TestAboutWindowButtons:
    """`Acknowledgements` swaps the About window's content. `Contributors` is network-backed
    (recon ▸ UNREACHED) and is never pressed."""

    @pytest.mark.rb(depth=2, jump_kind="reach",
                    expect="About ▸ 'Acknowledgements' swaps the copyright view for the bundled "
                           "dependency list: 'Sparkle' appears and 'Copyright ©' disappears")
    def test_acknowledgements_button_reveals_dependency_list(self, ax):
        w = rb_enter_about_window(ax)
        assert w is not None, "'CodeEdit > About CodeEdit' did not open the About window"
        btn = control_named(ax, w.id, "Acknowledgements")
        assert btn is not None, "the About window has no button labelled 'Acknowledgements'"
        assert "AXPress" in btn.actions, f"'Acknowledgements' has no AXPress: {btn.actions}"
        assert "Contributors" in names_in(ax, w.id, role="button", max_results=60, max_depth=12), (
            "the About window should also offer a 'Contributors' button (never pressed here)")

        before = kit.rb_showing(ax, max_depth=14)
        assert rb_reach_acknowledgements(ax, w), "pressing 'Acknowledgements' failed"
        after = kit.rb_showing(ax, max_depth=14)

        assert kit.rb_reach(before, after, target="Sparkle", source="Copyright ©"), (
            "the Acknowledgements view did not replace the copyright view")

    @pytest.mark.rb(depth=2, jump_kind="value",
                    expect="the Acknowledgements view lists the bundled dependencies AnyCodable, "
                           "Sparkle, SwiftTerm and swift-syntax (>=10 of the 24 recon recorded)")
    def test_acknowledgements_lists_bundled_dependencies(self, ax):
        w = rb_enter_about_window(ax)
        assert w is not None, "'CodeEdit > About CodeEdit' did not open the About window"
        assert rb_reach_acknowledgements(ax, w), "pressing 'Acknowledgements' failed"

        seen = (values_in(ax, w.id, max_results=400, max_depth=16)
                + names_in(ax, w.id, max_results=400, max_depth=16))
        for dep in ("AnyCodable", "Sparkle", "SwiftTerm", "swift-syntax"):
            assert kit.rb_value(seen, dep), (
                f"dependency {dep!r} is missing from the Acknowledgements view")
        found = [d for d in ACK_DEPENDENCIES if any(d == str(s) for s in seen)]
        assert len(found) >= 10, (
            f"only {len(found)} of the {len(ACK_DEPENDENCIES)} bundled dependencies are "
            f"listed: {found}")


# ───────────────────────── Extensions toolbar toggle button ─────────────────────────

class TestExtensionsToolbarButton:

    @pytest.mark.rb(depth=1, jump_kind="transition",
                    expect="the Extensions toolbar toggle renames 'Hide Sidebar' -> "
                           "'Show Sidebar' (splitter 140.0 -> -1.0) and pressing it again "
                           "restores 'Hide Sidebar'")
    def test_hide_sidebar_toolbar_button_toggles(self, ax):
        w = rb_enter_extensions_window(ax)
        assert w is not None, "'Extensions > Open Extensions Window' did not open the window"
        btn = control_named(ax, w.id, "Hide Sidebar")
        assert btn is not None, "the Extensions toolbar has no 'Hide Sidebar' button"
        assert btn.name, "toolbar buttons must carry a descriptive accessibility label"
        assert "AXPress" in btn.actions, f"'Hide Sidebar' has no AXPress action: {btn.actions}"

        def state():
            names = names_in(ax, w.id, role="button", max_results=80, max_depth=14)
            splits = [ax.get(s.id, ["AXValue"]).get("AXValue")
                      for s in ax.find(role="splitter", root_id=w.id,
                                       max_results=5, max_depth=14)]
            return ("Hide Sidebar" in names, "Show Sidebar" in names, splits)

        before = state()
        ax.action(btn.id, "AXPress")
        time.sleep(1.4)
        after = state()

        assert kit.rb_flip(before, after, "sidebar toolbar toggle"), (
            f"nothing changed after pressing 'Hide Sidebar' (state={before})")
        assert before[0] and not before[1], f"expected 'Hide Sidebar' initially: {before}"
        assert after[1], f"the toolbar button did not rename to 'Show Sidebar': {after}"
        assert not after[0], f"'Hide Sidebar' is still shown after collapsing: {after}"
        screenshot_assert(
            "button_test_extensions_hide_sidebar",
            "CodeEdit 'Extensions' window (split view) after its toolbar sidebar toggle was "
            "pressed: the empty left sidebar list is collapsed away, the toolbar button now "
            "reads 'Show Sidebar', and the right pane still shows the placeholder text "
            "'Select an extension'.")

        # toggle back off — recon: "Pressing again restores."
        back = control_named(ax, w.id, "Show Sidebar")
        assert back is not None, "'Show Sidebar' is not available to toggle the sidebar back"
        ax.action(back.id, "AXPress")
        time.sleep(1.4)
        restored = state()
        assert kit.rb_flip(after, restored, "sidebar toolbar toggle back"), (
            f"pressing 'Show Sidebar' changed nothing (state={after})")
        assert restored[0], f"'Hide Sidebar' did not come back after re-showing: {restored}"


# ───────────────────────── Settings window buttons ─────────────────────────

class TestSettingsPaneButtons:
    """Sidebar pane rows are selected with a REAL CG click (recon: AXPress does not select).
    The `Install` / `Check Now` / `Reset "Don't Ask Me" Warnings` buttons and the Locations
    path buttons are asserted by name + enabled-state ONLY — never pressed."""

    @pytest.mark.rb(depth=2, jump_kind="reach",
                    expect="the Accounts sidebar pane replaces the General pane and shows "
                           "'No accounts' next to an enabled 'Add Account...' button")
    def test_accounts_pane_add_account_button(self, ax):
        w = rb_enter_settings_window(ax)
        assert w is not None, "'CodeEdit > Settings...' did not open the Settings window"
        before = kit.rb_showing(ax, max_depth=16)
        pane = rb_reach_settings_pane(ax, "Accounts")
        after = kit.rb_showing(ax, max_depth=16)

        assert pane is not None, "could not select the 'Accounts' sidebar pane"
        assert kit.rb_reach(before, after, target="No accounts", source="File Icon Style"), (
            "the Accounts pane content did not replace the General pane content")
        add = control_named(ax, pane.id, "Add Account...")
        assert add is not None, "the Accounts pane has no 'Add Account...' button"
        assert add.actions, "'Add Account...' exposes no AX actions"
        assert enabled_of(ax, add), "'Add Account...' should be enabled"


    @pytest.mark.rb(depth=2, jump_kind="reach",
                    expect="the Search sidebar pane replaces the General pane and shows "
                           "'No excluded glob patterns' with its 'Add' and 'Remove' buttons")
    def test_search_pane_add_and_remove_buttons(self, ax):
        w = rb_enter_settings_window(ax)
        assert w is not None, "'CodeEdit > Settings...' did not open the Settings window"
        before = kit.rb_showing(ax, max_depth=16)
        pane = rb_reach_settings_pane(ax, "Search")
        after = kit.rb_showing(ax, max_depth=16)

        assert pane is not None, "could not select the 'Search' sidebar pane"
        assert kit.rb_reach(before, after,
                            target="No excluded glob patterns", source="File Icon Style"), (
            "the Search pane content did not replace the General pane content")
        add = control_named(ax, pane.id, "Add")
        rem = control_named(ax, pane.id, "Remove")
        assert add is not None, "the Search pane has no 'Add' button"
        assert rem is not None, "the Search pane has no 'Remove' button"
        assert add.actions and rem.actions, "the Add/Remove buttons expose no AX actions"
        assert enabled_of(ax, add), "'Add' should be enabled on the Search pane"


    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="the Locations pane's 4 path buttons are named "
                           "'<Application Support|Settings|Themes|Extensions>, <path>', are all "
                           "enabled, and every path points inside "
                           "Library/Application Support/CodeEdit "
                           "(recon: never press — they open Finder)")
    def test_locations_pane_path_button_names(self, ax):
        pane = rb_reach_settings_pane(ax, "Locations")
        assert pane is not None, "could not reach the Settings 'Locations' pane"
        buttons = [b for b in ax.find(role="button", root_id=pane.id,
                                      max_results=300, max_depth=16) if b.name]
        names = [b.name for b in buttons]
        for label in ("Application Support", "Settings", "Themes", "Extensions"):
            hit = [b for b in buttons if b.name.startswith(label + ", ")]
            assert hit, (
                f"the Locations pane has no '{label}, <path>' button; "
                f"saw {sorted(set(names))[:14]}")
            path = hit[0].name.replace("%20", " ")
            assert kit.rb_value(path, "Library/Application Support/CodeEdit"), (
                f"the '{label}' path button does not point inside the app-support folder: "
                f"{hit[0].name!r}")
            assert enabled_of(ax, hit[0]), f"the '{label}' path button should be enabled"


# ───────────────────── Workspace toolbar buttons (CG clicks) ─────────────────────

class TestWorkspaceToolbarButtons:

    @pytest.mark.rb(depth=1, jump_kind="transition",
                    expect="the workspace toolbar 'Navigator Sidebar' button collapses the "
                           "navigator: the Project Navigator outline and the Project / "
                           "Source Control / Search tab buttons all disappear")
    def test_navigator_sidebar_button_hides_navigator(self, ax):
        ws = rb_enter_workspace(ax)
        assert ws is not None, "the fixture folder did not open as a workspace window"
        btn = control_named(ax, ws.id, "Navigator Sidebar")
        assert btn is not None, "the workspace toolbar has no 'Navigator Sidebar' button"
        assert btn.name, "toolbar buttons must carry a descriptive accessibility label"
        assert btn.actions, "'Navigator Sidebar' exposes no AX actions"

        def state():
            return (project_navigator(ax, ws) is not None,
                    control_named(ax, ws.id, "Source Control") is not None)

        before = state()
        cg_click(ax, btn)
        after = state()

        assert kit.rb_flip(before, after, "navigator visibility"), (
            f"the navigator did not change after clicking 'Navigator Sidebar' ({before})")
        assert before == (True, True), f"the navigator should start visible: {before}"
        assert after == (False, False), (
            f"the navigator outline / tab buttons are still present after collapsing: {after}")



# ───────────────────── Workspace navigator tab buttons (CG clicks) ─────────────────────

class TestWorkspaceNavigatorTabButtons:

    @pytest.mark.rb(depth=2, jump_kind="reach",
                    expect="the navigator 'Source Control' tab button replaces the Project "
                           "Navigator with 'No Repository', 'This project is not a git "
                           "repository.' and an 'Initialize' button")
    def test_source_control_tab_button(self, ax):
        ws = rb_enter_workspace(ax)
        assert ws is not None, "the fixture folder did not open as a workspace window"
        tab = control_named(ax, ws.id, "Source Control")
        assert tab is not None, "the navigator has no 'Source Control' tab button"
        assert tab.name, "navigator tab buttons must carry a descriptive label"
        assert tab.actions, "the 'Source Control' tab exposes no AX actions"

        before = kit.rb_showing(ax, max_depth=16)
        assert rb_reach_workspace_tab(ax, ws, "Source Control", tab=tab) is not None, (
            "could not click the 'Source Control' navigator tab")
        after = kit.rb_showing(ax, max_depth=16)

        assert kit.rb_reach(before, after,
                            target="No Repository", source="outline|Project Navigator"), (
            "the Source Control navigator did not replace the Project Navigator")
        seen = values_in(ax, ws.id, max_results=300, max_depth=16)
        assert any("not a git repository" in str(v) for v in seen), (
            "the Source Control navigator does not explain that this is not a git repository")
        assert control_named(ax, ws.id, "Initialize") is not None, (
            "the Source Control navigator has no 'Initialize' button")

    @pytest.mark.rb(depth=2, jump_kind="reach",
                    expect="the navigator 'Search' tab button reveals the find-scope popups "
                           "'Find', 'Text' and 'Containing'")
    def test_search_tab_button(self, ax):
        ws = rb_enter_workspace(ax)
        assert ws is not None, "the fixture folder did not open as a workspace window"
        tab = control_named(ax, ws.id, "Search")
        assert tab is not None, "the navigator has no 'Search' tab button"
        assert tab.name, "navigator tab buttons must carry a descriptive label"
        assert tab.actions, "the 'Search' tab exposes no AX actions"

        before = kit.rb_showing(ax, max_depth=16)
        assert rb_reach_workspace_tab(ax, ws, "Search", tab=tab) is not None, (
            "could not click the 'Search' navigator tab")
        after = kit.rb_showing(ax, max_depth=16)

        assert kit.rb_reach(before, after, target="Containing"), (
            "the search navigator's 'Containing' scope popup did not appear")
        labels = popup_labels_in(ax, ws.id)
        for expected in ("Find", "Text", "Containing"):
            assert any(expected in p for p in labels), (
                f"the search navigator popup {expected!r} is missing; saw {labels}")

    @pytest.mark.rb(depth=2, jump_kind="value",
                    expect="clicking the navigator 'Project' tab after 'Source Control' brings "
                           "the Project Navigator back listing sample_project, src, README.md, "
                           "hello.py and notes.txt")
    def test_project_tab_button_restores_file_rows(self, ax):
        ws = rb_enter_workspace(ax)
        assert ws is not None, "the fixture folder did not open as a workspace window"
        assert rb_reach_workspace_tab(ax, ws, "Source Control") is not None, (
            "could not click the 'Source Control' navigator tab")
        assert project_navigator(ax, ws) is None, (
            "the Project Navigator is still shown while on the Source Control tab")

        project = control_named(ax, ws.id, "Project")
        assert project is not None, "the navigator has no 'Project' tab button"
        assert project.actions, "the 'Project' tab exposes no AX actions"
        assert rb_reach_workspace_tab(ax, ws, "Project", tab=project) is not None, (
            "could not click the 'Project' navigator tab")

        assert project_navigator(ax, ws) is not None, (
            "the Project Navigator did not come back after clicking the 'Project' tab")
        rows = [r for r in navigator_rows(ax, ws) if r]
        for name in ("sample_project", "src", "README.md", "hello.py", "notes.txt"):
            assert kit.rb_value(rows, name), (
                f"the project-navigator row {name!r} is missing after returning to the "
                f"Project tab: {rows}")


# ───────────────────── Workspace utility-area tab buttons (CG clicks) ─────────────────────

class TestWorkspaceUtilityTabButtons:

    @pytest.mark.rb(depth=2, jump_kind="reach",
                    expect="the utility-area 'Debug Console' tab button replaces the terminal "
                           "with 'No Task Selected' / 'No Tasks are Running'")
    def test_debug_console_tab_button(self, ax):
        ws = rb_enter_workspace(ax)
        assert ws is not None, "the fixture folder did not open as a workspace window"
        tab = control_named(ax, ws.id, "Debug Console")
        assert tab is not None, "the utility area has no 'Debug Console' tab button"
        assert tab.name, "utility-area tab buttons must carry a descriptive label"
        assert tab.actions, "the 'Debug Console' tab exposes no AX actions"

        before = kit.rb_showing(ax, max_depth=16)
        assert rb_reach_workspace_tab(ax, ws, "Debug Console", tab=tab) is not None, (
            "could not click the 'Debug Console' utility tab")
        after = kit.rb_showing(ax, max_depth=16)

        assert kit.rb_reach(before, after, target="No Task Selected"), (
            "the Debug Console pane did not appear after clicking its tab")
        seen = values_in(ax, ws.id, max_results=300, max_depth=16)
        assert any("No Tasks are Running" in str(v) for v in seen), (
            "the Debug Console does not report 'No Tasks are Running'")

    @pytest.mark.rb(depth=2, jump_kind="value",
                    expect="the utility-area 'Output' tab button shows the empty output view: "
                           "the exact placeholder 'No output' plus an 'Output Source' popup")
    def test_output_tab_button(self, ax):
        ws = rb_enter_workspace(ax)
        assert ws is not None, "the fixture folder did not open as a workspace window"
        tab = control_named(ax, ws.id, "Output")
        assert tab is not None, "the utility area has no 'Output' tab button"
        assert tab.name, "utility-area tab buttons must carry a descriptive label"
        assert tab.actions, "the 'Output' tab exposes no AX actions"

        assert rb_reach_workspace_tab(ax, ws, "Output", tab=tab) is not None, (
            "could not click the 'Output' utility tab")

        seen = values_in(ax, ws.id, max_results=300, max_depth=16)
        assert kit.rb_value(seen, "No output"), (
            f"the Output pane does not show the 'No output' placeholder: {seen[:16]}")
        labels = popup_labels_in(ax, ws.id)
        assert kit.rb_value(labels, "Output Source"), (
            f"the Output pane has no 'Output Source' popup; saw {labels}")