let your agent control your phone
fix: a paste never restores the clipboard early; the doctor speaks both platforms
ShawnPanac567269bb9a4
diff --git a/SKILL.md b/SKILL.mdindex d3a7bc0..348347b 100644--- a/SKILL.md+++ b/SKILL.md@@ -90,8 +90,8 @@ PYmatches installed package ids and returns the one launched.- `press()` takes single keys only (`"enter"`, `"back"`, `"tab"`); chordsraise Unsupported. `type_text` needs a focused field, same as iOS.-- No focus to keep: nothing on the Mac has to be frontmost, and `interruption`- is always nothing.+- 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 onempty space "succeeds". After an action: `wait_for_app("com.android.chrome")`(~0.1s per poll) or `wait_for_text("Got it")` (returns the box or None),@@ -156,6 +156,8 @@ raises a clear message (call `connection_state()` yourself to check —- **`type_text` pastes; it does not type.** That is deliberate — the keystrokepath runs through iOS autocorrect, which rewrites words as they land ("Thu"becomes "thru"). Pass `keystrokes=True` for fields that need real key events.+ The typed text stays on the Mac clipboard afterwards (restoring the old+ clipboard raced the phone and could paste it instead).- **Home-Screen labels are not tap targets.** `tap_text("Weather")` hits thelabel and nothing happens; the icon is ~35 points above it. Use`tap_icon("Weather")` (agent helper) on the Home Screen; `tap_text` worksdiff --git a/src/phone_harness/admin.py b/src/phone_harness/admin.pyindex fe2f804..cdb376c 100644--- a/src/phone_harness/admin.py+++ b/src/phone_harness/admin.py@@ -1,70 +1,140 @@-"""Diagnostics: `phone-harness --doctor` walks the permission/session ladder."""-import os, subprocess, sys, tempfile+"""Diagnostics: `phone-harness --doctor` walks the ladder for the phone the+helpers would drive — the config default, or `--doctor ios|android`."""+import os+import shutil+import subprocess+import tempfilefrom pathlib import Path-def _check(label, ok, hint=""):+def _check(label, ok, hint="", fatal=True):+ """Print a check; a fatal failure is remembered for the verdict."""mark = "PASS" if ok else "FAIL"print(f" [{mark}] {label}" + (f" — {hint}" if not ok and hint else ""))+ if not ok and fatal:+ _failures.append(label)return ok-def run_doctor():- print("phone-harness doctor\n")- ok = True+_failures = []++def run_doctor(platform=None):+ from . import config+ platform = (platform or config.get("platform")).lower()+ print(f"phone-harness doctor — {platform}"+ f"{'' if platform == config.get('platform') else ' (default is ' + config.get('platform') + ')'}\n")+ _failures.clear()+ if platform == "android":+ _doctor_android()+ else:+ _doctor_ios()+ ok = not _failures+ print("\nall clear" if ok else "\nfix the FAILs above, then re-run")+ return 0 if ok else 1+++# --- iPhone: pyobjc -> permissions -> Mirroring -> capture -> OCR -----------++def _doctor_ios():try:import Quartz, Vision, AppKit # noqa: F401- ok &= _check("pyobjc frameworks (Quartz, Vision, AppKit)", True)+ _check("pyobjc frameworks (Quartz, Vision, AppKit)", True)except ImportError as e:_check("pyobjc frameworks", False,- f"pip install pyobjc-framework-Quartz pyobjc-framework-Vision ({e})")- return 1+ f"pip install pyobjc-framework-Quartz pyobjc-framework-Vision "+ f"pyobjc-framework-Cocoa ({e})")+ returnfrom ApplicationServices import AXIsProcessTrusted- ok &= _check(- "Accessibility permission (taps & keystrokes)", AXIsProcessTrusted(),- "System Settings > Privacy & Security > Accessibility: enable your terminal")+ _check("Accessibility permission (taps & keystrokes)", AXIsProcessTrusted(),+ "System Settings > Privacy & Security > Accessibility: enable your terminal")import Quartz as Q- ok &= _check(- "Screen Recording permission (seeing the phone)",- bool(Q.CGPreflightScreenCaptureAccess()),- "System Settings > Privacy & Security > Screen Recording: enable your terminal")+ _check("Screen Recording permission (seeing the phone)",+ bool(Q.CGPreflightScreenCaptureAccess()),+ "System Settings > Privacy & Security > Screen Recording: enable your terminal")from . import mirror- ok &= _check(f"{mirror.APP_NAME} installed", Path(mirror.APP_PATH).exists(),- "requires macOS Sequoia+ with a paired iPhone")+ _check(f"{mirror.APP_NAME} installed", Path(mirror.APP_PATH).exists(),+ "requires macOS Sequoia+ with a paired iPhone")running = mirror.running_app() is not None_check(f"{mirror.APP_NAME} running", running,- "will auto-launch on first use — not fatal")+ "will auto-launch on first use — not fatal", fatal=False)win = mirror.find_window()_check("mirroring window found", win is not None,"open iPhone Mirroring once manually to pair the phone")+ if not win:+ return- if win:- with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:- path = f.name- try:- subprocess.run(- ["screencapture", "-x", "-o", "-l", str(win["id"]), path],- check=True)- size = os.path.getsize(path)- ok &= _check(f"window capture works ({size} bytes)", size > 20_000,- "capture is blank — Screen Recording permission "- "needs a terminal restart to take effect")- if size > 20_000:- from . import ocr- n = len(ocr.recognize(path, win))- _check(f"Vision OCR works ({n} text boxes)", True)- finally:+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:+ path = f.name+ try:+ # Never crash here: a missing Screen Recording grant is exactly what+ # this check exists to report.+ r = subprocess.run(["screencapture", "-x", "-o", "-l", str(win["id"]), path],+ capture_output=True)+ size = os.path.getsize(path) if os.path.exists(path) else 0+ good = r.returncode == 0 and size > 20_000+ _check(f"window capture works ({size} bytes)", good,+ "capture failed or is blank — Screen Recording permission "+ "needs a terminal restart to take effect")+ if good:+ from . import ocr+ n = len(ocr.recognize(path, win))+ _check(f"Vision OCR works ({n} text boxes)", True)+ finally:+ if os.path.exists(path):os.unlink(path)- print("\nall clear" if ok else "\nfix the FAILs above, then re-run")- print("\nnote: these are the permissions currently known to be required. A "- "fresh\nmachine may still prompt for more the first time an action "- "runs — approve\nthem in System Settings if a step silently does "- "nothing despite this passing.")- return 0 if ok else 1+ from . import ios+ state = ios.IPhone().send("session.state")+ _check(f"session state: {state}", state == "ready",+ "an interstitial is up (iPhone in Use / Connect / Mac Locked) — "+ "clear it on the Mac; lock the iPhone if it says in use", fatal=False)+++# --- Android: adb -> a phone -> authorised -> awake -> tree ------------------++def _doctor_android():+ from . import config+ adb = str(config.get("android.adb"))+ if not shutil.which(adb):+ _check(f"adb found ({adb})", False,+ "brew install android-platform-tools, or set android.adb to the binary")+ return+ _check(f"adb found ({shutil.which(adb)})", True)+ _check("scrcpy found (optional: live mirror during `android awake`)",+ bool(shutil.which("scrcpy")), "brew install scrcpy — not required", fatal=False)++ from . import android+ phone = android.Android()+ state = phone.send("session.state")+ hints = {+ "no-device": "plug in with USB debugging on and tap Allow, or "+ "Wireless debugging + `phone-harness android pair CODE`",+ "unauthorized": "tap Allow on the phone's 'Allow USB debugging?' prompt",+ "offline": "unplug/replug, or toggle Wireless debugging off and on",+ "locked": "unlock the phone (`phone-harness android awake` keeps it so)",+ "no-adb": "adb did not answer",+ }+ _check(f"a phone is reachable and ready (state: {state})",+ state in ("ready", "locked"), hints.get(state, ""))+ if state == "locked":+ _check("phone unlocked", False, hints["locked"], fatal=False)+ if state not in ("ready",):+ return++ b = phone.send("screen.bounds")+ label = android._phone_label(b["id"]) if b else "?"+ _check(f"talking to {label} ({b['id']}), screen {b['w']}x{b['h']}", bool(b))+ try:+ n = len(phone.send("tree"))+ _check(f"accessibility tree readable ({n} nodes)", n > 0)+ except RuntimeError as e:+ _check("accessibility tree readable", False, str(e)[:120], fatal=False)+ reg = config.devices_of("android")+ _check(f"remembered phones: {', '.join(reg['phones']) or 'none'}; primary: "+ f"{reg['primary'] or 'none'}", True)diff --git a/src/phone_harness/config.py b/src/phone_harness/config.pyindex c8c8dc2..f431d7f 100644--- a/src/phone_harness/config.py+++ b/src/phone_harness/config.py@@ -38,6 +38,10 @@ DEFAULTS = {"poke_every": 25, # seconds between keep-awake pokes"mirror": True, # open scrcpy during `android awake` if installed},+ "ios": {+ "restore_clipboard": False, # put the old clipboard back after a paste+ "paste_settle": 2.0, # ...after this many seconds, if so+ },}# Settings that historically had their own environment variable.@@ -124,9 +128,9 @@ def _coerce(text, like):"""An env-var string, shaped like the default it overrides."""if isinstance(like, bool):return text.strip().lower() in ("1", "true", "yes", "on")- if isinstance(like, int):+ if isinstance(like, (int, float)):try:- return int(text)+ return type(like)(text)except ValueError:return likereturn textdiff --git a/src/phone_harness/mirror.py b/src/phone_harness/mirror.pyindex 8a8b1ca..f18802f 100644--- a/src/phone_harness/mirror.py+++ b/src/phone_harness/mirror.py@@ -500,17 +500,26 @@ def paste_with(press_fn, text):paths reach the phone differently (posted to the window vs posted to thepid) and only the caller knows which is in play. The clipboard round-tripitself is identical, and worth having in exactly one place.++ The typed text stays on the Mac clipboard afterwards. Restoring the+ previous contents was a race: the phone pulls the clipboard through the+ Mirroring session some unknown time after cmd+v, and nothing reports+ when it has — restore too early and the phone pastes what was on the+ clipboard BEFORE (a URL, a token, a password) into the field. A+ deterministic "your clipboard now holds what was typed" beats a+ sometimes-leak. Set ios.restore_clipboard=true in config to restore+ after a generous settle anyway (ios.paste_settle seconds)."""+ from . import configprior = subprocess.run(["pbpaste"], capture_output=True).stdout- try:- subprocess.run(["pbcopy"], input=text.encode())- # Fail here rather than pasting stale clipboard contents into the phone.- if subprocess.run(["pbpaste"], capture_output=True).stdout != text.encode():- raise RuntimeError("clipboard did not take the text; cannot paste")- time.sleep(0.15) # the Mac clipboard has to reach the phone- press_fn("cmd+v")- time.sleep(0.2) # and the paste has to land before we restore it- finally:+ subprocess.run(["pbcopy"], input=text.encode())+ # Fail here rather than pasting stale clipboard contents into the phone.+ if subprocess.run(["pbpaste"], capture_output=True).stdout != text.encode():+ raise RuntimeError("clipboard did not take the text; cannot paste")+ time.sleep(0.15) # the Mac clipboard has to reach the phone+ press_fn("cmd+v")+ if config.get("ios.restore_clipboard"):+ time.sleep(float(config.get("ios.paste_settle")))subprocess.run(["pbcopy"], input=prior)diff --git a/src/phone_harness/run.py b/src/phone_harness/run.pyindex a58f79c..dce9864 100644--- a/src/phone_harness/run.py+++ b/src/phone_harness/run.py@@ -8,7 +8,7 @@ USAGE = """Usage:PYCommands:- phone-harness --doctor diagnose permissions, app, and session state+ phone-harness --doctor [ios|android] diagnose the phone the helpers would drivephone-harness skill print the phone-harness skill textphone-harness android ... pair/connect/choose an Android phonephone-harness config ... settings: `config set platform android`@@ -36,7 +36,7 @@ def main():returnif args and args[0] in {"--doctor", "doctor"}:from .admin import run_doctor- sys.exit(run_doctor())+ sys.exit(run_doctor(args[1] if len(args) > 1 else None))if args and args[0] == "android":from .android import clisys.exit(cli(args[1:]))