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
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
"""test_ax_text.py — TEXT-CONTENT lane for CodeEdit (AX behavioural recreation tests).

Every expected string below was OBSERVED on the reference app and recorded in
recon.md's `## TEXT` / `## AX_TREE` / `## VISUAL` sections. Nothing is read from source.

Locators are semantic (AXTitle/AXDescription + AXRole, or visible-text match scoped to a
named container) — never child indexes or tree paths — so the same test drives the
reference app and a recreation written in a different framework.

pytest only: Test* classes, the `ax` fixture, plain asserts, `@pytest.mark.rb(...)`
declarations. No argparse, no __main__, no self-written results JSON.
"""

# ─────────────────────────── 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 (verbatim) ─────────────────────────


SHOW_DEPTH = 14  # kit.rb_showing() depth; unioned with showing_texts() for the deep labels


# ── TEXT-lane verdict wrappers (tier3 `value`; names match rb_value* so the audit sees them) ──
def rb_value_present(observed_strings, expected):
    """EXACT-string value verdict: `expected` is exactly one of the observed strings."""
    obs = [o for o in (observed_strings or []) if isinstance(o, str)]
    hit = expected if expected in obs else None
    return kit.rb_value(hit, expected)


def rb_value_all_present(observed_strings, expected_items):
    """Every exact expected string must be observed (extra widgets are allowed)."""
    return all(rb_value_present(observed_strings, e) for e in expected_items)


def rb_value_at_least(observed_strings, expected_items, minimum):
    """At least `minimum` of the exact expected strings are observed (bundled lists)."""
    obs = [o for o in (observed_strings or []) if isinstance(o, str)]
    hits = [e for e in expected_items if e in obs]
    return kit.rb_value(len(hits) >= minimum, True)


def missing_of(observed_strings, expected_items):
    obs = [o for o in (observed_strings or []) if isinstance(o, str)]
    return [e for e in expected_items if e not in obs]


# ── local text readers / nav helpers ──
def texts_in(ax, root_id):
    """All AX text a surface exposes: AXValue strings + AXTitle/AXDescription names."""
    return values_in(ax, root_id) + names_in(ax, root_id)


def window_title(ax, w):
    return ax.get(w.id, ["AXTitle"]).get("AXTitle") or (w.name or "")


def wait_for_texts(ax, root_id, expected, timeout=6.0, reader=None):
    """Poll a surface until every `expected` exact string is readable (async content such as
    the spawned terminal row appears a beat after the window). Returns the last reading."""
    read = reader or texts_in
    end = time.time() + timeout
    obs = read(ax, root_id)
    while True:
        if not missing_of(obs, expected) or time.time() >= end:
            return obs
        time.sleep(0.4)
        obs = read(ax, root_id)


def ensure_app_ui(ax, timeout=6.0):
    """Reveal the app UI without betting on ONE path. CodeEdit shows the welcome window on
    every fresh launch, so this is normally an immediate no-op; if some other agent closed
    it, re-open via `Window > Welcome to CodeEdit`, then fall back to ax_helpers' reveal."""
    end = time.time() + timeout
    while time.time() < end:
        if all_windows(ax):
            return True
        rb_enter_menu_item(ax, "Window", "Welcome to CodeEdit", wait=1.0)
        if all_windows(ax):
            return True
        try:
            ax.ensure_ui_visible()
        except Exception:
            pass
        time.sleep(0.5)
    return bool(all_windows(ax))


def rb_enter_acknowledgements(ax):
    """depth 2: home -> About window -> Acknowledgements dependency list."""
    w = rb_enter_about_window(ax)
    if w is None:
        return None
    bs = buttons_named(ax, w.id, "Acknowledgements")
    if not bs:
        return None
    ax.action(bs[0].id, "AXPress")
    time.sleep(1.6)
    return find_window(ax, ident="about", timeout=4) or w


def navigator_group(ax, ws):
    for g in ax.find(role="group", root_id=ws.id, max_results=80, max_depth=14):
        if (g.name or "") == "navigator":
            return g
    return None


def rb_reach_navigator_tab(ax, ws, tab_name):
    """CG-click a workspace navigator tab (Project / Source Control / Search)."""
    grp = navigator_group(ax, ws)
    bs = buttons_named(ax, grp.id, tab_name) if grp is not None else []
    if not bs:
        bs = buttons_named(ax, ws.id, tab_name)
    if not bs:
        return None
    ax.click_element_cg(bs[0].id)
    time.sleep(1.4)
    return find_window(ax, ident="workspace", timeout=3) or ws


