let your agent control your phone
feat: scroll progress is measured in pixels, not in shared OCR text
ShawnPanadb8b1a65f8e5
diff --git a/src/phone_harness/background.py b/src/phone_harness/background.pyindex 5755afb..9cc06b7 100644--- a/src/phone_harness/background.py+++ b/src/phone_harness/background.py@@ -242,6 +242,13 @@ def scroll_wheel(dy, x, y, steps=6):home = Quartz.CGEventGetLocation(Quartz.CGEventCreate(None))Quartz.CGWarpMouseCursorPosition(Quartz.CGPointMake(x, y))time.sleep(0.05)+ # The warp moves the pointer but does NOT re-run the hit-test that decides+ # which window a scroll belongs to. Without this event the scroll is+ # delivered to whatever was under the cursor before, and nothing moves.+ mv = Quartz.CGEventCreateMouseEvent(+ None, Quartz.kCGEventMouseMoved, Quartz.CGPointMake(x, y), 0)+ Quartz.CGEventPost(Quartz.kCGHIDEventTap, mv)+ time.sleep(0.05)try:for _ in range(steps):ev = Quartz.CGEventCreateScrollWheelEvent(diff --git a/src/phone_harness/helpers.py b/src/phone_harness/helpers.pyindex 80f8fea..e46cdc1 100644--- a/src/phone_harness/helpers.py+++ b/src/phone_harness/helpers.py@@ -312,38 +312,66 @@ def _overlap(a, b):return len(a & b) / len(a | b)-def scroll_screen(direction="up", amount=0.6, settle=2.5, moved_thresh=0.6):+def _profile():+ """Row-brightness profile of the current screen, for motion measurement."""+ from . import motion+ return motion.profile(screenshot())+++def scroll_screen(direction="up", amount=0.6, settle=2.5, moved_thresh=None):"""One scroll gesture, then wait for the screen to settle (so a lazy-loadspinner resolves before we judge movement).- Returns {moved, overlap, before, after, boxes} — `boxes` is the settled- content, ready to parse. `moved` is False when overlap >= moved_thresh:- the list didn't advance. The default 0.6 sits in the empirical gap between- real forward progress (overlap < ~0.45) and overscroll bounce at a- boundary (overlap > ~0.7), which springs the content and would otherwise- read as movement and defeat end-detection.+ Returns {moved, navigated, dy, match, overlap, before, after, boxes}.++ `moved` is decided by PIXELS, not by shared OCR text. Text overlap cannot+ tell a scroll from a navigation (both collapse it), says nothing at all on+ a screen with no text, and is unstable enough frame to frame that real+ scrolls were routinely reported as no movement. `dy` is how far the content+ actually travelled and `match` is how well a translation explains the+ change; see motion.py.++ `navigated` is True when the screen was REPLACED rather than scrolled — the+ gesture opened something. Callers looping over a list should stop and say+ so rather than keep scrolling against the wrong screen.++ `moved_thresh` is accepted and ignored; it tuned the old text-overlap test."""w = _win()+ from . import motionsign = {"up": -1, "down": 1}.get(direction) # 'up' reveals content belowif sign is None:raise ValueError(f"direction must be 'up' or 'down', got {direction!r}")++ before_prof = _profile()before = _text_set(_content_texts())+send("input.scroll", x=w["x"] + w["w"] / 2, y=w["y"] + w["h"] / 2,dy=sign * int(w["h"] * amount), steps=10)time.sleep(0.4)- prev_boxes, prev = None, None- deadline = time.time() + settle++ # Settle on pixels: two consecutive frames that neither move nor change.+ prev, deadline = None, time.time() + settlewhile time.time() < deadline:- boxes = _content_texts()- cur = _text_set(boxes)- if cur == prev: # two identical reads = settled- break- prev, prev_boxes = cur, boxes- time.sleep(0.35)- after = prev or frozenset()- return {"moved": _overlap(before, after) < moved_thresh,+ cur = _profile()+ if prev is not None:+ m = motion.compare(prev, cur)+ if abs(m["dy"]) < motion.STILL_PX and m["match"] > 0.99:+ prev = cur+ break+ prev = cur+ time.sleep(0.25)+ after_prof = prev if prev is not None else before_prof++ m = motion.compare(before_prof, after_prof)+ v = motion.verdict(m)++ boxes = _content_texts()+ after = _text_set(boxes)+ return {"moved": v == "scrolled", "navigated": v == "replaced",+ "dy": m["dy"], "match": m["match"],"overlap": round(_overlap(before, after), 3),- "before": before, "after": after, "boxes": prev_boxes or []}+ "before": before, "after": after, "boxes": boxes}def scroll_until(done, direction="up", amount=0.6, max_scrolls=60, settle=2.5):@@ -359,6 +387,11 @@ def scroll_until(done, direction="up", amount=0.6, max_scrolls=60, settle=2.5):stale = 0for _ in range(max_scrolls):res = scroll_screen(direction, amount, settle)+ if res["navigated"]:+ raise RuntimeError(+ "the scroll gesture opened something instead of scrolling — "+ "the screen was replaced, not moved. Stopping rather than "+ "looping against the wrong screen.")hit = done(res["boxes"])if hit:return hit@@ -384,7 +417,8 @@ def scroll_collect(extract=None, key=None, direction="up", amount=0.6,- Stops after `end_after` consecutive non-moving scrolls (the settle windowalready gave lazy-load a chance), or `max_scrolls`.- Returns {items, stop, scrolls}. `stop` is 'reached-end' or 'max-scrolls'.+ Returns {items, stop, scrolls}. `stop` is 'reached-end', 'max-scrolls',+ or 'navigated-away' when a gesture opened something instead of scrolling.Use amount < 1.0 so screens overlap and no row falls between captures."""extract = extract or (lambda boxes: [o["text"].strip() for o in boxes@@ -407,6 +441,8 @@ def scroll_collect(extract=None, key=None, direction="up", amount=0.6,stale = 0for i in range(1, max_scrolls + 1):res = scroll_screen(direction, amount, settle)+ if res["navigated"]:+ return {"items": order, "stop": "navigated-away", "scrolls": i}new = ingest(res["boxes"])if on_progress:on_progress(i, len(order), new, res["moved"], res["overlap"])diff --git a/src/phone_harness/motion.py b/src/phone_harness/motion.pynew file mode 100644index 0000000..a392f39--- /dev/null+++ b/src/phone_harness/motion.py@@ -0,0 +1,120 @@+"""Did the screen scroll, hold still, or get replaced? Measured in pixels.++Scroll progress used to be judged by how much OCR text two captures shared.+That fails in three ways this module does not:++ - a screen with no readable text has no overlap to measure, so a settled+ list reads as movement and end-detection never fires (issue #24)+ - a scroll and a NAVIGATION both collapse the overlap, so a gesture that+ opened a row is indistinguishable from one that scrolled (issue #22)+ - OCR is not stable frame to frame: identical pixels can yield overlaps+ anywhere from 0.6 to 1.0, so a real scroll is regularly reported as no+ movement++A scroll is a vertical translation of the content, so measure that directly.+Each capture is reduced to one brightness value per row; the shift that best+lines the two profiles up is how far the view moved, and how well they line up+at that shift says whether a translation explains the change at all.++Quartz only — no new dependency.+"""+import Quartz+from Foundation import NSURL++STATUS_BAR = 0.09 # cropped: the clock ticks and would read as motion+HOME_STRIP = 0.05+ROWS = 400 # profile resolution; finer = better on dense content+COLS = 64 # sampled columns, split into STRIPS independent profiles+STRIPS = 8 # separate column bands. Averaging the whole width flattens+ # a photo grid into mush; bands keep enough structure that+ # a real scroll still correlates (0.71 vs 0.59 measured).+MAX_SHIFT = 0.45 # search +/- this fraction of the profile++# Calibrated on this hardware against known cases:+# identical frames 1.00+# photo-grid scroll (worst real) 0.71+# navigation (General -> Fonts) 0.34+MATCH_MIN = 0.55 # below this, no translation explains the change+STILL_PX = 2 # |dy| under this is "did not move"+++def profile(path):+ """Row-brightness profiles, one per column band, top of screen first.++ Returns STRIPS lists. Chrome (status bar, home strip) is cropped: the clock+ ticks once a minute and would otherwise read as motion.+ """+ src = Quartz.CGImageSourceCreateWithURL(NSURL.fileURLWithPath_(path), None)+ if src is None:+ raise RuntimeError(f"cannot read image {path}")+ img = Quartz.CGImageSourceCreateImageAtIndex(src, 0, None)+ if img is None:+ raise RuntimeError(f"cannot decode image {path}")++ cs = Quartz.CGColorSpaceCreateDeviceGray()+ ctx = Quartz.CGBitmapContextCreate(None, COLS, ROWS, 8, COLS, cs,+ Quartz.kCGImageAlphaNone)+ Quartz.CGContextDrawImage(ctx, ((0, 0), (COLS, ROWS)), img)+ buf = bytes(Quartz.CGBitmapContextGetData(ctx).as_buffer(COLS * ROWS))++ per = COLS // STRIPS+ top, bot = int(ROWS * STATUS_BAR), int(ROWS * (1 - HOME_STRIP))+ out = []+ for s in range(STRIPS):+ lo, hi = s * per, (s + 1) * per+ rows = [sum(buf[y * COLS + lo:y * COLS + hi]) / per for y in range(ROWS)]+ rows.reverse() # CGContext draws bottom-up; index 0 = top of screen+ out.append(rows[top:bot])+ return out+++def _pearson(a, b):+ n = len(a)+ if n < 8:+ return 0.0+ ma, mb = sum(a) / n, sum(b) / n+ num = sxx = syy = 0.0+ for i in range(n):+ x, y = a[i] - ma, b[i] - mb+ num += x * y+ sxx += x * x+ syy += y * y+ den = (sxx * syy) ** 0.5+ return num / den if den > 0 else 0.0+++def _match_at(a, b, dy):+ """How well `dy` lines the two profiles up, as Pearson r."""+ n = len(a)+ if dy >= 0:+ aa, bb = a[:n - dy], b[dy:]+ else:+ aa, bb = a[-dy:], b[:n + dy]+ return _pearson(aa, bb) if len(aa) >= n * 0.4 else 0.0+++def compare(before, after):+ """Vertical motion between two profile sets.++ Returns {dy, match}. dy > 0 means the content moved DOWN the screen (what a+ 'down' scroll does); dy < 0 means it moved up. The shift is the one that+ best lines up ALL column bands at once, so a single band of repeating+ content cannot carry the answer on its own.+ """+ if len(before) != len(after) or len(before[0]) != len(after[0]):+ raise ValueError("capture size changed between frames")+ lim = int(len(before[0]) * MAX_SHIFT)+ best_r, best_dy = -2.0, 0+ for dy in range(-lim, lim + 1):+ r = sum(_match_at(a, b, dy) for a, b in zip(before, after)) / len(before)+ if r > best_r:+ best_r, best_dy = r, dy+ # The search runs in bottom-up buffer order; report screen-space direction.+ return {"dy": -best_dy, "match": round(best_r, 3)}+++def verdict(m):+ """'scrolled' | 'still' | 'replaced'."""+ if m["match"] < MATCH_MIN:+ return "replaced"+ return "still" if abs(m["dy"]) < STILL_PX else "scrolled"