Skip to content

let your agent control your phone

Clear a dead cloud session after its error is shown, and call the screen reader screen(). (#121)

shawn pana58284a68c801
diff --git a/README.md b/README.md
index 933071a..b21f17e 100644
--- a/README.md
+++ b/README.md
@@ -54,7 +54,7 @@ phone-harness <<'PY'
open_app("Notes")
tap_text("New Note")
type_text("hello from the harness")
-print([o["text"] for o in ocr()][:10])
+print([o["text"] for o in screen()][:10])
PY
phone-harness --version
```
diff --git a/SKILL.md b/SKILL.md
index 54ab46d..ba69ecb 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -5,12 +5,48 @@ description: "Control the user's phone - an iPhone through the Mac's iPhone Mirr
# phone-harness
+The main helpers are listed in [Helpers](#helpers).
+
Direct control of a phone from Python scripts. The same helpers drive every
kind of phone below; what differs is how each one sees and touches the screen,
and that is what the per-phone sections below are for. Read **Which phone**, the
shared **Working method**, and then only the section for the phone in front
of you.
+## Helpers
+
+- `ensure_device()` - Screen bounds once the device is usable, or raises with what the user has to do.
+- `screen(min_confidence=0.3)` - Visible text as `{text, confidence, source, x, y, w, h}` boxes. On Android the boxes come from the accessibility tree; on iPhone Mirroring they come from recognizing text.
+- `screenshot(path=None)` - Capture the screen to a PNG and return its path.
+- `find_text(query, exact=False)` - Visible text boxes matching `query`.
+- `tap_text(query, index=0, exact=False)` - Tap the center of visible text matching `query`.
+- `tap(x, y)` - Tap one point.
+- `long_press(x, y, duration=0.8)` - Press and hold a point.
+- `type_text(text, delay=0.03, keystrokes=False)` - Type into the focused field.
+- `press(combo)` - Press a key, such as `press("enter")`.
+- `open_app(name)` - Launch an app and return the app id that launched.
+- `swipe(direction, distance=0.4, at=None)` - Flick. `direction` is finger motion: `"up"`, `"down"`, `"left"`, or `"right"`.
+- `scroll(direction="down", amount=0.3, at=None)` - Scroll. `direction` is the content to reveal: `"down"`, `"up"`, `"left"`, or `"right"`.
+- `scroll_screen(direction="down", amount=0.6, settle=2.5, moved_thresh=None, at=None)` - One scroll, then the text on screen before and after.
+- `scroll_until(done, direction="down", amount=0.6, max_scrolls=60, settle=2.5, at=None)` - Scroll until `done(boxes)` is truthy or the screen stops changing.
+- `scroll_collect(extract=None, key=None, direction="down", amount=0.6, max_scrolls=400, end_after=3, settle=2.5, on_progress=None, at=None)` - Scroll a list and return `{items, stop, scrolls}`.
+- `home()` - Go to the Home Screen.
+- `back()` - System Back, where the phone has one.
+- `app_switcher()` - Open the app switcher.
+- `wait_stable(timeout=6.0, interval=0.5, settle=2)` - Wait until the screen stops changing.
+- `wait_for_text(query, timeout=10.0, exact=False, interval=0.5)` - Poll until `query` is visible; return its box, or None.
+- `wait_for_app(app_id, timeout=10.0, interval=0.3)` - Poll until `app_id` is the foreground app.
+- `ui()` - The accessibility tree, where the device has one.
+- `tap_ui(query, index=0, exact=False, clickable_only=False)` - Tap an element in the accessibility tree.
+- `current_app()` - Foreground app id, where the device exposes one.
+- `list_apps(include_system=False)` - Installed app ids.
+- `screen_info()` - `{window, frontmost, img_px}`: bounds, focus, and capture size.
+- `find_window()` - Screen bounds `{x, y, w, h, id}`, or None if there is no device.
+- `image_point(x, y, image_size=None)` - Convert a screenshot pixel to a screen point.
+- `tap_image_point(x, y, image_size=None)` - Tap a point taken from a screenshot.
+- `connection_state()` - Backend state string; `"ready"` means usable.
+- `shell(cmd, binary=False, timeout=60)` - Run a shell command on the phone, where the device has a shell.
+
## Which phone?
| Phone | How it is reached | Eyes | Hands | Read |
@@ -48,7 +84,7 @@ phone-harness <<'PY'
# task: report the OS version and model name from Settings
# step: open Settings, find About, read the screen
open_app("Settings")
-print([o["text"] for o in ocr()][:10])
+print([o["text"] for o in screen()][:10])
PY
```
@@ -60,7 +96,7 @@ PY
you are about to do), one line after (what you saw). Never run two scripts
in a row in silence. The `# task:`/`# step:` comments are not this - the user
cannot see them.
-- **Read with `ocr()`, not by eyeballing screenshots.** Every visible string
+- **Read with `screen()`, not by eyeballing screenshots.** Every visible string
comes back with a tap-ready centre: `[{text, confidence, source, x, y, w, h}]`.
Filter in Python before printing. `tap_text("Weather")` taps by label and,
on failure, raises with what IS visible - read the exception before retrying.
@@ -71,7 +107,7 @@ PY
contents. Most phone failures are silent no-ops; if you cannot name the
expected change you cannot tell success from one.
2. Do one thing, then check that one thing: `wait_for_text("Got it")`,
- `wait_for_app("com.android.chrome")` or `wait_stable()`, then one `ocr()`.
+ `wait_for_app("com.android.chrome")` or `wait_stable()`, then one `screen()`.
Do not `wait(n)` for a screen to load.
3. Once a sequence is proven, batch it: a whole sub-task in one script is far
faster than a call per turn. Keep one cheap check at the end.
@@ -87,7 +123,7 @@ PY
workspace is never overwritten. To get a fresh default, delete the
workspace folder; it is recreated on the next run.
- **The harness reports, you decide.** Helpers return observations, never a
- verdict on your intent. Diff two `ocr()` sets, watch one label, count rows,
+ verdict on your intent. Diff two `screen()` sets, watch one label, count rows,
poll until something appears - whatever matches what you asked for.
- **Navigation:** `home()`, `back()`, `app_switcher()`, `open_app("Notes")`,
`type_text("...")`, `press("enter")`, `long_press(x, y)`, `tap(x, y)`.
@@ -107,7 +143,7 @@ PY
`{before, after, boxes}` for you to judge. `at=` aims the gesture at an
inner list or strip; only the scroll view under that point moves.
- **`type_text` needs a focused field** on every phone. Tap the field, wait for
- the keyboard, then type; verify with `ocr()`, because unfocused text goes
+ the keyboard, then type; verify with `screen()`, because unfocused text goes
elsewhere or nowhere.
- **Consent.** This is the user's real phone and real accounts. Stop and ask
before anything outward-facing or hard to reverse: sending, posting,
@@ -204,19 +240,23 @@ phone-harness cloud open # the dashboard: the user takes the
`cloud phone reset --yes` wipes that phone's stored state: apps, logins,
and data. The CLI has no iPhone reset; that is the operator's.
- **A cloud session that ends does not hand you another phone.** If the
- session attached to this script expires, the error says `session <sid> expired`.
+ session this command is using expires, the error says `session <sid> expired`.
If the service loses it, the error says the cloud phone failed and is
- unreachable. Either way the script stops. It does not drive the personal
- phone, and the CLI does not rent a replacement. Start the same catalog
- phone again with a longer duration and continue the task:
- `phone-harness cloud start <same phone> --for <longer>`. `<same phone>` is
- that phone's id or label (or `ios` / `android` when only one entry has that
- platform). `<longer>` is a duration longer than the session that just
- ended (`90s`, `15m`, or a number of minutes). A `--session` pin whose
- session expired is the same error, naming that sid. A missing cloud state
- file still means no cloud phone was attached, and the personal phone is
- used as today. An unreadable state file is an error, not a cue to switch
- phones. `cloud stop` clears the failure; a new `cloud start` does too.
+ unreachable. That command stops. It does not drive another phone, and the
+ CLI does not rent a replacement. The saved note of that dead session is
+ removed once the error has been reported, or once `phone-harness cloud` has
+ shown it once, so later status output does not repeat it. A command that
+ hits the dead session while that note is still there fails with the same
+ message. Start the same catalog phone again with a longer duration and
+ continue the task: `phone-harness cloud start <same phone> --for <longer>`.
+ `<same phone>` is that phone's id or label (or `ios` / `android` when only
+ one entry has that platform). `<longer>` is a duration longer than the
+ session that just ended (`90s`, `15m`, or a number of minutes). A
+ `--session` pin whose session expired is the same error, naming that sid.
+ A missing cloud state file still means no cloud phone was attached, and the
+ personal phone is used as today. An unreadable state file is an error, not
+ a cue to switch phones. `cloud stop` and a new `cloud start` also drop a
+ note that has not been reported yet.
- The adb address the CLI shows is not a secret; the unlock code is. Do not
look for it, print it, or ask the user for it.
@@ -280,24 +320,24 @@ documents or decodes.
Trust `GET /ops` when the host's list is shorter than this table.
- **Coordinates are `screen.bounds`.** `tap(x, y)`, `find_window()`,
- `send("screen.require")`, and OCR centres all use that space:
+ `send("screen.require")`, and centres from `screen()` all use that space:
`{x, y, w, h, id}`. A point read off the PNG goes through
`tap_image_point()` once `screen_info()` returns `img_px`. Otherwise tap
- an OCR centre.
+ a centre from `screen()`.
- **`screen_info()`, `image_point()`, and `tap_image_point()` measure the
PNG** so a point you read off a screenshot can become a tap. If
`screen_info()` raises `ModuleNotFoundError: No module named 'Quartz'`,
that helper imported the macOS Vision module to read the PNG's pixel size.
- `ocr()` sends `screen.text` to the host and still works - keep using
+ `screen()` sends `screen.text` to the host and still works - keep using
`tap_text()`. If `screen_info()` returns `img_px`, those three helpers work
on any OS. [PR #108](https://github.com/ShawnPana/phone-harness/pull/108)
("screen_info() no longer needs macOS") is the change that reads the PNG
header instead of importing Quartz; until `screen_info()` returns `img_px`
off a Mac, treat the Quartz error as those three helpers only.
- **`type_text()` types into the focused field.** Tap the field first. Text
- sent before the field has focus goes nowhere, so check with `ocr()`
+ sent before the field has focus goes nowhere, so check with `screen()`
afterwards.
-- **Act, then look.** One action, then `ocr()` or `screenshot()`, then the
+- **Act, then look.** One action, then `screen()` or `screenshot()`, then the
next. Do not `wait(n)` for a screen to load. The client allows
`screen.capture` 60s, `apps.launch` and `apps.list` 90s, and `input.text`
the timeout in the table.
@@ -311,7 +351,7 @@ Trust `GET /ops` when the host's list is shorter than this table.
does not list `tree`, `nav.back`, and `apps.current`. `home()` is the Home
button. `shell()` is Unsupported.
- **Confirm `open_app`.** It sends `apps.launch` and can return with the app
- still not in front. Check with `ocr()` or a screenshot. If it missed,
+ still not in front. Check with `screen()` or a screenshot. If it missed,
`home()` and tap the icon. `tap_icon()` in
`agent-workspace/agent_helpers.py` aims 35 points above the label for the
mirroring window, so measure this phone's icon yourself.
@@ -330,12 +370,12 @@ PY
```
- **Coordinates are device pixels;** the screenshot is 1:1 with `tap(x, y)`.
-- **`ocr()` is the accessibility tree** (`source: "tree"`) - exact, no
+- **`screen()` is the accessibility tree** (`source: "tree"`) - exact, no
misreads. Prefer `ui()` / `find_nodes()` / `tap_ui()`: they also see
elements with no visible text (icons with a content-description, fields by
resource-id like `tap_ui("url_bar")`).
- **Some screens never give up their tree** - a playing video, some Settings
- pages. On a Mac, `ocr()` then reads the screenshot with Vision instead
+ pages. On a Mac, `screen()` then reads the screenshot with Vision instead
(`source: "pixels"`, fuzzier, still tap-ready; the first read costs ~12s
while uiautomator gives up, later reads are fast). Elsewhere it raises
saying so; take a `screenshot()` and look at it instead of retrying.
@@ -361,14 +401,14 @@ PY
accented letters.
- **Verify cheaply, then read.** adb reports nothing about outcomes - a tap on
empty space "succeeds". After an action: `wait_for_app(...)` (~0.1s a poll)
- or `wait_for_text(...)` (returns the box or None), then `ui()`/`ocr()` once.
+ or `wait_for_text(...)` (returns the box or None), then `ui()`/`screen()` once.
The tree costs ~2-3s a call on a slow phone and a screenshot ~0.5s, so
batching a proven sub-task is worth a lot; a batch of unverified steps fails
silently and tells you nothing about which one broke.
- No focus to keep: nothing on the Mac has to be frontmost, and
`interruption(before, after)` always reports nothing disturbed.
- **A desk phone locks itself** after its screen timeout. `connection_state()`
- reports `locked`; taps and `ocr()` refuse with the same message. Ask the user
+ reports `locked`; taps and `screen()` refuse with the same message. Ask the user
to unlock - never type a PIN. `screenshot()` still works locked, so you can
show them what you see. For a task longer than a minute, ask the user, then
`phone-harness android awake --bg` keeps it awake without changing any phone
@@ -459,7 +499,7 @@ events into it for hands. All coordinates are global macOS screen points.
theory.
- **The window is a video stream.** macOS accessibility sees nothing inside
it; AppleScript `click at` fails silently. Only HID-level CGEvents work.
-- **The window moves.** Never cache coordinates across calls; `ocr()` and
+- **The window moves.** Never cache coordinates across calls; `screen()` and
`swipe()` re-query bounds every time.
- Mouse taps map to touches 1:1, but there is no multi-touch: no pinch, no
two-finger gestures.
diff --git a/install.md b/install.md
index 78a4543..75a06c0 100644
--- a/install.md
+++ b/install.md
@@ -6,7 +6,8 @@ iPhone Mirroring app, an **Android** over adb (USB or Wi‑Fi), or a phone from
Phone Harness Cloud — an Android over adb, or an iPhone the helpers drive over
HTTPS (`phone-harness cloud start` with that phone's name from `cloud ls`).
Same helpers either way; you
-choose a default and can switch per call.
+choose a default and can switch per call. Reading on-screen text is
+`screen()`; the helper names and signatures are in `SKILL.md`.
## Common
diff --git a/integrations/hermes/README.md b/integrations/hermes/README.md
index 96caaf1..7485bb1 100644
--- a/integrations/hermes/README.md
+++ b/integrations/hermes/README.md
@@ -10,7 +10,7 @@ phone_exec(code='''
ensure_device()
open_app("Weather")
wait_stable()
-print([o["text"] for o in ocr()][:12])
+print([o["text"] for o in screen()][:12])
''')
```
diff --git a/integrations/hermes/__init__.py b/integrations/hermes/__init__.py
index 705e310..36a23f2 100644
--- a/integrations/hermes/__init__.py
+++ b/integrations/hermes/__init__.py
@@ -41,7 +41,7 @@ DESCRIPTION = (
"window, an Android over adb, or a Phone Harness Cloud phone. `code` runs as Python with the phone "
"helpers pre-imported; print() whatever you need back. Each call is a fresh interpreter (variables "
"do not persist); the phone keeps its state. Start with ensure_device(); it covers iPhone "
- "Mirroring, Android, and a cloud phone. Ask the user before "
+ "Mirroring, Android, and a cloud phone. Read what is on screen with screen(). Ask the user before "
"anything outward-facing or hard to undo (sending, posting, buying, deleting, changing settings). "
"Never type passwords, PINs or 2FA codes. Read the skill phone-harness:phone-harness for the helpers."
)
diff --git a/onboarding.md b/onboarding.md
index b2733e2..a7980d1 100644
--- a/onboarding.md
+++ b/onboarding.md
@@ -43,8 +43,8 @@ Check with `phone-harness android` and `phone-harness --doctor android`.
## 4. Verify
`phone-harness --doctor` for the default phone (add `ios` or `android` to
-check the other), then a read-only proof: take a screenshot and read the
-screen back to the user.
+check the other), then a read-only proof: `screenshot()` and `screen()`,
+and read what came back to the user.
## 5. Demo (opt-in)
diff --git a/src/phone_harness/background.py b/src/phone_harness/background.py
index 4562391..8cc8677 100644
--- a/src/phone_harness/background.py
+++ b/src/phone_harness/background.py
@@ -27,7 +27,7 @@ it a click. Every write stays inside the buffer, so a wrong value is a no-op,
never a crash.
Select with PHONE_HARNESS_BACKGROUND=1. Coordinates use the same global
-screen-point convention as the mirror backend and ocr(), so every helper on
+screen-point convention as the mirror backend and screen(), so every helper on
top (tap_text, swipe, scroll_collect) works unchanged — just without focus.
Keyboard (type_text/press) still briefly activates the window: the keyboard
diff --git a/src/phone_harness/cloud.py b/src/phone_harness/cloud.py
index 1325d62..23e22aa 100644
--- a/src/phone_harness/cloud.py
+++ b/src/phone_harness/cloud.py
@@ -407,6 +407,91 @@ def ended_message(rec):
"The CLI does not rent a phone by itself.")
+# Sids whose ended-session message this process has already shown. The copy
+# on disk is removed at that moment so the next command does not print it
+# again. Remembering it here is what keeps the rest of this process from
+# treating the dead phone as "no phone" and driving a different one.
+_reported_dead = {}
+_reported_fallback = None
+
+
+def _reported_for(pin):
+ for sid, rec in _reported_dead.items():
+ if _pin_hits(sid, pin):
+ return rec
+ return None
+
+
+def _forget_stored_dead(sid):
+ """Drop the stored dead-session note for `sid`.
+
+ That is the `gone` mark and the saved session itself (the attached one
+ and the `--session` copy). Other remembered sessions stay. No network.
+ """
+ state = _load_state()
+ changed = False
+ gone = state.get("gone")
+ if isinstance(gone, dict) and (not sid or gone.get("sid") == sid):
+ state.pop("gone", None)
+ changed = True
+ sessions = dict(state.get("sessions") or {})
+ current = state.get("session") if isinstance(state.get("session"), dict) else None
+
+ def hits(rec, key=None):
+ if sid and (key == sid or (isinstance(rec, dict) and rec.get("sid") == sid)):
+ return True
+ return not sid and _expired(rec)
+
+ drop = []
+ for key, rec in sessions.items():
+ if hits(rec, key):
+ drop.append(key)
+ if current and hits(current, current.get("sid")) and current.get("sid") not in drop:
+ drop.append(current.get("sid"))
+ for target in drop:
+ rec = sessions.get(target)
+ if rec is None and current and current.get("sid") == target:
+ rec = current
+ linked = _as_linked(rec)
+ if linked and linked["link"]["kind"] == "adb":
+ try:
+ from .android import _run
+ _run("disconnect", serial_of(linked), timeout=10, check=False)
+ except Exception:
+ pass
+ if target in sessions:
+ sessions.pop(target, None)
+ changed = True
+ if current and current.get("sid") == target:
+ state.pop("session", None)
+ current = None
+ changed = True
+ if sessions:
+ state["sessions"] = sessions
+ elif "sessions" in state:
+ state.pop("sessions", None)
+ changed = True
+ if changed:
+ _save_state(state)
+
+
+def report_ended(rec):
+ """The ended-session message has been shown for this record.
+
+ Forget the stored copy so `phone-harness cloud` and later commands do not
+ print it again. This process still fails if it targets that sid.
+ """
+ global _reported_fallback
+ rec = dict(rec or {})
+ sid = rec.get("sid")
+ if sid:
+ _reported_dead[sid] = rec
+ if not os.environ.get("PHONE_HARNESS_SESSION"):
+ _reported_fallback = rec
+ _forget_stored_dead(sid)
+ return rec
+
+
def attached(kind=None):
"""The session the helpers should drive, or None; with `kind`, only a
session reached that way.
@@ -420,21 +505,29 @@ def attached(kind=None):
None means no cloud phone was attached. A pin whose session has expired
raises `session <sid> expired` instead of returning None, and an
unreadable state file raises too: both used to look like "no cloud phone"
- and the next call drove a different device. An unpinned session whose
- clock has run out still returns None; `lost()` tells `connect` to raise.
+ and the next call drove a different device. Raising reports that dead
+ session, and the stored note is cleared so a later command does not repeat
+ it. An unpinned session whose clock has run out still returns None;
+ `lost()` tells `connect` to raise.
"""
state = _load_state()
pin = os.environ.get("PHONE_HARNESS_SESSION")
if pin:
+ seen = _reported_for(pin)
+ if seen:
+ raise CloudPhoneError(ended_message(seen))
raw = _find_recorded(state, pin)
sess = _as_linked(raw)
if sess is None:
gone = state.get("gone")
if isinstance(gone, dict) and _pin_hits(gone.get("sid"), pin):
+ report_ended(gone)
raise CloudPhoneError(ended_message(gone))
sess = _pull_pinned(pin)
if _expired(sess):
- raise CloudPhoneError(ended_message(_ended_record(sess, "expired")))
+ rec = _ended_record(sess, "expired")
+ report_ended(rec)
+ raise CloudPhoneError(ended_message(rec))
else:
sess = _as_linked(state.get("session"))
if sess is None:
@@ -572,6 +665,9 @@ def _store_session(record, make_attached=True):
Every remembered session stays addressable by `--session`, so a later
start does not forget the previous phone. Storing one clears a previous
"gone" mark: the user has a phone again."""
+ _reported_dead.clear()
+ global _reported_fallback
+ _reported_fallback = None
state = _load_state()
sessions = _known_sessions(state)
sessions[record["sid"]] = record
@@ -666,7 +762,12 @@ def lost():
Either the service said it was gone, or its expiry passed while it was
still attached. `cause` is `expired` or `unreachable`. No network. An
- unreadable state file raises; it is not "no session"."""
+ unreadable state file raises; it is not "no session".
+
+ Once that message has been reported, the stored note is gone. This
+ process still sees a session it already reported, so a second call in the
+ same script fails instead of switching phones.
+ """
state = _load_state()
gone = state.get("gone")
if isinstance(gone, dict) and gone.get("sid"):
@@ -674,6 +775,8 @@ def lost():
sess = state.get("session") if isinstance(state.get("session"), dict) else None
if _expired(sess):
return _ended_record(sess, "expired", at=sess.get("expires_at"))
+ if _reported_fallback is not None and not os.environ.get("PHONE_HARNESS_SESSION"):
+ return _reported_fallback
return None
@@ -1282,6 +1385,9 @@ def _status(args):
lost_rec = lost()
if lost_rec:
print(term.err(ended_message(lost_rec), sys.stdout))
+ # Shown once. The next status must not print it again.
+ if lost_rec.get("sid") not in _reported_dead:
+ report_ended(lost_rec)
return 1
running = me.get("active_session_count") or 0
print("session none attached" + (f" ({running} running: `phone-harness cloud ls`)"
@@ -1289,8 +1395,9 @@ def _status(args):
return 0
if live is None:
cause = "expired" if _expired(sess) else "unreachable"
- print(term.err(ended_message(_ended_record(sess, cause)), sys.stdout))
- _detach(gone=True)
+ rec = _ended_record(sess, cause)
+ print(term.err(ended_message(rec), sys.stdout))
+ report_ended(rec)
return 1
state = ("closing — saving the phone"
if live["state"] == "closing" and _keeps_state(live)
diff --git a/src/phone_harness/helpers.py b/src/phone_harness/helpers.py
index 71f38c3..7748561 100644
--- a/src/phone_harness/helpers.py
+++ b/src/phone_harness/helpers.py
@@ -119,7 +119,7 @@ def screen_info():
def screenshot(path=None):
"""Capture the screen to a PNG and return its path. View it to see the
- phone; combine with ocr() for coordinates.
+ phone; combine with screen() for coordinates.
On iPhone Mirroring this still works when connection_state() is not
'ready', as long as the mirroring window exists. Looking does not
@@ -174,14 +174,20 @@ def interruption(before, after):
# --- reading the screen -----------------------------------------------------
-def ocr(min_confidence=0.3):
+def screen(min_confidence=0.3):
"""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."""
+ "tree" when the OS reported it exactly.
+
+ On Android the boxes come from the accessibility tree. On iPhone Mirroring
+ they come from recognizing the text in the mirror."""
return send("screen.text", min_confidence=min_confidence)
+ocr = screen # old name, still called by existing helpers and skills
+
+
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."""
@@ -191,7 +197,7 @@ def ocr_pixels(min_confidence=0.3):
def find_text(query, exact=False):
"""Visible text matching query (case-insensitive substring by default)."""
q = query.lower()
- return [o for o in ocr()
+ return [o for o in screen()
if (o["text"].lower() == q if exact else q in o["text"].lower())]
@@ -200,7 +206,7 @@ def tap_text(query, index=0, exact=False):
failure, so the next step is informed."""
hits = find_text(query, exact=exact)
if not hits:
- visible = [o["text"] for o in ocr()][:30]
+ visible = [o["text"] for o in screen()][:30]
raise RuntimeError(f"no visible text matches {query!r}; saw: {visible}")
hit = hits[index]
tap(hit["x"], hit["y"])
@@ -210,7 +216,7 @@ def tap_text(query, index=0, exact=False):
# --- accessibility tree (where the device has one) --------------------------
def ui():
- """The accessibility tree. Exact where ocr() is inferred. Raises
+ """The accessibility tree. Exact where screen() is inferred. Raises
Unsupported on iPhone Mirroring, whose window is an opaque video stream —
gate on supports('tree')."""
return send("tree")
@@ -313,7 +319,7 @@ def _point(at, win):
Aiming at the centre of Weather hits the temperature readout, which does
not scroll, while the hourly strip below it does.
- `at` may be (x, y) in screen points, or any box from ocr()/find_text()/
+ `at` may be (x, y) in screen points, or any box from screen()/find_text()/
find_nodes() — so `scroll("right", at=find_text("Now")[0])` reads the way
you would say it.
"""
@@ -375,7 +381,7 @@ def scroll(direction="down", amount=0.3, at=None):
'down' reveals content further down the list, 'right' what is off to the
right. `amount` is a fraction of the screen.
- `at` aims the gesture — (x, y) or a box from ocr()/find_text(). Only the
+ `at` aims the gesture — (x, y) or a box from screen()/find_text(). Only the
scroll view under that point moves, so pass it whenever the thing you want
to scroll is not the full-screen list: a horizontal strip, a carousel, an
inner list. Defaults to the window centre.
@@ -402,7 +408,7 @@ def _content_texts(min_conf=0.4, top_frac=0.06, bottom_frac=0.92):
win = _win()
top = win["y"] + win["h"] * top_frac
bot = win["y"] + win["h"] * bottom_frac
- return [o for o in ocr()
+ return [o for o in screen()
if top < o["y"] < bot and o["confidence"] >= min_conf]
diff --git a/src/phone_harness/transport.py b/src/phone_harness/transport.py
index fe4aaf0..db69b67 100644
--- a/src/phone_harness/transport.py
+++ b/src/phone_harness/transport.py
@@ -155,6 +155,11 @@ def connect(platform=None, **kw):
# same catalog phone again. This does not rent one itself.
lost = cloud.lost()
if lost:
+ # Reporting clears the stored note so the next command does
+ # not repeat it. This call still fails, and so does a later
+ # call in this process: lost() remembers what it reported.
+ if lost.get("sid") not in cloud._reported_dead:
+ cloud.report_ended(lost)
raise cloud.CloudPhoneError(cloud.ended_message(lost))
platform = platform.lower()
if platform in ("ios", "iphone", "ipad"):
diff --git a/tests/test_cloud.py b/tests/test_cloud.py
index efd040c..3cac953 100644
--- a/tests/test_cloud.py
+++ b/tests/test_cloud.py
@@ -635,6 +635,12 @@ class CloudCli(unittest.TestCase):
self.assertIn("<longer>", r.stdout)
self.assertNotIn("RAN", r.stdout)
self.assertNotIn("unreachable", r.stdout)
+ # Reported once. A later status does not repeat it. A new process that
+ # pins the same sid no longer has the stored note.
+ status = self.run_cli("cloud")
+ self.assertNotIn("expired", status.stdout)
+ self.assertNotIn("did not switch", status.stdout)
+ self.assertIn("none attached", status.stdout)
def test_an_expired_attached_session_does_not_fall_back(self):
self.login()
@@ -649,6 +655,77 @@ class CloudCli(unittest.TestCase):
self.assertIn('cloud start "Saved phone"', r.stdout)
self.assertIn("--for", r.stdout)
self.assertNotIn("RAN", r.stdout)
+ status = self.run_cli("cloud")
+ self.assertNotIn("expired", status.stdout)
+ self.assertNotIn("did not switch", status.stdout)
+ self.assertIn("none attached", status.stdout)
+ again = subprocess.run([sys.executable, "-c", self._connect_script()],
+ capture_output=True, text=True, env=self.env)
+ self.assertNotIn("expired", again.stdout)
+ self.assertNotIn("did not switch", again.stdout)
+ self.assertIn("RAN", again.stdout)
+
+ def test_an_expired_session_keeps_failing_for_the_rest_of_that_process(self):
+ """Clearing the stored note must not let the same script switch phones."""
+ self.login()
+ started = self.run_cli("cloud", "start", "Saved phone", "--no-watch")
+ self.assertEqual(started.returncode, 0, started.stderr)
+ sid = self._expire_attached()
+ script = (
+ "from phone_harness import transport\n"
+ "for i in range(2):\n"
+ " try:\n"
+ " transport.connect()\n"
+ " print('RAN', i)\n"
+ " except RuntimeError as e:\n"
+ " print('CONNECT', i, e)\n"
+ )
+ r = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, env=self.env)
+ self.assertIn("CONNECT 0", r.stdout, r.stderr)
+ self.assertIn("CONNECT 1", r.stdout)
+ self.assertIn(f"session {sid} expired", r.stdout)
+ self.assertNotIn("RAN", r.stdout)
+
+ def test_status_shows_an_expired_session_once(self):
+ self.login()
+ started = self.run_cli("cloud", "start", "Saved phone", "--no-watch")
+ self.assertEqual(started.returncode, 0, started.stderr)
+ sid = self._expire_attached()
+ FakeCloud.sessions[sid]["expires_at"] = time.time() - 30
+ first = self.run_cli("cloud")
+ self.assertNotEqual(first.returncode, 0, first.stdout)
+ self.assertIn(f"session {sid} expired", first.stdout)
+ self.assertIn("did not switch", first.stdout)
+ second = self.run_cli("cloud")
+ self.assertEqual(second.returncode, 0, second.stderr)
+ self.assertNotIn("expired", second.stdout)
+ self.assertNotIn("did not switch", second.stdout)
+ self.assertIn("none attached", second.stdout)
+ # The service still has that dead session. A script that targets it
+ # fails with the same message instead of driving another phone.
+ pinned = subprocess.run(
+ [sys.executable, "-c", self._connect_script()],
+ capture_output=True, text=True,
+ env={**self.env, "PHONE_HARNESS_SESSION": sid})
+ self.assertIn(f"session {sid} expired", pinned.stdout, pinned.stderr)
+ self.assertNotIn("RAN", pinned.stdout)
+
+ def test_a_stored_dead_session_fails_a_script_then_is_cleared(self):
+ state = Path(self.home.name) / "state"
+ state.mkdir(parents=True, exist_ok=True)
+ (state / "cloud.json").write_text(json.dumps({"gone": {
+ "sid": "dead1", "cause": "expired", "label": "Saved phone",
+ "selector": "label:Saved phone"}}))
+ r = subprocess.run([sys.executable, "-c", self._connect_script()],
+ capture_output=True, text=True, env=self.env)
+ self.assertIn("session dead1 expired", r.stdout, r.stderr)
+ self.assertIn("did not switch", r.stdout)
+ self.assertNotIn("RAN", r.stdout)
+ again = subprocess.run([sys.executable, "-c", self._connect_script()],
+ capture_output=True, text=True, env=self.env)
+ self.assertNotIn("expired", again.stdout)
+ self.assertNotIn("did not switch", again.stdout)
+ self.assertIn("RAN", again.stdout)
def test_a_session_that_dies_does_not_fall_back_to_a_local_phone(self):
self.login()
@@ -661,24 +738,18 @@ class CloudCli(unittest.TestCase):
self.assertIn('cloud start "Saved phone"', status.stdout)
self.assertIn("--for", status.stdout)
self.assertNotIn("expired", status.stdout)
- r = subprocess.run([sys.executable, "-c", self._connect_script()],
- capture_output=True, text=True, env=self.env)
- self.assertIn("CONNECT", r.stdout, r.stderr)
- self.assertIn("unreachable", r.stdout)
- self.assertIn("failed", r.stdout)
- self.assertIn('cloud start "Saved phone"', r.stdout)
- self.assertNotIn("RAN", r.stdout)
- self.assertNotIn("expired", r.stdout)
- still = subprocess.run(
- [sys.executable, "-c", "from phone_harness import cloud; print(cloud.lost() is not None)"],
- capture_output=True, text=True, env={**self.env, "PHONE_HARNESS_PLATFORM": "android"})
- self.assertEqual(still.stdout.strip(), "True", still.stderr)
- stopped = self.run_cli("cloud", "stop", "--all")
- self.assertEqual(stopped.returncode, 0, stopped.stderr)
+ # Status showed the dead session once, which clears the stored note.
+ again = self.run_cli("cloud")
+ self.assertNotIn("unreachable", again.stdout)
+ self.assertNotIn("did not switch", again.stdout)
+ self.assertIn("none attached", again.stdout)
+ self.assertEqual(again.returncode, 0, again.stderr)
cleared = subprocess.run(
[sys.executable, "-c", "from phone_harness import cloud; print(cloud.lost())"],
capture_output=True, text=True, env=self.env)
self.assertEqual(cleared.stdout.strip(), "None", cleared.stderr)
+ stopped = self.run_cli("cloud", "stop", "--all")
+ self.assertEqual(stopped.returncode, 0, stopped.stderr)
def test_start_waits_out_a_phone_that_is_still_closing(self):
self.login()
diff --git a/tests/test_hermes_plugin.py b/tests/test_hermes_plugin.py
index 5ec8592..cefe467 100644
--- a/tests/test_hermes_plugin.py
+++ b/tests/test_hermes_plugin.py
@@ -75,6 +75,7 @@ class Registration(Base):
def test_the_tool_description_points_at_the_skill(self):
description = self.ctx.tools["phone_exec"]["schema"]["description"]
self.assertIn("ensure_device()", description)
+ self.assertIn("screen()", description)
self.assertIn("phone-harness:phone-harness", description)
self.assertIn("passwords", description)
self.assertNotIn("scroll_until", description)
@@ -82,7 +83,7 @@ class Registration(Base):
class ApprovalGate(Base):
PHONE_ONLY = [
- 'ensure_device()\nprint([o["text"] for o in ocr()][:10])',
+ 'ensure_device()\nprint([o["text"] for o in screen()][:10])',
'import json, re, time\nprint(json.dumps(screen_info()))',
'from phone_harness import helpers\nhelpers.tap_text("Weather")',
'from collections import Counter\nprint(Counter(o["text"] for o in ocr()))',
diff --git a/tests/test_skill.py b/tests/test_skill.py
index e08b4d0..44be738 100644
--- a/tests/test_skill.py
+++ b/tests/test_skill.py
@@ -57,3 +57,16 @@ class SkillOutput(unittest.TestCase):
finally:
sys.stdout = old
self.assertEqual(out.buffer.getvalue(), "a \u2192 b".encode("utf-8"))
+
+ def test_skill_points_at_helpers_and_names_screen(self):
+ text = _skill_text()
+ self.assertIn("The main helpers are listed in [Helpers](#helpers).", text)
+ self.assertIn("\n## Helpers\n", text)
+ self.assertIn("`screen(min_confidence=0.3)`", text)
+ self.assertIn("`screen_info()`", text)
+ self.assertNotIn("ocr()", text)
+
+ def test_screen_is_the_name_of_ocr(self):
+ from phone_harness.helpers import ocr, screen
+ self.assertIs(ocr, screen)
+ self.assertEqual(screen.__defaults__, (0.3,))