def tab_bar_labels(ax, ws):
    """Text shown in the editor Tab Bar. Primary locator: the container whose visible name
    is 'Tab Bar'. Fallback (different hierarchy in a recreation): every AXStaticText value
    in the workspace — the navigator rows are AXTextFields, so they are not confused with
    tab labels."""
    for sa in ax.find(root_id=ws.id, max_results=200, max_depth=16):
        if (sa.name or "") == "Tab Bar":
            return values_in(ax, sa.id, max_results=80, max_depth=12)
    return [ax.get(t.id, ["AXValue"]).get("AXValue")
            for t in ax.find(role="label", root_id=ws.id, max_results=120, max_depth=18)]


def editor_text(ax, ws):
    tas = ax.find(role="text_area", root_id=ws.id, max_results=5, max_depth=18)
    if not tas:
        return None
    return ax.get(tas[0].id, ["AXValue"]).get("AXValue")


def showing_texts(ax, root_id):
    """A `role|text` snapshot set of one surface, built from AXValue AND AXTitle/AXDescription.
    Unioned with kit.rb_showing() so a reach verdict stays valid even when a recreation nests
    the same labels at a different tree depth."""
    out = set()
    for e in ax.find(root_id=root_id, max_results=800, max_depth=18):
        role = e.role or ""
        if e.name:
            out.add(f"{role}|{e.name}")
        v = ax.get(e.id, ["AXValue"]).get("AXValue")
        if isinstance(v, str) and v.strip():
            out.add(f"{role}|{v}")
    return out


# ── expected content, verbatim from recon.md ## TEXT ──
WELCOME_LABELS = ["CodeEdit", "Version 0.3.1 (42)", "No Recent Projects"]
WELCOME_BUTTONS = ["Create New File...", "Clone Git Repository...",
                   "Open File or Folder...", "Close"]
VERSION_HELP = "Copy System Information to Clipboard"
COPYRIGHT = "Copyright © 2022-2024 CodeEdit"

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",
]

SETTINGS_PANES = ["General", "Accounts", "Navigation", "Themes", "Text Editing",
                  "Terminal", "Search", "Source Control", "Locations"]

GENERAL_LABELS = [
    "Appearance", "File Icon Style", "Show Path Bar", "Dim editors without focus",
    "Navigator Tab Bar Position", "Inspector Tab Bar Position", "Show Issues",
    "Show Live Issues", "Automatically save changes to disk",
    "Automatically reveal in project navigator", "Reopen Behavior",
    "After the last window is closed", "File Extensions", "Project Navigator Size",
    "Find Navigator Detail", "Issue Navigator Detail",
    # curly quotes — the app uses U+201C / U+201D here
    "Show “Open With CodeEdit” option in Finder",
    "'codeedit' Shell Command", "Dialog Warnings", "Check for updates",
    "Last checked: Never",
]

THEMES_SWITCH_LABELS = [
    "Automatically change theme based on system appearance",
    "Always use dark terminal appearance",
    "Use theme background ",          # NOTE: the app's label has a TRAILING SPACE
]
THEME_NAMES = [
    "Presentation (Light)", "Classic (Light)", "Low Key", "Sunset", "GitHub (Light)",
    "High Contrast (Light)", "Default (Light)", "Solarized (Light)",
    "High Contrast (Dark)", "Classic (Dark)", "Presentation (Dark)", "Default (Dark)",
    "Solarized (Dark)", "Civic", "GitHub (Dark)", "Midnight", "Dusk",
]

TEXT_EDITING_LABELS = [
    "Prefer Indent Using", "Indent Width", "spaces", "Tab Width", "Font", "Font Size",
    "Font Weight", "Line Height", "Letter Spacing", "Wrap lines to editor width",
    "Use System Cursor", "Autocomplete braces",
    'Automatically insert closing braces ("}")', "Enable type-over completion",
    "Bracket Pair Highlight",
]

TERMINAL_LABELS = [
    "Shell", 'Use "Option" key as "Meta"', "Use text editor font",
    "Terminal Cursor Style", "Blink Cursor", "Shell Integration", "Use Login Shell",
]

SEARCH_LABELS = ["Exclude", "No excluded glob patterns"]

