let your agent control your phone
Files move through helpers, not commands: push_file, pull_file, open_url
ShawnPanac39ad1ef22e3
diff --git a/README.md b/README.mdindex 4ad1120..ed54700 100644--- a/README.md+++ b/README.md@@ -81,8 +81,6 @@ phone-harness cloud start ios # the account's iPhone, when only one is liphone-harness <<'PY'print(screenshot())PY-phone-harness push photo.jpg # a cloud iPhone opens the file in its browser-phone-harness pull # the phone shows an upload page; what is sent lands herephone-harness cloud stop # ends the session; a saved Android is written back```@@ -100,7 +98,7 @@ service gives an unnamed start, a temporary Android. A name is a catalog id or lis reached over adb, so every helper works on it unchanged. A cloud iPhone hasno shell: the helpers POST ops over HTTPS, OCR runs on the host, and drivingit is in [SKILL.md](SKILL.md). `phone-harness cloud` lists the rest, including-`watch`, `open`, `history`, and `phone` for the saved Android. `--session SID`+`watch`, `open`, `history`, and `phone` for the saved Android. Files move with the `push_file(path)` and `pull_file()` helpers (cloud iPhone only for now). `--session SID`(or `PHONE_HARNESS_SESSION`) pins one rented phone for this process.## Updatesdiff --git a/SKILL.md b/SKILL.mdindex 2f2af91..c2c828b 100644--- a/SKILL.md+++ b/SKILL.md@@ -46,6 +46,9 @@ no hardware and is always the fallback.- `type_text(text, delay=0.03, keystrokes=False)` - Type into the focused field.- `press(combo)` - Press a key, such as `press("enter")`.- `open_app(name)` - Launch an app and return the app id that launched.+- `open_url(url)` - Open an https link in the phone's browser, whole. Cloud phones only for now.+- `push_file(path)` - Send a file to the phone; it opens in the phone's browser under its own name. Cloud phones only for now.+- `pull_file(out_dir=".", timeout=300)` - The phone's browser opens an upload page; what is sent there is downloaded into `out_dir`. Returns `{path, size, sha256, content_type}`. Cloud phones only for now.- `swipe(direction, distance=0.4, at=None)` - Flick. `direction` is finger motion: `"up"`, `"down"`, `"left"`, or `"right"`.- `scroll(direction="down", amount=0.3, at=None)` - Scroll. `direction` is the content to reveal: `"down"`, `"up"`, `"left"`, or `"right"`.- `scroll_screen(direction="down", amount=0.6, settle=2.5, moved_thresh=None, at=None)` - One scroll, then the text on screen before and after.@@ -346,61 +349,25 @@ Trust `GET /ops` when the host's list is shorter than this table.### Files on a cloud iPhoneThere is no shell, so bytes move through storage links the service signs and-the phone's `url.open` op. Two commands wrap it; both take `--session SID`.--- `phone-harness push FILE` uploads FILE and opens it in the phone's- browser under its own name (a JPEG shows as an image, an MP4 plays). From- there the phone's own UI decides what to do with it; look at the screen and- act on what is there, as with any other task.-- `phone-harness pull [--out DIR]` opens a one-page upload form in the+the phone's `url.open` op. Three helpers wrap it, and they follow the+attached session (or `--session`) like every other helper.++- `push_file(path)` uploads the file and opens it in the phone's browser+ under its own name (a JPEG shows as an image, an MP4 plays). From there+ the phone's own UI decides what to do with it; look at the screen and act+ on what is there, as with any other task.+- `pull_file(out_dir=".", timeout=300)` opens a one-page upload form in thephone's browser and waits. Whoever is driving the phone picks a file on- that page and sends it; the command then downloads it and prints the local- path, size and sha256 as JSON.-- `open_url(url)` is the helper behind both: any https link, opened whole,- with no typing and no clipboard. Check `supports('url.open')` first; an- older host lists no such op.--Links expire within fifteen minutes and with the session; the files are-removed when the session ends. A link is a credential: do not paste one into-notes or output.---- **Coordinates are `screen.bounds`.** `tap(x, y)`, `find_window()`,- `send("screen.require")`, and centres from `screen()` all use that space:- `{x, y, w, h, id}`. A point read off the PNG goes through- `tap_image_point()` once `screen_info()` returns `img_px`. Otherwise tap- a centre from `screen()`.-- **`screen_info()`, `image_point()`, and `tap_image_point()` measure the- PNG** so a point you read off a screenshot can become a tap. If- `screen_info()` raises `ModuleNotFoundError: No module named 'Quartz'`,- that helper imported the macOS Vision module to read the PNG's pixel size.- `screen()` sends `screen.text` to the host and still works - keep using- `tap_text()`. If `screen_info()` returns `img_px`, those three helpers work- on any OS. [PR #108](https://github.com/ShawnPana/phone-harness/pull/108)- ("screen_info() no longer needs macOS") is the change that reads the PNG- header instead of importing Quartz; until `screen_info()` returns `img_px`- off a Mac, treat the Quartz error as those three helpers only.-- **`type_text()` types into the focused field.** Tap the field first. Text- sent before the field has focus goes nowhere, so check with `screen()`- afterwards.-- **Act, then look.** One action, then `screen()` or `screenshot()`, then the- next. Do not `wait(n)` for a screen to load. The client allows- `screen.capture` 60s, `apps.launch` and `apps.list` 90s, and `input.text`- the timeout in the table.-- **Errors the client raises.** HTTP 400 with `unsupported: true` raises- `Unsupported` (retrying will not help). HTTP 404 raises `RuntimeError`:- the session is gone or the grant expired. Any other HTTP status raises- `RuntimeError` with the host's `error` string. Create-time- `device_unavailable`, `profile_running`, and `phones_busy` happen on- `cloud start`, before any op, and are described under **Cloud phones**.-- **`ui()`, `back()`, and `current_app()` raise Unsupported** when the host- does not list `tree`, `nav.back`, and `apps.current`. `home()` is the Home- button. `shell()` is Unsupported.-- **Confirm `open_app`.** It sends `apps.launch` and can return with the app- still not in front. Check with `screen()` or a screenshot. If it missed,- `home()` and tap the icon. `tap_icon()` in the agent workspace's- `agent_helpers.py` aims 35 points above the label for the- mirroring window, so measure this phone's icon yourself.+ that page and sends it; the helper downloads it, prints the local path,+ and returns path, size and sha256.+- `open_url(url)` is the op behind both: any https link, opened whole, with+ no typing and no clipboard. Check `supports('url.open')` first; an older+ host lists no such op.++On a local phone all three raise `Unsupported` ("cloud phones only for+now"). Links expire within fifteen minutes and with the session; the files+are removed when the session ends. A link is a credential: do not paste one+into notes or output.## Androiddiff --git a/src/phone_harness/helpers.py b/src/phone_harness/helpers.pyindex d1a61f5..64783e6 100644--- a/src/phone_harness/helpers.py+++ b/src/phone_harness/helpers.py@@ -576,11 +576,28 @@ def open_app(name):def open_url(url):- """Open an https link in the phone's browser; the link arrives whole.- Unsupported where the phone has no such path (check supports('url.open'))."""+ """Open an https link in the phone's browser; the link arrives whole, with+ no typing and no clipboard. Cloud phones only for now."""+ if not phone.supports("url.open"):+ raise transport.Unsupported("cloud phones only for now: open_url needs a cloud phone whose host can open links")return phone.send("url.open", url=url)+def push_file(path):+ """Send a file to the phone: it opens in the phone's browser under its own+ name. Cloud phones only for now. Returns {filename, size, content_type, expires_at}."""+ from . import transfer+ return transfer.push_file(path, phone)+++def pull_file(out_dir=".", timeout=300):+ """The phone's browser opens an upload page; pick a file there and this+ downloads it into `out_dir`, printing the path. Cloud phones only for now.+ Returns {path, size, sha256, content_type}."""+ from . import transfer+ return transfer.pull_file(phone, out_dir=out_dir, timeout=timeout)++def current_app():"""Foreground app id. Unsupported where the device exposes no inventory."""return send("apps.current")diff --git a/src/phone_harness/run.py b/src/phone_harness/run.pyindex 0c2b46c..c4b063d 100644--- a/src/phone_harness/run.py+++ b/src/phone_harness/run.py@@ -24,8 +24,6 @@ Commands:phone-harness skill print the phone-harness skill textphone-harness android ... pair/connect/choose an Android phonephone-harness cloud ... rent a catalog phone: `cloud login`, `cloud ls`, `cloud start [PHONE]`- phone-harness push FILE send a file to the attached cloud phone; it opens in the phone's browser- phone-harness pull the phone shows an upload page; what is sent there lands herephone-harness config ... settings: `config set platform android`phone-harness update update this install: uv tool upgrade, git pull, or the pip command@@ -139,7 +137,7 @@ def _telemetry_command(args):return "version"if first in {"--doctor", "doctor"}:return "doctor"- if first in {"android", "cloud", "config", "skill", "update", "push", "pull"}:+ if first in {"android", "cloud", "config", "skill", "update"}:return firstreturn "usage"@@ -282,7 +280,7 @@ def _take_session(args):# These three parse their own argv, including --help. A leading --help is# the top-level parser, so only a bare command name takes this path.# --version is handled before this, in any position.-_OWNED = {"android", "cloud", "config", "push", "pull"}+_OWNED = {"android", "cloud", "config"}def _version_text():@@ -362,9 +360,6 @@ def _dispatch_owned(name, rest):from .android import clielif name == "cloud":from .cloud import cli- elif name in ("push", "pull"):- from . import transfer- cli = transfer.push if name == "push" else transfer.pullelse:from .config import clisys.exit(cli(rest))diff --git a/src/phone_harness/transfer.py b/src/phone_harness/transfer.pyindex 21ac4b4..6eb0169 100644--- a/src/phone_harness/transfer.py+++ b/src/phone_harness/transfer.py@@ -1,70 +1,55 @@-"""Files to a cloud phone and back: `phone-harness push FILE`, `phone-harness pull`.+"""Files to a cloud phone and back: the `push_file` and `pull_file` helpers.Both ride the session's file routes and the phone's `url.open` op. Theservice signs short-lived storage links; this machine uploads to or downloadsfrom them, and the phone opens one. Nothing here prints a link: a link is acredential for fifteen minutes.-push upload FILE, then the phone's browser opens it under its own name.- What happens next on the phone (saving it, sharing it) is the- caller's move.-pull the phone's browser opens a small upload page; whoever is driving- the phone picks a file there. This command waits for it, downloads- it, and prints the local path.+push_file upload a file, then the phone's browser opens it under its own+ name. What happens next on the phone is the caller's move.+pull_file the phone's browser opens a small upload page; whoever is driving+ the phone picks a file there. This waits, downloads it, and+ returns the local path.++Cloud phones only for now: both follow the attached session (or --session),+the one tap() drives, and a local phone raises Unsupported."""import hashlib-import jsonimport mimetypes-import os-import sysimport timeimport urllib.errorimport urllib.requestfrom pathlib import Path-from . import cloud, term-from .remote import Remote--CLI_USAGE = """Usage:- phone-harness push FILE [--session SID] send FILE to the cloud phone: it opens in the phone's browser- phone-harness pull [--out DIR] [--timeout SECONDS] [--session SID]- the phone opens an upload page; whatever is sent there lands in DIR (default .)-Both need a cloud phone whose host can open links (`supports('url.open')`); today that is a cloud iPhone.-"""+from . import cloud+from .transport import UnsupportedPOLL_SECONDS = 2DEFAULT_WAIT = 300+CLOUD_ONLY = "cloud phones only for now: {} needs a cloud phone whose host can open links (a cloud iPhone)"-def _session():- """The attached (or pinned) cloud session that is reached by a control link."""+def _session(what, backend):+ """The attached cloud session reached by a control link, or a clear error."""sess = cloud.attached()- if not sess:- sys.exit("No cloud phone attached. Start one with `phone-harness cloud start`, or pass --session SID.")- if sess["link"]["kind"] != "control":- sys.exit("File transfer needs a cloud phone the host can open links on; this session is an Android over adb "- "(use adb push/pull there).")+ if not sess or sess["link"]["kind"] != "control":+ raise Unsupported(CLOUD_ONLY.format(what) + ("" if sess else "; no cloud phone is attached"))+ if not backend.supports("url.open"):+ raise Unsupported(f"{what}: this phone's host cannot open links yet (no url.open op)")return sess-def _remote(sess):- phone = Remote(sess["link"]["url"], sess["link"]["token"])- if not phone.supports("url.open"):- sys.exit("This phone's host cannot open links yet (no url.open op); ask the operator to update the host.")- return phone--def _put(url, path, content_type):data = Path(path).read_bytes()req = urllib.request.Request(url, data=data, method="PUT", headers={"Content-Type": content_type})try:with urllib.request.urlopen(req, timeout=max(60, len(data) / 200_000)) as reply:if reply.status // 100 != 2:- raise CloudTransferError(f"the upload was refused (HTTP {reply.status})")+ raise TransferError(f"the upload was refused (HTTP {reply.status})")except urllib.error.HTTPError as e:- raise CloudTransferError(f"the upload was refused (HTTP {e.code})") from None+ raise TransferError(f"the upload was refused (HTTP {e.code})") from Noneexcept (urllib.error.URLError, OSError) as e:- raise CloudTransferError(f"could not reach the file store ({type(e).__name__})") from None+ raise TransferError(f"could not reach the file store ({type(e).__name__})") from Nonereturn len(data)@@ -80,57 +65,45 @@ def _get(url, dest):digest.update(chunk)size += len(chunk)except urllib.error.HTTPError as e:- raise CloudTransferError(f"the download was refused (HTTP {e.code})") from None+ raise TransferError(f"the download was refused (HTTP {e.code})") from Noneexcept (urllib.error.URLError, OSError) as e:- raise CloudTransferError(f"could not reach the file store ({type(e).__name__})") from None+ raise TransferError(f"could not reach the file store ({type(e).__name__})") from Nonereturn size, digest.hexdigest()-class CloudTransferError(RuntimeError):+class TransferError(RuntimeError):pass-def push(args):- args = list(args)- pinned = cloud._option(args, "--session")- if pinned:- os.environ["PHONE_HARNESS_SESSION"] = pinned- if len(args) != 1 or args[0].startswith("-"):- sys.exit(CLI_USAGE)- path = Path(args[0]).expanduser()+def push_file(path, backend):+ """Send a file to the phone: it opens in the phone's browser under its own+ name. Returns {filename, size, content_type, expires_at}."""+ path = Path(path).expanduser()if not path.is_file():- sys.exit(f"{path} is not a file")- sess = _session()- phone = _remote(sess)+ raise FileNotFoundError(f"{path} is not a file")+ sess = _session("push_file", backend)content_type = mimetypes.guess_type(path.name)[0] or "application/octet-stream"transfer = cloud._api("POST", f"/sessions/{sess['sid']}/files",{"filename": path.name, "content_type": content_type})size = _put(transfer["upload_url"], path, content_type)- phone.send("url.open", url=transfer["download_url"])- print(f"{term.mark()} {transfer['filename']} ({size:,} bytes, {content_type}) is open in the phone's browser; "- f"the link lasts until {time.strftime('%H:%M', time.localtime(transfer['expires_at']))}.")- return 0---def pull(args):- args = list(args)- pinned = cloud._option(args, "--session")- if pinned:- os.environ["PHONE_HARNESS_SESSION"] = pinned- out_dir = Path(cloud._option(args, "--out") or ".").expanduser()- wait = cloud._option(args, "--timeout")- wait = int(wait) if wait else DEFAULT_WAIT- if args:- sys.exit(CLI_USAGE)+ backend.send("url.open", url=transfer["download_url"])+ print(f"{transfer['filename']} ({size:,} bytes) is open in the phone's browser")+ return {"filename": transfer["filename"], "size": size, "content_type": content_type,+ "expires_at": transfer["expires_at"]}+++def pull_file(backend, out_dir=".", timeout=DEFAULT_WAIT):+ """The phone's browser opens an upload page; whoever is driving the phone+ picks a file there. Waits up to `timeout` seconds, downloads it into+ `out_dir`, prints the path, and returns {path, size, sha256, content_type}."""+ out_dir = Path(out_dir).expanduser()if not out_dir.is_dir():- sys.exit(f"{out_dir} is not a directory")- sess = _session()- phone = _remote(sess)+ raise NotADirectoryError(f"{out_dir} is not a directory")+ sess = _session("pull_file", backend)inbox = cloud._api("POST", f"/sessions/{sess['sid']}/files/inbox", {})- phone.send("url.open", url=inbox["page_url"])- print(f"{term.mark()} The phone's browser is showing an upload page; choose a file there. "- f"Waiting up to {wait} s.", flush=True)- deadline = time.monotonic() + wait+ backend.send("url.open", url=inbox["page_url"])+ print(f"the phone's browser is showing an upload page; waiting up to {int(timeout)} s for a file")+ deadline = time.monotonic() + timeoutstatus = {"state": "waiting"}while time.monotonic() < deadline:status = cloud._api("GET", f"/sessions/{sess['sid']}/files/{inbox['id']}")@@ -138,8 +111,8 @@ def pull(args):breaktime.sleep(POLL_SECONDS)if status.get("state") != "uploaded":- sys.exit(f"Nothing arrived within {wait} s. The page on the phone stays usable until "- f"{time.strftime('%H:%M', time.localtime(inbox['expires_at']))}; run pull again to wait longer.")+ raise TimeoutError(f"nothing arrived within {int(timeout)} s; the page on the phone stays usable "+ f"until {time.strftime('%H:%M', time.localtime(inbox['expires_at']))}")name = status.get("filename") or f"phone-{inbox['id']}"dest = out_dir / namestem, suffix, n = dest.stem, dest.suffix, 1@@ -147,6 +120,5 @@ def pull(args):dest = out_dir / f"{stem}-{n}{suffix}"n += 1size, sha = _get(status["download_url"], dest)- print(json.dumps({"path": str(dest), "size": size, "sha256": sha,- "content_type": status.get("content_type")}))- return 0+ print(str(dest))+ return {"path": str(dest), "size": size, "sha256": sha, "content_type": status.get("content_type")}diff --git a/tests/test_transfer.py b/tests/test_transfer.pyindex 6966328..7f5be43 100644--- a/tests/test_transfer.py+++ b/tests/test_transfer.py@@ -1,5 +1,5 @@-"""push and pull: the file routes, a storage link each way, and the phone's-url.open. No cloud: the API, the phone and the store are stand-ins."""+"""push_file and pull_file: the file routes, a storage link each way, and the+phone's url.open. No cloud: the API, the phone and the store are stand-ins."""import hashlibimport ioimport json@@ -15,6 +15,7 @@ from unittest import mocksys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))from phone_harness import cloud, transfer # noqa: E402+from phone_harness.transport import Unsupported # noqa: E402class Store(BaseHTTPRequestHandler):@@ -64,7 +65,7 @@ class Transfer(unittest.TestCase):self.calls.append((method, path, body))return self.api_replies[(method, path)]self.p = [mock.patch.object(cloud, "attached", lambda kind=None: sess), mock.patch.object(cloud, "_api", api),- mock.patch.object(transfer, "Remote", lambda url, token: self.phone), mock.patch.object(transfer, "POLL_SECONDS", 0)]+ mock.patch.object(transfer, "POLL_SECONDS", 0)]for patcher in self.p:patcher.start(); self.addCleanup(patcher.stop)self.tmp = tempfile.TemporaryDirectory(); self.addCleanup(self.tmp.cleanup)@@ -76,7 +77,8 @@ class Transfer(unittest.TestCase):"upload_url": self.base + "/t/file?sig=up", "download_url": self.base + "/t/file?sig=down"}out = io.StringIO()with redirect_stdout(out):- self.assertEqual(transfer.push([str(src)]), 0)+ result = transfer.push_file(str(src), self.phone)+ self.assertEqual(result, {"filename": "cat_photo.jpg", "size": 6, "content_type": "image/jpeg", "expires_at": 1_800_000_000})self.assertEqual(self.calls, [("POST", "/sessions/abc123def456/files", {"filename": "cat photo.jpg", "content_type": "image/jpeg"})])self.assertEqual(Store.objects["/t/file"], (b"\xff\xd8jpeg", "image/jpeg"))self.assertEqual(self.phone.opened, [("url.open", {"url": self.base + "/t/file?sig=down"})])@@ -99,9 +101,9 @@ class Transfer(unittest.TestCase):Store.objects["/t/file"] = (b"bytes", "image/jpeg")out = io.StringIO()with mock.patch.object(cloud, "_api", api), redirect_stdout(out):- self.assertEqual(transfer.pull(["--out", self.tmp.name]), 0)+ result = transfer.pull_file(self.phone, out_dir=self.tmp.name)self.assertEqual(self.phone.opened, [("url.open", {"url": self.base + "/t/inbox.html?sig=page"})])- result = json.loads(out.getvalue().strip().splitlines()[-1])+ self.assertEqual(out.getvalue().strip().splitlines()[-1], result["path"])self.assertEqual((result["path"], result["size"], result["sha256"]),(str(Path(self.tmp.name) / "IMG_0001.jpeg"), 5, hashlib.sha256(b"bytes").hexdigest()))self.assertEqual(Path(result["path"]).read_bytes(), b"bytes")@@ -110,16 +112,17 @@ class Transfer(unittest.TestCase):def test_a_phone_without_url_open_is_refused_before_anything_is_uploaded(self):self.phone.ops = set()src = Path(self.tmp.name) / "a.jpg"; src.write_bytes(b"x")- with self.assertRaises(SystemExit) as e:- transfer.push([str(src)])+ with self.assertRaises(Unsupported) as e:+ transfer.push_file(str(src), self.phone)self.assertIn("url.open", str(e.exception))self.assertEqual(self.calls, [])- def test_an_adb_session_is_refused(self):- with mock.patch.object(cloud, "attached", lambda kind=None: {"sid": "x", "link": {"kind": "adb", "host": "h", "port": 1}}):- with self.assertRaises(SystemExit) as e:- transfer.pull([])- self.assertIn("adb", str(e.exception))+ def test_a_local_or_adb_phone_is_cloud_only_for_now(self):+ for sess in ({"sid": "x", "link": {"kind": "adb", "host": "h", "port": 1}}, None):+ with self.subTest(sess=sess), mock.patch.object(cloud, "attached", lambda kind=None, s=sess: s):+ with self.assertRaises(Unsupported) as e:+ transfer.pull_file(self.phone, out_dir=self.tmp.name)+ self.assertIn("cloud phones only for now", str(e.exception))if __name__ == "__main__":