let your agent control your phone
Files go to the phone only: pull_file is gone until the upload page is reviewed
ShawnPana25396532d062
diff --git a/README.md b/README.mdindex ed54700..387dafa 100644--- a/README.md+++ b/README.md@@ -98,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. Files move with the `push_file(path)` and `pull_file()` helpers (cloud iPhone only for now). `--session SID`+`watch`, `open`, `history`, and `phone` for the saved Android. A file goes to the phone with the `push_file(path)` helper (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 c2c828b..6c17455 100644--- a/SKILL.md+++ b/SKILL.md@@ -48,7 +48,6 @@ no hardware and is always the fallback.- `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.@@ -349,22 +348,19 @@ 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. Three helpers wrap it, and they follow the-attached session (or `--session`) like every other helper.+the phone's `url.open` op. Two helpers wrap it, and they follow the+attached session (or `--session`) like every other helper. Files go to the+phone only; nothing comes back this way.- `push_file(path)` uploads the file and opens it in the phone's browserunder its own name (a JPEG shows as an image, an MP4 plays). From therethe phone's own UI decides what to do with it; look at the screen and acton what is there, as with any other task.-- `pull_file(out_dir=".", timeout=300)` 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 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, withno typing and no clipboard. Check `supports('url.open')` first; an olderhost lists no such op.-On a local phone all three raise `Unsupported` ("cloud phones only for+On a local phone both raise `Unsupported` ("cloud phones only fornow"). Links expire within fifteen minutes and with the session; the filesare removed when the session ends. A link is a credential: do not paste oneinto notes or output.diff --git a/src/phone_harness/helpers.py b/src/phone_harness/helpers.pyindex 64783e6..5420be0 100644--- a/src/phone_harness/helpers.py+++ b/src/phone_harness/helpers.py@@ -590,14 +590,6 @@ def push_file(path):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/transfer.py b/src/phone_harness/transfer.pyindex bf4a11c..18e1d47 100644--- a/src/phone_harness/transfer.py+++ b/src/phone_harness/transfer.py@@ -1,4 +1,4 @@-"""Files to a cloud phone and back: the `push_file` and `pull_file` helpers.+"""Files to a cloud phone: the `push_file` helper.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 downloads@@ -7,14 +7,10 @@ credential for fifteen minutes.push_file upload a file, then the phone's browser opens it under its ownname. 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),+Cloud phones only for now: it follows the attached session (or --session),the one tap() drives, and a local phone raises Unsupported."""-import hashlibimport mimetypesimport timeimport urllib.error@@ -24,8 +20,6 @@ from pathlib import Pathfrom . import cloudfrom .transport import Unsupported-POLL_SECONDS = 2-DEFAULT_WAIT = 300CLOUD_ONLY = "cloud phones only for now: {} needs a cloud phone whose host can open links (a cloud iPhone)"@@ -55,24 +49,6 @@ def _put(url, path, headers):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 TransferError(f"the download was refused (HTTP {e.code})") from None- except (urllib.error.URLError, OSError) as e:- raise TransferError(f"could not reach the file store ({type(e).__name__})") from None- return size, digest.hexdigest()--class TransferError(RuntimeError):pass@@ -93,35 +69,3 @@ def push_file(path, backend):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():- raise NotADirectoryError(f"{out_dir} is not a directory")- sess = _session("pull_file", backend)- inbox = cloud._api("POST", f"/sessions/{sess['sid']}/files/inbox", {})- 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() + timeout- 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":- 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 / 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(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 c428a3c..a646d75 100644--- a/tests/test_transfer.py+++ b/tests/test_transfer.py@@ -1,5 +1,4 @@-"""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."""+"""push_file: the file route, a storage link, and the phone's url.open. No cloud: the API, the phone and the store are stand-ins."""import hashlibimport ioimport json@@ -78,8 +77,7 @@ class Transfer(unittest.TestCase):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, "POLL_SECONDS", 0)]+ self.p = [mock.patch.object(cloud, "attached", lambda kind=None: sess), mock.patch.object(cloud, "_api", api)]for patcher in self.p:patcher.start(); self.addCleanup(patcher.stop)self.tmp = tempfile.TemporaryDirectory(); self.addCleanup(self.tmp.cleanup)@@ -101,30 +99,6 @@ class Transfer(unittest.TestCase):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):- 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"})])- 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")- 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")@@ -134,11 +108,18 @@ class Transfer(unittest.TestCase):self.assertEqual(self.calls, [])def test_a_local_or_adb_phone_is_cloud_only_for_now(self):+ src = Path(self.tmp.name) / "a.jpg"; src.write_bytes(b"x")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)+ transfer.push_file(str(src), self.phone)self.assertIn("cloud phones only for now", str(e.exception))+ self.assertEqual(self.calls, [])++ def test_there_is_no_pull(self):+ from phone_harness import helpers+ self.assertFalse(hasattr(transfer, "pull_file"))+ self.assertFalse(hasattr(helpers, "pull_file"))if __name__ == "__main__":