SOURCE_CONTROL_LABELS = [
    "Enable source control", "Refresh local status automatically",
    "Fetch and refresh server status automatically", "Add and remove files automatically",
    "Select files to commit automatically", "Show source control changes",
    "Include upstream changes", "Comparison view", "Source control navigator",
    "Default branch name", "Cannot contain spaces, backslashes, or other symbols",
]

LOCATION_ENTRIES = ["Application Support", "Settings", "Themes", "Extensions"]
LOCATION_PATH_FRAGMENT = "Library/Application Support/CodeEdit"

NAVIGATOR_ROWS = ["sample_project", "src", "README.md", "hello.py", "notes.txt"]
NOTES_TXT_TEXT = "alpha\nbeta\ngamma\n"
HELLO_PY_TEXT = 'def greet(name):\n    return f"Hello, {name}!"\n\n\nprint(greet("CodeEdit"))\n'


class TestWelcomeWindowText:
    """depth 0 — the welcome window is CodeEdit's fresh-launch home surface."""

    @pytest.mark.rb(depth=0, jump_kind="value",
                    expect="welcome window labels 'CodeEdit' / 'Version 0.3.1 (42)' / "
                           "'No Recent Projects' and buttons Create New File... / "
                           "Clone Git Repository... / Open File or Folder... / Close")
    def test_welcome_labels_and_button_names(self, ax):
        ensure_app_ui(ax)
        w = rb_enter_welcome(ax)
        assert w is not None, "welcome window (AXIdentifier 'welcome') not found"
        assert kit.rb_value(window_title(ax, w), "Welcome To CodeEdit"), \
            f"welcome window title == {window_title(ax, w)!r}"

        vals = values_in(ax, w.id)
        assert rb_value_all_present(vals, WELCOME_LABELS), \
            f"missing welcome label AXValues {missing_of(vals, WELCOME_LABELS)}; observed={vals}"

        btns = names_in(ax, w.id, role="button")
        assert rb_value_all_present(btns, WELCOME_BUTTONS), \
            f"missing welcome buttons {missing_of(btns, WELCOME_BUTTONS)}; observed={btns}"

        screenshot_assert(
            "text_test_welcome_labels_and_button_names",
            "CodeEdit welcome window (740x460, centred): large app icon with the title text "
            "'CodeEdit' and 'Version 0.3.1 (42)' beneath it; three full-width action rows with "
            "SF-Symbol icons reading 'Create New File...', 'Clone Git Repository...' and "
            "'Open File or Folder...' on the left half; the right column is the empty recent-"
            "projects list showing the placeholder text 'No Recent Projects'.")

    @pytest.mark.rb(depth=0, jump_kind="value",
                    expect="AXHelp of the 'Version 0.3.1 (42)' label == "
                           "'Copy System Information to Clipboard'")
    def test_version_label_help_text(self, ax):
        ensure_app_ui(ax)
        w = rb_enter_welcome(ax)
        assert w is not None, "welcome window not found"
        version_els = [e for e in ax.find(root_id=w.id, max_results=400, max_depth=18)
                       if ax.get(e.id, ["AXValue"]).get("AXValue") == "Version 0.3.1 (42)"]
        assert version_els, "no widget whose AXValue == 'Version 0.3.1 (42)'"
        help_texts = [ax.get(e.id, ["AXHelp"]).get("AXHelp") for e in version_els]
        assert rb_value_present(help_texts, VERSION_HELP), \
            f"version label AXHelp == {help_texts!r}, expected {VERSION_HELP!r}"


