let your agent control your phone
Setup from first principles: check the environment, fall back to the cloud (#138)
shawn pana68d883f7dc40
diff --git a/README.md b/README.mdindex 5448770..4f74ce1 100644--- a/README.md+++ b/README.md@@ -42,7 +42,9 @@ that need your hands: pairing iPhone Mirroring and granting Accessibility andScreen Recording, or turning on Android developer options and approving adb.It also offers a cloud Android — the same helpers with nothing to pair, andthe first 100 minutes free; only cloud Android bills by the minute — so an iPhone user can test on Android too.-`phone-harness --doctor` checks the chain. Details in [install.md](install.md).+No Mac or no phone? The agent uses a cloud phone instead; nothing to install+but the CLI. `phone-harness doctor` checks the chain. Details in+[install.md](install.md) and [setup/](setup/).**Hermes Agent:** `hermes plugins install ShawnPana/phone-harness/integrations/hermes`adds a `phone_exec` tool and this skill. See [integrations/hermes](integrations/hermes/README.md).diff --git a/SKILL.md b/SKILL.mdindex 978732d..402bf4e 100644--- a/SKILL.md+++ b/SKILL.md@@ -13,6 +13,27 @@ and that is what the per-phone sections below are for. Read **Which phone**, theshared **Working method**, and then only the section for the phone in frontof you.+## Setup++Check what this machine can do (OS, shell, install rights, network,+attached phones; `phone-harness doctor` does the phone part), tell the user+in a sentence or two which phone you can drive with what is here, and use+the best one that actually runs. A phone on the desk wins; the cloud needs+no hardware and is always the fallback.++| Mode | Needs |+| --- | --- |+| Personal iPhone | macOS 15+, iPhone Mirroring paired to an iOS 18+ iPhone, Accessibility + Screen Recording for the app that runs Python |+| Android on the desk | macOS, Linux or Windows; adb; USB debugging (or Wireless debugging, Android 11+) |+| Cloud iPhone | HTTPS to phone-harness.com hosts; a signed-in account. No adb, any OS |+| Cloud Android | the cloud iPhone list, plus adb and outbound TCP to the phone's adb port |+| No install possible | HTTPS and an HTTP client: the API directly |++- If something is missing, name it and the one step the user can take.+- Ask the user only to approve sign-in and to pick a phone.+- Detail: [iPhone](https://github.com/ShawnPana/phone-harness/blob/main/setup/ios.md), [Android](https://github.com/ShawnPana/phone-harness/blob/main/setup/android.md),+ [Cloud](https://github.com/ShawnPana/phone-harness/blob/main/setup/cloud.md), [API](https://github.com/ShawnPana/phone-harness/blob/main/setup/api.md).+## Helpers- `ensure_device()` - Screen bounds once the device is usable, or raises with what the user has to do.diff --git a/install.md b/install.mdindex e4696ae..6f44864 100644--- a/install.md+++ b/install.md@@ -11,6 +11,18 @@ default and can switch per call. Reading on-screen text is `screen()`;the helper names and signatures are in the skill (`SKILL.md`, printed by`phone-harness skill`).+## Which mode can this machine run?++| Mode | Needs | Detail |+| --- | --- | --- |+| Personal iPhone | macOS 15+, paired iPhone Mirroring (iOS 18+), Accessibility + Screen Recording for the app that runs Python | [setup/ios.md](https://github.com/ShawnPana/phone-harness/blob/main/setup/ios.md) |+| Android on the desk | macOS, Linux or Windows; adb; USB or Wireless debugging | [setup/android.md](https://github.com/ShawnPana/phone-harness/blob/main/setup/android.md) |+| Cloud iPhone | HTTPS only; a signed-in account | [setup/cloud.md](https://github.com/ShawnPana/phone-harness/blob/main/setup/cloud.md) |+| Cloud Android | HTTPS, adb, and outbound TCP to the phone's adb port | [setup/cloud.md](https://github.com/ShawnPana/phone-harness/blob/main/setup/cloud.md) |+| Can't install anything | an HTTP client | [setup/api.md](https://github.com/ShawnPana/phone-harness/blob/main/setup/api.md) |++No Mac and no phone is not a dead end: the cloud needs no hardware.+## Fast Path```bash@@ -93,43 +105,13 @@ writing into the checkout.## iPhone-- macOS Sequoia+ with **iPhone Mirroring** paired to the phone (open the app- once and finish its pairing prompts — this needs the physical phone).-- Two permissions for your **terminal**, in System Settings → Privacy & Security:- - **Accessibility** — taps and keystrokes. Takes effect immediately.- - **Screen Recording** — seeing the phone. Takes effect after the terminal- restarts.- ```bash- open "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"- open "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture"- ```-- Then `phone-harness --doctor ios`.--> You may need to grant more than these two. They are the permissions we-> *know* are required and all `--doctor` checks; a fresh machine may prompt for-> more the first time an action runs. If `--doctor` passes but taps, typing, or-> capture silently do nothing, look for a macOS permission prompt.+See [setup/ios.md](https://github.com/ShawnPana/phone-harness/blob/main/setup/ios.md), then `phone-harness doctor ios`.## Android-- adb: `brew install android-platform-tools` (macOS), `apt install adb` (Debian/Ubuntu),- `winget install Google.PlatformTools` (Windows). Optional: `scrcpy` (`brew` /- `apt` / `winget install Genymobile.scrcpy`) for a live mirror window during- `phone-harness android awake`.-- On the phone, once: Settings → About phone → tap **Build number** 7× →- Settings → System → **Developer options**.-- **USB**: Developer options → **USB debugging** on → plug in → tap **Allow**- (tick "Always allow from this computer"). Done.-- **Wi‑Fi** (Android 11+, same network as the Mac): Developer options →- **Wireless debugging** on → tap the row → **Pair device with pairing code** →- `phone-harness android pair 123456` with the code shown. The phone is- remembered by name; from then on the harness finds and connects it itself.-- `phone-harness config set platform android` to make it the default, then- `phone-harness --doctor android`.-- `phone-harness android` shows known phones and what is attached; a plugged-in- phone always wins over Wi‑Fi. Long task? `phone-harness android awake --bg`- keeps the phone unlocked for the session without changing any setting;- `phone-harness android rest` ends it.+See [setup/android.md](https://github.com/ShawnPana/phone-harness/blob/main/setup/android.md), then `phone-harness doctor android`.+`phone-harness android` shows known phones; `phone-harness android awake --bg`+keeps one unlocked for a long task and `phone-harness android rest` ends it.## Both@@ -142,10 +124,11 @@ cloud iPhone is a third path: HTTPS ops, covered in the skill.## If It Fails-`--doctor` walks the ladder in order and names the missing step. Common ones:+`phone-harness doctor` walks the ladder in order and names the missing step. When a+local check fails it also points at the cloud. Common ones:- **iPhone — capture is blank/black**: Screen Recording granted but the- terminal wasn't restarted; or Mirroring shows an interstitial (iPhone in Use /+ app that runs your commands wasn't restarted; or Mirroring shows an interstitial (iPhone in Use /Connect / Mac Locked) — clear it on the Mac, lock the iPhone if it says in use.- **iPhone — taps do nothing**: Accessibility missing, or another window stolefocus (helpers re-activate the window; check for a macOS prompt).diff --git a/onboarding.md b/onboarding.mdindex f8a368a..a9958cd 100644--- a/onboarding.md+++ b/onboarding.md@@ -5,10 +5,20 @@ possible: detect what is already in place, and stop only for the steps thatneed the user's hands. Tell them exactly what to do on the phone or in SystemSettings, then wait.+## 0. Look before you ask++Check what this machine has: the OS, whether you can run and install+commands, network access, and any phone (`phone-harness doctor`). Then tell+the user in a sentence or two what you can drive from here, for example "This+is a Linux box with no phone attached, so I can use a cloud iPhone or Android."+iPhone Mirroring needs a Mac; without a Mac or a phone, the cloud (step 6) is+the setup. If you cannot install anything, use the API:+https://github.com/ShawnPana/phone-harness/blob/main/setup/api.md+## 1. One question"Which phone should be your default — your iPhone, an Android on your desk,-or an Android in the cloud?" (Both an iPhone and an Android is fine: set up+or a phone in the cloud (Android or iPhone)?" (Both an iPhone and an Android is fine: set upeach, then ask which is the default.) Someone with no phone at all picks thecloud: for them, step 6 is the setup and the demo runs there.@@ -18,11 +28,12 @@ Works through the macOS iPhone Mirroring app. Two things only the user can do:- Pair iPhone Mirroring with the phone once (open the app; the pairing promptsneed the physical phone).-- Grant the terminal **Accessibility** and **Screen Recording** in System- Settings → Privacy & Security (Screen Recording takes effect after the- terminal restarts).+- Grant **Accessibility** and **Screen Recording** in System Settings →+ Privacy & Security to the app that runs your commands (a terminal, or your+ own agent app). `phone-harness doctor ios` names that app. Screen Recording+ takes effect after that app restarts.-Check first — `phone-harness --doctor ios` — and only ask for what is missing.+Check first — `phone-harness doctor ios` — and only ask for what is missing.Whenever you capture or verify the screen, bring the Mirroring window forwardso the user can see what you're doing.diff --git a/pyproject.toml b/pyproject.tomlindex 32a6927..004704d 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -49,4 +49,4 @@ packages = ["src/phone_harness"]"agent-workspace/agent_helpers.py" = "phone_harness/agent_workspace/agent_helpers.py"[tool.hatch.build.targets.sdist]-include = ["src/phone_harness", "SKILL.md", "onboarding.md", "README.md", "LICENSE", "install.md", "agent-workspace/agent_helpers.py"]+include = ["src/phone_harness", "SKILL.md", "onboarding.md", "README.md", "LICENSE", "install.md", "setup", "agent-workspace/agent_helpers.py"]diff --git a/setup/android.md b/setup/android.mdnew file mode 100644index 0000000..a74a7ac--- /dev/null+++ b/setup/android.md@@ -0,0 +1,28 @@+# Android on the desk++Drives an Android phone over adb, from macOS, Linux or Windows.++## Needs++- Python 3.10+ and adb (Android platform-tools):+ `brew install android-platform-tools` (macOS),+ `apt install adb` (Debian/Ubuntu), `winget install Google.PlatformTools`+ (Windows). Optional: `scrcpy` for a live mirror window.+- Developer options on the phone: Settings > About phone > tap+ **Build number** 7 times.++## Steps only the user can do++- **USB:** Developer options > **USB debugging** on, plug in, tap **Allow**+ ("Always allow from this computer").+- **Wi-Fi** (Android 11+, same network as the computer): Developer options >+ **Wireless debugging** > **Pair device with pairing code**, then+ `phone-harness android pair CODE` with the 6 digits. The phone is remembered.++## Check++`phone-harness config set platform android` to make it the default, then+`phone-harness doctor android`. `locked` means unlock the phone; the harness+never types a PIN.++No phone? Use a [cloud phone](cloud.md).diff --git a/setup/api.md b/setup/api.mdnew file mode 100644index 0000000..3dafdee--- /dev/null+++ b/setup/api.md@@ -0,0 +1,39 @@+# Cloud API (no install)++For agents that can make HTTPS requests but cannot install the CLI.+Full reference: https://phone-harness.com/docs++All calls send `Authorization: Bearer $PHONE_HARNESS_API_KEY` (see+[cloud.md](cloud.md) for getting a key).++```bash+API=https://api.phone-harness.com+AUTH="Authorization: Bearer $PHONE_HARNESS_API_KEY"++curl -s -H "$AUTH" $API/me # account; phones under "available"+curl -s -H "$AUTH" -H 'Content-Type: application/json' \+ -H "Idempotency-Key: $(uuidgen)" -d '{"platform":"ios","kind":"device","device_id":"ID","timeout_seconds":900}' \+ $API/sessions # start; returns the session (id, state)+curl -s -H "$AUTH" $API/sessions/SID # poll until "state" is "ready"+curl -s -H "$AUTH" -X DELETE $API/sessions/SID # stop+```++A ready cloud iPhone session has `control.url` and `control.token`. Drive it+with the control token (not the API key):++```bash+C="Authorization: Bearer $CONTROL_TOKEN"+curl -s -H "$C" $CONTROL_URL/ops # supported ops+curl -s -H "$C" -H 'Content-Type: application/json' \+ -d '{"op":"screen.text","kw":{}}' $CONTROL_URL/op # visible text+curl -s -H "$C" -H 'Content-Type: application/json' \+ -d '{"op":"screen.capture","kw":{}}' $CONTROL_URL/op # {"png_b64", "bounds"}+curl -s -H "$C" -H 'Content-Type: application/json' \+ -d '{"op":"input.tap","kw":{"x":375,"y":667}}' $CONTROL_URL/op # tap a point+curl -s -H "$C" -H 'Content-Type: application/json' \+ -d '{"op":"nav.home","kw":{}}' $CONTROL_URL/op # Home Screen+```++`GET /me` lists each phone's `id` under `available`. Each `/op` answers `{"result": ...}`. A cloud Android is reached over adb+instead (`POST /sessions/SID/adb` returns host, port and unlock code), so it+needs adb and the CLI is the easier path.diff --git a/setup/cloud.md b/setup/cloud.mdnew file mode 100644index 0000000..6142d15--- /dev/null+++ b/setup/cloud.md@@ -0,0 +1,45 @@+# Cloud phones++Phone Harness Cloud hosts an Android or an iPhone. No hardware, any OS.++## Needs++| | Cloud iPhone | Cloud Android |+| --- | --- | --- |+| Python 3.10+ and phone-harness | yes | yes |+| HTTPS to `api.phone-harness.com` and `clerk.phone-harness.com` | yes | yes |+| HTTPS to the phone's control URL | yes | no |+| adb installed | no | yes |+| Outbound TCP to the phone's adb host and port (not HTTPS) | no | yes |+| Billing | not per minute | per minute, from account credit |++A sandbox that only allows HTTPS can drive a cloud iPhone but not a cloud+Android. If installing is not possible at all, use the [API](api.md).++## Sign in++- **Someone can open a browser (any device):** `phone-harness cloud login`+ prints a URL and a code. The user approves in any browser; the command+ waits up to about 10 minutes, so run it in the background if your commands+ time out sooner. `--no-browser` skips opening a browser here.+- **No one to approve (CI, unattended agents):** set `PHONE_HARNESS_API_KEY`.+ Mint one with `phone-harness cloud keys create LABEL` from a signed-in+ machine; it is shown once.++Never sign up, join or approve for the user.++## Use++```bash+phone-harness cloud ls # phones on the account+phone-harness cloud start PHONE # an id or label from `cloud ls`; `ios`/`android` when only one matches+phone-harness <<'PY' # checks the attached phone+print(ensure_device())+PY+phone-harness cloud stop # ends the session+```++New accounts get $5 of credit (100 Android minutes). Only a cloud Android+bills by the minute; a cloud iPhone does not, so it can stay running.+A cloud iPhone is a separate phone from the user's own, with its own apps+and logins; if an app asks for an Apple ID or any sign-in, ask the user.diff --git a/setup/ios.md b/setup/ios.mdnew file mode 100644index 0000000..bc9bb93--- /dev/null+++ b/setup/ios.md@@ -0,0 +1,36 @@+# Personal iPhone (iPhone Mirroring)++Drives the user's own iPhone through the Mac's iPhone Mirroring window.++## Needs++- A Mac on macOS 15 (Sequoia) or later, with the iPhone Mirroring app.+ Apple's own requirements apply: an iOS 18+ iPhone signed in to the same+ Apple ID, nearby, locked, with Bluetooth and Wi-Fi on.+- Python 3.10+ and the Mac-only dependencies, which the normal install pulls.+- Two macOS permissions for **the app that runs Python** (the terminal, or+ the agent's own app if it runs commands itself), in System Settings >+ Privacy & Security:+ - **Accessibility**: taps and typing. Takes effect at once.+ - **Screen Recording**: seeing the phone. Takes effect after that app+ restarts.+ macOS asks about the outermost app, not Python itself; `phone-harness+ doctor ios` prints its name when a permission is missing.++```bash+open "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"+open "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture"+```++## Steps only the user can do++1. Open iPhone Mirroring once and finish pairing (needs the phone in hand).+2. Grant the two permissions above, then restart the app that runs Python.++## Check++`phone-harness doctor ios`. It checks each step in order and names the first+one that is missing. If it passes but taps or capture do nothing, look for a+macOS permission prompt on the Mac.++Not on a Mac, or no iPhone nearby? Use a [cloud phone](cloud.md).diff --git a/src/phone_harness/admin.py b/src/phone_harness/admin.pyindex 890b762..47e3dba 100644--- a/src/phone_harness/admin.py+++ b/src/phone_harness/admin.py@@ -32,9 +32,38 @@ def run_doctor(platform=None):_doctor_ios()ok = not _failuresprint("\nall clear" if ok else "\nfix the FAILs above, then re-run")+ if not ok:+ print(CLOUD_HINT)return 0 if ok else 1+CLOUD_HINT = ("\nNo working phone here? A cloud phone needs no hardware: "+ "`phone-harness cloud login`, `phone-harness cloud ls`, then "+ "`phone-harness cloud start PHONE` (a cloud iPhone needs no adb; "+ "a cloud Android needs adb). "+ "No install possible? Use the HTTPS API: "+ "https://github.com/ShawnPana/phone-harness/blob/main/setup/api.md")+++def _host_app():+ """The app macOS asks about: the outermost .app this process runs under+ (a terminal, or an agent's own app). Falls back to a description."""+ found, pid = None, os.getppid()+ for _ in range(40):+ if pid <= 1:+ break+ try:+ out = subprocess.run(["ps", "-o", "ppid=,comm=", "-p", str(pid)],+ capture_output=True, text=True, timeout=5).stdout.strip()+ ppid, comm = out.split(None, 1)+ except (OSError, ValueError, subprocess.SubprocessError):+ break+ if ".app/" in comm:+ found = comm.split(".app/")[0].rsplit("/", 1)[-1]+ pid = int(ppid)+ return f'"{found}"' if found else "the app that runs this command (your terminal or agent app)"++# --- iPhone: pyobjc -> permissions -> Mirroring -> capture -> OCR -----------def _doctor_ios():@@ -48,13 +77,15 @@ def _doctor_ios():returnfrom ApplicationServices import AXIsProcessTrusted+ host = _host_app()_check("Accessibility permission (taps & keystrokes)", AXIsProcessTrusted(),- "System Settings > Privacy & Security > Accessibility: enable your terminal")+ f"System Settings > Privacy & Security > Accessibility: turn on {host}")import Quartz as Q_check("Screen Recording permission (seeing the phone)",bool(Q.CGPreflightScreenCaptureAccess()),- "System Settings > Privacy & Security > Screen Recording: enable your terminal")+ f"System Settings > Privacy & Security > Screen Recording: turn on {host}, "+ f"then quit and reopen it")from . import mirror_check(f"{mirror.APP_NAME} installed", Path(mirror.APP_PATH).exists(),diff --git a/tests/test_cli.py b/tests/test_cli.pyindex 583d98b..2d381ea 100644--- a/tests/test_cli.py+++ b/tests/test_cli.py@@ -496,3 +496,49 @@ class SessionAndStdinGuard(unittest.TestCase):if __name__ == "__main__":unittest.main()+++class DoctorSuggestsCloud(unittest.TestCase):+ def test_failed_local_doctor_points_at_cloud(self):+ import contextlib, io+ from unittest import mock+ from phone_harness import admin+ out = io.StringIO()+ with mock.patch.object(admin, "_doctor_android",+ lambda: admin._check("adb found", False)), \+ contextlib.redirect_stdout(out):+ code = admin.run_doctor("android")+ self.assertEqual(code, 1)+ self.assertIn("phone-harness cloud login", out.getvalue())+ self.assertIn("setup/api.md", out.getvalue())++ def test_passing_doctor_does_not_mention_cloud(self):+ import contextlib, io+ from unittest import mock+ from phone_harness import admin+ out = io.StringIO()+ with mock.patch.object(admin, "_doctor_android",+ lambda: admin._check("adb found", True)), \+ contextlib.redirect_stdout(out):+ self.assertEqual(admin.run_doctor("android"), 0)+ self.assertNotIn("cloud login", out.getvalue())+++class DoctorNamesTheHostApp(unittest.TestCase):+ def test_outermost_app_is_named(self):+ from phone_harness import admin+ chain = {50: "40 /bin/zsh", 40: "30 /Applications/Helper.app/Contents/MacOS/Helper",+ 30: "1 /Applications/Agent.app/Contents/MacOS/Agent"}++ def fake(cmd, **kw):+ return mock.Mock(stdout=chain[int(cmd[-1])])+ with mock.patch.object(admin.os, "getppid", return_value=50), \+ mock.patch.object(admin.subprocess, "run", fake):+ self.assertEqual(admin._host_app(), '"Agent"')++ def test_no_app_falls_back(self):+ from phone_harness import admin+ with mock.patch.object(admin.os, "getppid", return_value=50), \+ mock.patch.object(admin.subprocess, "run",+ lambda cmd, **kw: mock.Mock(stdout="1 /bin/zsh")):+ self.assertIn("terminal or agent app", admin._host_app())