File size: 30,034 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
import os
import re
import time
import warnings
import subprocess
from dataclasses import dataclass, field
from typing import Optional
from collections import Counter, deque

from ApplicationServices import (
    AXUIElementCreateApplication,
    AXUIElementCreateSystemWide,
    AXUIElementCopyAttributeNames,
    AXUIElementCopyAttributeValue,
    AXUIElementGetAttributeValueCount,
    AXUIElementCopyAttributeValues,
    AXUIElementIsAttributeSettable,
    AXUIElementSetAttributeValue,
    AXUIElementCopyMultipleAttributeValues,
    AXUIElementCopyParameterizedAttributeNames,
    AXUIElementCopyParameterizedAttributeValue,
    AXUIElementCopyActionNames,
    AXUIElementCopyActionDescription,
    AXUIElementPerformAction,
    AXUIElementCopyElementAtPosition,
    AXUIElementGetPid,
    AXUIElementSetMessagingTimeout,
    kAXValueCGPointType,
    kAXValueCGSizeType,
    AXValueGetValue,
)
import Quartz

ROLE_MAP = {
    "AXButton": "button",
    "AXStaticText": "label",
    "AXTextField": "text_field",
    "AXTextArea": "text_area",
    "AXCheckBox": "checkbox",
    "AXRadioButton": "radio",
    "AXPopUpButton": "popup",
    "AXComboBox": "combobox",
    "AXSlider": "slider",
    "AXImage": "image",
    "AXGroup": "group",
    "AXList": "list",
    "AXTable": "table",
    "AXGrid": "grid",
    "AXCell": "cell",
    "AXRow": "row",
    "AXColumn": "column",
    "AXOutline": "outline",
    "AXToolbar": "toolbar",
    "AXTabGroup": "tab_group",
    "AXTab": "tab",
    "AXScrollArea": "scroll_area",
    "AXScrollBar": "scroll_bar",
    "AXWindow": "window",
    "AXSheet": "sheet",
    "AXDialog": "dialog",
    "AXPopover": "popover",
    "AXMenu": "menu",
    "AXMenuBar": "menu_bar",
    "AXMenuBarItem": "menu_bar_item",
    "AXMenuItem": "menu_item",
    "AXSplitGroup": "split_group",
    "AXSplitter": "splitter",
    "AXProgressIndicator": "progress",
    "AXBusyIndicator": "busy",
    "AXValueIndicator": "value_indicator",
    "AXLink": "link",
    "AXDisclosureTriangle": "disclosure",
}


@dataclass
class AXElement:
    id: str
    role: str
    name: Optional[str] = None
    value: Optional[str] = None
    text: Optional[str] = None
    enabled: bool = True
    actions: list = field(default_factory=list)
    ref: object = field(default=None, repr=False)


_DYNAMIC_TEXT_PATTERNS = [
    re.compile(r"^\d{1,2}:\d{2}(:\d{2})?(\s*[AP]M)?$"),
    re.compile(r"^\d{4}-\d{2}-\d{2}"),
    re.compile(r"^\d{1,2}/\d{1,2}/\d{2,4}$"),
]


def _bundle_for_pid(pid):
    """Best-effort .app bundle path for a running pid (via its executable path)."""
    try:
        out = subprocess.run(
            ["ps", "-o", "comm=", "-p", str(int(pid))],
            capture_output=True, text=True,
        ).stdout.strip()
    except Exception:
        return ""
    marker = "/Contents/MacOS/"
    return out.split(marker)[0] if marker in out else ""


def is_electron_app(pid):
    """True if the app for `pid` is a Chromium-based app (Electron or CEF) whose web
    content AX tree stays empty unless launched with --force-renderer-accessibility.
    Detected by the presence of the Electron/CEF framework — precise, and does NOT
    false-positive on a native app that merely bundles a "* Helper.app" (XPC helper)."""
    bundle = _bundle_for_pid(pid)
    if not bundle:
        return False
    fw = bundle + "/Contents/Frameworks"
    return (os.path.isdir(fw + "/Electron Framework.framework")
            or os.path.isdir(fw + "/Chromium Embedded Framework.framework"))


