let your agent control your phone
push and pull: files to a cloud iPhone and back, and the url.open op
ShawnPanab741e5437650
diff --git a/README.md b/README.mdindex 4f74ce1..4ad1120 100644--- a/README.md+++ b/README.md@@ -81,6 +81,8 @@ 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```diff --git a/SKILL.md b/SKILL.mdindex 402bf4e..2f2af91 100644--- a/SKILL.md+++ b/SKILL.md@@ -337,11 +337,34 @@ documents or decodes.| `session.detail` | | a string. Local. || `focus.probe` | | an opaque snapshot. Local: `(True,)`. || `focus.diff` | `before, after` | `{raised, stole_focus}`. Local: both false. |+| `url.open` | `url` | app id. Opens an https link in the phone's browser, whole. Timeout 60s. || `tree` | | `[node]` where the device has one || `raw` | backend-specific | host result |Trust `GET /ops` when the host's list is shorter than this table.+### Files on a cloud iPhone++There 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+ phone'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 throughdiff --git a/src/phone_harness/helpers.py b/src/phone_harness/helpers.pyindex 891a716..d1a61f5 100644--- a/src/phone_harness/helpers.py+++ b/src/phone_harness/helpers.py@@ -575,6 +575,12 @@ def open_app(name):return result+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'))."""+ return phone.send("url.open", url=url)++def current_app():"""Foreground app id. Unsupported where the device exposes no inventory."""return send("apps.current")diff --git a/src/phone_harness/remote.py b/src/phone_harness/remote.pyindex 168c934..cb17118 100644--- a/src/phone_harness/remote.py+++ b/src/phone_harness/remote.py@@ -168,6 +168,9 @@ class Remote(Backend):def _apps_list(self, include_system=False):return self._op("apps.list", timeout=90, include_system=include_system)+ def _url_open(self, url):+ return self._op("url.open", timeout=60, url=url)+def _session_refocus(self):return Nonediff --git a/src/phone_harness/run.py b/src/phone_harness/run.pyindex c4b063d..0c2b46c 100644--- a/src/phone_harness/run.py+++ b/src/phone_harness/run.py@@ -24,6 +24,8 @@ 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@@ -137,7 +139,7 @@ def _telemetry_command(args):return "version"if first in {"--doctor", "doctor"}:return "doctor"- if first in {"android", "cloud", "config", "skill", "update"}:+ if first in {"android", "cloud", "config", "skill", "update", "push", "pull"}:return firstreturn "usage"@@ -280,7 +282,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"}+_OWNED = {"android", "cloud", "config", "push", "pull"}def _version_text():@@ -360,6 +362,9 @@ 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.pynew file mode 100644index 0000000..21ac4b4--- /dev/null+++ b/src/phone_harness/transfer.py@@ -0,0 +1,152 @@+"""Files to a cloud phone and back: `phone-harness push FILE`, `phone-harness pull`.++Both ride the session's file routes and the phone's `url.open` op. The+service signs short-lived storage links; this machine uploads to or downloads+from them, and the phone opens one. Nothing here prints a link: a link is a+credential 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.+"""+import hashlib+import json+import mimetypes+import os+import sys+import time+import urllib.error+import urllib.request+from 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.+"""++POLL_SECONDS = 2+DEFAULT_WAIT = 300+++def _session():+ """The attached (or pinned) cloud session that is reached by a control link."""+ 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).")+ 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})")+ except urllib.error.HTTPError as e:+ raise CloudTransferError(f"the upload was refused (HTTP {e.code})") from None+ except (urllib.error.URLError, OSError) as e:+ raise CloudTransferError(f"could not reach the file store ({type(e).__name__})") from None+ return len(data)+++def _get(url, dest):+ try:+ with urllib.request.urlopen(url, timeout=120) as reply, open(dest, "wb") as out:+ digest, size = hashlib.sha256(), 0+ while True:+ chunk = reply.read(1 << 20)+ if not chunk:+ break+ out.write(chunk)+ digest.update(chunk)+ size += len(chunk)+ except urllib.error.HTTPError as e:+ raise CloudTransferError(f"the download was refused (HTTP {e.code})") from None+ except (urllib.error.URLError, OSError) as e:+ raise CloudTransferError(f"could not reach the file store ({type(e).__name__})") from None+ return size, digest.hexdigest()+++class CloudTransferError(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()+ if not path.is_file():+ sys.exit(f"{path} is not a file")+ sess = _session()+ phone = _remote(sess)+ 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)+ if not out_dir.is_dir():+ sys.exit(f"{out_dir} is not a directory")+ sess = _session()+ phone = _remote(sess)+ 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+ status = {"state": "waiting"}+ while time.monotonic() < deadline:+ status = cloud._api("GET", f"/sessions/{sess['sid']}/files/{inbox['id']}")+ if status.get("state") == "uploaded":+ break+ time.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.")+ name = status.get("filename") or f"phone-{inbox['id']}"+ dest = out_dir / name+ stem, suffix, n = dest.stem, dest.suffix, 1+ while dest.exists():+ dest = out_dir / f"{stem}-{n}{suffix}"+ n += 1+ size, sha = _get(status["download_url"], dest)+ print(json.dumps({"path": str(dest), "size": size, "sha256": sha,+ "content_type": status.get("content_type")}))+ return 0diff --git a/src/phone_harness/transport.py b/src/phone_harness/transport.pyindex 1cd61db..767fb1f 100644--- a/src/phone_harness/transport.py+++ b/src/phone_harness/transport.py@@ -59,6 +59,12 @@ nothing in common — so the shared layer is this vocabulary instead.focus.probe -> opaque snapshotfocus.diff before, after -> {raised, stole_focus}+ url.open url -> app id++ Opens an https link in the phone's browser. The link arrives whole,+ without typing or the clipboard. Unsupported where the phone has no+ such path; a link is often a credential, so it is never logged.+Whether driving the phone disturbed whatever the user was doing. Twoseparate questions on purpose: taking keyboard focus is a mildannoyance, covering the screen is not, and a backend that reaches the@@ -92,6 +98,7 @@ OP_NAMES = ("apps.launch", "apps.current", "apps.list","session.state", "session.require", "session.refocus", "session.detail","focus.probe", "focus.diff",+ "url.open","tree", "raw",)diff --git a/tests/test_transfer.py b/tests/test_transfer.pynew file mode 100644index 0000000..6966328--- /dev/null+++ b/tests/test_transfer.py@@ -0,0 +1,126 @@+"""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."""+import hashlib+import io+import json+import os+import sys+import tempfile+import threading+import unittest+from contextlib import redirect_stdout+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from unittest import mock++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))+from phone_harness import cloud, transfer # noqa: E402+++class Store(BaseHTTPRequestHandler):+ objects = {}++ def log_message(self, *a):+ pass++ def do_PUT(self):+ n = int(self.headers.get("Content-Length") or 0)+ Store.objects[self.path.split("?")[0]] = (self.rfile.read(n), self.headers.get("Content-Type"))+ self.send_response(200); self.send_header("Content-Length", "0"); self.end_headers()++ def do_GET(self):+ body, _ = Store.objects.get(self.path.split("?")[0], (None, None))+ self.send_response(200 if body is not None else 404)+ self.send_header("Content-Length", str(len(body or b""))); self.end_headers()+ if body:+ self.wfile.write(body)+++class FakePhone:+ def __init__(self, ops=("url.open",)):+ self.ops, self.opened = set(ops), []++ def supports(self, op):+ return op in self.ops++ def send(self, op, **kw):+ self.opened.append((op, kw))+ return "com.apple.mobilesafari"+++class Transfer(unittest.TestCase):+ def setUp(self):+ Store.objects = {}+ self.srv = ThreadingHTTPServer(("127.0.0.1", 0), Store)+ threading.Thread(target=self.srv.serve_forever, daemon=True).start()+ self.addCleanup(self.srv.server_close); self.addCleanup(self.srv.shutdown)+ self.base = f"http://127.0.0.1:{self.srv.server_port}"+ self.phone = FakePhone()+ self.calls = []+ sess = {"sid": "abc123def456", "link": {"kind": "control", "url": "https://api.test/iphone/c/tok", "token": "t"}}+ self.api_replies = {}++ def api(method, path, body=None, **kw):+ 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)]+ for patcher in self.p:+ patcher.start(); self.addCleanup(patcher.stop)+ self.tmp = tempfile.TemporaryDirectory(); self.addCleanup(self.tmp.cleanup)++ def test_push_uploads_then_the_phone_opens_the_download_link(self):+ src = Path(self.tmp.name) / "cat photo.jpg"; src.write_bytes(b"\xff\xd8jpeg")+ self.api_replies[("POST", "/sessions/abc123def456/files")] = {+ "id": "0123456789abcdef", "filename": "cat_photo.jpg", "content_type": "image/jpeg", "expires_at": 1_800_000_000,+ "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)+ 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"})])+ self.assertIn("cat_photo.jpg", out.getvalue())+ self.assertNotIn("sig=", out.getvalue()) # links are credentials: never printed++ def test_pull_opens_the_inbox_page_waits_and_downloads_under_the_phone_s_name(self):+ self.api_replies[("POST", "/sessions/abc123def456/files/inbox")] = {+ "id": "0123456789abcdef", "page_url": self.base + "/t/inbox.html?sig=page", "expires_at": 1_800_000_000}+ states = iter([{"id": "0123456789abcdef", "state": "waiting"},+ {"id": "0123456789abcdef", "state": "uploaded", "filename": "IMG_0001.jpeg", "size": 5,+ "content_type": "image/jpeg", "download_url": self.base + "/t/file?sig=get", "expires_at": 1_800_000_000}])+ self.api_replies[("GET", "/sessions/abc123def456/files/0123456789abcdef")] = None+ real = cloud._api++ def api(method, path, body=None, **kw):+ if method == "GET":+ return next(states)+ return real(method, path, body)+ 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)+ 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((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")+ self.assertNotIn("sig=", out.getvalue())++ 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)])+ 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))+++if __name__ == "__main__":+ unittest.main()