class TestAboutWindowText:
    """depth 1-2 — About window (CodeEdit > About CodeEdit) and its Acknowledgements view."""

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="About window shows 'CodeEdit', 'Version 0.3.1 (42)', "
                           "'Copyright © 2022-2024 CodeEdit', an AXLink 'MIT License', buttons "
                           "Contributors/Acknowledgements, and its own window title is ''")
    def test_about_window_text_and_empty_title(self, ax):
        w = rb_enter_about_window(ax)
        assert w is not None, "About window (AXIdentifier 'about') did not open"

        title = ax.get(w.id, ["AXTitle"]).get("AXTitle") or ""
        assert kit.rb_value(title, ""), f"About window title should be '' but is {title!r}"

        vals = values_in(ax, w.id)
        expected = ["CodeEdit", "Version 0.3.1 (42)", COPYRIGHT]
        assert rb_value_all_present(vals, expected), \
            f"missing About text {missing_of(vals, expected)}; observed={vals}"

        links = ax.find(role="link", root_id=w.id, max_results=20, max_depth=16)
        link_texts = [lk.name for lk in links]
        link_texts += [ax.get(lk.id, ["AXValue"]).get("AXValue") for lk in links]
        assert rb_value_present(link_texts, "MIT License"), \
            f"no AXLink named/valued 'MIT License'; observed links={link_texts}"

        btns = names_in(ax, w.id, role="button")
        assert rb_value_all_present(btns, ["Contributors", "Acknowledgements"]), \
            f"missing About buttons {missing_of(btns, ['Contributors', 'Acknowledgements'])}; " \
            f"observed={btns}"

        screenshot_assert(
            "text_test_about_window_text_and_empty_title",
            "CodeEdit About panel: small borderless window (no title bar text) with the app "
            "icon, the text 'CodeEdit', 'Version 0.3.1 (42)', two buttons labelled "
            "'Contributors' and 'Acknowledgements', a hyperlink reading 'MIT License' and the "
            "copyright line 'Copyright © 2022-2024 CodeEdit'.")

    @pytest.mark.rb(depth=2, jump_kind="value",
                    expect="Acknowledgements view lists the bundled dependency names "
                           "(Sparkle, SwiftTerm, swift-syntax, GRDB.swift, LanguageClient, "
                           "TextStory, ...) — >=12 of the 24 exact names, and the copyright "
                           "line is gone")
    def test_acknowledgements_dependency_names(self, ax):
        w = rb_enter_acknowledgements(ax)
        assert w is not None, "Acknowledgements view (About > Acknowledgements) not reached"
        must_have = ["Sparkle", "SwiftTerm", "swift-syntax"]
        vals = wait_for_texts(ax, w.id, must_have, timeout=6.0, reader=values_in)

        assert rb_value_at_least(vals, ACK_DEPENDENCIES, 12), (
            "expected >=12 of the bundled dependency names; missing="
            f"{missing_of(vals, ACK_DEPENDENCIES)}; observed={vals}")

        assert rb_value_all_present(vals, must_have), \
            f"missing dependency labels {missing_of(vals, must_have)}; observed={vals}"

        assert COPYRIGHT not in vals, \
            f"'{COPYRIGHT}' should disappear in the Acknowledgements view; observed={vals}"


class TestExtensionsWindowText:
    """depth 1 — Extensions > Open Extensions Window."""

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Extensions window: title 'Extensions', placeholder "
                           "'Select an extension', toolbar 'Hide Sidebar' and "
                           "'more toolbar items'")
    def test_extensions_window_text(self, ax):
        w = rb_enter_extensions_window(ax)
        assert w is not None, "Extensions window (AXIdentifier 'extensions') did not open"

        assert kit.rb_value(window_title(ax, w), "Extensions"), \
            f"Extensions window title == {window_title(ax, w)!r}"

        vals = values_in(ax, w.id)
        assert rb_value_present(vals, "Select an extension"), \
            f"placeholder 'Select an extension' not shown; observed={vals}"

        names = names_in(ax, w.id)
        expected = ["Hide Sidebar", "more toolbar items"]
        assert rb_value_all_present(names, expected), \
            f"missing Extensions controls {missing_of(names, expected)}; observed={names}"

    @pytest.mark.rb(depth=1, jump_kind="transition",
                    expect="Extensions toolbar button text flips 'Hide Sidebar' -> "
                           "'Show Sidebar' when pressed")
    def test_hide_sidebar_button_renames(self, ax):
        w = rb_enter_extensions_window(ax)
        assert w is not None, "Extensions window did not open"

        hide = buttons_named(ax, w.id, "Hide Sidebar")
        assert hide, f"no 'Hide Sidebar' button; buttons={names_in(ax, w.id, role='button')}"
        before = "Hide Sidebar"

        ax.action(hide[0].id, "AXPress")
        time.sleep(1.2)
        w2 = find_window(ax, ident="extensions", timeout=3) or w
        if buttons_named(ax, w2.id, "Hide Sidebar") and not buttons_named(ax, w2.id, "Show Sidebar"):
            # AXPress may be a no-op in a recreation — fall back to a real CG click.
            ax.click_element_cg(hide[0].id)
            time.sleep(1.2)
            w2 = find_window(ax, ident="extensions", timeout=3) or w

        if buttons_named(ax, w2.id, "Show Sidebar"):
            after = "Show Sidebar"
        elif buttons_named(ax, w2.id, "Hide Sidebar"):
            after = "Hide Sidebar"
        else:
            after = None

        assert kit.rb_flip(before, after, expect="Hide Sidebar -> Show Sidebar"), \
            f"sidebar toolbar button text did not change (before={before!r}, after={after!r})"
        assert after == "Show Sidebar", \
            f"button should read 'Show Sidebar' after hiding the sidebar, reads {after!r}"


