let your agent control your phone
input: hold real modifier keys, and paste instead of typing
ShawnPana4c6ef176fba2
diff --git a/SKILL.md b/SKILL.mdindex f629ca6..8ccddca 100644--- a/SKILL.md+++ b/SKILL.md@@ -92,7 +92,12 @@ raises a clear message (call `connection_state()` yourself to check —tap through the resume screen — stop and ask the user to lock/connect thephone (see "Connection is the user's job").- **`type_text` needs an iOS text field focused first** — tap the field, wait- for the keyboard, then type.+ for the keyboard, then type. It fails *silently* when nothing is focused: the+ text goes to whatever is focused instead, or nowhere. Verify with a capture,+ and if a tap will not take focus, `press("tab")` moves between fields.+- **`type_text` pastes; it does not type.** That is deliberate — the keystroke+ path runs through iOS autocorrect, which rewrites words as they land ("Thu"+ becomes "thru"). Pass `keystrokes=True` for fields that need real key events.- **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/background.py b/src/phone_harness/background.pyindex e5421f2..15c19c0 100644--- a/src/phone_harness/background.py+++ b/src/phone_harness/background.py@@ -35,6 +35,7 @@ event-record layout isn't implemented yet, so those fall back to the mirrorpath. Mouse actions are fully background."""import ctypes, ctypes.util, os, struct, subprocess, tempfile, time+from contextlib import contextmanagerfrom pathlib import Pathimport Quartz@@ -259,14 +260,41 @@ def _make_key(pid, wid):_sky.SLPSPostEventRecordTo(ctypes.byref(psn), ctypes.byref(buf))+def _key_edge(pid, wid, code, down, flags=0):+ _make_key(pid, wid) # keep the window key across the keystroke+ ev = Quartz.CGEventCreateKeyboardEvent(None, code, down)+ if flags:+ # Mac-side consumers only. iPhone Mirroring forwards raw HID keycodes+ # to iOS and drops the flag mask, so a modifier expressed as a flag+ # never reaches the phone — it has to be a key that is held.+ Quartz.CGEventSetFlags(ev, flags)+ Quartz.CGEventPostToPid(pid, ev)+ time.sleep(0.03)++def _key(pid, wid, code, flags=0):for down in (True, False):- _make_key(pid, wid) # keep the window key across the keystroke- ev = Quartz.CGEventCreateKeyboardEvent(None, code, down)- if flags:- Quartz.CGEventSetFlags(ev, flags)- Quartz.CGEventPostToPid(pid, ev)- time.sleep(0.03)+ _key_edge(pid, wid, code, down, flags)+++@contextmanager+def _holding(pid, wid, mods):+ """Hold real modifier keys down around the body. See mirror._holding."""+ acc = 0+ for m in mods:+ acc |= mirror._MODIFIERS[m]+ _key_edge(pid, wid, mirror._MOD_KEYCODES[m], True, acc)+ try:+ yield acc+ finally:+ # Unconditional: a latched modifier corrupts every later keystroke, and+ # the damage surfaces somewhere else entirely.+ for m in reversed(mods):+ # Clear the bit *before* posting the release. A key-up still+ # carrying its own flag reads as "still held", which latches shift+ # on and turns the rest of the string into 1,200 -> !<@)).+ acc &= ~mirror._MODIFIERS[m]+ _key_edge(pid, wid, mirror._MOD_KEYCODES[m], False, acc)def press(combo):@@ -276,14 +304,16 @@ def press(combo):key, mods = parts[-1], parts[:-1]if key not in mirror._KEYCODES:raise ValueError(f"unknown key {key!r}")- flags = 0for m in mods:- flags |= mirror._MODIFIERS[m]- _key(pid, win["id"], mirror._KEYCODES[key], flags)+ if m not in mirror._MOD_KEYCODES:+ raise ValueError(f"unknown modifier {m!r}")+ with _holding(pid, win["id"], mods) as flags:+ _key(pid, win["id"], mirror._KEYCODES[key], flags)-def type_text(text, delay=0.03):- """Type into the focused iOS field via real keycodes, no focus change."""+def _type_keystrokes(text, delay=0.03):+ """Type via real keycodes, no focus change. Subject to iOS autocorrect,+ which rewrites words as they are typed."""pid, win = _ctx()for i, line in enumerate(text.split("\n")):if i:@@ -292,6 +322,17 @@ def type_text(text, delay=0.03):code, shifted = mirror._keycode_for(ch)if code is None:raise ValueError(f"cannot type {ch!r} via keycodes")- _key(pid, win["id"], code,- Quartz.kCGEventFlagMaskShift if shifted else 0)+ with _holding(pid, win["id"], ["shift"] if shifted else []) as flags:+ _key(pid, win["id"], code, flags)time.sleep(delay)+++def type_text(text, delay=0.03, keystrokes=False):+ """Type into the focused iOS field, no focus change.++ Pastes by default so the text arrives exactly as written, past autocorrect+ and keyboard layout both. keystrokes=True sends real key events instead.+ """+ if keystrokes or not text:+ return _type_keystrokes(text, delay)+ mirror.paste_with(press, text)diff --git a/src/phone_harness/helpers.py b/src/phone_harness/helpers.pyindex 2904fb5..4b10bbd 100644--- a/src/phone_harness/helpers.py+++ b/src/phone_harness/helpers.py@@ -214,10 +214,14 @@ def press(combo):return send("input.keys", combo=combo)-def type_text(text, delay=0.03):+def type_text(text, delay=0.03, keystrokes=False):"""Type into the focused field. Tap the field and let the keyboard appear- first — text sent before it has focus goes nowhere."""- return send("input.text", s=text, delay=delay)+ first — text sent before it has focus goes nowhere, silently, so check a+ capture afterwards.++ Pastes by default so the text arrives exactly as written; keystrokes=True+ sends real key events for fields that need them."""+ return send("input.text", s=text, delay=delay, keystrokes=keystrokes)# --- gestures relative to the screen ----------------------------------------diff --git a/src/phone_harness/ios.py b/src/phone_harness/ios.pyindex 67e7552..0db6da2 100644--- a/src/phone_harness/ios.py+++ b/src/phone_harness/ios.py@@ -98,8 +98,8 @@ class IPhone(Backend):def _input_keys(self, combo):self.mirror.press(combo)- def _input_text(self, s, delay=0.03):- self.mirror.type_text(s, delay=delay)+ def _input_text(self, s, delay=0.03, keystrokes=False):+ self.mirror.type_text(s, delay=delay, keystrokes=keystrokes)# --- navigation -----------------------------------------------------@@ -117,7 +117,10 @@ class IPhone(Backend):"""Spotlight (Cmd+3): type the name, let results populate, commit."""self.mirror.press("cmd+3")_sleep(0.9)- self.mirror.type_text(name)+ # Keystrokes on purpose: Spotlight is the load-bearing path behind+ # open_app and demonstrably works this way. Move it to paste only once+ # that path has miles on it.+ self.mirror.type_text(name, keystrokes=True)_sleep(1.2)self.mirror.press("return")return namediff --git a/src/phone_harness/mirror.py b/src/phone_harness/mirror.pyindex 0aa9489..8a8b1ca 100644--- a/src/phone_harness/mirror.py+++ b/src/phone_harness/mirror.py@@ -6,6 +6,7 @@ macOS accessibility sees nothing inside it, so input is synthesized at theHID level and the window must be frontmost or events are swallowed."""import subprocess, tempfile, time+from contextlib import contextmanagerimport ApplicationServices as _ASfrom pathlib import Path@@ -402,6 +403,52 @@ _MODIFIERS = {"option": Quartz.kCGEventFlagMaskAlternate,"ctrl": Quartz.kCGEventFlagMaskControl,}+# The physical keys behind those flags. Left-hand only: a synthesized event has+# no physical side, so kVK_RightShift and friends (54, 60, 61, 62) would be dead+# weight. kVK_CapsLock (57) is left out on purpose — it is a toggle with its own+# flag mask and synthesizes unreliably, and shift covers every case we want.+_MOD_KEYCODES = {+ "cmd": 55, "shift": 56, "alt": 58, "option": 58, "ctrl": 59,+}+++def _post_key(code, down, flags=0):+ ev = Quartz.CGEventCreateKeyboardEvent(None, code, down)+ if flags:+ # Only Mac-side consumers ever read these. Set them so macOS's own+ # state machine stays consistent; iOS never sees them.+ Quartz.CGEventSetFlags(ev, flags)+ Quartz.CGEventPost(Quartz.kCGHIDEventTap, ev)+++@contextmanager+def _holding(mods):+ """Hold real modifier keys down around the body.++ iPhone Mirroring forwards raw HID keycodes to iOS and drops the CGEvent+ flag mask, so a flag set on the key event reaches the Mac app but never the+ phone. That is why cmd+1 (a menu shortcut the Mac app handles) works while+ cmd+v aimed at an iOS text field arrives as a bare 'v'. Shift is a key you+ hold, not a bit you set.+ """+ acc = 0+ for m in mods:+ acc |= _MODIFIERS[m]+ _post_key(_MOD_KEYCODES[m], True, acc)+ time.sleep(0.01)+ try:+ yield acc+ finally:+ # Unconditional: a modifier left latched by an exception mid-string+ # corrupts every later keystroke in the session, and the damage shows+ # up somewhere else entirely.+ for m in reversed(mods):+ # Clear the bit *before* posting the release. A key-up still+ # carrying its own flag reads as "still held", which latches shift+ # on and turns the rest of the string into 1,200 -> !<@)).+ acc &= ~_MODIFIERS[m]+ _post_key(_MOD_KEYCODES[m], False, acc)+ time.sleep(0.01)def press(combo):@@ -411,15 +458,13 @@ def press(combo):key, mods = parts[-1], parts[:-1]if key not in _KEYCODES:raise ValueError(f"unknown key {key!r}")- flags = 0for m in mods:- flags |= _MODIFIERS[m]- for down in (True, False):- ev = Quartz.CGEventCreateKeyboardEvent(None, _KEYCODES[key], down)- if flags:- Quartz.CGEventSetFlags(ev, flags)- Quartz.CGEventPost(Quartz.kCGHIDEventTap, ev)- time.sleep(0.03)+ if m not in _MOD_KEYCODES:+ raise ValueError(f"unknown modifier {m!r}")+ with _holding(mods) as flags:+ for down in (True, False):+ _post_key(_KEYCODES[key], down, flags)+ time.sleep(0.03)# iPhone Mirroring forwards raw HID keycodes to iOS and ignores the unicode@@ -448,9 +493,35 @@ def _keycode_for(ch):return code, shifted-def type_text(text, delay=0.03):- """Type text into the focused iOS field via real keycodes (US layout).- \n presses return. Raises on characters with no keycode (emoji etc.)."""+def paste_with(press_fn, text):+ """Put text on the Mac clipboard and paste it into the phone.++ Takes the press function rather than calling one, because the two input+ paths reach the phone differently (posted to the window vs posted to the+ pid) and only the caller knows which is in play. The clipboard round-trip+ itself is identical, and worth having in exactly one place.+ """+ prior = 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=prior)+++def _type_keystrokes(text, delay=0.03):+ """Type via real keycodes (US layout). Newline presses return. Raises on+ characters with no keycode (emoji etc.).++ Subject to iOS autocorrect, which rewrites words as they are typed --+ 'Thu' becomes 'thru', 'Fri' becomes 'Friday'. Prefer type_text's paste+ path for anything whose exact wording matters.+ """_focus()for i, line in enumerate(text.split("\n")):if i:@@ -459,10 +530,24 @@ def type_text(text, delay=0.03):code, shifted = _keycode_for(ch)if code is None:raise ValueError(f"cannot type {ch!r} via keycodes")- for down in (True, False):- ev = Quartz.CGEventCreateKeyboardEvent(None, code, down)- if shifted:- Quartz.CGEventSetFlags(ev, Quartz.kCGEventFlagMaskShift)- Quartz.CGEventPost(Quartz.kCGHIDEventTap, ev)- time.sleep(0.01)+ with _holding(["shift"] if shifted else []) as flags:+ for down in (True, False):+ _post_key(code, down, flags)+ time.sleep(0.01)time.sleep(delay)+++def type_text(text, delay=0.03, keystrokes=False):+ """Type text into the focused iOS field.++ Pastes by default, which is immune to both autocorrect and keyboard layout+ -- the text arrives exactly as given. Set keystrokes=True for fields that+ need real key events.++ Either path needs a focused field. Neither can tell whether it got one:+ text sent to an unfocused field goes nowhere, silently, so verify with a+ capture afterwards.+ """+ if keystrokes or not text:+ return _type_keystrokes(text, delay)+ paste_with(press, text)diff --git a/src/phone_harness/transport.py b/src/phone_harness/transport.pyindex e01286d..48ccc8c 100644--- a/src/phone_harness/transport.py+++ b/src/phone_harness/transport.py@@ -30,7 +30,13 @@ nothing in common — so the shared layer is this vocabulary instead.input.drag x1, y1, x2, y2, duration, stepsinput.scroll x, y, dy, steps +dy scrolls content upinput.keys combo- input.text s, delay+ input.text s, delay, keystrokes++ input.text pastes by default, which is exact; keystrokes=True asks for+ real key events instead. The distinction is in the vocabulary because+ it changes what arrives: a keystroke path runs through the device's own+ autocorrect and keyboard layout, a paste does not. Backends without a+ shared clipboard may only support keystrokes.duration and steps stay in the vocabulary rather than being hidden. OniOS a fast short drag is a momentum flick and a slow one barely