Let an AI model use a real iPhone with a $7 ESP32: AirPlay eyes, USB HID hands, any OpenAI-compatible vision model. No Mac, no developer account, no jailbreak.
pointer: two-point auto calibration, learned correction, sensitive change detection
Henryb27a47ebae1d
diff --git a/server/hidagent/phone.py b/server/hidagent/phone.pyindex c95e216..79d084c 100644--- a/server/hidagent/phone.py+++ b/server/hidagent/phone.py@@ -6,9 +6,11 @@ cancel drift. Coordinates are fractions of the screen (0..1, origin top-left), swork for any frame size."""+import asyncioimport jsonimport loggingimport time+from collections import dequefrom pathlib import Pathfrom . import vision@@ -16,36 +18,93 @@ from .device import Devicelog = logging.getLogger(__name__)-CALIBRATION_MOVE = 400 # mouse units moved diagonally during calibration+CALIBRATION_MOVE = 200 # mouse units moved diagonally for a manual (one point) calibration; stays on screen+CALIBRATION_STOPS = (150, 350) # automatic calibration finds the pointer at these distances from the cornerREHOME_EVERY = 10 # gestures between re-homing+HOLD = 0.25 # seconds to rest before lifting, so iOS adds no momentum (the swipe stops where it ends)+TAP_GAP = 0.15 # seconds to stay still after a click, so iOS sees a finished tap, not the start of a dragNUDGE = 12 # mouse units the pointer is wiggled by to find it on screenAIM_TOLERANCE = 0.008 # screen fraction; a bigger miss is corrected before pressing+MAX_MISS = 0.06 # bigger misses are still corrected, but not learned from (they may be misreadings)class Phone:def __init__(self, device: Device, calibration_file: Path, screen=None):self.device, self._file, self.screen = device, calibration_file, screen# mouse units needed to cross the full screen width / height- self.span = json.loads(calibration_file.read_text()) if calibration_file.exists() else None+ saved = json.loads(calibration_file.read_text()) if calibration_file.exists() else None+ self.span = {"w": saved["w"], "h": saved["h"]} if saved else Noneself._pos = None # pointer position in mouse units; None = unknownself._moves = 0self._link = 0 # device.links when the pointer was last homed+ # where the pointer really landed (seen on screen) for the screen fraction we aimed at, per axis;+ # a straight-line fit through them corrects every later move, so taps get better as the agent works+ self._seen = {axis: deque(map(tuple, (saved or {}).get("seen", {}).get(axis, [])), maxlen=12)+ for axis in ("x", "y")}@propertydef calibrated(self) -> bool:return self.span is not None- async def start_calibration(self) -> None:+ async def start_calibration(self) -> bool:+ """Find the pointer on screen at two known distances from the corner and fit the mapping from both.++ Two points give the scale and the offset, which one point cannot (iOS pointer motion is not exactly+ proportional). Returns True when it calibrated itself; otherwise the user clicks the pointer+ (finish_calibration).+ """self._pos = Noneawait self.device.send("home")- await self.device.send(f"move {CALIBRATION_MOVE} {CALIBRATION_MOVE}")+ seen = []+ for units in CALIBRATION_STOPS:+ step = units - (seen[-1][0] if seen else 0)+ await self.device.send(f"move {step} {step}")+ found = await self._find_pointer() if self.screen is not None and self.screen.live else None+ if not found:+ break+ seen.append((units, *found))+ if len(seen) < 2:+ log.info("calibration: pointer not found on screen, waiting for a click")+ if not seen:+ await self.device.send("home")+ await self.device.send(f"move {CALIBRATION_MOVE} {CALIBRATION_MOVE}")+ return False+ (u1, x1, y1), (u2, x2, y2) = seen+ self.span = {"w": round((u2 - u1) / (x2 - x1)), "h": round((u2 - u1) / (y2 - y1))}+ for samples in self._seen.values():+ samples.clear()+ for units, x, y in seen: # where each stop landed, so moves are corrected for the offset too+ self._seen["x"].append((units / self.span["w"], x))+ self._seen["y"].append((units / self.span["h"], y))+ self._save()+ log.info("calibration: pointer at %s, span %s", [(round(x, 3), round(y, 3)) for _, x, y in seen], self.span)+ return True++ async def _find_pointer(self) -> tuple[float, float] | None:+ """Wiggle the pointer and find it anywhere on screen (the span may still be unknown)."""+ await self.screen.settled(quiet=0.2, least=0.3, most=1.5)+ before, sent = self.screen.frame, time.time()+ await self.device.send(f"move {NUDGE} 0")+ after = await self.screen.fresh(sent, 1.0)+ if after:+ await self.screen.settled(quiet=0.15, least=0.1, most=0.6)+ after = self.screen.frame+ await self.device.send(f"move -{NUDGE} 0")+ found = before and after and vision.pointer(before, after, (0.5, 0.5), 0.025, reach=(0.5, 0.5))+ return found if found and 0.03 < found[0] < 0.97 and 0.03 < found[1] < 0.97 else Nonedef finish_calibration(self, x: float, y: float) -> None:- """x, y: where the pointer ended up after start_calibration()."""+ """x, y: where the pointer ended up after start_calibration() (one point, picked by the user)."""self.span = {"w": round(CALIBRATION_MOVE / x), "h": round(CALIBRATION_MOVE / y)}- self._file.write_text(json.dumps(self.span))+ for samples in self._seen.values():+ samples.clear()+ self._save()- async def point(self, x: float, y: float, aim: bool = True) -> None:+ def _save(self) -> None:+ """Calibration plus the observed landings, so the correction survives a restart."""+ self._file.write_text(json.dumps({**self.span, "seen": {k: list(v) for k, v in self._seen.items()}}))++ async def point(self, x: float, y: float, aim: bool = False) -> None:if not self.calibrated:raise RuntimeError("pointer not calibrated")await self._move_to(self._dx(x), self._dy(y))@@ -53,7 +112,7 @@ class Phone:await self._aim(x, y)async def _aim(self, x: float, y: float) -> None:- """Closed loop: find the real pointer on screen, fix a miss, and refine the calibration."""+ """Closed loop: find the real pointer on screen, fix a miss, and learn the error for later moves."""nudge = NUDGE if x < 0.9 else -NUDGE # stay clear of the screen edgeawait self.screen.settled(quiet=0.15, least=0.1, most=0.6) # pointer at restbefore, sent = self.screen.frame, time.time()@@ -63,23 +122,38 @@ class Phone:await self.screen.settled(quiet=0.1, least=0.05, most=0.4)after = self.screen.frameawait self.device.send(f"move {-nudge} 0")- found = before and after and vision.pointer(before, after, (x, y), nudge / self.span["w"])+ shift = nudge / self.span["w"]+ found = before and after and (vision.pointer(before, after, (x, y), shift) # near the target first,+ or vision.pointer(before, after, (0.5, 0.5), shift, reach=(0.5, 0.5))) # anywhereif not found:- log.debug("aim (%.3f, %.3f): pointer not found", x, y)+ log.debug("aim (%.3f, %.3f): pointer not found (%s)", x, y,+ "no new frame after the nudge" if not after else "no pointer-sized change near the target")returnfx, fy = foundlog.debug("aim (%.3f, %.3f): pointer at (%.3f, %.3f)", x, y, fx, fy)+ if max(abs(fx - x), abs(fy - y)) <= MAX_MISS: # learn from normal drift only, never from a stray reading+ self._seen["x"].append((self._fix(x, "x"), fx))+ self._seen["y"].append((self._fix(y, "y"), fy))+ self._save()if abs(fx - x) <= AIM_TOLERANCE and abs(fy - y) <= AIM_TOLERANCE:return- # moves are measured from the top-left corner, so a miss is mostly a wrong span- for axis, want, got in (("w", x, fx), ("h", y, fy)):- if want > 0.2 and 0.8 < got / want < 1.25:- self.span[axis] = round(self.span[axis] * (1 + 0.5 * (want / got - 1)))- self._file.write_text(json.dumps(self.span))- dx, dy = round((x - fx) * self.span["w"]), round((y - fy) * self.span["h"])+ dx, dy = round((x - fx) * self.span["w"]), round((y - fy) * self.span["h"]) # fix this miss right awayawait self.device.send(f"move {dx} {dy}")self._pos = (self._pos[0] + dx, self._pos[1] + dy)+ def _fix(self, t: float, axis: str) -> float:+ """The fraction to aim at so the pointer lands on t, from the line through the observed landings."""+ pts = self._seen[axis]+ if len(pts) < 2:+ return t+ n = len(pts)+ mc, mf = sum(c for c, _ in pts) / n, sum(f for _, f in pts) / n+ var = sum((c - mc) ** 2 for c, _ in pts)+ a = sum((c - mc) * (f - mf) for c, f in pts) / var if var > 1e-4 else 1.0 # landed = a * aimed + b+ a = a if 0.85 < a < 1.15 else 1.0+ b = mf - a * mc+ return (t - b) / a if abs(b) < 0.1 else t+async def _move_to(self, tx: int, ty: int, rehome: bool = True) -> None:if self._link != self.device.links: # new link: a dropped gesture may have left the button downawait self.device.send("release")@@ -99,20 +173,28 @@ class Phone:await self.device.send("home")self._pos, self._moves = (0, 0), 0- async def tap(self, x: float, y: float) -> None:- await self.point(x, y)+ async def tap(self, x: float, y: float, aim: bool = False) -> None:+ """aim=True finds the pointer on screen first (slower); worth it when a tap just missed."""+ await self.point(x, y, aim)await self.device.send("click")+ await asyncio.sleep(TAP_GAP)++ async def swipe(self, x1: float, y1: float, x2: float, y2: float, hold: bool = True) -> None:+ await self.drag([(x1, y1), (x2, y2)], hold)- async def swipe(self, x1: float, y1: float, x2: float, y2: float) -> None:- await self.drag([(x1, y1), (x2, y2)])+ async def drag(self, points: list[tuple[float, float]], hold: bool = True) -> None:+ """Press at the first point, move through the rest, release: one continuous stroke.- async def drag(self, points: list[tuple[float, float]]) -> None:- """Press at the first point, move through the rest, release: one continuous stroke."""+ hold=True rests at the end first, so lists and pickers stop exactly there instead of flinging on.+ System gestures (home, back) need the flick, so they pass hold=False.+ """await self.point(*points[0])await self.device.send("press")try:for x, y in points[1:]:await self._move_to(self._dx(x), self._dy(y), rehome=False) # never home mid-drag+ if hold:+ await asyncio.sleep(HOLD)finally:await self.device.send("release")@@ -127,13 +209,13 @@ class Phone:await self.device.send(f"key {combo}")async def go_home(self) -> None:- await self.swipe(0.5, 0.995, 0.5, 0.6)+ await self.swipe(0.5, 0.995, 0.5, 0.6, hold=False) # resting here would open the app switcherasync def go_back(self) -> None:- await self.swipe(0.005, 0.45, 0.6, 0.45)+ await self.swipe(0.005, 0.45, 0.6, 0.45, hold=False)def _dx(self, x: float) -> int:- return round(min(max(x, 0), 1) * self.span["w"])+ return round(min(max(self._fix(x, "x"), 0), 1) * self.span["w"])def _dy(self, y: float) -> int:- return round(min(max(y, 0), 1) * self.span["h"])+ return round(min(max(self._fix(y, "y"), 0), 1) * self.span["h"])diff --git a/server/hidagent/screen.py b/server/hidagent/screen.pyindex 6c30a34..7aeb40c 100644--- a/server/hidagent/screen.py+++ b/server/hidagent/screen.py@@ -18,6 +18,7 @@ class Screen:self.frame: bytes | None = Noneself.updated = 0.0self._proc = None+ self._clients_at, self._clients_n = 0.0, Noneself._stopping = Falsedef start(self) -> None:@@ -47,9 +48,38 @@ class Screen:@propertydef live(self) -> bool:- # AirPlay sends no frames while the screen is still, so allow a long quiet gaprunning = self._proc is not None and self._proc.poll() is None- return running and self.frame is not None and time.time() - self.updated < 90+ if not running or self.frame is None:+ return False+ clients = self._clients()+ if clients is not None: # Linux: is a phone connected to UxPlay right now?+ return clients > 0+ return time.time() - self.updated < 90 # elsewhere: AirPlay sends no frames while the screen is still++ def _clients(self) -> int | None:+ """Established TCP connections of the UxPlay process (a mirroring phone keeps some open).++ Read from /proc, cached for a second; None where /proc is not available (e.g. macOS).+ """+ if time.time() - self._clients_at < 1:+ return self._clients_n+ try:+ fds = os.listdir(f"/proc/{self._proc.pid}/fd")+ inodes = set()+ for fd in fds:+ link = os.readlink(f"/proc/{self._proc.pid}/fd/{fd}")+ if link.startswith("socket:["):+ inodes.add(link[8:-1])+ n = 0+ for table in ("/proc/net/tcp", "/proc/net/tcp6"):+ with open(table) as f:+ for row in f.readlines()[1:]:+ cols = row.split()+ n += cols[3] == "01" and cols[9] in inodes # 01 = ESTABLISHED+ except OSError:+ n = None+ self._clients_at, self._clients_n = time.time(), n+ return n@propertydef aspect(self) -> float:@@ -60,7 +90,7 @@ class Screen:return 9 / 19.5return int.from_bytes(f[i + 7:i + 9], "big") / int.from_bytes(f[i + 5:i + 7], "big")- async def settled(self, quiet: float = 0.5, least: float = 0.4, most: float = 4) -> None:+ async def settled(self, quiet: float = 0.35, least: float = 0.25, most: float = 4) -> None:"""Wait until the screen stops changing (AirPlay only sends frames on change)."""started = time.time()await asyncio.sleep(least)diff --git a/server/hidagent/vision.py b/server/hidagent/vision.pyindex f8eb974..036971b 100644--- a/server/hidagent/vision.py+++ b/server/hidagent/vision.py@@ -9,32 +9,55 @@ def _gray(jpeg: bytes) -> Image.Image:return Image.open(io.BytesIO(jpeg)).convert("L")-def changed(before: bytes | None, after: bytes | None, threshold: float = 1.0) -> bool:- """True when the screen content changed. Tiny thumbnails ignore the pointer and JPEG noise."""+def changed(before: bytes | None, after: bytes | None, ignore: tuple = (), threshold: float = 1.0) -> bool:+ """True when the screen content changed, including small things such as a checkmark.++ `ignore` lists screen points (fractions) where the pointer was or went: those spots are masked, so pointer+ moves never count. The status bar (clock) is ignored too.+ """if not before or not after:return True- a, b = (_gray(f).resize((32, 64), Image.BILINEAR) for f in (before, after))- diff = ImageChops.difference(a, b).tobytes()- return sum(diff) / len(diff) > threshold---def pointer(before: bytes, after: bytes, near: tuple[float, float], shift: float) -> tuple[float, float] | None:+ a, b = _gray(before), _gray(after)+ if a.size != b.size:+ return True+ small = ImageChops.difference(a.resize((32, 64), Image.BILINEAR), b.resize((32, 64), Image.BILINEAR)).tobytes()+ if sum(small) / len(small) > threshold: # a big change: new screen, scrolled list, keyboard+ return True+ w, h = a.size[0] // 2, a.size[1] // 2 # fine pass for small changes, at half resolution+ diff = ImageChops.difference(a.resize((w, h), Image.BILINEAR), b.resize((w, h), Image.BILINEAR)).tobytes()+ masks = [(px * w, py * h) for px, py in ignore]+ hits = 0+ for i, v in enumerate(diff):+ if v > 25:+ x, y = i % w, i // w+ if y > 0.06 * h and all((x - mx) ** 2 + (y - my) ** 2 > (0.05 * w) ** 2 for mx, my in masks):+ hits += 1+ return hits >= 6+++def pointer(before: bytes, after: bytes, near: tuple[float, float], shift: float,+ reach: tuple[float, float] = (0.12, 0.08)) -> tuple[float, float] | None:"""Where the pointer is in `before`, given it moved right by `shift` (fraction of width) in `after`.- Only the pointer moved between the two frames, so the changed pixels around `near` are the pointer- at both spots; their centroid sits shift/2 to the right of the first one. None if unclear.+ Only the pointer moved between the two frames, so the changed pixels within `reach` of `near` are the+ pointer at both spots; their centroid sits shift/2 to the right of the first one. None if unclear:+ nothing moved, or the change is too big or too spread out to be one small pointer."""a, b = _gray(before), _gray(after)if a.size != b.size:return Nonew, h = a.size- left, top = max(0, int((near[0] - 0.12) * w)), max(0, int((near[1] - 0.08) * h))- box = (left, top, min(w, int((near[0] + 0.12) * w)), min(h, int((near[1] + 0.08) * h)))+ rx, ry = reach+ left, top = max(0, int((near[0] - rx) * w)), max(int(0.05 * h), int((near[1] - ry) * h)) # skip the status bar+ box = (left, top, min(w, int((near[0] + rx) * w)), min(h, int((near[1] + ry) * h)))diff = ImageChops.difference(a.crop(box), b.crop(box)).tobytes()bw = box[2] - box[0]hits = [(i % bw, i // bw) for i, v in enumerate(diff) if v > 30]if not 15 <= len(hits) <= len(diff) // 4: # nothing moved, or much more than a pointerreturn None+ xs, ys = [x for x, _ in hits], [y for _, y in hits]+ if max(xs) - min(xs) > 0.15 * w or max(ys) - min(ys) > 0.07 * h: # not one compact spot+ return Nonecx = sum(x for x, _ in hits) / len(hits) + leftcy = sum(y for _, y in hits) / len(hits) + topreturn cx / w - shift / 2, cy / hdiff --git a/server/tests/test_agent.py b/server/tests/test_agent.pyindex 1984361..85fd90f 100644--- a/server/tests/test_agent.py+++ b/server/tests/test_agent.py@@ -50,3 +50,45 @@ def test_circle_is_closed_and_round_on_a_tall_screen():assert pts[0] == pytest.approx(pts[-1])for x, y in pts: # equal radius in pixels: y offsets shrink by the aspect ratioassert math.hypot(x - 0.5, (y - 0.5) / aspect) == pytest.approx(0.2)+++def test_actor_may_not_repeat_a_move_that_changed_nothing():+ import asyncio++ from hidagent.agent import Agent+ from hidagent.debug import Trace++ class Screen:+ live, frame, aspect = True, b"jpeg", 0.46++ class Actor:+ model = "fake"+ def __init__(self):+ self.prompts = []+ async def chat(self, system, text, image=None, max_tokens=600, temperature=0):+ self.prompts.append(text)+ return "THINK: again\nDO: swipe 382 253 382 150" if len(self.prompts) == 1 else "THINK: other\nDO: tap 1 2"++ actor = Actor()+ agent = Agent(phone=None, screen=Screen(), actor=actor, planner=actor, trace=Trace(None))+ agent.steps = [{"action": "swipe", "x1": 382, "y1": 253, "x2": 382, "y2": 150, "changed": False}]+ acts = asyncio.run(agent._next_actions())+ assert acts[0]["action"] == "tap"+ assert "changed nothing" in actor.prompts[1]+++def test_repeating_a_move_that_keeps_changing_the_screen_is_not_stuck():+ from hidagent.agent import Agent+ from hidagent.debug import Trace++ agent = Agent(phone=None, screen=None, actor=None, planner=None, trace=Trace(None))+ swipe = {"action": "swipe", "x1": 500, "y1": 800, "x2": 500, "y2": 400}+ agent.steps = [{**swipe, "changed": True}, {**swipe, "changed": True}]+ assert not agent._repeating(dict(swipe))+ agent.steps[-1]["changed"] = False # reached the end of the list+ assert agent._repeating(dict(swipe))+++def test_precise_tap_flag():+ assert parse_command("tap 120 640 precise") == {"action": "tap", "x": 120, "y": 640, "precise": True}+ assert "precise" not in parse_command("tap 120 640")diff --git a/server/tests/test_vision.py b/server/tests/test_vision.pyindex 994488a..526380f 100644--- a/server/tests/test_vision.py+++ b/server/tests/test_vision.py@@ -25,7 +25,7 @@ def screen(pointer_at=None, button=False) -> bytes:def test_pointer_move_is_not_a_screen_change():- assert not changed(screen((260, 856)), screen((272, 856)))+ assert not changed(screen((260, 856)), screen((272, 856)), ignore=((260 / W, 856 / H), (272 / W, 856 / H)))def test_new_content_is_a_screen_change():@@ -47,3 +47,28 @@ def test_pointer_is_found_from_a_nudge():def test_pointer_not_found_when_nothing_moved():frame = screen((262, 856))assert pointer(frame, frame, near=(0.5, 0.8), shift=12 / W) is None+++def checkmark_screen(checked: bool, pointer_at=(100, 500)) -> bytes:+ img = Image.open(io.BytesIO(screen(pointer_at))).convert("RGB")+ if checked:+ ImageDraw.Draw(img).line([(430, 495), (438, 505), (452, 485)], fill=(255, 149, 0), width=4)+ buf = io.BytesIO()+ img.save(buf, "JPEG", quality=75)+ return buf.getvalue()+++def test_small_checkmark_counts_as_a_change():+ assert changed(checkmark_screen(False), checkmark_screen(True))+++def test_masked_pointer_move_is_not_a_change():+ before, after = checkmark_screen(False, (100, 500)), checkmark_screen(False, (300, 500))+ assert not changed(before, after, ignore=((100 / W, 500 / H), (300 / W, 500 / H)))+++def test_pointer_far_from_the_target_is_found_with_a_full_screen_search():+ before, after = screen((354, 136)), screen((366, 136))+ assert pointer(before, after, near=(0.9, 0.1), shift=12 / W) is None # outside the window near the target+ found = pointer(before, after, near=(0.5, 0.5), shift=12 / W, reach=(0.5, 0.5))+ assert found[0] * W == pytest.approx(354, abs=3) and found[1] * H == pytest.approx(136, abs=3)