RecreationBench / macos /buddax2-tmpnote /tests /tmpnote_helpers.py
VoyagerXHF's picture
Upload folder using huggingface_hub (part 4)
41dfd8d verified
Raw History Blame Contribute Delete
20.7 kB
"""Shared navigation / observation helpers for the tmpNote AX test suite.
tmpNote is an LSUIElement (menu-bar / status-item) app: it has NO window at launch.
Every surface is reached from a status-bar icon, so each lane needs the same reveal
and read primitives. They live here so all six test modules agree on them and so a
recreation that wires the SAME feature slightly differently still gets found.
Portability contract (this module is scanned by rb_lint_sources):
* never spawns the app, never hardcodes an install path or bundle id
* only talks to the AXHelper instance handed in by the `ax` pytest fixture
* every locator is tolerant (AXDescription -> AXHelp -> AXTitle keyword match)
Navigation entry points are deliberately named `rb_enter_*` / `rb_reach_*` so
rb_audit_depth() can see that a declared depth>=1 is backed by a real surface
crossing.
"""
import os
import re
import subprocess
import time
import Foundation
from ApplicationServices import (
AXUIElementCopyParameterizedAttributeValue,
AXValueCreate,
kAXValueCFRangeType,
)
import rb_testgen_kit as kit
import verifier_helpers as helpers
# ── timing ────────────────────────────────────────────────────────────────────
T_CLICK = 0.35 # after a plain button press
T_SURFACE = 1.3 # after a press that opens/closes a surface
T_MODE = 1.3 # after a content-mode switch (rebuilds the text view)
# ── canonical AXDescription of every popover control (official app) ───────────
BTN_LOCK = "Lock app on screen button"
BTN_WINDOW = "Open in a separate window"
BTN_SHARE = "Share button"
BTN_MENU = "Menu button"
BTN_CLEAR = "Clear button"
VIEW_BUTTONS = ["View 1", "View 2", "View 3", "View 4", "View 5"]
# AXHelp of the three content-mode segments of the mode radio group
MODE_TEXT = "Plain text mode"
MODE_MARKDOWN = "Markdown preview mode"
MODE_DRAWING = "Drawing mode"
# Keyword fallbacks, so a recreation that labels things a little differently
# is still located rather than scored 0 for a naming difference.
_KW = {
BTN_LOCK: ("lock", "hide on deactivate", "pin"),
BTN_WINDOW: ("separate window", "window", "detach", "panel"),
BTN_SHARE: ("share",),
BTN_MENU: ("menu", "settings", "preferences", "gear"),
BTN_CLEAR: ("clear", "trash", "erase"),
}
_MODE_KW = {
MODE_TEXT: ("plain", "text box", "text"),
MODE_MARKDOWN: ("markdown", "quick look", "preview"),
MODE_DRAWING: ("draw", "sketch"),
}
# ── low level reads ──────────────────────────────────────────────────────────
def attrs(ax, el_id, names=("AXDescription", "AXHelp", "AXTitle", "AXValue", "AXEnabled")):
"""Read several attributes at once, tolerating a dead element id."""
try:
return ax.get(el_id, list(names)) or {}
except Exception:
return {}
def _label_blob(ax, el_id):
a = attrs(ax, el_id, ("AXDescription", "AXHelp", "AXTitle"))
return " ".join(str(a.get(k) or "") for k in ("AXDescription", "AXHelp", "AXTitle")).lower()
def find_button(ax, desc, root_id=None):
"""Locate a popover button by exact AXDescription, then by keyword."""
buttons = ax.find(role="button", root_id=root_id, max_results=40, max_depth=14)
for b in buttons:
if (attrs(ax, b.id, ("AXDescription",)).get("AXDescription") or "") == desc:
return b
for kw in _KW.get(desc, ()):
for b in buttons:
if kw in _label_blob(ax, b.id):
return b
return None
def find_button_by_title(ax, title, root_id=None):
"""Locate a button by AXTitle (alert buttons carry their label in AXTitle)."""
want = title.strip().lower()
for b in ax.find(role="button", root_id=root_id, max_results=40, max_depth=14):
got = (attrs(ax, b.id, ("AXTitle",)).get("AXTitle") or "").strip().lower()
if got == want:
return b
return None
def mode_radios(ax):
"""The three content-mode segments, in tree order."""
groups = ax.find(role="radiogroup", max_results=3, max_depth=14)
for g in groups:
radios = ax.find(role="radio", root_id=g.id, max_results=8)
if len(radios) >= 2:
return radios
return []
def find_mode_radio(ax, mode_help):
"""Locate one content-mode segment by AXHelp, then by keyword, then by index."""
radios = mode_radios(ax)
for r in radios:
if (attrs(ax, r.id, ("AXHelp",)).get("AXHelp") or "") == mode_help:
return r
for kw in _MODE_KW.get(mode_help, ()):
for r in radios:
if kw in _label_blob(ax, r.id):
return r
order = [MODE_TEXT, MODE_MARKDOWN, MODE_DRAWING]
if mode_help in order and len(radios) > order.index(mode_help):
return radios[order.index(mode_help)]
return None
def mode_values(ax):
"""AXValue of each mode segment -> [1, 0, 0] means plain-text is selected."""
out = []
for r in mode_radios(ax):
v = attrs(ax, r.id, ("AXValue",)).get("AXValue")
try:
out.append(int(v))
except (TypeError, ValueError):
out.append(0)
return out
def selected_mode_index(ax):
vals = mode_values(ax)
for i, v in enumerate(vals):
if v:
return i
return -1
def text_area(ax):
"""The note's editable text surface."""
found = ax.find(role="text_area", max_results=3, max_depth=14)
return found[0] if found else None
def note_text(ax):
ta = text_area(ax)
if ta is None:
return None
return attrs(ax, ta.id, ("AXValue",)).get("AXValue")
def set_note_text(ax, value):
"""Write the note body. NSTextView accepts an AXValue write and, unlike a
blind keystroke, it does not depend on which app is frontmost."""
ta = text_area(ax)
if ta is None:
return False
ok = bool(ax.set_value(ta.id, value))
time.sleep(0.45)
return ok
def note_is_editable(ax):
"""True when the note text can be typed into (plain-text mode)."""
ta = text_area(ax)
if ta is None:
return False
try:
return bool(ax.is_attribute_settable(ta.id, "AXValue"))
except Exception:
return False
def glyph_bounds(ax, length=10):
"""(width, height) in points of the first `length` characters of the note.
The only AX-visible consequence of a font-size change: NSTextView reports the
rendered rect of a character range, and that rect grows/shrinks with the font.
Returns None when the surface does not implement AXBoundsForRange.
"""
ta = text_area(ax)
if ta is None:
return None
try:
ref = ax._get_ref(ta.id)
rng = AXValueCreate(kAXValueCFRangeType, Foundation.NSRange(0, length))
err, val = AXUIElementCopyParameterizedAttributeValue(
ref, "AXBoundsForRange", rng, None)
if err != 0 or val is None:
return None
m = re.search(r"w:([0-9.]+)\s+h:([0-9.]+)", str(val))
return (float(m.group(1)), float(m.group(2))) if m else None
except Exception:
return None
def popover(ax):
found = ax.find(role="popover", max_results=5, max_depth=12)
return found[0] if found else None
def note_surface(ax):
"""The container currently holding the note UI: popover, or the detached window."""
p = popover(ax)
if p is not None:
return p
for w in ax.find(role="window", max_results=8, max_depth=3):
if find_button(ax, BTN_CLEAR, root_id=w.id) is not None:
return w
return None
def window_titled(ax, title):
want = title.strip().lower()
for w in ax.find(role="window", max_results=8, max_depth=3):
got = (w.name or attrs(ax, w.id, ("AXTitle",)).get("AXTitle") or "").strip().lower()
if got == want:
return w
return None
def sheet(ax):
found = ax.find(role="sheet", max_results=4, max_depth=12)
if found:
return found[0]
found = ax.find(role="dialog", max_results=4, max_depth=12)
return found[0] if found else None
def surface_texts(ax, root_id=None):
"""Every static-text / label value on a surface."""
out = []
for role in ("label", "static_text", "text"):
for t in ax.find(role=role, root_id=root_id, max_results=60, max_depth=14):
v = attrs(ax, t.id, ("AXValue", "AXTitle")).get("AXValue")
if v is None:
v = t.name
if v not in (None, ""):
out.append(str(v))
if out:
break
return out
def menu_items_of(ax, *required):
"""Find an open menu that contains all of `required` items; return its items.
Used to identify a specific popped-up menu among the many menus a Cocoa app
exposes (the whole main menu bar is always in the tree).
"""
want = [r.lower() for r in required]
for m in ax.find(role="menu", max_results=80, max_depth=14):
kids = ax.find(role="menu_item", root_id=m.id, max_results=25)
names = [(k.name or "").lower() for k in kids]
if all(any(w in n for n in names) for w in want):
return kids
return []
def menu_item_named(items, name):
want = name.strip().lower().rstrip(".…")
for k in items:
got = (k.name or "").strip().lower().rstrip(".…")
if got == want:
return k
for k in items:
if want and want in (k.name or "").strip().lower():
return k
return None
# ── navigation: reveal / enter surfaces ──────────────────────────────────────
def _status_items(ax):
"""Menu-bar items that are NOT the app's own main menus.
A status item has no title; the main menus (Apple/tmpNote/File/…) all do.
Unnamed items are returned last-first because the extras menu bar is walked
after the main menu bar.
"""
items = ax.find(role="menu_bar_item", max_results=25, max_depth=6)
blank = [m for m in items if not (m.name or "").strip()]
return list(reversed(blank))
def rb_reach_popover(ax, timeout=12.0):
"""Reveal the note surface from the status-bar icon. Returns the container.
Fast path: press the unnamed status item directly (the app's own main menus
never open the popover, so pressing them is pure latency). Falls back to the
generic ensure_panel_open() reveal ladder for a recreation whose status item
is exposed differently.
"""
existing = note_surface(ax)
if existing is not None:
return existing
deadline = time.time() + timeout
for si in _status_items(ax):
try:
ax.action(si.id, "AXPress")
except Exception:
continue
time.sleep(T_SURFACE)
surface = note_surface(ax)
if surface is not None:
return surface
try:
ax.click_element_cg(si.id)
except Exception:
pass
time.sleep(T_SURFACE)
surface = note_surface(ax)
if surface is not None:
return surface
if time.time() > deadline:
break
helpers.ensure_panel_open(ax)
time.sleep(0.4)
return note_surface(ax)
# `ensure_note_surface` reads better at call sites that only need the container.
ensure_note_surface = rb_reach_popover
def rb_enter_app_menu(ax):
"""Open the popover's own gear menu (Preferences / font size / quit).
The gear button pops an NSMenu via `NSMenu.popUp(positioning:at:in:)`; an
AXPress does not run that nested tracking loop, so a real CGEvent click is
required. Returns the menu's items.
"""
rb_reach_popover(ax)
btn = find_button(ax, BTN_MENU)
if btn is None:
return []
try:
ax.click_element_cg(btn.id)
except Exception:
return []
time.sleep(T_SURFACE)
items = menu_items_of(ax, "font size")
if not items:
items = menu_items_of(ax, "preferences")
return items
def rb_enter_preferences(ax):
"""Open the Preferences window (gear menu -> "Preferences..."). Returns the window."""
existing = window_titled(ax, "tmpNote")
items = rb_enter_app_menu(ax)
target = menu_item_named(items, "Preferences") if items else None
if target is not None:
try:
ax.action(target.id, "AXPress")
except Exception:
pass
time.sleep(1.8)
win = window_titled(ax, "Preferences")
if win is None:
# A recreation may put settings behind the standard ⌘, instead.
dismiss_open_menu(ax)
_keystroke(",", "command")
time.sleep(1.5)
win = window_titled(ax, "Preferences")
if win is None:
for w in ax.find(role="window", max_results=8, max_depth=3):
if existing is not None and w.id == existing.id:
continue
if ax.find(role="checkbox", root_id=w.id, max_results=4):
return w
return win
def rb_enter_clear_dialog(ax):
"""Press Clear and return the confirmation sheet (or None)."""
rb_reach_popover(ax)
btn = find_button(ax, BTN_CLEAR)
if btn is None:
return None
try:
ax.action(btn.id, "AXPress")
except Exception:
return None
time.sleep(1.7)
return sheet(ax)
def _button_labels(ax):
names = set()
for b in ax.find(role="button", max_results=70, max_depth=14):
title = (attrs(ax, b.id, ("AXTitle",)).get("AXTitle") or "").strip()
if not title:
title = (b.name or "").strip()
if title:
names.add(title)
return names
def rb_enter_share_picker(ax):
"""Press Share and return only the service buttons the picker ADDED.
Diffed against the buttons already on the note surface, so the result is the
share picker's own contents rather than the popover's toolbar.
"""
rb_reach_popover(ax)
btn = find_button(ax, BTN_SHARE)
if btn is None:
return []
before = _button_labels(ax)
try:
ax.action(btn.id, "AXPress")
except Exception:
return []
time.sleep(2.0)
return sorted(_button_labels(ax) - before)
def close_note_surface(ax, timeout=6.0):
"""Hide the note surface so a reveal test can prove a real surface jump.
Escape is the app's documented dismiss (cancelOperation); pressing the status
item again is the toggle. Returns True once no note surface is exposed.
"""
deadline = time.time() + timeout
while time.time() < deadline:
if note_surface(ax) is None:
return True
dismiss_open_menu(ax)
time.sleep(0.7)
if note_surface(ax) is None:
return True
items = _status_items(ax)
if items:
try:
ax.action(items[0].id, "AXPress")
except Exception:
pass
time.sleep(T_SURFACE)
return note_surface(ax) is None
def rb_enter_detached_window(ax):
"""Press "Open in a separate window" and return the detached window."""
rb_reach_popover(ax)
btn = find_button(ax, BTN_WINDOW)
if btn is None:
return None
try:
ax.action(btn.id, "AXPress")
except Exception:
return None
time.sleep(2.2)
win = window_titled(ax, "tmpNote")
if win is not None:
return win
for w in ax.find(role="window", max_results=8, max_depth=3):
if find_button(ax, BTN_CLEAR, root_id=w.id) is not None:
return w
return None
def rb_enter_view_menu(ax):
"""Open the main menu bar's View menu; return its items."""
for m in ax.find(role="menu_bar_item", max_results=25, max_depth=6):
if (m.name or "").strip().lower() == "view":
try:
ax.action(m.id, "AXPress")
except Exception:
return []
time.sleep(T_SURFACE)
return ax.find(role="menu_item", root_id=m.id, max_results=30, max_depth=3)
return []
def rb_reach_mode(ax, mode_help):
"""Switch content mode via the popover's mode segments. Returns True on success."""
rb_reach_popover(ax)
r = find_mode_radio(ax, mode_help)
if r is None:
return False
try:
ax.action(r.id, "AXPress")
except Exception:
return False
time.sleep(T_MODE)
return True
def press_button(ax, desc):
"""Press a popover button by description. Returns True when it was pressed."""
btn = find_button(ax, desc)
if btn is None:
return False
try:
ax.action(btn.id, "AXPress")
except Exception:
return False
time.sleep(T_CLICK)
return True
# ── teardown ─────────────────────────────────────────────────────────────────
def _keystroke(key, modifier=None):
script = f'tell application "System Events" to keystroke "{key}"'
if modifier:
script += f" using {modifier} down"
try:
subprocess.run(["osascript", "-e", script], capture_output=True, timeout=5)
except Exception:
pass
def dismiss_open_menu(ax):
"""Close a popped-up menu without closing the note surface, best effort."""
try:
helpers.send_key(helpers.KC_ESCAPE)
except Exception:
pass
time.sleep(0.4)
def reset_ui(ax):
"""Return the app to its default surface state: no dialog, no menu, no
detached window, plain-text mode, empty note. Called at the top of a test so
the previous test's leftovers cannot decide this one's verdict."""
for _ in range(3):
s = sheet(ax)
if s is None:
break
cancel = find_button_by_title(ax, "Cancel", root_id=s.id)
if cancel is not None:
try:
ax.action(cancel.id, "AXPress")
except Exception:
pass
else:
dismiss_open_menu(ax)
time.sleep(0.9)
dismiss_open_menu(ax)
prefs = window_titled(ax, "Preferences")
if prefs is not None:
_close_window(ax, prefs)
surface = note_surface(ax)
if surface is None:
surface = rb_reach_popover(ax)
if surface is None:
return None
# A detached window is a different surface than the popover; fold it back.
if window_titled(ax, "tmpNote") is not None and popover(ax) is None:
if press_button(ax, BTN_WINDOW):
time.sleep(2.0)
if popover(ax) is None:
rb_reach_popover(ax)
if selected_mode_index(ax) != 0:
rb_reach_mode(ax, MODE_TEXT)
if note_is_editable(ax):
set_note_text(ax, "")
return note_surface(ax)
def _close_window(ax, win):
for b in ax.find(role="button", root_id=win.id, max_results=20):
if (attrs(ax, b.id, ("AXSubrole",)).get("AXSubrole")) == "AXCloseButton":
try:
ax.action(b.id, "AXPress")
except Exception:
pass
time.sleep(1.0)
return True
dismiss_open_menu(ax)
return False
# ── screenshots for the VLM judge ────────────────────────────────────────────
def results_dir():
return (os.environ.get("RESULTS_DIR")
or os.environ.get("AX_RESULTS_DIR")
or os.path.join(os.path.dirname(os.path.abspath(__file__)), "baseline_results"))
def screenshot_assert(test_name, description, out_dir=None):
"""Capture the screen and record what a VLM should see in it."""
import json
base = out_dir or results_dir()
ss_dir = os.path.join(base, "screenshots")
try:
os.makedirs(ss_dir, exist_ok=True)
subprocess.run(["screencapture", "-x", os.path.join(ss_dir, f"{test_name}.png")],
timeout=8, capture_output=True)
path = os.path.join(ss_dir, "assertions.json")
data = {}
if os.path.exists(path):
try:
with open(path) as fh:
data = json.load(fh)
except Exception:
data = {}
data[f"{test_name}.png"] = description
with open(path, "w") as fh:
json.dump(data, fh, indent=2)
except Exception:
pass
# Re-export so lanes need a single import for the verdict primitives.
rb_showing = kit.rb_showing
rb_reach = kit.rb_reach
rb_flip = kit.rb_flip
rb_value = kit.rb_value