def wait_for_web_ax(pid, timeout=8.0):
    """For Electron apps launched with --force-renderer-accessibility, the Chromium
    AXWebArea appears a few seconds after launch (async). Poll until it shows up so
    a read right after launch doesn't capture an empty window. Fast no-op for
    non-Electron apps (native/Gecko already expose AX). Best-effort; returns True
    when settled or when the app isn't Electron."""
    try:
        if not is_electron_app(pid):
            return True
        app = AXUIElementCreateApplication(int(pid))
    except Exception:
        return True
    try:
        AXUIElementSetMessagingTimeout(app, 5.0)
    except Exception:
        pass
    deadline = time.time() + timeout
    while time.time() < deadline:
        dq = deque([app])
        seen = 0
        while dq and seen < 8000:
            el = dq.popleft()
            seen += 1
            err, role = AXUIElementCopyAttributeValue(el, "AXRole", None)
            if err == 0 and str(role) == "AXWebArea":
                return True  # Chromium web content is built
            err, kids = AXUIElementCopyAttributeValue(el, "AXChildren", None)
            if err == 0 and kids:
                for k in kids:
                    dq.append(k)
        time.sleep(0.5)
    return True


class AXHelper:
    def __init__(self, app_name_or_pid, wait_for_ready=True, ready_timeout=10, prime=True):
        if isinstance(app_name_or_pid, int):
            self._pid = app_name_or_pid
        else:
            self._pid = self._find_pid_by_name(app_name_or_pid)
        self._app_ref = AXUIElementCreateApplication(self._pid)
        self._element_cache = {}

        # Electron apps launched with --force-renderer-accessibility build their
        # Chromium AXWebArea a few seconds after launch (async). Wait for it here so
        # the first real read sees full web content, not an empty window. Runs even
        # when wait_for_ready=False (e.g. the pytest `ax` fixture). Fast no-op for
        # non-Electron apps (native/Gecko already expose AX).
        if prime:
            wait_for_web_ax(self._pid)

        if wait_for_ready:
            self._wait_until_ready(ready_timeout)

    def _wait_until_ready(self, timeout):
        deadline = time.time() + timeout
        while time.time() < deadline:
            try:
                err, role = AXUIElementCopyAttributeValue(self._app_ref, "AXRole", None)
                if err == 0 and role:
                    err, children = AXUIElementCopyAttributeValue(
                        self._app_ref, "AXChildren", None
                    )
                    if err == 0 and children and len(children) > 0:
                        return
            except Exception:
                pass
            time.sleep(0.3)
        warnings.warn(f"AX tree for PID {self._pid} not ready after {timeout}s")

    def _find_pid_by_name(self, name):
        search_name = name[:15]
        result = subprocess.run(
            ["pgrep", "-x", search_name], capture_output=True, text=True
        )
        if result.returncode != 0:
            result = subprocess.run(
                ["pgrep", "-f", search_name], capture_output=True, text=True
            )
        if result.returncode != 0:
            raise RuntimeError(f"Process '{name}' not found")
        return int(result.stdout.strip().split("\n")[0])

    # ── Core API ──

    def find(
        self,
        role=None,
        name=None,
        name_contains=None,
        value=None,
        enabled=None,
        max_results=50,
        root_id=None,
        max_depth=None,
    ):
        root_ref = self._get_ref(root_id) if root_id else self._app_ref
        results = []

        def _recurse(ref, depth):
            if max_depth is not None and depth > max_depth:
                return
            if len(results) >= max_results:
                return
            el = self._ref_to_element(ref)
            if self._matches(el, role, name, name_contains, value, enabled):
                results.append(el)
            err, children = AXUIElementCopyAttributeValue(ref, "AXChildren", None)
            if err == 0 and children:
                for child in children:
                    _recurse(child, depth + 1)
                    if len(results) >= max_results:
                        return

        _recurse(root_ref, 0)
        return results

    def action(self, element_id, action_name):
        ref = self._get_ref(element_id)
        if ref is None:
            return False
        try:
            err = AXUIElementPerformAction(ref, action_name)
            return err == 0
        except Exception:
            return False

    def action_checked(self, element_id, action_name):
        success = self.action(element_id, action_name)
        if not success:
            warnings.warn(f"Action '{action_name}' failed on {element_id}")
        return success

    def click_element_cg(self, element_id):
        """Simulate a real mouse click at the element's screen position using CGEvent.

        Use this when AXPress doesn't work — e.g. menu bar apps that use
        NSEvent.addLocalMonitorForEvents instead of button target-action.
        """
        ref = self._get_ref(element_id)
        if ref is None:
            return False
        center = self._get_element_center(ref)
        if center is None:
            return False
        point = Quartz.CGPointMake(center[0], center[1])
        event_down = Quartz.CGEventCreateMouseEvent(
            None, Quartz.kCGEventLeftMouseDown, point, Quartz.kCGMouseButtonLeft
        )
        Quartz.CGEventPost(Quartz.kCGHIDEventTap, event_down)
        time.sleep(0.05)
        event_up = Quartz.CGEventCreateMouseEvent(
            None, Quartz.kCGEventLeftMouseUp, point, Quartz.kCGMouseButtonLeft
        )
        Quartz.CGEventPost(Quartz.kCGHIDEventTap, event_up)
        return True

    def get(self, element_id, attributes):
        # element_id=None 表示 APPLICATION 元素,与 find(root_id=None)/attribute_names(None) 一致。
        # 否则 ax.get(None, ["AXTitle"]) 走不进元素缓存、返回 {},读 app 自身标题的 test 拿到 None。
        ref = self._get_ref(element_id) if element_id else self._app_ref
        if ref is None:
            return {}
        result = {}
        for attr in attributes:
            try:
                err, val = AXUIElementCopyAttributeValue(ref, attr, None)
                if err == 0:
                    result[attr] = self._serialize_value(val)
                else:
                    result[attr] = None
            except Exception:
                result[attr] = None
        return result

    def activate(self):
        """把本 helper 绑定的 app 提到前台,返回是否成功。

        有些 toolkit 只在进程被 ACTIVATED 时才装原生菜单栏:olive(Qt)启动后 90s 仍只有
        ['Apple','Olive'];zotero(Gecko/XUL)一直只有 ['Apple','Zotero','File','Window'],
        且搜索框会吞掉合成键。一次激活即补齐。用 AX API 设 AXFrontmost 会返回成功但无效,
        所以走 NSRunningApplication。
        """
        try:
            from AppKit import NSRunningApplication
        except Exception:
            return False
        try:
            app = NSRunningApplication.runningApplicationWithProcessIdentifier_(int(self._pid))
            if app is None:
                return False
            return bool(app.activateWithOptions_(1 << 1))  # IgnoringOtherApps
        except Exception:
            return False

    def set_value(self, element_id, value):
        ref = self._get_ref(element_id)
        if ref is None:
            return False
        try:
            err = AXUIElementSetAttributeValue(ref, "AXValue", value)
            return err == 0
        except Exception:
            return False

    # ── Attribute Introspection ──

    def attribute_names(self, element_id=None):
        ref = self._get_ref(element_id) if element_id else self._app_ref
        if ref is None:
            return []
        try:
            err, names = AXUIElementCopyAttributeNames(ref, None)
            if err == 0 and names:
                return list(names)
        except Exception:
            pass
        return []

    def is_attribute_settable(self, element_id, attribute):
        ref = self._get_ref(element_id)
        if ref is None:
            return False
        try:
            err, settable = AXUIElementIsAttributeSettable(ref, attribute, None)
            return err == 0 and bool(settable)
        except Exception:
            return False

    def attribute_value_count(self, element_id, attribute):
        ref = self._get_ref(element_id)
        if ref is None:
            return 0
        try:
            err, count = AXUIElementGetAttributeValueCount(ref, attribute, None)
            return count if err == 0 else 0
        except Exception:
            return 0

    def attribute_values_range(self, element_id, attribute, index, count):
        ref = self._get_ref(element_id)
        if ref is None:
            return []
        try:
            err, values = AXUIElementCopyAttributeValues(ref, attribute, index, count, None)
            if err == 0 and values:
                return [self._serialize_value(v) for v in values]
        except Exception:
            pass
        return []

    def get_multiple(self, element_id, attributes):
        ref = self._get_ref(element_id)
        if ref is None:
            return {}
        try:
            err, values, errors = AXUIElementCopyMultipleAttributeValues(
                ref, attributes, 0, None, None
            )
            if err == 0 and values:
                result = {}
                for i, attr in enumerate(attributes):
                    if i < len(values):
                        result[attr] = self._serialize_value(values[i])
                    else:
                        result[attr] = None
                return result
        except Exception:
            pass
        return self.get(element_id, attributes)

    # ── Parameterized Attributes ──

    def parameterized_attribute_names(self, element_id=None):
        ref = self._get_ref(element_id) if element_id else self._app_ref
        if ref is None:
            return []
        try:
            err, names = AXUIElementCopyParameterizedAttributeNames(ref, None)
            if err == 0 and names:
                return list(names)
        except Exception:
            pass
        return []

    def parameterized_attribute_value(self, element_id, attribute, parameter):
        ref = self._get_ref(element_id)
        if ref is None:
            return None
        try:
            err, value = AXUIElementCopyParameterizedAttributeValue(
                ref, attribute, parameter, None
            )
            if err == 0:
                return self._serialize_value(value)
        except Exception:
            pass
        return None

    # ── Action Introspection ──

    def action_description(self, element_id, action_name):
        ref = self._get_ref(element_id)
        if ref is None:
            return ""
        try:
            err, desc = AXUIElementCopyActionDescription(ref, action_name, None)
            if err == 0 and desc:
                return str(desc)
        except Exception:
            pass
        return ""

    # ── Position / PID / Timeout ──

    def element_at_position(self, x, y):
        try:
            sys_ref = AXUIElementCreateSystemWide()
            err, el_ref = AXUIElementCopyElementAtPosition(sys_ref, float(x), float(y), None)
            if err == 0 and el_ref:
                element = self._ref_to_element(el_ref)
                return element
        except Exception:
            pass
        return None

    def get_pid(self, element_id=None):
        ref = self._get_ref(element_id) if element_id else self._app_ref
        if ref is None:
            return -1
        try:
            err, pid = AXUIElementGetPid(ref, None)
            return pid if err == 0 else -1
        except Exception:
            return -1

    def set_messaging_timeout(self, element_id, timeout_seconds):
        ref = self._get_ref(element_id) if element_id else self._app_ref
        if ref is None:
            return False
        try:
            err = AXUIElementSetMessagingTimeout(ref, float(timeout_seconds))
            return err == 0
        except Exception:
            return False

    @staticmethod
    def create_system_wide():
        return AXUIElementCreateSystemWide()

    def tree(self, max_depth=5, root_id=None):
        root_ref = self._get_ref(root_id) if root_id else self._app_ref

        def _build(ref, depth):
            el = self._ref_to_element(ref)
            node = {
                "role": el.role,
                "name": el.name,
                "id": el.id,
                "actions": el.actions,
            }
            if el.value:
                node["value"] = str(el.value)[:100]
            if depth < max_depth:
                err, children = AXUIElementCopyAttributeValue(ref, "AXChildren", None)
                if err == 0 and children:
                    node["children"] = [_build(c, depth + 1) for c in children]
            return node

        return _build(root_ref, 0)

    def list_apps(self):
        from AppKit import NSWorkspace

        apps = NSWorkspace.sharedWorkspace().runningApplications()
        return [
            {
                "name": app.localizedName(),
                "pid": app.processIdentifier(),
                "bundle_id": app.bundleIdentifier() or "",
                "type": "regular"
                if app.activationPolicy() == 0
                else "accessory",
            }
            for app in apps
            if app.activationPolicy() in (0, 1)
        ]

    # ── Capability-based Search ──

    def find_clickable(self, root_id=None, max_results=50):
        all_elements = self._walk_tree(root_id, max_results * 3)
        clickable = []
        for el in all_elements:
            if "AXPress" in el.actions or "AXConfirm" in el.actions:
                subrole = self._get_attr(el.ref, "AXSubrole", "")
                if subrole in (
                    "AXCloseButton",
                    "AXMinimizeButton",
                    "AXZoomButton",
                    "AXFullScreenButton",
                ):
                    continue
                clickable.append(el)
                if len(clickable) >= max_results:
                    break
        return clickable

    def find_text_elements(self, root_id=None, max_results=100):
        all_elements = self._walk_tree(root_id, max_results * 3)
        text_elements = []
        for el in all_elements:
            text = (
                self._get_attr(el.ref, "AXValue", "")
                or self._get_attr(el.ref, "AXTitle", "")
                or self._get_attr(el.ref, "AXDescription", "")
                or el.name
                or ""
            )
            if isinstance(text, str) and text.strip():
                el.text = text.strip()
                text_elements.append(el)
                if len(text_elements) >= max_results:
                    break
        return text_elements

    def find_value_settable(self, root_id=None, max_results=20):
        all_elements = self._walk_tree(root_id, max_results * 3)
        settable = []
        for el in all_elements:
            try:
                err, is_settable = AXUIElementIsAttributeSettable(
                    el.ref, "AXValue", None
                )
                if err == 0 and is_settable:
                    settable.append(el)
                    if len(settable) >= max_results:
                        break
            except Exception:
                continue
        return settable

    def find_togglable(self, root_id=None, max_results=20):
        all_elements = self._walk_tree(root_id, max_results * 3)
        togglable = []
        for el in all_elements:
            if "AXPress" in el.actions:
                value = self._get_attr(el.ref, "AXValue", None)
                if value in (0, 1, True, False, "0", "1"):
                    togglable.append(el)
                    if len(togglable) >= max_results:
                        break
        return togglable

    # ── Text Snapshot ──

    def snapshot_all_text(self, exclude_dynamic=True):
        text_elements = self.find_text_elements(max_results=200)
        texts = []
        for el in text_elements:
            text = el.text
            if exclude_dynamic and any(
                p.match(text) for p in _DYNAMIC_TEXT_PATTERNS
            ):
                continue
            texts.append(text)
        return Counter(texts)

    def wait_for_text_change(self, original_text, timeout=3.0):
        deadline = time.time() + timeout
        while time.time() < deadline:
            current = self.snapshot_all_text()
            if current != original_text:
                return current
            time.sleep(0.2)
        return self.snapshot_all_text()

    def wait_for(self, role=None, name=None, timeout=5.0, max_results=1):
        deadline = time.time() + timeout
        while time.time() < deadline:
            results = self.find(role=role, name=name, max_results=max_results)
            if results:
                return results
            time.sleep(0.3)
        return []

    # ── Verifier Helpers ──

    def find_safe_buttons(self, max_results=20):
        clickable = self.find_clickable(max_results=max_results * 2)
        safe = []
        for el in clickable:
            name_lower = (el.name or "").lower()
            if any(
                kw in name_lower
                for kw in [
                    "quit", "delete", "remove", "erase",
                    "reset", "clear all", "uninstall",
                ]
            ):
                continue
            safe.append(el)
            if len(safe) >= max_results:
                break
        return safe

    def ensure_ui_visible(self):
        _CONTAINER_ROLES = ["window", "popover", "group", "sheet"]
        # Menu-item labels that reveal the main UI via a Settings/Preferences
        # window (EN + ZH). Kept deliberately narrow and high-signal: broader
        # verbs like "open"/"show" risk pressing File-menu items such as
        # "Open…" that pop a file dialog instead of revealing the main UI.
        _REVEAL_KW = ("preference", "settings", "偏好", "设置")

        def _visible():
            # max_depth=12 (was 3): status-item / menu-bar popovers sit ~7-8 levels
            # deep in the AX tree, so a depth-3 check reported "not visible" even
            # after the popover opened -> reveal loops gave up / tests saw no UI.
            for role in _CONTAINER_ROLES:
                if self.find(role=role, max_results=1, max_depth=12):
                    return True
            return False

        if _visible():
            return True
        menu_items = self.find(role="menu_bar_item", max_results=8, max_depth=3)
        for item in menu_items:
            self.action(item.id, "AXPress")
            time.sleep(0.5)
            if _visible():
                return True
            # Two-level reveal: pressing the status/menu-bar item may open a MENU
            # (not the window). A valid recreation can wire it as
            # icon -> menu -> "Preferences…" -> window. Click a reveal item.
            for mi in self.find(role="menu_item", max_results=40, max_depth=6):
                name = (mi.name or "").lower()
                if name and any(k in name for k in _REVEAL_KW):
                    self.action(mi.id, "AXPress")
                    time.sleep(0.5)
                    if _visible():
                        return True
            # AXPress may not work for apps using NSEvent mouse monitoring;
            # fall back to a real CGEvent click at the element's position.
            self.click_element_cg(item.id)
            time.sleep(1.0)
            if _visible():
                return True
        # Preferences hotkey (⌘,) — standard macOS "show settings" trigger.
        # Guarded so this method preserves its contract of never raising
        # (osascript can hit the subprocess timeout).
        try:
            subprocess.run(
                [
                    "osascript", "-e",
                    'tell application "System Events" to '
                    'keystroke "," using command down',
                ],
                capture_output=True,
                timeout=3,
            )
            time.sleep(0.5)
        except Exception:
            pass
        return _visible()

    def dismiss_any_dialog(self):
        for role in ["sheet", "dialog"]:
            dialogs = self.find(role=role, max_results=3, max_depth=3)
            for dlg in dialogs:
                buttons = self.find(role="button", root_id=dlg.id, max_results=10)
                for btn in buttons:
                    name_lower = (btn.name or "").lower()
                    if name_lower in (
                        "cancel", "ok", "close", "dismiss", "don't save",
                    ):
                        self.action(btn.id, "AXPress")
                        time.sleep(0.3)
                        return True
                subprocess.run(
                    [
                        "osascript", "-e",
                        'tell application "System Events" to key code 53',
                    ],
                    capture_output=True,
                    timeout=2,
                )
                time.sleep(0.3)
                return True
        return False

    def get_main_window(self):
        windows = self.find(role="window", max_results=10, max_depth=1)
        if not windows:
            return None
        if len(windows) == 1:
            return windows[0].id
        for w in windows:
            attrs = self.get(w.id, ["AXMain"])
            if attrs.get("AXMain"):
                return w.id
        best, best_area = None, 0
        for w in windows:
            attrs = self.get(w.id, ["AXSize"])
            size = attrs.get("AXSize")
            if size is not None:
                area = getattr(size, "width", 0) * getattr(size, "height", 0)
            else:
                area = 0
            if area > best_area:
                best_area = area
                best = w.id
        return best

    # ── Internal ──

    def _walk_tree(self, root_id, max_count):
        root_ref = self._get_ref(root_id) if root_id else self._app_ref
        results = []

        def _recurse(ref):
            if len(results) >= max_count:
                return
            el = self._ref_to_element(ref)
            results.append(el)
            err, children = AXUIElementCopyAttributeValue(ref, "AXChildren", None)
            if err == 0 and children:
                for child in children:
                    _recurse(child)
                    if len(results) >= max_count:
                        return

        _recurse(root_ref)
        return results

    def _ref_to_element(self, ref):
        el_id = str(hash(ref))
        self._element_cache[el_id] = ref

        role_raw = self._get_attr(ref, "AXRole", "")
        role = ROLE_MAP.get(
            role_raw,
            role_raw.replace("AX", "").lower() if role_raw else "unknown",
        )
        name = self._get_attr(ref, "AXTitle", "") or self._get_attr(
            ref, "AXDescription", ""
        )
        value = self._get_attr(ref, "AXValue", "")
        enabled = self._get_attr(ref, "AXEnabled", True)

        actions = []
        try:
            err, action_names = AXUIElementCopyActionNames(ref, None)
            if err == 0 and action_names:
                actions = list(action_names)
        except Exception:
            pass

        return AXElement(
            id=el_id,
            role=role,
            name=name,
            value=value,
            enabled=enabled,
            actions=actions,
            ref=ref,
        )

    def _get_ref(self, element_id):
        return self._element_cache.get(element_id)

    def _get_element_center(self, ref):
        """Return (x, y) screen coordinates of the element's center, or None."""
        pos_val = self._get_attr(ref, "AXPosition", None)
        size_val = self._get_attr(ref, "AXSize", None)
        if pos_val is None or size_val is None:
            return None
        pos_str = str(pos_val)
        size_str = str(size_val)
        pos_nums = re.findall(r"[-\d.]+", pos_str)
        size_nums = re.findall(r"[-\d.]+", size_str)
        if len(pos_nums) < 2 or len(size_nums) < 2:
            return None
        px, py = float(pos_nums[-2]), float(pos_nums[-1])
        sw, sh = float(size_nums[-2]), float(size_nums[-1])
        return (px + sw / 2, py + sh / 2)

    def _get_attr(self, ref, attr_name, default=None):
        try:
            err, val = AXUIElementCopyAttributeValue(ref, attr_name, None)
            return val if err == 0 else default
        except Exception:
            return default

    def _matches(self, el, role, name, name_contains, value, enabled):
        if role and el.role != role:
            return False
        if name and el.name != name:
            return False
        if name_contains and (not el.name or name_contains not in el.name):
            return False
        if value is not None and el.value != value:
            return False
        if enabled is not None and el.enabled != enabled:
            return False
        return True

    def _serialize_value(self, val):
        if val is None:
            return None
        if isinstance(val, (str, int, float, bool)):
            return val
        if hasattr(val, "width") and hasattr(val, "height"):
            return {"width": val.width, "height": val.height}
        if hasattr(val, "x") and hasattr(val, "y"):
            return {"x": val.x, "y": val.y}
        return str(val)


def _pid_by_name(name):
    """Resolve a pid from a process name using the same MAXCOMLEN(15)/pgrep logic
    the stage shells use."""
    s = name[:15]
    r = subprocess.run(["pgrep", "-x", s], capture_output=True, text=True)
    if r.returncode != 0:
        r = subprocess.run(["pgrep", "-f", s], capture_output=True, text=True)
    if r.returncode != 0:
        return None
    out = r.stdout.strip()
    return int(out.split("\n")[0]) if out else None