Skip to content

let your agent control your phone

android: a never-idle screen is asked once, then read from pixels (#77)

shawn pana374f14d44c7e
diff --git a/SKILL.md b/SKILL.md
index b7e70fe..c0b0266 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -186,9 +186,12 @@ PY
- `press()` takes single keys only (`"enter"`, `"back"`, `"tab"`); chords
raise Unsupported. `type_text` needs a focused field, same as iOS, and types
ASCII: adb cannot type emoji or accented letters.
-- **Some screens never give up their tree** — a playing video, a screen that
- animates. `ocr()` / `ui()` then raise saying so; take a `screenshot()` and
- look at it instead of retrying.
+- **Some screens never give up their tree** — a playing video, some Settings
+ pages. On a Mac, `ocr()` 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.
+ `ui()` / `tap_ui()` need the real tree and keep raising on such screens.
- No focus to keep: nothing on the Mac has to be frontmost, and
`interruption(before, after)` always reports nothing disturbed.
- **Verify cheaply, then read.** adb reports nothing about outcomes — a tap on
diff --git a/src/phone_harness/android.py b/src/phone_harness/android.py
index 01e3ef4..5081519 100644
--- a/src/phone_harness/android.py
+++ b/src/phone_harness/android.py
@@ -24,6 +24,7 @@ still "pixel-8". The first phone paired over Wi-Fi becomes the primary;
`phone-harness android use NAME` changes that; ANDROID_SERIAL overrides
everything.
"""
+import importlib.util
import os
import re
import shlex
@@ -39,6 +40,16 @@ from datetime import datetime, timezone
from . import config
from .transport import Backend, Unsupported
+# Apple's Vision OCR ships with the iPhone backend; on a Mac it can read an
+# Android screenshot too, so a screen the accessibility tree cannot describe
+# still yields text. Checked cheaply here, imported only when needed.
+_VISION = importlib.util.find_spec("Vision") is not None
+
+# How long a never-idle screen keeps the tree off. uiautomator itself waits
+# ~10s for idle before refusing, so one refusal is expensive; asking again a
+# second later gets the same answer.
+_TREE_BUSY_FOR = 20
+
def _adb_bin():
return str(config.get("android.adb"))
@@ -155,6 +166,10 @@ def _remember(cfg, serial, model, host=None, name=None, primary=False):
return key
+class TreeUnavailable(RuntimeError):
+ """uiautomator would not dump this screen; retrying will not change that."""
+
+
class Android(Backend):
name = "android"
@@ -163,6 +178,7 @@ class Android(Backend):
os.environ["ANDROID_SERIAL"] = serial
self._bounds = None
self._motionevents = None # does this phone's `input` know motionevent?
+ self._tree_busy_until = 0.0 # after "could not get idle state": read pixels
self._resolved = False
self._gate_at = 0.0
@@ -320,18 +336,44 @@ class Android(Backend):
return path, bounds
def _screen_text(self, min_confidence=0.3):
- """From the accessibility tree: exact strings, exact boxes."""
+ """From the accessibility tree: exact strings, exact boxes. When the
+ tree is unavailable (uiautomator refuses a screen that never goes
+ idle) and Vision is here, read the pixels instead — slower and fuzzy,
+ but an answer. `source` says which."""
+ if time.time() < self._tree_busy_until and _VISION:
+ return self._pixel_text(min_confidence)
+ try:
+ nodes = self._tree()
+ except TreeUnavailable:
+ if not _VISION:
+ raise
+ return self._pixel_text(min_confidence)
out = []
- for n in self._tree():
+ for n in nodes:
s = n["text"] or n["desc"]
if s:
out.append({"text": s, "confidence": 1.0, "source": "tree",
"x": n["x"], "y": n["y"], "w": n["w"], "h": n["h"]})
return out
- # No _screen_text_pixels: the tree is the text source here, and a caller
- # that needs pixels can look at screen.capture. Keeps this backend free of
- # anything but adb.
+ def _pixel_text(self, min_confidence=0.3):
+ """Vision OCR over a screenshot. Android screenshots are 1:1 with
+ device pixels, so the boxes are tap-ready as they come."""
+ from . import ocr as _vision
+ path, bounds = self._screen_capture()
+ try:
+ rows = _vision.recognize(path, {"x": 0, "y": 0, "w": bounds["w"], "h": bounds["h"]})
+ finally:
+ try:
+ os.unlink(path)
+ except OSError:
+ pass
+ return [{**r, "source": "pixels"} for r in rows if r["confidence"] >= min_confidence]
+
+ if _VISION:
+ def _screen_text_pixels(self, min_confidence=0.3):
+ """Force pixel OCR: canvases, games, WebViews the tree cannot see."""
+ return self._pixel_text(min_confidence)
# --- input --------------------------------------------------------------
@@ -581,32 +623,38 @@ class Android(Backend):
def _tree(self):
"""[{text, desc, id, class, clickable, x, y, w, h}] from
- `uiautomator dump`, retried briefly: it refuses while the UI is
- settling ("could not get idle state")."""
+ `uiautomator dump`. uiautomator waits about ten seconds for the UI to
+ go idle and then refuses ("could not get idle state"); a screen that
+ never idles — a playing video, some Settings pages — answers that
+ every time, so it is asked once and remembered. Other failures (a
+ transition mid-dump, a truncated tree) are retried briefly."""
self._screen_require()
self._gate()
last = None
- for i in range(5):
+ for i in range(3):
try:
raw = self._adb("exec-out", "uiautomator", "dump", "/dev/tty",
binary=True, timeout=30)
start = raw.find(b"<?xml")
if start < 0: # uiautomator printed an error, not a tree
last = raw.decode(errors="replace").strip() or "empty dump"
+ if "idle" in last:
+ self._tree_busy_until = time.time() + _TREE_BUSY_FOR
+ raise TreeUnavailable(
+ "the accessibility tree is not available on this screen "
+ "(uiautomator: could not get idle state). Read it from "
+ "screenshot() instead.")
raise ValueError(last)
xml = raw[start:raw.rfind(b">") + 1]
root = ET.fromstring(xml)
+ self._tree_busy_until = 0.0
break
except (RuntimeError, ValueError, ET.ParseError) as e:
+ if isinstance(e, TreeUnavailable):
+ raise
last = str(e)
- time.sleep(0.5 * (i + 1)) # 0.5, 1, 1.5, 2s: transitions settle
+ time.sleep(0.5 * (i + 1)) # 0.5, 1s: a transition settles
else:
- if "idle" in (last or ""):
- raise RuntimeError(
- "the accessibility tree is unavailable on this screen: it "
- "never goes idle (something animates or auto-refreshes), so "
- "uiautomator will not dump it. Read it from screenshot() "
- "instead, or navigate to a screen that settles.")
raise RuntimeError(f"uiautomator dump failed: {last}")
nodes = []
for el in root.iter("node"):
diff --git a/tests/test_android.py b/tests/test_android.py
index d005486..4455ad8 100644
--- a/tests/test_android.py
+++ b/tests/test_android.py
@@ -1,19 +1,40 @@
"""Android backend behaviour that needs no phone: the commands it would send."""
import sys
import unittest
+import unittest.mock
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
-from phone_harness.android import Android # noqa: E402
+from phone_harness import android as android_mod # noqa: E402
+from phone_harness.android import Android, TreeUnavailable # noqa: E402
class Recorded(Android):
"""An Android whose adb shell is a list."""
- def __init__(self, installed=(), fail_motionevent=False):
+ def __init__(self, installed=(), fail_motionevent=False, dumps=()):
super().__init__()
self.sent, self.installed, self.fail_motionevent = [], list(installed), fail_motionevent
+ self.dumps, self.dump_calls, self.shots = list(dumps), 0, 0
self._bounds = {"x": 0, "y": 0, "w": 720, "h": 1280, "id": "fake"}
+ self._resolved = True
+
+ def _screen_require(self):
+ return self._bounds
+
+ def _adb(self, *args, binary=False, timeout=60):
+ if "uiautomator" in args:
+ self.dump_calls += 1
+ return self.dumps.pop(0) if self.dumps else b"ERROR: could not get idle state."
+ if "screencap" in args:
+ self.shots += 1
+ return b"\x89PNG-fake"
+ raise AssertionError(args)
+
+ def _pixel_text(self, min_confidence=0.3):
+ self.shots += 1
+ return [{"text": "Device name", "confidence": 0.9, "source": "pixels",
+ "x": 160, "y": 570, "w": 220, "h": 40}]
def _gate(self):
pass
@@ -55,6 +76,47 @@ class Scroll(unittest.TestCase):
self.assertEqual(sum("motionevent" in c for c in phone.sent), 1) # asked once
+TREE = (b'<?xml version="1.0"?><hierarchy><node text="Apps" content-desc="" resource-id="" '
+ b'class="android.widget.TextView" clickable="true" bounds="[100,900][300,960]"/></hierarchy>')
+
+
+class Tree(unittest.TestCase):
+ def test_a_never_idle_screen_is_asked_once_then_read_from_pixels(self):
+ phone = Recorded()
+ with unittest.mock.patch.object(android_mod, "_VISION", True):
+ rows = phone._screen_text()
+ self.assertEqual(phone.dump_calls, 1) # not five
+ self.assertEqual([r["source"] for r in rows], ["pixels"])
+ self.assertEqual(rows[0]["text"], "Device name")
+ with unittest.mock.patch.object(android_mod, "_VISION", True):
+ phone._screen_text() # within the busy window:
+ self.assertEqual(phone.dump_calls, 1) # ...no second dump at all
+
+ def test_without_vision_it_fails_at_once_with_a_plain_message(self):
+ phone = Recorded()
+ with unittest.mock.patch.object(android_mod, "_VISION", False):
+ with self.assertRaises(TreeUnavailable) as cm:
+ phone._screen_text()
+ self.assertEqual(phone.dump_calls, 1)
+ self.assertIn("screenshot()", str(cm.exception))
+ self.assertNotIn("animates", str(cm.exception))
+
+ def test_a_good_tree_is_preferred_and_clears_the_busy_window(self):
+ phone = Recorded(dumps=[TREE])
+ phone._tree_busy_until = 0.0
+ rows = phone._screen_text()
+ self.assertEqual([(r["text"], r["source"], r["x"], r["y"]) for r in rows],
+ [("Apps", "tree", 200, 930)])
+ self.assertEqual(phone.shots, 0)
+
+ def test_a_transient_failure_is_retried_briefly(self):
+ phone = Recorded(dumps=[b"garbage", TREE])
+ with unittest.mock.patch.object(android_mod.time, "sleep"):
+ rows = phone._screen_text()
+ self.assertEqual(phone.dump_calls, 2)
+ self.assertEqual(rows[0]["text"], "Apps")
+
+
class Launch(unittest.TestCase):
INSTALLED = ["com.android.chrome", "com.android.chrome.helper", "com.facebook.orca",
"com.facebook.katana", "com.zhiliaoapp.musically", "com.whatsapp"]