Skip to content

let your agent control your phone

refactor: put every device behind one send() seam

ShawnPanaa3675378acbb
diff --git a/src/phone_harness/background.py b/src/phone_harness/background.py
index 8b3a8c5..e5421f2 100644
--- a/src/phone_harness/background.py
+++ b/src/phone_harness/background.py
@@ -86,6 +86,9 @@ def find_window():
running_app = mirror.running_app
window_ax_content = mirror.window_ax_content
+focus_probe = mirror.focus_probe
+interruption = mirror.interruption
+frontmost_window = mirror.frontmost_window
# Shared with the mirror backend. Nothing here needs focus, but screen_info()
diff --git a/src/phone_harness/helpers.py b/src/phone_harness/helpers.py
index 768ead4..2904fb5 100644
--- a/src/phone_harness/helpers.py
+++ b/src/phone_harness/helpers.py
@@ -1,153 +1,137 @@
-"""Phone control via iPhone Mirroring.
+"""Phone control — one flat API over any device.
Core helpers live here. Agent-editable helpers live in
PH_AGENT_WORKSPACE/agent_helpers.py (defaults to <repo>/agent-workspace).
-Raw Quartz is always available: `import Quartz` in your script for anything
-these helpers don't cover.
+
+Everything below is a thin wrapper over send(), which is defined first on
+purpose: the helpers are conveniences, not a wall. Drop to send() for anything
+they don't cover, and below that to the backend itself — `import Quartz` on
+iOS. The agent picks its own altitude.
+
+Nothing in this file knows which platform it is driving. Platform differences
+live inside one backend each, behind the ops documented in transport.py, so
+`nav.home` and `screen.text` mean the same thing everywhere even though an
+iPhone answers them with a Cmd+1 keystroke and Vision OCR.
"""
-import hashlib, importlib, importlib.util, os, time
+import hashlib, importlib.util, os, time
from pathlib import Path
-from . import ocr as _ocr
-
-# Every helper below rests on two primitives — capture + tap — so the transport
-# is swappable. The background backend drives iPhone Mirroring without ever
-# taking focus (SkyLight event records) and is the default: not stealing the
-# user's screen is what you want unless something is broken. Set
-# PHONE_HARNESS_BACKGROUND=0 to force the classic mirror backend, which must
-# bring the window frontmost. If the background backend can't load (its private
-# SkyLight symbols aren't guaranteed across macOS builds), fall back rather than
-# leaving the harness unusable.
-_BACKGROUND = os.environ.get("PHONE_HARNESS_BACKGROUND", "1").lower() not in (
- "0", "false", "no")
-if _BACKGROUND:
- try:
- mirror = importlib.import_module(".background", __package__)
- except Exception:
- mirror = importlib.import_module(".mirror", __package__)
- _BACKGROUND = False
-else:
- mirror = importlib.import_module(".mirror", __package__)
-
-tap = mirror.tap
-long_press = mirror.long_press
-drag = mirror.drag
-press = mirror.press
-type_text = mirror.type_text
-activate = mirror.activate
-find_window = mirror.find_window
+from . import transport
+from .transport import Unsupported # re-exported for agent scripts
CORE_DIR = Path(__file__).resolve().parent
REPO_ROOT = CORE_DIR.parent.parent
AGENT_WORKSPACE = Path(
os.environ.get("PH_AGENT_WORKSPACE", REPO_ROOT / "agent-workspace"))
+# The default device. connect() returns a fresh backend, so a script needing
+# two phones at once can hold them side by side instead of being limited to
+# this one.
+phone = transport.connect()
+connect = transport.connect
+
+
+def send(op, **kw):
+ """Raw transport. send('input.tap', x=100, y=200), send('screen.text').
+
+ The op vocabulary is documented in transport.py. Unsupported means this
+ device genuinely cannot do it, not that the call failed.
+ """
+ return phone.send(op, **kw)
+
+
+def supports(op):
+ """True if this device implements `op`. Gate optional work on it."""
+ return phone.supports(op)
-# --- session / state ---
-# Distinctive text on the not-connected interstitials. Reconnecting past any of
-# these is a PHYSICAL action only the user can do (open the app, and if it says
-# "iPhone in Use", LOCK the phone). The agent must never tap through them.
-# Fallback only. The primary check is structural (see connection_state), and
-# a phrase list cannot be complete: it missed "Connection Paused" and the Mac
-# login screen in English, and misses every interstitial on a non-English
-# system.
-_BLOCKED_MARKERS = ("iphone in use", "lock your iphone", "mirroring ended",
- "to connect", "connection paused", "connection interrupted",
- "is locked", "enter the mac login", "try again")
+def ops():
+ """Every op the current device implements."""
+ return phone.ops()
+# --- session / state --------------------------------------------------------
+
def connection_state():
- """'ready' | 'blocked' | 'no-window' | 'not-running'.
-
- 'blocked' means an interstitial is up — iPhone in Use, paused, ended,
- connect, or the Mac login screen — and nothing should be tapped or typed
- until the user clears it.
-
- Detected structurally: the live phone image is a video stream that
- accessibility cannot see into, so a working session exposes no UI inside
- the window, while every interstitial is an ordinary Mac view with labels
- and a button. That holds in any language and for screens Apple has not
- shipped yet, where matching known phrases does neither — the old list
- missed both "Connection Paused" and the Mac login prompt, and reported
- 'ready' for a password field.
-
- The phrase list is kept as a fallback in case an interstitial exposes no
- accessibility content.
- """
- if mirror.running_app() is None:
- return "not-running"
- if mirror.find_window() is None:
- return "no-window"
- if mirror.window_ax_content():
- return "blocked"
- path, win = mirror.capture() # window exists, so this won't launch anything
- texts = " ".join(o["text"] for o in _ocr.recognize(path, win)).lower()
- return "blocked" if any(m in texts for m in _BLOCKED_MARKERS) else "ready"
-
-
-def ensure_mirroring():
- """Return the mirroring window if the phone is connected and ready.
-
- Never launches the app, taps Connect/Continue, or polls to reconnect —
- resuming mirroring is physical and only the user can do it. If the session
- isn't ready, raises with instructions for the user. STOP and relay that
- message; do not try to tap through the connect screen yourself.
+ """Backend-defined state string; 'ready' means usable.
+
+ On iPhone Mirroring: 'ready' | 'blocked' | 'no-window' | 'not-running',
+ where 'blocked' means an interstitial is up and nothing should be tapped
+ or typed until the user clears it.
"""
- state = connection_state()
- if state == "ready":
- mirror.activate()
- return mirror.find_window()
- if state == "not-running":
- raise RuntimeError(
- "iPhone Mirroring isn't running. Please open the iPhone Mirroring "
- "app and connect your phone, then retry — reconnecting is physical, "
- "so I can't do it for you.")
- if state == "no-window":
- raise RuntimeError(
- "iPhone Mirroring is open but no phone is connected. Please connect "
- "your phone in the app, then retry.")
- # Quote the interstitial itself rather than guessing which one it is.
- # Button titles are unreliable — the same screen reported 'Connect' once
- # and an empty title a minute later — so only static text is used.
- said = " ".join(t for role, t in mirror.window_ax_content()
- if role == "AXStaticText" and t)
- detail = f" It says: {said}" if said else ""
- raise RuntimeError(
- "iPhone Mirroring is not connected — an interstitial is on screen."
- + detail
- + " This needs you: clear it on the Mac, and if it says 'iPhone in "
- "Use', LOCK your iPhone so mirroring can resume. Then retry. I will "
- "not tap Connect for you.")
+ return send("session.state")
+
+
+def ensure_device():
+ """Screen bounds if the device is usable, else raise telling the user what
+ they physically need to do. Never reconnects — that is the user's job."""
+ return send("session.require")
+
+
+ensure_mirroring = ensure_device # the old iOS-flavoured name still works
+
+
+def activate():
+ """Refocus if the transport needs it. A no-op where nothing needs focus."""
+ return send("session.refocus")
+
+
+def find_window():
+ """Screen bounds {x, y, w, h, id}, or None if there is no device."""
+ return send("screen.bounds")
def screen_info():
- """{window, frontmost, img_px} — bounds in screen points, capture size in px."""
- path, win = mirror.capture()
- w, h = _ocr.image_size(path)
- return {"window": win, "frontmost": mirror.is_frontmost(), "img_px": [w, h]}
+ """{window, frontmost, img_px} — bounds, focus state, capture size."""
+ from . import ocr as _vision
+ path, win = send("screen.capture")
+ w, h = _vision.image_size(path)
+ return {"window": win, "frontmost": bool(send("focus.probe")[0]),
+ "img_px": [w, h]}
def screenshot(path=None):
- """Capture the phone window to a PNG and return its path. View it to see
- the phone; combine with ocr() for coordinates."""
- p, _ = mirror.capture(path)
+ """Capture the screen to a PNG and return its path. View it to see the
+ phone; combine with ocr() for coordinates."""
+ p, _ = send("screen.capture", path=path)
return p
-# --- reading the screen ---
+# --- did we interrupt the user ----------------------------------------------
+
+def focus_probe():
+ """Opaque snapshot for focus.diff. Cheap; take one before and after."""
+ return send("focus.probe")
+
+
+def interruption(before, after):
+ """{raised, stole_focus} between two focus_probe() readings.
+
+ raised is the failure that matters — the window covered whatever the user
+ was looking at. stole_focus alone is tolerable: keystrokes are rerouted
+ but the screen is untouched.
+ """
+ return send("focus.diff", before=before, after=after)
+
+
+# --- reading the screen -----------------------------------------------------
def ocr(min_confidence=0.3):
- """All visible text with tap-ready screen-point centers:
- [{text, confidence, x, y, w, h}]. This is the element tree — prefer it
- over eyeballing screenshots for anything with a text label."""
- path, win = mirror.capture()
- return [o for o in _ocr.recognize(path, win)
- if o["confidence"] >= min_confidence]
+ """All visible text with tap-ready centers: [{text, confidence, source,
+ x, y, w, h}]. Prefer this over eyeballing screenshots for anything with a
+ text label. `source` is "pixels" when a recogniser inferred the string and
+ "tree" when the OS reported it exactly."""
+ return send("screen.text", min_confidence=min_confidence)
+
+
+def ocr_pixels(min_confidence=0.3):
+ """Force pixel OCR even where a tree exists — for canvas, games, and
+ WebViews without accessibility, whose text a tree cannot see."""
+ return send("screen.text_pixels", min_confidence=min_confidence)
def find_text(query, exact=False):
- """OCR results matching query (case-insensitive substring by default)."""
+ """Visible text matching query (case-insensitive substring by default)."""
q = query.lower()
return [o for o in ocr()
if (o["text"].lower() == q if exact else q in o["text"].lower())]
@@ -165,14 +149,87 @@ def tap_text(query, index=0, exact=False):
return hit
-# --- gestures relative to the phone window ---
+# --- accessibility tree (where the device has one) --------------------------
+
+def ui():
+ """The accessibility tree. Exact where ocr() is inferred. Raises
+ Unsupported on iPhone Mirroring, whose window is an opaque video stream —
+ gate on supports('tree')."""
+ return send("tree")
+
+
+def find_nodes(query=None, exact=False, clickable_only=False, nodes=None):
+ """Tree nodes matching `query` across text, description and resource-id."""
+ items = ui() if nodes is None else nodes
+ if clickable_only:
+ items = [n for n in items if n["clickable"]]
+ if query is None:
+ return items
+ q = query.lower()
+ return [n for n in items
+ if any((f.lower() == q if exact else q in f.lower())
+ for f in (n["text"], n["desc"], n["id"]) if f)]
+
+
+def tap_node(node):
+ """Tap a tree node's center."""
+ tap(node["x"], node["y"])
+ return node
+
+
+def tap_ui(query, index=0, exact=False, clickable_only=False):
+ """Find an element in the accessibility tree and tap it.
+
+ Preferred over tap_text() where a tree exists: exact bounds, and it sees
+ elements with no visible label — an icon carrying only a
+ content-description is invisible to OCR but present here.
+ """
+ nodes = ui()
+ hits = find_nodes(query, exact=exact, clickable_only=clickable_only,
+ nodes=nodes)
+ if not hits:
+ visible = [n["text"] or n["desc"] or n["id"]
+ for n in nodes if n["text"] or n["desc"] or n["id"]][:30]
+ raise RuntimeError(f"no element matches {query!r}; saw: {visible}")
+ return tap_node(hits[index])
+
+
+# --- input ------------------------------------------------------------------
+
+def tap(x, y):
+ return send("input.tap", x=x, y=y)
+
+
+def long_press(x, y, duration=0.8):
+ return send("input.press", x=x, y=y, duration=duration)
+
+
+def drag(x1, y1, x2, y2, duration=0.35, steps=14):
+ return send("input.drag", x1=x1, y1=y1, x2=x2, y2=y2,
+ duration=duration, steps=steps)
+
+
+def press(combo):
+ """press('return'), press('cmd+1')."""
+ return send("input.keys", combo=combo)
+
+
+def type_text(text, delay=0.03):
+ """Type into the focused field. Tap the field and let the keyboard appear
+ first — text sent before it has focus goes nowhere."""
+ return send("input.text", s=text, delay=delay)
+
+
+# --- gestures relative to the screen ----------------------------------------
def _win():
- return mirror.ensure_window()
+ """Bounds for gesture maths. screen.require, not session.require: reading
+ the rect should not run the full interstitial check on every swipe."""
+ return send("screen.require")
def swipe(direction, distance=0.4):
- """swipe('up'|'down'|'left'|'right') — a touch-drag centered in the window.
+ """swipe('up'|'down'|'left'|'right') — a touch-drag centered on screen.
Direction is finger motion: swipe('up') moves content up (scrolls down)."""
w = _win()
cx, cy = w["x"] + w["w"] / 2, w["y"] + w["h"] / 2
@@ -183,31 +240,33 @@ def swipe(direction, distance=0.4):
# Fast, short drag = a momentum flick. A slow drag barely registers on iOS
# (it won't even flip a Home-Screen page); the flick is what snaps pages
# and carousels. For scrolling lists use scroll()/scroll_collect() instead.
- mirror.drag(cx - dx / 2, cy - dy / 2, cx + dx / 2, cy + dy / 2,
- duration=0.12, steps=6)
+ drag(cx - dx / 2, cy - dy / 2, cx + dx / 2, cy + dy / 2,
+ duration=0.12, steps=6)
def scroll(amount=300):
- """Scroll-gesture at window center. Positive scrolls content down the way
- a trackpad two-finger-up does; use swipe() when momentum matters."""
+ """Scroll at screen center. Positive scrolls content down the way a
+ trackpad two-finger-up does; use swipe() when momentum matters."""
w = _win()
- mirror.scroll_wheel(-amount, w["x"] + w["w"] / 2, w["y"] + w["h"] / 2)
+ send("input.scroll", x=w["x"] + w["w"] / 2, y=w["y"] + w["h"] / 2,
+ dy=-amount)
-# --- scrolling through lists ---
+# --- scrolling through lists ------------------------------------------------
#
# End-of-list is decided by whether the SCREEN MOVED, never by whether the
-# caller's parser found new items. A dense list or a missed OCR row must not
-# read as "done" — only the pixels going still (after a settle window that lets
+# caller's parser found new items. A dense list or a missed row must not read
+# as "done" — only the content going still (after a settle window that lets
# lazy-loaded content arrive) means the end.
def _content_texts(min_conf=0.4, top_frac=0.06, bottom_frac=0.92):
- """OCR of the scrollable content area, excluding the volatile status bar
- (clock/battery) at top and the nav/home strip at bottom."""
- path, win = mirror.capture()
+ """Visible text within the scrollable band, excluding the volatile status
+ bar (clock/battery) at top and the nav/home strip at bottom — a clock that
+ ticks over would read as movement and stop end-detection ever firing."""
+ win = _win()
top = win["y"] + win["h"] * top_frac
bot = win["y"] + win["h"] * bottom_frac
- return [o for o in _ocr.recognize(path, win)
+ return [o for o in ocr()
if top < o["y"] < bot and o["confidence"] >= min_conf]
@@ -227,29 +286,26 @@ def scroll_screen(direction="up", amount=0.6, settle=2.5, moved_thresh=0.6):
spinner resolves before we judge movement).
Returns {moved, overlap, before, after, boxes} — `boxes` is the settled
- content OCR, ready to parse. `moved` is False when overlap >= moved_thresh:
+ content, ready to parse. `moved` is False when overlap >= moved_thresh:
the list didn't advance. The default 0.6 sits in the empirical gap between
- real forward progress (overlap < ~0.45) and overscroll bounce at a boundary
- (overlap > ~0.7), which springs the content and would otherwise read as
- movement and defeat end-detection.
+ real forward progress (overlap < ~0.45) and overscroll bounce at a
+ boundary (overlap > ~0.7), which springs the content and would otherwise
+ read as movement and defeat end-detection.
"""
- w = mirror.ensure_window()
+ w = _win()
sign = {"up": -1, "down": 1}.get(direction) # 'up' reveals content below
if sign is None:
raise ValueError(f"direction must be 'up' or 'down', got {direction!r}")
before = _text_set(_content_texts())
- # Wheel scroll, not drag: a slow touch-drag barely moves an iOS list and
- # bounces back, while wheel events advance it deterministically (proven on
- # long lists). amount is a fraction of window height.
- mirror.scroll_wheel(sign * int(w["h"] * amount),
- w["x"] + w["w"] / 2, w["y"] + w["h"] / 2, steps=10)
+ send("input.scroll", x=w["x"] + w["w"] / 2, y=w["y"] + w["h"] / 2,
+ dy=sign * int(w["h"] * amount), steps=10)
time.sleep(0.4)
prev_boxes, prev = None, None
deadline = time.time() + settle
while time.time() < deadline:
boxes = _content_texts()
cur = _text_set(boxes)
- if cur == prev: # two identical captures = settled
+ if cur == prev: # two identical reads = settled
break
prev, prev_boxes = cur, boxes
time.sleep(0.35)
@@ -262,9 +318,8 @@ def scroll_screen(direction="up", amount=0.6, settle=2.5, moved_thresh=0.6):
def scroll_until(done, direction="up", amount=0.6, max_scrolls=60, settle=2.5):
"""Scroll until `done(boxes)` is truthy or the list stops moving.
- `done` receives the current content OCR (list of boxes) and returns a
- truthy value to stop; that value is returned. Returns None if the end of
- the list is reached first.
+ `done` receives the current content and returns a truthy value to stop;
+ that value is returned. Returns None if the end is reached first.
"""
boxes = _content_texts()
hit = done(boxes)
@@ -283,7 +338,7 @@ def scroll_until(done, direction="up", amount=0.6, max_scrolls=60, settle=2.5):
if stale >= 2: # confirmed still after a retry
return None
time.sleep(0.8)
- mirror.activate()
+ activate()
return None
@@ -331,34 +386,52 @@ def scroll_collect(extract=None, key=None, direction="up", amount=0.6,
if stale >= end_after:
return {"items": order, "stop": "reached-end", "scrolls": i}
time.sleep(0.8) # extra grace for a slow lazy-load
- mirror.activate()
+ activate()
return {"items": order, "stop": "max-scrolls", "scrolls": max_scrolls}
-# --- navigation ---
+# --- navigation -------------------------------------------------------------
def home():
- """Go to the iPhone Home Screen (Cmd+1)."""
- press("cmd+1")
- time.sleep(0.8)
+ """Go to the Home Screen."""
+ return send("nav.home")
+
+
+def back():
+ """System Back. Unsupported on iPhone Mirroring — iOS has no Back button,
+ and faking one with an edge swipe is indistinguishable from a real result.
+ Gate on supports('nav.back')."""
+ return send("nav.back")
def app_switcher():
- press("cmd+2")
- time.sleep(0.8)
+ return send("nav.recents")
def open_app(name):
- """Open an app via Spotlight (Cmd+3): type name, return, wait for launch."""
- press("cmd+3")
- time.sleep(0.9)
- type_text(name)
- time.sleep(1.2) # let results populate before committing
- press("return")
+ """Launch an app. Returns the app id that was launched."""
+ result = send("apps.launch", name=name)
wait_stable()
+ return result
+
+
+def current_app():
+ """Foreground app id. Unsupported where the device exposes no inventory."""
+ return send("apps.current")
+
+
+def list_apps(include_system=False):
+ """Installed app ids."""
+ return send("apps.list", include_system=include_system)
+
+
+def shell(cmd, binary=False, timeout=60):
+ """Backend escape hatch. Unsupported on iOS, where the substrate is Quartz
+ rather than a command channel — `import Quartz` in your own script."""
+ return send("raw", cmd=cmd, binary=binary, timeout=timeout)
-# --- timing ---
+# --- timing -----------------------------------------------------------------
def wait(seconds=1.0):
time.sleep(seconds)
@@ -370,7 +443,7 @@ def wait_stable(timeout=6.0, interval=0.5, settle=2):
prev, same = None, 0
deadline = time.time() + timeout
while time.time() < deadline:
- path, _ = mirror.capture()
+ path, _ = send("screen.capture")
digest = hashlib.md5(Path(path).read_bytes()).hexdigest()
same = same + 1 if digest == prev else 0
if same >= settle - 1:
diff --git a/src/phone_harness/ios.py b/src/phone_harness/ios.py
new file mode 100644
index 0000000..67e7552
--- /dev/null
+++ b/src/phone_harness/ios.py
@@ -0,0 +1,203 @@
+"""iOS backend: the op vocabulary over iPhone Mirroring.
+
+An adapter, not a rewrite. mirror.py and background.py keep their shape and are
+imported as they are — they hold the details that were expensive to learn (why
+NSWorkspace's frontmost value is a constant, why a slow drag barely registers
+on iOS, why the live phone image is opaque to accessibility) and none of that
+should move just to change the seam above it.
+
+What iPhone Mirroring cannot do appears here as absence rather than emulation:
+
+ no `nav.back` iOS has no system Back button. Guessing at an edge swipe
+ returns something the caller cannot tell from a real Back.
+ no `apps.current` the window exposes no app inventory; the foreground app is
+ no `apps.list` only knowable by reading the screen.
+ no `tree` the phone image is a video stream, which is the whole
+ reason screen.text has to recognise glyphs.
+ no `raw` there is no single command channel the way adb is one. The
+ substrate is Quartz: `import Quartz` in your own script,
+ or reach through this backend's .mirror module.
+
+Each raises Unsupported, so a caller can ask rather than discover it by
+getting a plausible wrong answer.
+"""
+import importlib
+import os
+
+from . import ocr as _vision
+from .transport import Backend
+
+# Fallback only. The primary check is structural (see _session_state), and a
+# phrase list cannot be complete: it missed "Connection Paused" and the Mac
+# login screen in English, and misses every interstitial on a non-English
+# system.
+_BLOCKED_MARKERS = ("iphone in use", "lock your iphone", "mirroring ended",
+ "to connect", "connection paused", "connection interrupted",
+ "is locked", "enter the mac login", "try again")
+
+
+def _load_transport():
+ """background drives iPhone Mirroring without ever taking the window to the
+ front (SkyLight event records) and is the default: not covering the user's
+ screen is what you want unless something is broken. Its private SkyLight
+ symbols are not guaranteed across macOS builds, so fall back rather than
+ leaving the harness unusable."""
+ want_bg = os.environ.get("PHONE_HARNESS_BACKGROUND", "1").lower() not in (
+ "0", "false", "no")
+ if want_bg:
+ try:
+ return importlib.import_module(".background", __package__), True
+ except Exception:
+ pass
+ return importlib.import_module(".mirror", __package__), False
+
+
+class IPhone(Backend):
+ name = "iphone-mirroring"
+
+ def __init__(self):
+ self.mirror, self.background = _load_transport()
+
+ # --- screen ---------------------------------------------------------
+
+ def _screen_bounds(self):
+ return self.mirror.find_window()
+
+ def _screen_require(self):
+ """Bounds for gesture maths. Distinct from session.require, which is
+ the full connected gate — reading the window rect should not put the
+ session through an interstitial check on every swipe."""
+ return self.mirror.ensure_window()
+
+ def _screen_capture(self, path=None):
+ return self.mirror.capture(path)
+
+ def _screen_text(self, min_confidence=0.3):
+ path, win = self.mirror.capture()
+ return [dict(o, source="pixels")
+ for o in _vision.recognize(path, win)
+ if o["confidence"] >= min_confidence]
+
+ # Pixels are the only source iOS has ever had.
+ _screen_text_pixels = _screen_text
+
+ # --- input ----------------------------------------------------------
+
+ def _input_tap(self, x, y):
+ self.mirror.tap(x, y)
+
+ def _input_press(self, x, y, duration=0.8):
+ self.mirror.long_press(x, y, duration)
+
+ def _input_drag(self, x1, y1, x2, y2, duration=0.35, steps=14):
+ self.mirror.drag(x1, y1, x2, y2, duration=duration, steps=steps)
+
+ def _input_scroll(self, x, y, dy, steps=6):
+ self.mirror.scroll_wheel(dy, x, y, steps=steps)
+
+ def _input_keys(self, combo):
+ self.mirror.press(combo)
+
+ def _input_text(self, s, delay=0.03):
+ self.mirror.type_text(s, delay=delay)
+
+ # --- navigation -----------------------------------------------------
+
+ def _nav_home(self):
+ self.mirror.press("cmd+1")
+ _sleep(0.8)
+
+ def _nav_recents(self):
+ self.mirror.press("cmd+2")
+ _sleep(0.8)
+
+ # No _nav_back: iOS has no system Back button.
+
+ def _apps_launch(self, name):
+ """Spotlight (Cmd+3): type the name, let results populate, commit."""
+ self.mirror.press("cmd+3")
+ _sleep(0.9)
+ self.mirror.type_text(name)
+ _sleep(1.2)
+ self.mirror.press("return")
+ return name
+
+ # --- session --------------------------------------------------------
+
+ def _session_state(self):
+ """'ready' | 'blocked' | 'no-window' | 'not-running'.
+
+ 'blocked' means an interstitial is up — iPhone in Use, paused, ended,
+ connect, or the Mac login screen — and nothing should be tapped or
+ typed until the user clears it.
+
+ Detected structurally: the live phone image is a video stream that
+ accessibility cannot see into, so a working session exposes no UI
+ inside the window, while every interstitial is an ordinary Mac view
+ with labels and a button. That holds in any language and for screens
+ Apple has not shipped yet, where matching known phrases does neither —
+ the old list missed both "Connection Paused" and the Mac login prompt,
+ and reported 'ready' for a password field.
+ """
+ if self.mirror.running_app() is None:
+ return "not-running"
+ if self.mirror.find_window() is None:
+ return "no-window"
+ if self.mirror.window_ax_content():
+ return "blocked"
+ path, win = self.mirror.capture() # window exists, launches nothing
+ texts = " ".join(o["text"] for o in _vision.recognize(path, win)).lower()
+ return "blocked" if any(m in texts for m in _BLOCKED_MARKERS) else "ready"
+
+ def _session_detail(self):
+ """What the interstitial says, quoted rather than guessed at.
+
+ Button titles are not used: the same screen reported 'Connect' once and
+ an empty title a minute later.
+ """
+ return " ".join(t for role, t in self.mirror.window_ax_content()
+ if role == "AXStaticText" and t)
+
+ def _session_require(self):
+ """Bounds if the phone is connected and ready, else raise for the user.
+
+ Never launches the app, taps Connect/Continue, or polls to reconnect —
+ resuming mirroring is physical and only the user can do it. Relay the
+ message; do not try to tap through the connect screen.
+ """
+ state = self._session_state()
+ if state == "ready":
+ self.mirror.activate()
+ return self.mirror.find_window()
+ if state == "not-running":
+ raise RuntimeError(
+ "iPhone Mirroring isn't running. Please open the iPhone "
+ "Mirroring app and connect your phone, then retry — "
+ "reconnecting is physical, so I can't do it for you.")
+ if state == "no-window":
+ raise RuntimeError(
+ "iPhone Mirroring is open but no phone is connected. Please "
+ "connect your phone in the app, then retry.")
+ said = self._session_detail()
+ raise RuntimeError(
+ "iPhone Mirroring is not connected — an interstitial is on screen."
+ + (f" It says: {said}" if said else "")
+ + " This needs you: clear it on the Mac, and if it says 'iPhone in "
+ "Use', LOCK your iPhone so mirroring can resume. Then retry. I "
+ "will not tap Connect for you.")
+
+ def _session_refocus(self):
+ self.mirror.activate()
+
+ # --- interruption ---------------------------------------------------
+
+ def _focus_probe(self):
+ return self.mirror.focus_probe()
+
+ def _focus_diff(self, before, after):
+ return self.mirror.interruption(before, after)
+
+
+def _sleep(s):
+ import time
+ time.sleep(s)
diff --git a/src/phone_harness/transport.py b/src/phone_harness/transport.py
new file mode 100644
index 0000000..e01286d
--- /dev/null
+++ b/src/phone_harness/transport.py
@@ -0,0 +1,133 @@
+"""The one seam every device sits behind.
+
+A backend implements a single method — send(op, **kw) — over the op vocabulary
+below. Ops are named for what they MEAN, never for how a platform does them,
+which is what lets helpers.py carry no platform knowledge at all: `nav.home`
+means the same thing to an iPhone and a Pixel, though one is a Cmd+1 keystroke
+into a video stream and the other is a KEYCODE_HOME over adb.
+
+This mirrors browser-harness, where helpers.py has no idea whether the browser
+is local or in the cloud because everything funnels through cdp(). Phones have
+no shared wire protocol to funnel through — SkyLight event records and adb have
+nothing in common — so the shared layer is this vocabulary instead.
+
+ screen.capture path=None -> (png_path, bounds)
+ screen.bounds -> {x, y, w, h, id} or None
+ screen.require -> bounds, or raise
+ screen.text min_confidence -> [{text, confidence, source, x, y, w, h}]
+ screen.text_pixels min_confidence -> same, forced through pixel OCR
+
+ screen.text is the load-bearing op. iOS answers with Vision OCR over a
+ capture; a device with an accessibility tree answers from the tree.
+ Same contract, same coordinate space, very different fidelity, so each
+ box carries `source`: "pixels" means a recogniser inferred it and may
+ have misread, "tree" means the OS reported it exactly. It has to be an
+ explicit field — Vision returns confidence 1.0 for clean text just as a
+ tree does, so confidence cannot tell them apart.
+
+ input.tap x, y
+ input.press x, y, duration long press
+ input.drag x1, y1, x2, y2, duration, steps
+ input.scroll x, y, dy, steps +dy scrolls content up
+ input.keys combo
+ input.text s, delay
+
+ duration and steps stay in the vocabulary rather than being hidden. On
+ iOS a fast short drag is a momentum flick and a slow one barely
+ registers; over adb the same knob decides whether a list flings past
+ rows between captures. Abstracting it away would cost behaviour.
+
+ nav.home / nav.back / nav.recents
+ apps.launch name -> app id
+ apps.current -> app id or None
+ apps.list include_system=False -> [app id]
+
+ Unsupported where the concept does not exist, rather than emulated.
+ iPhone Mirroring has no system Back button and exposes no app
+ inventory; Android has no Spotlight. A fake Back that guesses at an
+ edge swipe returns a result the caller cannot tell from a real one.
+
+ session.state -> backend-defined string, 'ready' when usable
+ session.require -> bounds, or raise telling the USER what to do
+ session.refocus -> None (a no-op where nothing needs focus)
+ session.detail -> str, why the session is unusable
+
+ focus.probe -> opaque snapshot
+ focus.diff before, after -> {raised, stole_focus}
+
+ Whether driving the phone disturbed whatever the user was doing. Two
+ separate questions on purpose: taking keyboard focus is a mild
+ annoyance, covering the screen is not, and a backend that reaches the
+ device directly does neither.
+
+ tree -> [node] where the device has one
+ raw ... backend-specific escape hatch
+
+Anything a backend genuinely cannot do raises Unsupported. Callers gate on
+supports(op) rather than guessing.
+"""
+import importlib
+import os
+
+
+class Unsupported(RuntimeError):
+ """This device cannot do that op, and retrying will not help.
+
+ Distinct from a failure: iPhone Mirroring has no accessibility tree, so
+ `tree` is not a flaky call, it is absent.
+ """
+
+
+OP_NAMES = (
+ "screen.capture", "screen.bounds", "screen.require",
+ "screen.text", "screen.text_pixels",
+ "input.tap", "input.press", "input.drag", "input.scroll",
+ "input.keys", "input.text",
+ "nav.home", "nav.back", "nav.recents",
+ "apps.launch", "apps.current", "apps.list",
+ "session.state", "session.require", "session.refocus", "session.detail",
+ "focus.probe", "focus.diff",
+ "tree", "raw",
+)
+
+
+class Backend:
+ """Dispatches send() to _screen_capture, _input_tap, _nav_home, and so on.
+
+ A subclass defines only the ops it can honour; everything it omits becomes
+ Unsupported automatically, so a backend never keeps a capability list in
+ sync with its own code.
+ """
+
+ name = "backend"
+
+ def _slot(self, op):
+ return "_" + op.replace(".", "_")
+
+ def send(self, op, **kw):
+ fn = getattr(self, self._slot(op), None)
+ if fn is None:
+ raise Unsupported(f"{self.name} cannot {op!r}")
+ return fn(**kw)
+
+ def supports(self, op):
+ return getattr(self, self._slot(op), None) is not None
+
+ def ops(self):
+ """Every op this backend implements, filtered against the vocabulary so
+ internal helpers can never masquerade as ops."""
+ return [op for op in OP_NAMES if self.supports(op)]
+
+
+def connect(platform=None, **kw):
+ """Build a backend. PHONE_HARNESS_PLATFORM selects one; default is ios.
+
+ Returns an object rather than installing a module global, so a script can
+ hold two devices at once instead of being limited to one per process.
+ helpers.py binds one of these as its default.
+ """
+ platform = (platform
+ or os.environ.get("PHONE_HARNESS_PLATFORM", "ios")).lower()
+ if platform in ("ios", "iphone", "ipad"):
+ return importlib.import_module(".ios", __package__).IPhone(**kw)
+ raise ValueError(f"unknown platform {platform!r}")