class TestSettingsWindowTitles:
    """depth 1 — the Settings window TITLE equals the selected sidebar pane."""

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Settings window title equals the selected pane for General, "
                           "Accounts, Navigation, Themes")
    def test_settings_window_title_first_four_panes(self, ax):
        for pane in SETTINGS_PANES[:4]:
            w = rb_reach_settings_pane(ax, pane)
            assert w is not None, f"Settings pane {pane!r} not reachable"
            title = window_title(ax, w)
            assert kit.rb_value(title, pane), \
                f"Settings window title after selecting {pane!r} == {title!r}"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Settings window title equals the selected pane for Text Editing, "
                           "Terminal, Search, Source Control, Locations")
    def test_settings_window_title_last_five_panes(self, ax):
        for pane in SETTINGS_PANES[4:]:
            w = rb_reach_settings_pane(ax, pane)
            assert w is not None, f"Settings pane {pane!r} not reachable"
            title = window_title(ax, w)
            assert kit.rb_value(title, pane), \
                f"Settings window title after selecting {pane!r} == {title!r}"


class TestSettingsPaneText:
    """depth 1 — exact label text of each Settings pane (pristine profile)."""

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="General pane labels incl. 'Show “Open With CodeEdit” option in "
                           "Finder' (curly quotes), \"'codeedit' Shell Command\" and "
                           "'Last checked: Never'")
    def test_general_pane_labels(self, ax):
        w = rb_reach_settings_pane(ax, "General")
        assert w is not None, "Settings > General not reachable"
        vals = values_in(ax, w.id)
        assert rb_value_all_present(vals, GENERAL_LABELS), \
            f"missing General labels {missing_of(vals, GENERAL_LABELS)}; observed={vals}"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Accounts pane shows 'No accounts' + 'Add Account...'; Navigation "
                           "pane shows 'Navigation Style' with popup value 'Open in Tabs'")
    def test_accounts_and_navigation_pane_labels(self, ax):
        w = rb_reach_settings_pane(ax, "Accounts")
        assert w is not None, "Settings > Accounts not reachable"
        acc_text = texts_in(ax, w.id)
        expected_acc = ["No accounts", "Add Account..."]
        assert rb_value_all_present(acc_text, expected_acc), \
            f"missing Accounts text {missing_of(acc_text, expected_acc)}; observed={acc_text}"

        w = rb_reach_settings_pane(ax, "Navigation")
        assert w is not None, "Settings > Navigation not reachable"
        nav_text = values_in(ax, w.id)
        expected_nav = ["Navigation Style", "Open in Tabs"]
        assert rb_value_all_present(nav_text, expected_nav), \
            f"missing Navigation text {missing_of(nav_text, expected_nav)}; observed={nav_text}"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Themes pane switch labels incl. 'Use theme background ' (trailing "
                           "space) plus the 'Light Appearance'/'Dark Appearance' segments")
    def test_themes_pane_switch_labels(self, ax):
        w = rb_reach_settings_pane(ax, "Themes")
        assert w is not None, "Settings > Themes not reachable"
        vals = values_in(ax, w.id)
        assert rb_value_all_present(vals, THEMES_SWITCH_LABELS), \
            f"missing Themes switch labels {missing_of(vals, THEMES_SWITCH_LABELS)}; " \
            f"observed={vals}"

        segs = texts_in(ax, w.id)
        expected_segs = ["Light Appearance", "Dark Appearance"]
        assert rb_value_all_present(segs, expected_segs), \
            f"missing appearance segments {missing_of(segs, expected_segs)}; observed={segs}"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Themes pane lists the 17 bundled theme names "
                           "(Presentation (Light) ... Dusk)")
    def test_themes_pane_theme_names(self, ax):
        w = rb_reach_settings_pane(ax, "Themes")
        assert w is not None, "Settings > Themes not reachable"
        vals = values_in(ax, w.id)
        assert rb_value_all_present(vals, THEME_NAMES), \
            f"missing theme names {missing_of(vals, THEME_NAMES)}; observed={vals}"

        screenshot_assert(
            "text_test_themes_pane_theme_names",
            "CodeEdit Settings window with the Themes pane selected (window title reads "
            "'Themes'): a Light/Dark segmented control labelled 'Light Appearance' / "
            "'Dark Appearance', three toggle rows including 'Use theme background ', and a "
            "scrolling list of theme preview rows whose names read 'Presentation (Light)', "
            "'Classic (Light)', 'Low Key', 'Sunset', 'GitHub (Light)' ... 'Dusk', each preview "
            "rendering the word 'CodeEdit'; an 'Import...' button sits at the bottom.")

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Text Editing pane labels incl. 'Prefer Indent Using', 'spaces' and "
                           "'Automatically insert closing braces (\"}\")'")
    def test_text_editing_pane_labels(self, ax):
        w = rb_reach_settings_pane(ax, "Text Editing")
        assert w is not None, "Settings > Text Editing not reachable"
        vals = values_in(ax, w.id)
        assert rb_value_all_present(vals, TEXT_EDITING_LABELS), \
            f"missing Text Editing labels {missing_of(vals, TEXT_EDITING_LABELS)}; " \
            f"observed={vals}"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Terminal pane labels incl. 'Use \"Option\" key as \"Meta\"'; Search "
                           "pane shows 'Exclude' + 'No excluded glob patterns'")
    def test_terminal_and_search_pane_labels(self, ax):
        w = rb_reach_settings_pane(ax, "Terminal")
        assert w is not None, "Settings > Terminal not reachable"
        term = values_in(ax, w.id)
        assert rb_value_all_present(term, TERMINAL_LABELS), \
            f"missing Terminal labels {missing_of(term, TERMINAL_LABELS)}; observed={term}"

        w = rb_reach_settings_pane(ax, "Search")
        assert w is not None, "Settings > Search not reachable"
        search = texts_in(ax, w.id)
        assert rb_value_all_present(search, SEARCH_LABELS), \
            f"missing Search labels {missing_of(search, SEARCH_LABELS)}; observed={search}"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Source Control pane labels incl. 'Cannot contain spaces, "
                           "backslashes, or other symbols' and the 'Default branch name' "
                           "AXTextField whose value is exactly 'main'")
    def test_source_control_pane_labels_and_default_branch(self, ax):
        w = rb_reach_settings_pane(ax, "Source Control")
        assert w is not None, "Settings > Source Control not reachable"
        vals = values_in(ax, w.id)
        assert rb_value_all_present(vals, SOURCE_CONTROL_LABELS), \
            f"missing Source Control labels {missing_of(vals, SOURCE_CONTROL_LABELS)}; " \
            f"observed={vals}"

        field_vals = [ax.get(t.id, ["AXValue"]).get("AXValue")
                      for t in ax.find(role="text_field", root_id=w.id,
                                       max_results=60, max_depth=18)]
        assert rb_value_present(field_vals, "main"), \
            f"no AXTextField whose value is exactly 'main' (Default branch name); " \
            f"observed text fields={field_vals}"

    @pytest.mark.rb(depth=1, jump_kind="value",
                    expect="Locations pane exposes the 4 '<Name>, <path>' buttons (Application "
                           "Support / Settings / Themes / Extensions) and every path contains "
                           "'Library/Application Support/CodeEdit'")
    def test_locations_pane_paths(self, ax):
        w = rb_reach_settings_pane(ax, "Locations")
        assert w is not None, "Settings > Locations not reachable"
        btns = names_in(ax, w.id, role="button")

        found = {}
        for name in btns:
            for label in LOCATION_ENTRIES:
                if name.startswith(label + ", "):
                    found.setdefault(label, name.split(", ", 1)[1])
        assert rb_value_all_present(list(found.keys()), LOCATION_ENTRIES), \
            f"missing Locations entries {missing_of(list(found.keys()), LOCATION_ENTRIES)}; " \
            f"observed buttons={btns}"

        for label, path in found.items():
            # the Extensions entry is percent-encoded ("Application%20Support") — normalise
            assert kit.rb_value(path.replace("%20", " "), LOCATION_PATH_FRAGMENT), \
                f"{label} path {path!r} does not contain {LOCATION_PATH_FRAGMENT!r}"