Skip to content

let your agent control your phone

Press Connect once when iPhone Mirroring is paused (#115)

shawn pana9a6fb5dd3865
diff --git a/SKILL.md b/SKILL.md
index 9d81ffa..5665136 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -16,9 +16,19 @@ of you.
| Phone | How it is reached | Eyes | Hands | Read |
| --- | --- | --- | --- | --- |
| **Cloud Android** - rented from Phone Harness Cloud, the user's own saved phone | `phone-harness cloud start` connects it; nothing to export | accessibility tree (exact), Vision OCR fallback on a Mac | adb `input` | Working method, then **Cloud phones** and **Android** |
-| **Cloud iPhone** - an iOS entry in the account catalog | `phone-harness cloud start` with its id, label, or `ios` when that is the only one | server-side OCR (`source: "pixels"`), from any OS | ops over HTTPS | Working method, then **Cloud iPhone** |
+| **Cloud iPhone** - a second iPhone hosted by Phone Harness Cloud, not the one in the user's pocket; an iOS entry in the account catalog | `phone-harness cloud start` with its id, label, or `ios` when that is the only one | server-side OCR (`source: "pixels"`), from any OS | ops over HTTPS | Working method, then **Cloud iPhone** |
| **Android on the desk** - USB or paired Wi-Fi | the harness finds it | accessibility tree (exact), Vision OCR fallback on a Mac | adb `input` | Working method, then **Android** |
-| **iPhone** - through the Mac's iPhone Mirroring window | the user connects it | screenshots + Vision OCR | HID-level CGEvents into the window | Working method, then **iPhone** |
+| **Personal iPhone** - the user's own phone, through the Mac's iPhone Mirroring window | the harness opens Mirroring and presses Connect; the user locks the phone | screenshots + Vision OCR | HID-level CGEvents into the window | Working method, then **iPhone** |
+
+**"My phone" means the personal one.** The personal iPhone and the cloud
+iPhone are two different devices with different apps and logins: the first is
+in the user's pocket and mirrored onto the Mac, the second lives in a data
+centre and is reached over HTTPS. When the user says "my phone", "my iPhone",
+or names an app they use, drive the personal iPhone. Use a cloud phone only
+when the user names it ("the cloud phone", `cloud start`) or the task is
+clearly about it. If the personal phone cannot be reached, say so and ask;
+never fall through to a cloud session that happens to be running, even one
+the user started - it is theirs, and it is a different phone.
`phone-harness config` shows the default platform (`ios` on a Mac, `android`
elsewhere) and every other setting. `phone-harness cloud` shows whether a cloud
@@ -104,11 +114,14 @@ PY
following, purchasing, deleting, changing settings. Never type a PIN, a
password or a 2FA code; on a cloud phone, hand the controls over instead
(`phone-harness cloud open`, below).
-- **Connection is the user's job.** Pairing, unlocking, tapping Allow,
- locking an iPhone that says "iPhone in Use", approving a cloud sign-in in
- the browser: when the harness says the phone is not reachable, relay its
- message and ask - never tap through a Connect screen and never loop-poll.
- Retry once after the user says it is done.
+- **The harness reconnects what it can; the rest is the user's.** On a
+ personal iPhone, start the task with `ensure_mirroring()`: it opens iPhone
+ Mirroring if it is closed, presses the window's Connect once, and brings
+ the window to the front so the user can watch. Pairing, unlocking, tapping Allow,
+ locking an iPhone that says "iPhone in Use" or "Timed Out", approving a
+ cloud sign-in in the browser: when the harness still says the phone is not
+ reachable, relay its message and ask - never loop-poll. Retry once after
+ the user says it is done; that retry presses Connect again.
## Cloud phones
@@ -207,9 +220,11 @@ unambiguous, or the entry's id or label (`cloud ls`). The create body is
`platform: "ios"`, `kind: "device"`, and `device_id` set to that entry's id.
A ready session carries `control: {url, token, expires_at}` and no `adb`.
From then on the helpers drive it over HTTPS. This machine needs no adb, no
-shell, and no Mac. `cloud stop` ends billing and returns at once; the phone
-keeps its own data. There is no Android-style disk save, and nothing on this
-phone for `cloud phone` to wipe.
+shell, and no Mac. It is a phone granted to the user's account and kept
+between sessions - not the personal iPhone mirrored on the Mac, which is a
+different device with its own apps and logins. `cloud stop` ends billing
+and returns at once; the phone keeps its own data. There is no Android-style
+disk save, and nothing on this phone for `cloud phone` to wipe.
An Android session can stay up beside it. Target one with `--session SID`.
`cloud use SID` only changes the terminal fallback.
@@ -366,8 +381,15 @@ The Mac's iPhone Mirroring app renders the phone as a window; the harness
captures that window and OCRs it with Vision for eyes, and posts HID-level
events into it for hands. All coordinates are global macOS screen points.
-- `ensure_mirroring()` launches the window and gates on connection. The
- default build works the phone **without taking the user's focus**: capture
+- **Start every task with `ensure_mirroring()`.** It opens iPhone Mirroring
+ if it is not running, brings the window to the front so the user sees what
+ you see, presses the interstitial's Connect once through accessibility,
+ and waits for the live stream. A phone that is in use shows up within
+ about three seconds and it raises then, with the window's own words,
+ rather than sitting out a timeout. It is the cheapest first line a script
+ can have: a phone that cannot be driven fails there, not five taps in.
+ Call it once in the first script of a task, not before every action.
+ After that, the default build works the phone **without taking the user's focus**: capture
is by window id and taps and keystrokes are event records delivered straight
to the app. Scrolling is the exception - macOS routes a scroll to whichever
window sits under the pointer, so a scroll raises the mirroring window for
@@ -396,13 +418,22 @@ events into it for hands. All coordinates are global macOS screen points.
Pass `keystrokes=True` for fields that need real key events. The typed text
stays on the Mac clipboard afterwards. If a tap will not take focus,
`press("tab")` moves between fields.
-- **Connecting is the user's job, and so is resuming.** `ensure_mirroring()`
- raises a clear message when the phone is not connected (`connection_state()`
- is `ready` / `blocked` / `no-window` / `not-running`). **STOP and relay it.**
- Never tap `Connect` / `Continue` and never loop-poll: tapping Connect while
- the phone is unlocked does nothing, and the only fix is the user locking or
- connecting the phone. **Unlocking the physical phone pauses the session**
- ("iPhone in Use") - do not tap through the resume screen.
+- **What the harness cannot clear is physical.** Connect only works while
+ the iPhone is locked; "iPhone in Use" and "Timed Out ... due to iPhone use"
+ mean it was not. `ensure_mirroring()` presses Connect once and then raises
+ quoting the screen (`connection_state()` is `ready` / `blocked` /
+ `no-window` / `not-running`). **STOP and relay it**, ask the user to lock
+ the phone, and retry once when they say so. The app reconnects by itself
+ the moment the phone is locked, so the retry usually finds it live; if
+ not, it presses Connect again. Do not press it yourself in a loop and do
+ not tap the window (an interstitial is a Mac view; taps meant for the
+ phone go nowhere). **Unlocking the physical phone pauses the session**
+ ("iPhone in Use") - the same rule applies mid-task. Taps, scrolls, swipes,
+ typing, key presses, `open_app`, `home`, and `screenshot` raise that same
+ message and do not press Connect. Ask the user to lock the phone, then
+ call `ensure_mirroring()` and continue from the step that raised.
+ The Mac login prompt that
+ sometimes appears in the window is never typed into.
- **Unfocused input is swallowed silently - for events you post yourself.**
The helpers are immune in the background build, but raw CGEvents and the
`PHONE_HARNESS_BACKGROUND=0` path need the window frontmost: `activate()`
diff --git a/src/phone_harness/background.py b/src/phone_harness/background.py
index ddbd943..4562391 100644
--- a/src/phone_harness/background.py
+++ b/src/phone_harness/background.py
@@ -87,6 +87,11 @@ def find_window():
running_app = mirror.running_app
window_ax_content = mirror.window_ax_content
+window_ax_buttons = mirror.window_ax_buttons
+press_window_button = mirror.press_window_button
+ax_observer_target = mirror.ax_observer_target
+ax_session_hint = mirror.ax_session_hint
+launch = mirror.launch
focus_probe = mirror.focus_probe
interruption = mirror.interruption
frontmost_window = mirror.frontmost_window
@@ -103,6 +108,11 @@ def activate():
return None
+# session.require shows the window once at the start of a task so the user
+# can watch; that is the only time this backend raises it on purpose.
+show = mirror.activate
+
+
def ensure_window(timeout=5.0):
win = find_window()
if win is None:
diff --git a/src/phone_harness/helpers.py b/src/phone_harness/helpers.py
index 65f2b90..0ff7b24 100644
--- a/src/phone_harness/helpers.py
+++ b/src/phone_harness/helpers.py
@@ -62,14 +62,18 @@ def connection_state():
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.
+ or typed until it is cleared — ensure_device() tries that once.
"""
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."""
+ """Screen bounds once the device is usable, else raise telling the user
+ what they physically need to do.
+
+ On iPhone Mirroring this launches the app if it is not running and
+ presses the interstitial's Connect once; what it cannot clear (an
+ unlocked phone, a login prompt) comes back as the error text."""
return send("session.require")
diff --git a/src/phone_harness/ios.py b/src/phone_harness/ios.py
index 6d287db..f145181 100644
--- a/src/phone_harness/ios.py
+++ b/src/phone_harness/ios.py
@@ -57,6 +57,22 @@ class IPhone(Backend):
def __init__(self):
self.mirror, self.background = _load_transport()
+ self._session_watch = None
+ self._session_watch_off = False
+ self._session_lost = None
+ self._note_seen = False
+
+ def send(self, op, **kw):
+ """Run `op`. Actions and captures check the stream first and again
+ after, and raise if it is no longer live. They do not press Connect:
+ a takeover means the user has the phone."""
+ watch = op in _ACTION_OPS
+ if watch:
+ self._raise_if_not_live()
+ result = super().send(op, **kw)
+ if watch:
+ self._raise_if_not_live()
+ return result
# --- screen ---------------------------------------------------------
@@ -65,8 +81,8 @@ class IPhone(Backend):
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."""
+ the full connected gate. The liveness check lives on the action
+ (see send), not on this bounds read."""
return self.mirror.ensure_window()
def _screen_capture(self, path=None):
@@ -162,32 +178,312 @@ class IPhone(Backend):
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.
+ """Bounds once the phone is connected and ready.
+
+ First does what the user would do by hand: opens iPhone Mirroring
+ when it is not running, and presses the interstitial's own button
+ (Connect, Try Again, Continue) once. What is left after that is
+ physical — an unlocked phone ("iPhone in Use", "Timed Out"), the Mac
+ login prompt, a phone that is not paired — and only the user can
+ clear it, so this raises quoting the window rather than pressing
+ again. A Connecting screen is not that case, and neither is the blank
+ window launch draws before any label: no text and no buttons. Both
+ are waited out. A cold launch connects by itself.
+ Once the phone is live the window is brought to the front so
+ the user can watch the task. One press per call: a caller that retries after the user says
+ the phone is locked gets a fresh press.
"""
state = self._session_state()
+ if state == "not-running":
+ self.mirror.launch()
+ state = self._wait_state(("blocked", "ready"), _LAUNCH_WAIT)
+ # Shown before anything else so the user sees what the harness sees,
+ # the interstitial included, not only a session that worked.
+ self._show()
+ if state == "no-window":
+ state = self._wait_state(("blocked", "ready"), _WINDOW_WAIT)
+ pressed = None
+ if state == "blocked":
+ pressed = self._press_connect()
+ # Wait when the press is in flight: we pressed something, the
+ # window says "Connecting to", or it is still the blank window
+ # launch draws before any label. A finished interstitial (text
+ # or a button, and not Connecting) raises below instead.
+ if pressed or not self._finished_interstitial():
+ state = self._wait_connected(_CONNECT_WAIT)
if state == "ready":
- self.mirror.activate()
return self.mirror.find_window()
+ self._raise_not_live(state, pressed)
+
+ def _raise_if_not_live(self):
+ """Raise the session-require error if the stream is no longer live.
+
+ Does not press Connect and does not launch the app. A long-lived
+ accessibility observer is drained with a zero timeout so a window
+ change already queued is applied first; a missed notification still
+ loses to one structural read (no capture, no OCR)."""
+ state = self._live_probe()
+ if state != "ready":
+ self._raise_not_live(state)
+
+ def _live_probe(self):
+ """Current liveness, cheaply.
+
+ Two structural reads bracket each guarded action (before and after).
+ Each read is one ax_session_hint(): the running app, the phone
+ window, and whether that window has any accessibility children. A
+ live stream has none. There is no screen capture and no Vision OCR,
+ which is what a full session.state costs.
+
+ When the observer is up, a zero-timeout run-loop turn delivers a
+ notification that arrived since the last action, and that
+ notification's own read is the answer. The turn does not sleep.
+ Measured here, where there is no accessibility server: the guard
+ around one live action is under 0.01 ms of Python. On a Mac the
+ rest is ax_session_hint, twice per action (before and after): one
+ lookup of the app, its window, and that window's children. A live
+ stream has no children, so the walk stops at the window.
+ """
+ self._arm_session_watch()
+ self._note_seen = False
+ if self._session_watch is not None:
+ _drain_run_loop()
+ if self._note_seen:
+ return self._session_lost
+ return self._structural_state()
+
+ def _arm_session_watch(self):
+ """Install the observer once. A transport with no target (the fakes)
+ fails closed and every later probe uses the structural read."""
+ if not hasattr(self, "_session_watch"):
+ self._session_watch = None
+ self._session_watch_off = False
+ self._session_lost = None
+ self._note_seen = False
+ if self._session_watch is not None or self._session_watch_off:
+ return
+
+ def on_notify():
+ state = self._structural_state()
+ self._session_lost = state
+ self._note_seen = True
+
+ try:
+ self._session_watch = _ax_watch_open(self.mirror, on_notify)
+ except _ObserverUnavailable:
+ self._session_watch = None
+ self._session_watch_off = True
+
+ def _structural_state(self):
+ """ready | blocked | no-window | not-running, without capture or OCR."""
+ hint = getattr(self.mirror, "ax_session_hint", None)
+ if hint is not None:
+ return hint()
+ 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"
+ return "ready"
+
+ def _raise_not_live(self, state, pressed=None):
+ """The error ensure_mirroring raises, without pressing anything."""
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.")
+ "iPhone Mirroring would not launch. Please open the iPhone "
+ "Mirroring app and connect your phone, then retry.")
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()
+ "iPhone Mirroring is open but shows no phone window. Pair "
+ "the phone in the app (it has to be nearby, locked, and "
+ "signed in to the same Apple Account), then retry.")
+ said = self._session_detail() or "an interstitial with no text"
+ did = (f"I pressed {pressed} and it came back with"
+ if pressed else "It says")
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.")
+ f"iPhone Mirroring is not connected. {did}: {said}. This needs "
+ "you: if it mentions the iPhone being in use or timing out, LOCK "
+ "your iPhone, then tell me and I will try once more. I never "
+ "type a passcode.")
+
+ def _show(self):
+ """Bring the mirroring window to the front so the user can watch.
+ Best effort: a window that will not come forward is not a reason to
+ fail the session, since the background build drives it regardless."""
+ try:
+ self.mirror.show()
+ except Exception:
+ pass
+
+ def _press_connect(self):
+ """Press the interstitial's button through accessibility, once.
+
+ Returns the title pressed, or None when there is nothing safe to
+ press: no button, several buttons (the choice is the user's), or a
+ login prompt — pressing Unlock without a password does nothing, and
+ the password is never ours to type.
+ """
+ content = self.mirror.window_ax_content()
+ if any(role in ("AXTextField", "AXSecureTextField")
+ for role, _ in content):
+ return None
+ buttons = [t for role, t in content if role == "AXButton"]
+ if len(buttons) == 1 and buttons[0].lower() not in _NOT_CONNECT_BUTTONS:
+ return self.mirror.press_window_button()
+ return self.mirror.press_window_button(_CONNECT_BUTTONS)
+
+ def _wait_state(self, wanted, timeout):
+ """Poll until the session is in one of `wanted` or time runs out;
+ returns the last state seen."""
+ deadline = _now() + timeout
+ state = self._session_state()
+ while state not in wanted and _now() < deadline:
+ _sleep(0.5)
+ state = self._session_state()
+ return state
+
+ def _wait_connected(self, timeout):
+ """Wait for the live stream, and fail fast otherwise.
+
+ Used after a Connect press, and when the window is already the
+ Connecting screen so there was nothing to press.
+
+ The attempt is watched through an accessibility observer on iPhone
+ Mirroring, so the Connecting screen is noticed when it changes rather
+ than on a timer. A hang emits nothing, so the wait still gives up at
+ `timeout`. If the observer cannot be installed, the same decision is
+ made by polling.
+
+ 'ready' has to hold for three evaluations in a row. Measured: the
+ press empties the window for about half a second before "Connecting
+ to" draws, and one empty read in that gap looks live.
+
+ The Connecting screen is in progress when its text contains
+ "Connecting to" or it offers a Background button. So is a blocked
+ window with no text and no buttons: measured on a cold launch, that
+ blank is what is drawn before "Connecting to" appears, and treating
+ it as a finished interstitial raised "an interstitial with no text"
+ while the stream was still coming up. A blocked interstitial with
+ recognizable text or buttons that is not Connecting — "iPhone in
+ Use", locked, timed out — is the answer once the attempt has had a
+ couple of seconds to draw, so it fails then instead of sitting out
+ the cap. The user locking the phone is what fixes it, and the app
+ reconnects by itself, so the next session.require finds it live."""
+ try:
+ return self._wait_connected_events(timeout)
+ except _ObserverUnavailable:
+ return self._wait_connected_polling(timeout)
+
+ def _wait_connected_events(self, timeout):
+ """Event-driven wait. One evaluation on entry, then again on every
+ accessibility notification. If a notification is missed, the same
+ check runs about once a second so the attempt cannot stall."""
+ start = _now()
+ streak = 0
+ state = "blocked"
+ decided = None
+ last_event = start
+
+ def evaluate():
+ nonlocal streak, state, decided
+ state = self._session_state()
+ decided, streak = self._connection_choice(
+ state, streak, _now() - start)
+
+ def on_notify():
+ nonlocal last_event
+ last_event = _now()
+ evaluate()
+ if decided is not None:
+ _stop_run_loop()
+
+ watch = _ax_watch_open(self.mirror, on_notify)
+ try:
+ evaluate()
+ if decided is not None:
+ return decided
+ while _now() - start < timeout:
+ remaining = timeout - (_now() - start)
+ before = _now()
+ _run_loop_slice(min(_EVENT_SLICE, remaining))
+ if decided is not None:
+ return decided
+ # A hang, or a notification the observer did not deliver.
+ if _now() - last_event >= _EVENT_QUIET:
+ evaluate()
+ last_event = _now()
+ if decided is not None:
+ return decided
+ if _now() <= before:
+ _sleep(min(_EVENT_SLICE, timeout - (_now() - start)))
+ return "blocked" if state == "ready" and streak < 3 else state
+ finally:
+ watch.close()
+
+ def _wait_connected_polling(self, timeout):
+ """The pre-observer wait, used when AXObserver cannot be installed.
+
+ Same decisions as the event wait, including treating a "Connecting
+ to" screen with no buttons as still in progress."""
+ start = _now()
+ _sleep(1.0)
+ streak = 0
+ state = self._session_state()
+ while _now() - start < timeout:
+ decided, streak = self._connection_choice(
+ state, streak, _now() - start)
+ if decided is not None:
+ return decided
+ _sleep(0.5)
+ state = self._session_state()
+ return "blocked" if state == "ready" and streak < 3 else state
+
+ def _connection_choice(self, state, streak, elapsed):
+ """('ready' | 'blocked' | None, streak) for one look at the window.
+
+ None means the attempt is still in progress. 'ready' only after the
+ live stream has held for three looks. 'blocked' is a finished
+ interstitial (recognizable text or buttons, and not Connecting)
+ once the attempt has had time to draw a label. A blank window is
+ not finished."""
+ streak = streak + 1 if state == "ready" else 0
+ if streak >= 3:
+ return "ready", streak
+ if (state == "blocked" and elapsed > _ATTEMPT_SETTLE
+ and self._finished_interstitial()):
+ return "blocked", streak
+ return None, streak
+
+ def _finished_interstitial(self):
+ """A blocked window that has something to read, and is not Connecting.
+
+ No text and no buttons is transitional: the phone window is up but
+ the Connecting label has not been drawn. That holds before a press
+ and after one. "Connecting to" or a Background button is the same
+ wait, not a failure."""
+ if self._still_connecting():
+ return False
+ return self._recognizable_ui()
+
+ def _recognizable_ui(self):
+ """True when the window shows text or a button title."""
+ content = self.mirror.window_ax_content()
+ if any(t.strip() for _role, t in content if t):
+ return True
+ return any(t.strip() for t, _el in self.mirror.window_ax_buttons() if t)
+
+ def _still_connecting(self):
+ """The Connecting screen, including one that has no buttons.
+
+ The words are the signal. A Background button is the other form of
+ the same screen; either one means the press has not finished."""
+ content = self.mirror.window_ax_content()
+ text = " ".join(t for _role, t in content if t).lower()
+ if "connecting to" in text:
+ return True
+ return any(t.lower() == "background"
+ for t, _el in self.mirror.window_ax_buttons())
def _session_refocus(self):
self.mirror.activate()
@@ -201,6 +497,228 @@ class IPhone(Backend):
return self.mirror.interruption(before, after)
+# Buttons an interstitial offers that mean "try to connect"; pressed once
+# per session.require. Lower-case; matched case-insensitively.
+_CONNECT_BUTTONS = ("connect", "try again", "retry", "continue", "reconnect")
+# A lone button that is not an attempt to connect: "Background" on the
+# Connecting screen sends the app behind, "Cancel" gives up.
+_NOT_CONNECT_BUTTONS = ("background", "cancel", "quit", "unlock", "ok",
+ "done", "settings")
+_LAUNCH_WAIT = 12.0 # app launch to phone window
+_WINDOW_WAIT = 6.0 # app running, window still coming up
+_CONNECT_WAIT = 12.0 # press to live stream, the cap; a hang emits no events
+_ATTEMPT_SETTLE = 2.5 # a press has drawn Connecting and then its outcome by now
+_EVENT_SLICE = 0.2 # how long one CFRunLoopRunInMode turn waits
+_EVENT_QUIET = 1.0 # re-check when no notification arrives for this long
+
+# Posted on the app element and the phone window. A Connecting screen that
+# never exposes a button still changes one of these as its label appears and
+# as the live stream replaces it.
+_AX_NOTIFICATIONS = (
+ "kAXValueChangedNotification",
+ "kAXTitleChangedNotification",
+ "kAXUIElementDestroyedNotification",
+ "kAXCreatedNotification",
+ "kAXWindowCreatedNotification",
+ "kAXLayoutChangedNotification",
+ "kAXFocusedUIElementChangedNotification",
+)
+_AX_NOTIFICATION_NAMES = (
+ "AXValueChanged",
+ "AXTitleChanged",
+ "AXUIElementDestroyed",
+ "AXCreated",
+ "AXWindowCreated",
+ "AXLayoutChanged",
+ "AXFocusedUIElementChanged",
+)
+
+
+class _ObserverUnavailable(Exception):
+ """AXObserver could not be installed. The polling wait is the fallback."""
+
+
+class _AxWatch:
+ """An observer and the run-loop source it was scheduled on.
+
+ close() removes both. It is safe to call twice, and a failure while
+ removing one does not skip the other."""
+
+ def __init__(self, remove_note, remove_source, notes, callback):
+ self._remove_note = remove_note
+ self._remove_source = remove_source
+ self._notes = list(notes)
+ self._callback = callback # the observer holds this too
+ self.closed = False
+
+ def close(self):
+ if self.closed:
+ return
+ self.closed = True
+ try:
+ self._remove_source()
+ except Exception:
+ pass
+ for el, name in self._notes:
+ try:
+ self._remove_note(el, name)
+ except Exception:
+ pass
+
+
+def _ax_watch_open(mirror, on_notify):
+ """Observe iPhone Mirroring and call `on_notify` for each notification.
+
+ `on_notify` takes no arguments. The caller runs the observer's run-loop
+ source in short slices via `_run_loop_slice` and must `close()` the
+ returned watch.
+
+ Raises _ObserverUnavailable, without probing the app, when this transport
+ has no `ax_observer_target`. A test double therefore falls straight
+ through to polling and does not consume a scripted frame.
+ """
+ target = getattr(mirror, "ax_observer_target", None)
+ if target is None:
+ raise _ObserverUnavailable(
+ "this transport has no accessibility observer")
+ try:
+ opened = target()
+ except Exception as exc:
+ raise _ObserverUnavailable(
+ "could not read the mirroring app for an observer") from exc
+ if not opened or len(opened) != 2:
+ raise _ObserverUnavailable("the mirroring app is not observable")
+ pid, elements = opened
+ elements = [el for el in (elements or []) if el is not None]
+ if pid is None or not elements:
+ raise _ObserverUnavailable("the mirroring app is not observable")
+
+ try:
+ import ApplicationServices as ax
+ import CoreFoundation as cf
+ except Exception as exc:
+ raise _ObserverUnavailable(
+ "accessibility observer support is unavailable") from exc
+
+ holder = {"fn": on_notify}
+
+ def callback(observer, element, notification, refcon):
+ # One bad notification must not kill the run loop. The caller's
+ # quiet re-check evaluates again outside the callback.
+ try:
+ holder["fn"]()
+ except Exception:
+ pass
+
+ try:
+ try:
+ created = ax.AXObserverCreate(int(pid), callback, None)
+ except TypeError:
+ created = ax.AXObserverCreate(int(pid), callback)
+ except Exception as exc:
+ raise _ObserverUnavailable("AXObserverCreate failed") from exc
+ if isinstance(created, tuple):
+ err = created[0]
+ observer = created[1] if len(created) > 1 else None
+ else:
+ err, observer = 0, created
+ if err or observer is None:
+ raise _ObserverUnavailable("AXObserverCreate failed")
+
+ try:
+ source = ax.AXObserverGetRunLoopSource(observer)
+ except Exception as exc:
+ raise _ObserverUnavailable(
+ "the observer has no run-loop source") from exc
+ if source is None:
+ raise _ObserverUnavailable("the observer has no run-loop source")
+ try:
+ loop = cf.CFRunLoopGetCurrent()
+ mode = cf.kCFRunLoopDefaultMode
+ cf.CFRunLoopAddSource(loop, source, mode)
+ except Exception as exc:
+ raise _ObserverUnavailable(
+ "could not schedule the observer") from exc
+
+ names = [getattr(ax, const, None) or fallback
+ for const, fallback in zip(_AX_NOTIFICATIONS,
+ _AX_NOTIFICATION_NAMES)]
+ added = []
+
+ def remove_source():
+ cf.CFRunLoopRemoveSource(loop, source, mode)
+
+ try:
+ for el in elements:
+ for name in names:
+ try:
+ note_err = ax.AXObserverAddNotification(
+ observer, el, name, None)
+ except Exception:
+ continue
+ if not note_err:
+ added.append((el, name))
+ if not added:
+ raise _ObserverUnavailable(
+ "no accessibility notifications were registered")
+ except _ObserverUnavailable:
+ try:
+ remove_source()
+ except Exception:
+ pass
+ raise
+
+ def remove_note(el, name):
+ ax.AXObserverRemoveNotification(observer, el, name)
+
+ return _AxWatch(remove_note, remove_source, added, callback)
+
+
+# Ops that drive the phone or read its screen. Each one refuses to run
+# against a paused window. session.require is not here: that is the one
+# call allowed to press Connect, and only when the user asks to resume.
+_ACTION_OPS = frozenset({
+ "screen.capture", "screen.text", "screen.text_pixels",
+ "input.tap", "input.press", "input.drag", "input.scroll",
+ "input.keys", "input.text",
+ "nav.home", "nav.recents",
+ "apps.launch",
+})
+
+
+def _drain_run_loop():
+ """Deliver accessibility notifications already queued. Does not wait.
+
+ Timeout 0 and returnAfterSourceHandled true: one ready source runs, and
+ if none is ready this returns immediately. A hang cannot add a sleep to
+ every tap.
+ """
+ import CoreFoundation as cf
+ cf.CFRunLoopRunInMode(cf.kCFRunLoopDefaultMode, 0, True)
+
+
+def _run_loop_slice(seconds):
+ """Run the current thread's run loop long enough for one burst of
+ accessibility notifications. returnAfterSourceHandled is false so a
+ single event does not end the slice early; the callback stops the loop
+ itself once the attempt is decided."""
+ import CoreFoundation as cf
+ cf.CFRunLoopRunInMode(cf.kCFRunLoopDefaultMode, float(seconds), False)
+
+
+def _stop_run_loop():
+ try:
+ import CoreFoundation as cf
+ cf.CFRunLoopStop(cf.CFRunLoopGetCurrent())
+ except Exception:
+ pass
+
+
+def _now():
+ import time
+ return time.time()
+
+
def _sleep(s):
import time
time.sleep(s)
diff --git a/src/phone_harness/mirror.py b/src/phone_harness/mirror.py
index b80fe3f..8a47451 100644
--- a/src/phone_harness/mirror.py
+++ b/src/phone_harness/mirror.py
@@ -149,10 +149,93 @@ def window_ax_content():
minute later — so callers should read AXStaticText for anything shown to
a user.
"""
+ out = []
+ for role, text, _el in _window_ax_nodes():
+ out.append((role, text))
+ return out
+
+
+def window_ax_buttons():
+ """The AXButtons drawn inside the phone window, as [(title, element)].
+
+ Empty on a connected session, where the window is a video stream. On an
+ interstitial it is the button the user would click — Connect, Try Again,
+ Continue — and press_window_button() presses it through accessibility, so
+ it works on a window the user cannot see and never moves the mouse.
+ """
+ return [(text, el) for role, text, el in _window_ax_nodes()
+ if role == "AXButton"]
+
+
+def press_window_button(titles=None):
+ """Press one button inside the phone window and return its title, or None.
+
+ With `titles`, only a button whose title matches (case-insensitive) is
+ pressed; without, the window's single button is, and a window with
+ several is left alone — a choice is the user's.
+ """
+ buttons = window_ax_buttons()
+ if titles:
+ want = {t.lower() for t in titles}
+ buttons = [(t, el) for t, el in buttons if t.lower() in want]
+ elif len(buttons) != 1:
+ return None
+ if not buttons:
+ return None
+ title, el = buttons[0]
+ err = _AS.AXUIElementPerformAction(el, "AXPress")
+ return title if not err else None
+
+
+def launch(timeout=12.0):
+ """Open iPhone Mirroring without bringing it in front, and wait for its
+ phone window. Returns the window bounds, or None when none appeared in
+ time (the app is launched either way).
+
+ `open -g` keeps the user's focus where it is; the app connects to the
+ paired phone on its own once it is up.
+ """
+ if running_app() is None:
+ subprocess.run(["open", "-g", "-a", APP_PATH], capture_output=True)
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ win = find_window(on_screen=False)
+ if win is not None:
+ return win
+ time.sleep(0.4)
+ return find_window(on_screen=False)
+
+
+def ax_session_hint():
+ """'not-running' | 'no-window' | 'blocked' | 'ready', from accessibility only.
+
+ One pass over the running app, its phone window, and whether that window
+ has any native UI. A live stream has none, so this does not capture the
+ screen and does not run OCR. Callers that need the words still use
+ window_ax_content().
+ """
app = running_app()
+ if app is None:
+ return "not-running"
+ win = find_window(on_screen=False)
+ if win is None:
+ return "no-window"
+ return "blocked" if _window_ax_nodes(app, win) else "ready"
+
+
+def _window_ax_nodes(app=None, win=None):
+ """[(role, text, element)] for the native UI inside the phone window.
+
+ The shared walk behind window_ax_content() and window_ax_buttons().
+ `app` and `win` can be passed in by ax_session_hint() so a liveness
+ check does not look them up a second time.
+ """
+ if app is None:
+ app = running_app()
if app is None:
return []
- win = find_window()
+ if win is None:
+ win = find_window(on_screen=False)
if win is None:
return []
err, ax_wins = _AS.AXUIElementCopyAttributeValue(
@@ -197,7 +280,7 @@ def window_ax_content():
ea, v = _AS.AXUIElementCopyAttributeValue(node, attr, None)
if not ea and isinstance(v, str) and v.strip():
parts.append(v.strip())
- out.append((role, " ".join(parts)))
+ out.append((role, " ".join(parts), node))
ek, kids = _AS.AXUIElementCopyAttributeValue(node, "AXChildren", None)
for k in (kids or []):
walk(k, depth + 1)
@@ -297,6 +380,29 @@ def is_frontmost():
return bool(win) and win.get("kCGWindowOwnerPID") == app.processIdentifier()
+def ax_observer_target():
+ """(pid, [app element, window element]) for an accessibility observer.
+
+ The window element is included when it can be matched. Notifications on
+ the app catch a window being created; notifications on the window catch
+ the Connecting label appearing and the live stream replacing it. Raises
+ when the app is not running so the caller can fall back to polling.
+ """
+ app = running_app()
+ if app is None:
+ raise RuntimeError(f"{APP_NAME} isn't running")
+ pid = app.processIdentifier()
+ app_el = _AS.AXUIElementCreateApplication(pid)
+ if app_el is None:
+ raise RuntimeError(f"{APP_NAME} has no accessibility element")
+ elements = [app_el]
+ win = find_window(on_screen=False)
+ window_el = _ax_window_element(app, win) if win else None
+ if window_el is not None:
+ elements.append(window_el)
+ return pid, elements
+
+
def _ax_window_element(app, win):
"""The AXUIElement for `win`, matched by geometry against the app's
AXWindows the way window_ax_content() does, or None.
@@ -350,16 +456,32 @@ def activate(timeout=2.5):
# for the full timeout doing nothing. AXRaise on the window's own
# AXUIElement works even in that stuck state, so it runs alongside
# activateWithOptions_ on every iteration rather than only as a fallback.
- win = find_window()
+ # Off-screen too: a minimized window, or one on another Space, is exactly
+ # the window that needs raising, and the on-screen lookup returned None
+ # for it, so AXRaise never ran and this loop spun out with AXFrontmost
+ # true and the window still in the Dock.
+ win = find_window(on_screen=False)
+ el = _ax_window_element(app, win) if win else None
+ if el is not None:
+ err, minimized = _AS.AXUIElementCopyAttributeValue(el, "AXMinimized", None)
+ if not err and minimized:
+ _AS.AXUIElementSetAttributeValue(el, "AXMinimized", False)
deadline = time.time() + timeout
while time.time() < deadline:
app.activateWithOptions_(1 << 1) # NSApplicationActivateIgnoringOtherApps
- el = _ax_window_element(app, win) if win else None
if el is not None:
_AS.AXUIElementPerformAction(el, "AXRaise")
time.sleep(0.08)
if is_frontmost():
return
+ # Last resort: ask Launch Services. It switches to the window's Space,
+ # which nothing above does for a window on another desktop.
+ subprocess.run(["open", "-a", APP_PATH], capture_output=True)
+ deadline = time.time() + 1.5
+ while time.time() < deadline:
+ time.sleep(0.1)
+ if is_frontmost():
+ return
# is_frontmost() now requires both AXFrontmost and z-order to agree, so a
# failure can be either signal (or both) — name the one that's actually
# missing rather than a generic "still has focus", since the two failure
@@ -379,6 +501,10 @@ def activate(timeout=2.5):
f"{detail}. Input would be swallowed, so nothing was sent.")
+# Showing the window to the user is the same move as taking focus for input.
+show = activate
+
+
def ensure_window(timeout=5.0):
"""Return the mirroring window bounds. Does not launch or connect anything —
if the app isn't running or has no phone window, raises so the user can
diff --git a/tests/test_ios_session.py b/tests/test_ios_session.py
new file mode 100644
index 0000000..7633794
--- /dev/null
+++ b/tests/test_ios_session.py
@@ -0,0 +1,439 @@
+"""session.require on iPhone Mirroring does the user's first two moves —
+open the app, press Connect — and no more. No phone needed: the mirroring
+transport is faked and the clock does not tick.
+
+ python -m unittest tests.test_ios_session
+"""
+import sys
+import unittest
+from pathlib import Path
+
+SRC = Path(__file__).resolve().parents[1] / "src"
+sys.path.insert(0, str(SRC))
+
+try:
+ from phone_harness import ios
+except ImportError: # no pyobjc: stub the frameworks so the
+ ios = None # session machine can still be tested
+
+if ios is None:
+ import types
+
+ class _LazyModule(types.ModuleType):
+ def __getattr__(self, name):
+ if name.startswith("__"):
+ raise AttributeError(name)
+ obj = type(name, (), {})
+ setattr(self, name, obj)
+ return obj
+
+ import importlib.machinery
+ for _name in ("Quartz", "Vision", "Foundation", "AppKit",
+ "ApplicationServices", "objc", "CoreFoundation"):
+ if _name in sys.modules:
+ continue
+ _mod = _LazyModule(_name)
+ _mod.__spec__ = importlib.machinery.ModuleSpec(_name, loader=None)
+ sys.modules[_name] = _mod
+ try:
+ from phone_harness import ios
+ except ImportError:
+ ios = None
+
+WIN = {"x": 0, "y": 0, "w": 400, "h": 800, "id": 1}
+CONNECT = [("AXImage", "iPhoneOff"), ("AXStaticText", "Timed Out"),
+ ("AXStaticText", "iPhone Mirroring timed out due to iPhone use "
+ "while connecting.\n\nLock your iPhone before "
+ "connecting."), ("AXButton", "Connect")]
+IN_USE = [("AXStaticText", "iPhone in Use"),
+ ("AXStaticText", "Lock your iPhone to continue."),
+ ("AXButton", "Try Again")]
+CONNECTING = [("AXStaticText", "Connecting to"),
+ ("AXStaticText", "iPhone 17 Pro Max"), ("AXButton", "Background")]
+# The Connecting screen from a live attempt: the words, and no button at all.
+# Treating "no Background button" as a finished failure gave up while this
+# was still on screen.
+CONNECTING_PLAIN = [("AXStaticText", "Connecting to"),
+ ("AXStaticText", "iPhone 17 Pro Max")]
+# Cold launch draws the phone window before any label. Accessibility sees
+# a node, so the session is blocked, but there is nothing to read and
+# nothing to press. That is not a finished interstitial.
+BLANK = [("AXImage", "")]
+IN_USE_RETRYING = [("AXStaticText", "iPhone in Use"),
+ ("AXStaticText", "Lock your iPhone to connect.")]
+LOGIN = [("AXStaticText", "Enter the Mac login password"),
+ ("AXSecureTextField", ""), ("AXButton", "Unlock")]
+LIVE = []
+
+
+class FakeMirror:
+ """Scripted: each session-state probe pops the next frame. A frame is
+ None (app not running), "no-window", or the AX content of the window."""
+
+ def __init__(self, frames):
+ self.frames = list(frames)
+ self.current = self.frames[0]
+ self.launched = 0
+ self.pressed = []
+ self.activated = 0
+ self.actions = []
+
+ def _advance(self):
+ if len(self.frames) > 1:
+ self.frames.pop(0)
+ self.current = self.frames[0]
+
+ def running_app(self):
+ self._advance()
+ return None if self.current is None else object()
+
+ def find_window(self, on_screen=False):
+ return None if self.current in (None, "no-window") else dict(WIN)
+
+ def window_ax_content(self):
+ return [] if self.current in (None, "no-window") else list(self.current)
+
+ def window_ax_buttons(self):
+ return [(t, object()) for r, t in self.window_ax_content()
+ if r == "AXButton"]
+
+ def press_window_button(self, titles=None):
+ buttons = [t for t, _ in self.window_ax_buttons()]
+ if titles:
+ buttons = [t for t in buttons if t.lower() in
+ {x.lower() for x in titles}]
+ elif len(buttons) != 1:
+ return None
+ if not buttons:
+ return None
+ self.pressed.append(buttons[0])
+ return buttons[0]
+
+ def launch(self, timeout=12.0):
+ self.launched += 1
+ return self.find_window()
+
+ def capture(self, path=None):
+ self.actions.append("capture")
+ return "/dev/null", dict(WIN)
+
+ def ax_session_hint(self):
+ """Same one-step advance as running_app(), then the structural state.
+ A live frame is []; anything else with text is an interstitial."""
+ self.running_app()
+ if self.current is None:
+ return "not-running"
+ if self.current == "no-window":
+ return "no-window"
+ if self.current:
+ return "blocked"
+ return "ready"
+
+ def tap(self, x, y):
+ self.actions.append("tap")
+
+ def long_press(self, x, y, duration=0.8):
+ self.actions.append("long_press")
+
+ def drag(self, x1, y1, x2, y2, duration=0.35, steps=14):
+ self.actions.append("drag")
+
+ def scroll_wheel(self, dy, x, y, steps=6, dx=0):
+ self.actions.append("scroll")
+
+ def press(self, combo):
+ self.actions.append("press")
+
+ def type_text(self, text, delay=0.03, keystrokes=False):
+ self.actions.append("type")
+
+ def activate(self):
+ self.activated += 1
+
+ def show(self):
+ self.shown = getattr(self, "shown", 0) + 1
+
+ def ensure_window(self, timeout=5.0):
+ return self.find_window()
+
+
+class FakeVision:
+ @staticmethod
+ def recognize(path, win):
+ return []
+
+
[email protected](ios is None, "pyobjc not installed")
+class SessionRequire(unittest.TestCase):
+ def setUp(self):
+ self._sleep, self._now, self._vision = ios._sleep, ios._now, ios._vision
+ self._open, self._slice = ios._ax_watch_open, ios._run_loop_slice
+ self._drain = ios._drain_run_loop
+ self.clock = [0.0]
+ ios._sleep = lambda s: self.clock.__setitem__(0, self.clock[0] + s)
+ ios._now = lambda: self.clock[0]
+ ios._vision = FakeVision
+
+ def tearDown(self):
+ ios._sleep, ios._now, ios._vision = self._sleep, self._now, self._vision
+ ios._ax_watch_open, ios._run_loop_slice = self._open, self._slice
+ ios._drain_run_loop = self._drain
+
+ def watch_events(self, notify):
+ """A fake observer. Each run-loop slice advances the fake clock and,
+ when `notify` is true, delivers one accessibility notification."""
+ holder = {}
+
+ class Watch:
+ def __init__(self):
+ self.closed = False
+
+ def close(self):
+ self.closed = True
+
+ def opener(mirror, on_notify):
+ watch = Watch()
+ holder["watch"] = watch
+ holder["on_notify"] = on_notify
+ return watch
+
+ def slice(seconds):
+ self.clock[0] += seconds
+ if notify:
+ holder["on_notify"]()
+
+ ios._ax_watch_open = opener
+ ios._run_loop_slice = slice
+ return holder
+
+ def phone(self, *frames):
+ p = ios.IPhone.__new__(ios.IPhone)
+ p.mirror = FakeMirror(frames)
+ p.background = True
+ return p
+
+ def test_ready_does_nothing(self):
+ p = self.phone(LIVE)
+ self.assertEqual(p._session_require(), WIN)
+ self.assertEqual(p.mirror.launched, 0)
+ self.assertEqual(p.mirror.pressed, [])
+ self.assertEqual(p.mirror.shown, 1, "the window is shown once")
+
+ def test_launches_then_presses_connect_then_ready(self):
+ p = self.phone(None, None, "no-window", CONNECT, CONNECT,
+ CONNECTING, CONNECTING, LIVE)
+ self.assertEqual(p._session_require(), WIN)
+ self.assertEqual(p.mirror.launched, 1)
+ self.assertEqual(p.mirror.pressed, ["Connect"])
+
+ def test_phone_in_use_presses_once_and_raises_with_the_screen(self):
+ p = self.phone(CONNECT, CONNECT, CONNECTING, CONNECTING, CONNECTING,
+ CONNECTING, CONNECTING, CONNECTING, CONNECTING,
+ CONNECTING, IN_USE)
+ with self.assertRaises(RuntimeError) as cm:
+ p._session_require()
+ msg = str(cm.exception)
+ self.assertIn("pressed Connect", msg)
+ self.assertIn("iPhone in Use", msg)
+ self.assertIn("LOCK your iPhone", msg)
+ self.assertEqual(p.mirror.pressed, ["Connect"])
+ self.assertLess(self.clock[0], ios._CONNECT_WAIT, "stopped before the cap")
+
+ def test_transient_ready_after_the_press_is_not_a_connection(self):
+ # Measured: the window reads empty for ~0.5s between the press and
+ # the Connecting screen. One such poll must not count as live.
+ p = self.phone(CONNECT, CONNECT, LIVE, CONNECTING, CONNECTING,
+ IN_USE_RETRYING, IN_USE_RETRYING, IN_USE)
+ with self.assertRaises(RuntimeError) as cm:
+ p._session_require()
+ self.assertIn("iPhone in Use", str(cm.exception))
+ self.assertEqual(p.mirror.pressed, ["Connect"])
+
+ def test_a_slow_connect_is_waited_for(self):
+ p = self.phone(CONNECT, CONNECT, CONNECTING, CONNECTING, CONNECTING,
+ CONNECTING, CONNECTING, CONNECTING, CONNECTING, LIVE)
+ self.assertEqual(p._session_require(), WIN)
+ self.assertEqual(p.mirror.pressed, ["Connect"])
+
+ def test_in_use_fails_fast_and_shows_the_window_first(self):
+ # The app says "iPhone in Use" ~2s after the press and retries by
+ # itself; waiting out the cap would only delay the user's lock.
+ p = self.phone(CONNECT, CONNECT, CONNECTING, CONNECTING,
+ IN_USE_RETRYING)
+ with self.assertRaises(RuntimeError) as cm:
+ p._session_require()
+ self.assertIn("iPhone in Use", str(cm.exception))
+ self.assertLess(self.clock[0], 5.0, "gave up within a few seconds")
+ self.assertEqual(p.mirror.shown, 1, "the window was raised even so")
+
+ def test_connecting_screen_background_button_is_not_pressed(self):
+ p = self.phone(CONNECTING)
+ with self.assertRaises(RuntimeError) as cm:
+ p._session_require()
+ self.assertEqual(p.mirror.pressed, [])
+ self.assertIn("Connecting to", str(cm.exception))
+ self.assertGreaterEqual(self.clock[0], ios._CONNECT_WAIT,
+ "a Connecting screen is waited out to the cap")
+
+ def test_launch_blank_then_connecting_then_live(self):
+ # The blank window comes first, then "Connecting to", then the stream.
+ # Raising on the blank ("an interstitial with no text") gave up
+ # while the phone was still connecting.
+ p = self.phone(None, None, BLANK, BLANK,
+ *([CONNECTING_PLAIN] * 6), LIVE)
+ self.assertEqual(p._session_require(), WIN)
+ self.assertEqual(p.mirror.launched, 1)
+ self.assertEqual(p.mirror.pressed, [])
+ self.assertGreater(self.clock[0], ios._ATTEMPT_SETTLE)
+ self.assertLess(self.clock[0], ios._CONNECT_WAIT)
+
+ def test_launch_blank_for_the_whole_cap_raises(self):
+ p = self.phone(None, None, BLANK)
+ with self.assertRaises(RuntimeError) as cm:
+ p._session_require()
+ self.assertIn("an interstitial with no text", str(cm.exception))
+ self.assertEqual(p.mirror.launched, 1)
+ self.assertEqual(p.mirror.pressed, [])
+ self.assertGreaterEqual(self.clock[0], ios._CONNECT_WAIT)
+ self.assertLess(self.clock[0], ios._CONNECT_WAIT + 1)
+
+ def test_launch_into_connecting_with_no_button_waits_then_is_ready(self):
+ # Cold start. The app is not running; once launched it connects by
+ # itself and the window says "Connecting to" with no Connect button.
+ # That used to raise in about a second. Wait, and the stream comes up.
+ p = self.phone(None, None, *([CONNECTING_PLAIN] * 6), LIVE)
+ self.assertEqual(p._session_require(), WIN)
+ self.assertEqual(p.mirror.launched, 1)
+ self.assertEqual(p.mirror.pressed, [])
+ self.assertGreater(self.clock[0], ios._ATTEMPT_SETTLE)
+ self.assertLess(self.clock[0], ios._CONNECT_WAIT)
+
+ def test_login_prompt_is_never_pressed(self):
+ p = self.phone(LOGIN)
+ with self.assertRaises(RuntimeError) as cm:
+ p._session_require()
+ self.assertEqual(p.mirror.pressed, [])
+ self.assertIn("login password", str(cm.exception))
+
+ def test_launch_without_a_window_raises(self):
+ p = self.phone(None, None, "no-window")
+ with self.assertRaises(RuntimeError) as cm:
+ p._session_require()
+ self.assertEqual(p.mirror.launched, 1)
+ self.assertIn("no phone window", str(cm.exception))
+
+ def test_connecting_without_a_button_keeps_waiting_then_connects(self):
+ # No notifications arrive. The once-a-second re-check must still see
+ # "Connecting to" (there is no Background button) and wait it out.
+ holder = self.watch_events(notify=False)
+ p = self.phone(CONNECT, CONNECT, *([CONNECTING_PLAIN] * 6), LIVE)
+ self.assertEqual(p._session_require(), WIN)
+ self.assertEqual(p.mirror.pressed, ["Connect"])
+ self.assertGreater(self.clock[0], ios._ATTEMPT_SETTLE)
+ self.assertLess(self.clock[0], ios._CONNECT_WAIT)
+ self.assertTrue(holder["watch"].closed)
+
+ def test_iphone_in_use_fails_fast_on_an_accessibility_event(self):
+ holder = self.watch_events(notify=True)
+ p = self.phone(CONNECT, CONNECT, CONNECTING_PLAIN, IN_USE)
+ with self.assertRaises(RuntimeError) as cm:
+ p._session_require()
+ self.assertIn("iPhone in Use", str(cm.exception))
+ self.assertIn("pressed Connect", str(cm.exception))
+ self.assertLess(self.clock[0], 5.0, "gave up within a few seconds")
+ self.assertGreater(self.clock[0], ios._ATTEMPT_SETTLE)
+ self.assertTrue(holder["watch"].closed)
+ self.assertEqual(p.mirror.pressed, ["Connect"])
+
+ def test_observer_setup_failure_falls_back_and_waits_out_connecting(self):
+ # Observer setup fails closed. Polling then treats the button-less
+ # Connecting screen as still in progress and waits for the stream.
+ def boom(mirror, on_notify):
+ raise ios._ObserverUnavailable("AXObserverCreate failed")
+
+ ios._ax_watch_open = boom
+ p = self.phone(CONNECT, CONNECT, *([CONNECTING_PLAIN] * 5), LIVE)
+ self.assertEqual(p._session_require(), WIN)
+ self.assertEqual(p.mirror.pressed, ["Connect"])
+ self.assertGreater(self.clock[0], ios._ATTEMPT_SETTLE)
+ self.assertLess(self.clock[0], ios._CONNECT_WAIT)
+
+ def test_scroll_raises_once_the_window_is_iphone_in_use(self):
+ p = self.phone(IN_USE)
+ with self.assertRaises(RuntimeError) as cm:
+ p.send("input.scroll", x=1, y=1, dy=-10, dx=0)
+ msg = str(cm.exception)
+ self.assertIn("iPhone in Use", msg)
+ self.assertIn("LOCK your iPhone", msg)
+ self.assertIn("passcode", msg)
+ self.assertEqual(p.mirror.pressed, [])
+ self.assertNotIn("scroll", p.mirror.actions)
+
+ def test_a_scroll_that_loses_the_phone_raises_afterwards(self):
+ # Before the gesture the stream is live. The gesture runs. The
+ # window is then "iPhone in Use", so the scroll does not return
+ # success, and Connect is not pressed.
+ p = self.phone(LIVE, LIVE, IN_USE)
+ with self.assertRaises(RuntimeError) as cm:
+ p.send("input.scroll", x=1, y=1, dy=-10, dx=0)
+ self.assertIn("iPhone in Use", str(cm.exception))
+ self.assertEqual(p.mirror.actions, ["scroll"])
+ self.assertEqual(p.mirror.pressed, [])
+
+ def test_live_actions_are_not_interrupted(self):
+ p = self.phone(LIVE)
+ p.send("input.scroll", x=1, y=1, dy=-10, dx=0)
+ p.send("input.tap", x=1, y=2)
+ p.send("input.press", x=1, y=2, duration=0.2)
+ p.send("input.drag", x1=0, y1=0, x2=3, y2=4)
+ p.send("input.keys", combo="return")
+ p.send("input.text", s="hi")
+ p.send("nav.home")
+ p.send("apps.launch", name="Settings")
+ p.send("screen.capture")
+ self.assertEqual(
+ p.mirror.actions,
+ ["scroll", "tap", "long_press", "drag", "press", "type",
+ "press", "press", "type", "press", "capture"])
+ self.assertEqual(p.mirror.pressed, [])
+
+ def test_observer_notification_of_iphone_in_use_raises_before_the_action(self):
+ holder = {}
+
+ class Watch:
+ def close(self):
+ self.closed = True
+
+ def opener(mirror, on_notify):
+ holder["notify"] = on_notify
+ holder["watch"] = Watch()
+ return holder["watch"]
+
+ def drain():
+ if holder.get("fire"):
+ holder["notify"]()
+
+ ios._ax_watch_open = opener
+ ios._drain_run_loop = drain
+ p = self.phone(LIVE)
+ p.send("input.tap", x=1, y=1)
+ p.mirror.frames = [IN_USE]
+ p.mirror.current = IN_USE
+ holder["fire"] = True
+ with self.assertRaises(RuntimeError) as cm:
+ p.send("input.scroll", x=1, y=1, dy=-10, dx=0)
+ self.assertIn("iPhone in Use", str(cm.exception))
+ self.assertIn("LOCK your iPhone", str(cm.exception))
+ self.assertNotIn("scroll", p.mirror.actions)
+ self.assertEqual(p.mirror.pressed, [])
+
+ def test_screenshot_raises_when_the_phone_is_in_use(self):
+ p = self.phone(IN_USE)
+ with self.assertRaises(RuntimeError) as cm:
+ p.send("screen.capture")
+ self.assertIn("iPhone in Use", str(cm.exception))
+ self.assertNotIn("capture", p.mirror.actions)
+
+
+if __name__ == "__main__":
+ unittest.main()