let your agent control your phone
phone-harness cloud: rent a phone from the CLI; Android helpers work as promised (#75)
shawn pana183ad7ec22f3
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 8faccbd..1a2ee00 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -29,6 +29,9 @@ jobs:out=$(PHONE_HARNESS_PLATFORM=android phone-harness --doctor android 2>&1 || true)echo "$out"echo "$out" | grep -q "adb found"+ - name: unit tests (fake cloud API, fake adb)+ if: runner.os != 'Windows' # the fake adb is a shell script+ run: python -m unittest discover tests- name: iPhone is refused with a clear message off macOSif: runner.os != 'macOS'shell: bashdiff --git a/.gitignore b/.gitignoreindex 201ffa5..e263f9c 100644--- a/.gitignore+++ b/.gitignore@@ -3,3 +3,4 @@ __pycache__/dist/*.egg-info/.venv/+.envdiff --git a/README.md b/README.mdindex 1f921f7..5db4eb2 100644--- a/README.md+++ b/README.md@@ -55,6 +55,22 @@ PYHelpers are pre-imported. [SKILL.md](SKILL.md) is the agent's day-to-dayguide; [helpers.py](src/phone_harness/helpers.py) is the full list.+## No phone on your desk? Rent one++```bash+phone-harness cloud login # once: approve in your browser+phone-harness cloud start # your own Android phone; apps and logins are kept+phone-harness <<'PY'+print(screenshot())+PY+phone-harness cloud stop # billing stops, the phone is saved+```++[Phone Harness Cloud](https://phone-harness.com/cloud) phones are Android+phones reached over adb, so every helper works on them unchanged and there is+nothing to export or select. `phone-harness cloud` lists the rest: `ls`,+`watch`, `history`, and `start --temp` for a throwaway phone.+## How it works**iPhone.** iPhone Mirroring renders the phone as a Mac window and forwardsdiff --git a/SKILL.md b/SKILL.mdindex 19db740..7f32b64 100644--- a/SKILL.md+++ b/SKILL.md@@ -38,6 +38,11 @@ PY# task: report the iOS version and model name from Settings# step: scroll to General, open About, read the screen```+- **Tell the user what you are doing as you go.** A phone task is many short+ scripts, and the user sees none of them: say one line before each script+ (what you are about to do) and one line after it (what you saw). Never run+ two scripts in a row in silence. The `# task:` / `# step:` comments are not+ this — the user cannot see them.- Helpers are pre-imported. All coordinates are global screen points.- `ensure_mirroring()` launches the window and gates on connection. Thedefault build works the phone **without taking the user's focus**: capture is@@ -159,10 +164,31 @@ PYPrefer `ui()` / `find_nodes()` / `tap_ui()`: they also see elements with novisible text (icons with a content-description, fields by resource-id like`tap_ui("url_bar")`). `ocr_pixels()` is Unsupported here.-- `back()`, `current_app()`, `list_apps()` exist. `open_app("chrome")`- matches installed package ids and returns the one launched.+- **adb is the native language here, and it is first-class.** `shell(cmd)`+ runs `adb shell cmd` on whichever phone the harness chose, so anything you+ know how to do with adb, do: `shell("input tap 360 640")`,+ `shell("input keyevent KEYCODE_BACK")`, `shell("am start -n pkg/.Activity")`,+ `shell("dumpsys notification --noredact")`, `shell("pm list packages -3")`.+ The input helpers (`tap`, `swipe`, `press`, `home`) are one-line wrappers+ over the same commands — use whichever you think in. What the harness adds+ that raw adb does not: finding and reconnecting the phone, and reading the+ screen as a short list instead of a page of XML.+- **On Android, `scroll` and `swipe` are different gestures.** `scroll` moves+ the content and stops: no momentum, the same distance every time, so use it+ (and `scroll_until` / `scroll_collect`) to walk a list without skipping+ rows. `swipe` is a flick and coasts past whatever was next — right for "next+ video" or changing pages, wrong for reading a list. (The note above about+ vertical swipes doing nothing is about iPhone Mirroring; here both work.)+- `open_app("TikTok")` takes the name a person would say, a package id, or a+ fragment of one, and returns the package it launched. When nothing matches,+ the error lists what is installed. `back()`, `current_app()`, `list_apps()`+ exist.- `press()` takes single keys only (`"enter"`, `"back"`, `"tab"`); chords- raise Unsupported. `type_text` needs a focused field, same as iOS.+ raise Unsupported. `type_text` needs a focused field, same as iOS, and types+ ASCII: adb cannot type emoji or accented letters.+- **Some screens never give up their tree** — a playing video, a screen that+ animates. `ocr()` / `ui()` then raise saying so; take a `screenshot()` and+ look at it instead of retrying.- No focus to keep: nothing on the Mac has to be frontmost, and`interruption(before, after)` always reports nothing disturbed.- **Verify cheaply, then read.** adb reports nothing about outcomes — a tap on@@ -186,6 +212,42 @@ PYerror names the missing step — relay it, don't retry-loop.`phone-harness android` shows known phones and what is attached.+## Cloud phones++`phone-harness cloud start` rents the user's own Android phone from Phone+Harness Cloud and connects to it; from then on every script drives that phone+with nothing exported, exactly as the Android section describes. It is the+same phone each time: apps, logins and normally the exact screen are kept+between sessions.++```bash+phone-harness cloud # signed in? a phone attached? minutes left?+phone-harness cloud start # about 15s; safe to run twice, it reattaches+phone-harness cloud watch # opens the live view for the user+phone-harness cloud stop # ends billing and saves the phone+```++- **It bills by the minute while it is up.** Start it once and keep it for the+ whole conversation — a stop and a restart between two requests wastes more+ than it saves. Stop it when the user is done, and say that you did.+- **Stop before the deadline, because a session cannot be extended.** One+ that simply runs out keeps the phone's data but not its running state. The+ harness warns on stderr when under two minutes remain; `phone-harness cloud`+ shows the time left. If the task needs longer, stop and start again: the+ phone comes back where it was in about 15 seconds. `cloud stop` returns at+ once; the save finishes on its own, and a `cloud start` during it waits.+- **A session the user started is theirs.** `cloud start` attaches to a phone+ that is already running instead of starting another; leave that one running+ unless they ask you to stop it.+- `Not signed in` means the user has to run `phone-harness cloud login` and+ approve it in a browser. Relay that; you cannot do it for them.+- Offer `cloud watch` early on a long task, so the user can see the phone+ instead of waiting for your report. `cloud start --temp` is a throwaway+ phone that keeps nothing.+- The connection is handled for you, including reconnecting after a drop.+ The adb address the CLI shows is not a secret; the unlock code is, and you+ never need it — do not look for it, print it, or ask the user for it.+## ConsentThis is the user's real phone. Stop and ask before anything outward-facing ordiff --git a/pyproject.toml b/pyproject.tomlindex ab80722..8b9065b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -1,16 +1,18 @@[project]name = "phone-harness"-version = "0.2.1"-description = "Control a real iPhone through macOS iPhone Mirroring: OCR eyes, CGEvent hands"+version = "0.3.0"+description = "Let an agent drive a real phone: an iPhone through macOS iPhone Mirroring, an Android over adb, or a rented cloud Android"readme = "README.md"license = "MIT"license-files = ["LICENSE"]requires-python = ">=3.10"-keywords = ["iphone", "automation", "agent", "iphone-mirroring", "macos"]+keywords = ["iphone", "android", "adb", "automation", "agent", "iphone-mirroring", "cloud-phone"]classifiers = ["Development Status :: 3 - Alpha",- "Environment :: MacOS X",+ "Environment :: Console","Operating System :: MacOS",+ "Operating System :: POSIX :: Linux",+ "Operating System :: Microsoft :: Windows","Programming Language :: Python :: 3","Topic :: Software Development :: Testing",]diff --git a/src/phone_harness/android.py b/src/phone_harness/android.pyindex b29483b..01e3ef4 100644--- a/src/phone_harness/android.py+++ b/src/phone_harness/android.py@@ -55,6 +55,29 @@ _KEYS = {}+# Names people say -> package ids that do not contain them. Only apps whose+# id would not be found by matching the name against installed ids; first+# installed one wins.+_APP_IDS = {+ "tiktok": ("com.zhiliaoapp.musically", "com.ss.android.ugc.trill"),+ "x": ("com.twitter.android",), "twitter": ("com.twitter.android",),+ "threads": ("com.instagram.barcelona",),+ "facebook": ("com.facebook.katana", "com.facebook.lite"),+ "messenger": ("com.facebook.orca",),+ "signal": ("org.thoughtcrime.securesms",),+ "gmail": ("com.google.android.gm",),+ "playstore": ("com.android.vending",), "googleplay": ("com.android.vending",),+ "uber": ("com.ubercab",), "ubereats": ("com.ubercab.eats",),+ "cashapp": ("com.squareup.cash",),+ "amazon": ("com.amazon.mShop.android.shopping",),+ "googlemaps": ("com.google.android.apps.maps",),+ "messages": ("com.google.android.apps.messaging",),+ "phone": ("com.google.android.dialer", "com.android.dialer"),+ "clock": ("com.google.android.deskclock", "com.android.deskclock"),+ "files": ("com.google.android.documentsui", "com.android.documentsui"),+}++# --- adb, without a device yet -----------------------------------------------def _run(*args, binary=False, timeout=60, check=True):@@ -139,6 +162,7 @@ class Android(Backend):if serial:os.environ["ANDROID_SERIAL"] = serialself._bounds = None+ self._motionevents = None # does this phone's `input` know motionevent?self._resolved = Falseself._gate_at = 0.0@@ -150,6 +174,20 @@ class Android(Backend):unpinned command then fails with "more than one device"."""if not self._resolved and self._resolve() is None:self._session_require() # raises with the physical step+ from . import cloud+ rented = cloud.attached()+ if not rented or os.environ.get("ANDROID_SERIAL") != cloud.serial_of(rented):+ return _run(*args, binary=binary, timeout=timeout)+ # A rented phone is reached over the internet, and every new connection+ # to it starts locked (commands answer "locked"): reconnect once, and+ # only then is a failure real.+ try:+ out = _run(*args, binary=binary, timeout=timeout)+ if out.strip() not in ("locked", b"locked"):+ return out+ except RuntimeError:+ pass+ cloud.ensure_connected(rented)return _run(*args, binary=binary, timeout=timeout)def _sh(self, cmd, timeout=60):@@ -161,13 +199,22 @@ class Android(Backend):"""Pin ANDROID_SERIAL to one ready device, connecting a paired phoneover Wi-Fi if nothing is attached. Returns the adb id or None.- Order: the user's explicit ANDROID_SERIAL; then a USB phone (wired+ Order: the user's explicit ANDROID_SERIAL; then a phone rented with+ `phone-harness cloud start` (asked for by name, and paid for by the+ minute); then a USB phone (wiredalways wins — it is right there); then a live Wi-Fi link, the savedprimary first; then mDNS — the primary if it is on the LAN, else thefirst known phone, else any paired phone."""if os.environ.get("ANDROID_SERIAL"):self._resolved = Truereturn os.environ["ANDROID_SERIAL"]+ from . import cloud+ rented = cloud.attached()+ if rented:+ # Not remembered below: its address is reused by other phones.+ os.environ["ANDROID_SERIAL"] = cloud.ensure_connected(rented)+ self._resolved = True+ return os.environ["ANDROID_SERIAL"]cfg = _load()primary = (cfg.get("phones") or {}).get(cfg.get("primary") or "", {})known = {p.get("serial") for p in (cfg.get("phones") or {}).values()}@@ -302,13 +349,41 @@ class Android(Backend):self._sh(f"input swipe {int(x1)} {int(y1)} {int(x2)} {int(y2)} "f"{int(duration * 1000)}")- def _input_scroll(self, x, y, dy, steps=6):- """A finger drag standing in for a wheel: +dy moves content up the- way wheel-up does (revealing what is above), so the finger travels- +dy pixels downward. Slow enough not to fling."""+ def _input_scroll(self, x, y, dy, dx=0, steps=6):+ """A finger drag standing in for a wheel, in content space: +dy reveals+ what is above, so the finger travels +dy pixels down (and +dx right).++ It must not fling. `input swipe` lifts the finger while it is still+ moving, so the list coasts on by a quarter of the distance and a walk+ skips rows without any error. So: touch down, move in steps, hold+ still, then lift. The gesture is centred on (x, y) and kept on the+ glass, since a drag that starts at the centre and runs off the edge+ is cut short."""self._gate()- self._sh(f"input swipe {int(x)} {int(y)} {int(x)} {int(y + dy)} "- f"{max(150, int(steps) * 50)}")+ b = self._screen_bounds() or {}+ w, h = b.get("w", 0), b.get("h", 0)+ x1, y1, x2, y2 = x - dx / 2, y - dy / 2, x + dx / 2, y + dy / 2+ if w and h:+ keep = lambda v, size: min(max(v, size * 0.06), size * 0.94)+ x1, x2, y1, y2 = keep(x1, w), keep(x2, w), keep(y1, h), keep(y2, h)+ n = max(2, int(steps))+ if self._motionevents is not False:+ moves = " && ".join(+ f"input motionevent MOVE {int(x1 + (x2 - x1) * i / n)} {int(y1 + (y2 - y1) * i / n)}"+ for i in range(1, n + 1))+ try:+ self._sh(f"input motionevent DOWN {int(x1)} {int(y1)} && {moves} && "+ f"sleep 0.2 && input motionevent UP {int(x2)} {int(y2)}")+ self._motionevents = True+ return+ except RuntimeError:+ if self._motionevents: # it has worked before: a real failure+ raise+ self._motionevents = False # an older Android without `motionevent`+ # The fallback still lifts a moving finger; slow enough that it coasts little.+ travel = max(abs(x2 - x1), abs(y2 - y1))+ self._sh(f"input swipe {int(x1)} {int(y1)} {int(x2)} {int(y2)} "+ f"{max(600, int(travel * 4))}")def _input_keys(self, combo):self._gate()@@ -323,7 +398,7 @@ class Android(Backend):raise Unsupported(f"android has no key named {combo!r}")self._sh(f"input keyevent KEYCODE_{code}")- def _input_text(self, s, delay=0.03):+ def _input_text(self, s, delay=0.03, keystrokes=False):self._gate()"""`input text` takes one ASCII token; newlines and backspaces becomekeyevents, spaces become %s, and the rest is shell-quoted."""@@ -353,18 +428,30 @@ class Android(Backend):# --- apps ---------------------------------------------------------------def _apps_launch(self, name):- """A package id, or a name matched against installed package ids- ('chrome' -> com.android.chrome). Returns the package launched."""+ """A package id, or the name a person would say. Android only knows+ apps by package id, and plenty of ids do not contain the brand+ ("TikTok" is com.zhiliaoapp.musically), so a name is tried as: an+ installed id; a well-known app (_APP_IDS); a fragment of an id+ ('chrome' -> com.android.chrome); and last the label on the launcher,+ tapped like a person would. Returns the package launched."""self._gate()- pkg = name if "." in name else None+ pkgs = self._apps_list(include_system=True)+ want = re.sub(r"[^a-z0-9]+", "", name.lower())+ pkg = name if name in pkgs else next(+ (p for p in _APP_IDS.get(want, ()) if p in pkgs), None)if pkg is None:- pkgs = self._apps_list(include_system=True)- hits = [p for p in pkgs if name.lower() in p.lower()]- if not hits:- raise RuntimeError(f"no installed app matches {name!r}")+ hits = [p for p in pkgs if want and want in p.lower().replace(".", "")]# shortest match is the least-qualified, e.g. com.android.chrome# over com.android.chrome.helper- pkg = sorted(hits, key=len)[0]+ pkg = sorted(hits, key=len)[0] if hits else None+ if pkg is None:+ launched = self._launch_by_label(name)+ if launched:+ return launched+ raise RuntimeError(+ f"no installed app matches {name!r}. Installed: "+ f"{', '.join(self._apps_list()) or 'no third-party apps'}. "+ "Pass one of these package ids.")out = self._sh("cmd package resolve-activity --brief "f"-c android.intent.category.LAUNCHER {shlex.quote(pkg)}")comp = next((l.strip() for l in reversed(out.splitlines())@@ -374,6 +461,33 @@ class Android(Backend):self._sh(f"am start -W -n {shlex.quote(comp)}")return pkg+ def _launch_by_label(self, name):+ """Tap the icon labelled `name` on the home screen, else in the app+ drawer. -> the package that came to the front, or None."""+ want = name.strip().lower()+ self._nav_home()+ launcher = self._apps_current()+ for opened_drawer in (False, True):+ if opened_drawer:+ b = self._screen_bounds() or {"w": 720, "h": 1280}+ self._sh(f"input swipe {b['w'] // 2} {int(b['h'] * 0.8)} "+ f"{b['w'] // 2} {int(b['h'] * 0.25)} 250")+ time.sleep(1.0)+ try:+ nodes = self._tree()+ except RuntimeError:+ continue+ for n in nodes:+ if (n["text"] or n["desc"]).strip().lower() == want:+ self._sh(f"input tap {n['x']} {n['y']}")+ for _ in range(20):+ time.sleep(0.25)+ now = self._apps_current()+ if now and now != launcher:+ return now+ self._nav_home()+ return None+def _apps_current(self):out = self._sh("dumpsys activity activities")m = (re.search(r"topResumedActivity=ActivityRecord\{[^}]*?\bu\d+ ([\w.]+)/", out)diff --git a/src/phone_harness/cloud.py b/src/phone_harness/cloud.pynew file mode 100644index 0000000..3de892b--- /dev/null+++ b/src/phone_harness/cloud.py@@ -0,0 +1,814 @@+"""Phone Harness Cloud: rent an Android phone, then drive it like any other.++This module decides which phone exists and who pays for it. It never drives+one: a cloud phone is an Android device at host:port, so once `cloud start`+has run `adb connect` and `unlock`, android.py and every helper work on it+unchanged. The ADB endpoint and unlock code stay in here; nobody copies them.++ auth.json (config dir, 0600) this machine's sign-in: OAuth tokens from+ `cloud login`, refreshed here as they expire+ cloud.json (state dir) the attached session and the cached profile id++Signing in is the browser's job (OAuth device flow); nobody pastes a key.+PHONE_HARNESS_API_KEY, if set, is used instead: that is for CI, where there+is no one to click Approve.++Stdlib only. API reference: https://phone-harness.com/docs+"""+import json+import os+import shutil+import sys+import time+import urllib.error+import urllib.parse+import urllib.request+import uuid+import webbrowser++from . import config++SAVE_WAIT = 90 # seconds to let a stopped profile phone finish closing and saving+READY_WAIT = 240 # seconds to wait for `ready` before giving the phone back+LOW_TIME = 120 # warn the script when the session has less than this left+# Named, because the sign-in host's CDN refuses urllib's default signature.+USER_AGENT = "phone-harness-cli"+++class CloudError(RuntimeError):+ def __init__(self, status, body):+ self.status = status+ self.body = body if isinstance(body, dict) else {}+ self.code = self.body.get("code")+ super().__init__(self.body.get("error") or f"HTTP {status}")+++# Where the cloud is. Like gh, vercel and gcloud, the CLI names itself to the+# sign-in system with a public OAuth client id: it identifies the app and+# proves nothing, so it is safe here. PHONE_HARNESS_CLOUD_API and friends+# override these for tests and for a Phone Harness instance of your own.+API = "https://api.phone-harness.com"+DASHBOARD = "https://phone-harness.com/dashboard"+OAUTH_ISSUER = "https://clerk.phone-harness.com"+OAUTH_CLIENT_ID = "Fu2QHJcGewhL7uKh" # the "phone-harness CLI" OAuth app+++def _target(key):+ return os.environ.get(f"PHONE_HARNESS_CLOUD_{key}") or globals()[key]+++def _dashboard():+ return _target("DASHBOARD").rstrip("/")+++# --- files -------------------------------------------------------------------++def _auth_path():+ return config.config_dir() / "auth.json"+++def _state_path():+ return config.state_dir() / "cloud.json"+++def _load_state():+ return config._read(_state_path(), {})+++def _save_state(state):+ config._write(_state_path(), state)+ _private(_state_path()) # it holds the phone's unlock code+++def _private(path):+ try:+ os.chmod(path, 0o600)+ except OSError:+ pass+++def _save_auth(record):+ path = _auth_path()+ config._write(path, record)+ _private(path)+++def _oauth():+ return _target("OAUTH_ISSUER").rstrip("/"), _target("OAUTH_CLIENT_ID")+++def _form_post(url, fields):+ req = urllib.request.Request(url, data=urllib.parse.urlencode(fields).encode(),+ headers={"Accept": "application/json",+ "User-Agent": USER_AGENT}, method="POST")+ try:+ with urllib.request.urlopen(req, timeout=30) as r:+ return r.status, json.loads(r.read() or b"{}")+ except urllib.error.HTTPError as e:+ try:+ return e.code, json.loads(e.read())+ except ValueError:+ return e.code, {"error": f"HTTP {e.code}"}+++def _store_tokens(tok, email=None):+ old = config._read(_auth_path(), {})+ _save_auth({"access_token": tok["access_token"],+ # a refresh may or may not rotate the refresh token+ "refresh_token": tok.get("refresh_token") or old.get("refresh_token"),+ "expires_at": time.time() + int(tok.get("expires_in") or 3600),+ "email": email or old.get("email")})+ return tok["access_token"]+++def _refresh(record):+ """-> a fresh access token, or None when the sign-in is no longer good."""+ if not record.get("refresh_token"):+ return None+ issuer, client_id = _oauth()+ status, tok = _form_post(f"{issuer}/oauth/token", {+ "grant_type": "refresh_token", "client_id": client_id,+ "refresh_token": record["refresh_token"]})+ if status != 200 or not tok.get("access_token"):+ return None+ return _store_tokens(tok)+++def _bearer(required=True, force_refresh=False):+ if os.environ.get("PHONE_HARNESS_API_KEY"):+ return os.environ["PHONE_HARNESS_API_KEY"]+ record = config._read(_auth_path(), {})+ token = record.get("access_token")+ if token and (force_refresh or time.time() > (record.get("expires_at") or 0) - 60):+ token = _refresh(record)+ if not token and required:+ sys.exit("Not signed in. Run: phone-harness cloud login")+ return token+++# --- http --------------------------------------------------------------------++def _api(method, path, body=None, token=None, headers=None, timeout=40):+ """-> parsed JSON. CloudError for an HTTP error, OSError if unreachable."""+ try:+ return _request(method, path, body, token or _bearer(), headers, timeout)+ except CloudError as e:+ # The access token can be refused before its stated expiry (clock+ # skew, a revoked grant): one refresh, one retry, then it is a 401.+ fresh = None if token or e.status != 401 else _bearer(required=False, force_refresh=True)+ if not fresh:+ raise+ return _request(method, path, body, fresh, headers, timeout)+++def _request(method, path, body, token, headers, timeout):+ h = {"Authorization": f"Bearer {token}", "Accept": "application/json",+ "User-Agent": USER_AGENT, **(headers or {})}+ # A gate in front of a private instance (exe.dev's, for the dev VM) admits this bearer.+ proxy = os.environ.get("PHONE_HARNESS_CLOUD_PROXY_TOKEN")+ if proxy:+ h["X-Exedev-Authorization"] = f"Bearer {proxy}"+ data = None+ if body is not None:+ h["Content-Type"] = "application/json"+ data = json.dumps(body).encode()+ req = urllib.request.Request(_target("API").rstrip("/") + path,+ data=data, headers=h, method=method)+ try:+ with urllib.request.urlopen(req, timeout=timeout) as r:+ raw = r.read()+ except urllib.error.HTTPError as e:+ raw = e.read()+ try:+ parsed = json.loads(raw)+ except ValueError:+ parsed = {"error": raw.decode(errors="replace")[:200]}+ raise CloudError(e.code, parsed) from None+ return json.loads(raw) if raw.strip() else {}+++def _explain(e):+ """A CloudError, as the next thing the user should do."""+ if e.status == 401:+ return "This machine is signed out. Run: phone-harness cloud login"+ if e.status == 403:+ return (f"Your account isn't enabled for phones yet ({e}). "+ f"Request access at {_dashboard()}")+ if e.status == 402 or "balance_cents" in e.body:+ cents = e.body.get("balance_cents")+ have = f" (${cents / 100:.2f})" if isinstance(cents, int) else ""+ return f"Not enough credit{have}. Add credit at {_dashboard()}"+ if "available_session_slots" in e.body:+ return (f"Session limit reached ({e.body.get('active_session_count')} of "+ f"{e.body.get('session_limit')}). `phone-harness cloud ls` shows them.")+ return f"{e} (HTTP {e.status})"+++# --- the attached session ----------------------------------------------------++def attached():+ """The session the helpers should drive, or None. Read by transport.py and+ android.py on every run, so: no network, and never raises."""+ try:+ sess = _load_state().get("session")+ except Exception:+ return None+ if not isinstance(sess, dict) or not sess.get("host") or not sess.get("code"):+ return None+ if sess.get("expires_at") and time.time() >= sess["expires_at"]:+ return None+ return sess+++def serial_of(sess):+ return f"{sess['host']}:{sess['port']}"+++def ensure_connected(sess, quiet=False):+ """adb connect + unlock, skipped when the link is already up. Every new+ adb connection starts locked, so this runs once per process and again+ after a drop. -> the adb serial."""+ from .android import _run+ serial = serial_of(sess)+ probe = _run("-s", serial, "shell", "echo", "ph-ok", timeout=15, check=False)+ if "ph-ok" not in probe:+ # A link that went `offline` still counts as connected to adb, and+ # `connect` would answer "already connected": drop it first.+ _run("disconnect", serial, timeout=10, check=False)+ out = _run("connect", serial, timeout=20, check=False)+ if "connected" not in out or "cannot" in out or "failed" in out:+ raise RuntimeError(f"could not reach the cloud phone at {serial}: {out.strip()} "+ "— `phone-harness cloud` shows whether it is still running")+ _run("-s", serial, "shell", "unlock", sess["code"], timeout=20, check=False)+ probe = _run("-s", serial, "shell", "echo", "ph-ok", timeout=15, check=False)+ if "ph-ok" not in probe:+ raise RuntimeError(f"the cloud phone at {serial} stayed locked; its unlock code "+ "may have been reset — run `phone-harness cloud use "+ f"{sess.get('sid', 'SID')}` to fetch the current one")+ left = (sess.get("expires_at") or 0) - time.time()+ if not quiet and 0 < left < LOW_TIME:+ print(f"phone-harness: the cloud phone expires in {int(left)}s — run "+ "`phone-harness cloud stop` now to keep its running state", file=sys.stderr)+ return serial+++def _attach(session, profile_id=None):+ """Remember a ready session and connect to it."""+ adb = session.get("adb") or {}+ if not adb.get("host") or not adb.get("code"):+ # Only after someone turned ADB off for this session; ready phones have it.+ adb = _api("POST", f"/sessions/{session['id']}/adb")+ state = _load_state()+ state["session"] = {+ "sid": session["id"], "host": adb["host"], "port": adb["port"],+ "code": adb["code"], "profile": session.get("profile"),+ "expires_at": session.get("expires_at"), "watch_url": session.get("watch_url"),+ }+ if profile_id:+ state["profile_id"] = profile_id+ _save_state(state)+ return ensure_connected(state["session"], quiet=True)+++def _detach(sid=None):+ state = _load_state()+ sess = state.get("session")+ if sess and (sid is None or sess.get("sid") == sid):+ try:+ from .android import _run+ _run("disconnect", serial_of(sess), timeout=10, check=False)+ except Exception:+ pass+ state.pop("session", None)+ _save_state(state)+++# --- small things ------------------------------------------------------------++def _flag(args, name):+ if name in args:+ args.remove(name)+ return True+ return False+++def _option(args, *names):+ for name in names:+ if name in args:+ i = args.index(name)+ if i + 1 >= len(args):+ sys.exit(f"{name} needs a value")+ value = args[i + 1]+ del args[i:i + 2]+ return value+ return None+++def _int(text, what):+ try:+ return int(text)+ except (TypeError, ValueError):+ sys.exit(f"{what} must be a number, not {text!r}")+++def _money(cents):+ return f"${(cents or 0) / 100:.2f}"+++def _left(expires_at):+ if not expires_at:+ return "?"+ s = int(expires_at - time.time())+ return "expired" if s <= 0 else f"{s // 60} min" if s >= 120 else f"{s}s"+++def _ago(ts):+ if not ts:+ return "never"+ s = int(time.time() - ts)+ for size, unit in ((86400, "day"), (3600, "hour"), (60, "min")):+ if s >= size:+ n = s // size+ return f"{n} {unit}{'s' if n != 1 and unit != 'min' else ''} ago"+ return "just now"+++def _resolve_sid(given):+ """A session id, a unique prefix of one, or (None) the attached session."""+ if given is None:+ sess = attached()+ if not sess:+ sys.exit("No cloud phone attached. `phone-harness cloud ls` lists running ones.")+ return sess["sid"]+ ids = [s["id"] for s in _api("GET", "/sessions")]+ hits = [i for i in ids if i == given] or [i for i in ids if i.startswith(given)]+ if len(hits) != 1:+ sys.exit(f"{given!r} matches {len(hits)} running sessions"+ + (f": {', '.join(hits)}" if hits else ""))+ return hits[0]+++def _wait_ready(sid):+ deadline = time.monotonic() + READY_WAIT+ shown = None+ while True:+ session = _api("GET", f"/sessions/{sid}")+ if session["state"] == "ready":+ return session+ if session["state"] in ("error", "closing"):+ sys.exit(f"The phone did not start: {session.get('error') or session['state']}")+ if time.monotonic() >= deadline:+ try:+ _api("DELETE", f"/sessions/{sid}")+ except (CloudError, OSError):+ pass+ sys.exit(f"Gave up after {READY_WAIT}s waiting for the phone; asked the service "+ f"to end session {sid}.")+ prog = session.get("progress") or {}+ line = prog.get("phase") or "provisioning"+ if prog.get("queue_position"):+ line += f", position {prog['queue_position']} in the queue"+ if line != shown:+ print(f" … {line}")+ shown = line+ time.sleep(2)+++# --- login -------------------------------------------------------------------++def _login(args):+ """OAuth 2.0 Device Authorization Grant (RFC 8628): works the same on a+ laptop and over SSH, because the approval happens in any browser."""+ open_browser = not _flag(args, "--no-browser")+ issuer, client_id = _oauth()+ status, start = _form_post(f"{issuer}/oauth/device_authorization", {+ "client_id": client_id, "scope": "openid profile email offline_access"})+ if status != 200 or "device_code" not in start:+ sys.exit("Could not start sign-in: "+ f"{start.get('error_description') or start.get('error') or start.get('title') or status}")+ print(f"To sign in, open: {start['verification_uri']}\n"+ f"and enter code: {start['user_code']}\n")+ if open_browser:+ try:+ webbrowser.open(start.get("verification_uri_complete") or start["verification_uri"])+ except Exception:+ pass+ print("Waiting for you to approve in the browser…", flush=True)+ interval = int(start.get("interval", 5))+ deadline = time.monotonic() + int(start.get("expires_in") or 600)+ tok = None+ while time.monotonic() < deadline:+ time.sleep(interval)+ status, tok = _form_post(f"{issuer}/oauth/token", {+ "client_id": client_id, "device_code": start["device_code"],+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code"})+ if status == 200 and tok.get("access_token"):+ break+ err, tok = tok.get("error"), None+ if err == "slow_down":+ interval += 5+ elif err != "authorization_pending":+ sys.exit("Sign-in was denied." if err == "access_denied"+ else f"Sign-in failed: {err}")+ if not tok:+ sys.exit("Sign-in timed out. Run `phone-harness cloud login` again.")+ try:+ me = _api("GET", "/me", token=tok["access_token"])+ except CloudError as e:+ sys.exit(f"Signed in, but the Phone Harness API refused the sign-in: {_explain(e)}")+ _store_tokens(tok, email=me.get("email"))+ state = _load_state()+ state["profile_id"] = (me.get("profile") or {}).get("id")+ _save_state(state)+ print(f"✓ Signed in as {me.get('email') or me.get('uid')}")+ _print_account(me)+ print("\nStart your phone with: phone-harness cloud start")+ return 0+++def _logout(args):+ record = config._read(_auth_path(), {})+ if not record.get("access_token"):+ print("Not signed in.")+ return 0+ issuer, client_id = _oauth()+ for kind in ("refresh_token", "access_token"): # best effort; the file goes either way+ if record.get(kind):+ try:+ _form_post(f"{issuer}/oauth/token/revoke", {+ "client_id": client_id, "token": record[kind], "token_type_hint": kind})+ except OSError:+ pass+ _auth_path().unlink(missing_ok=True)+ print("Signed out.")+ if attached():+ print("A cloud phone is still running and billing; sign in again to stop it.")+ return 0+++def _print_account(me):+ rate = me.get("price_cents_per_minute") or 0+ minutes = f" (about {me.get('balance_cents', 0) // rate} min)" if rate else ""+ print(f" credit {_money(me.get('balance_cents'))}{minutes}")+ print(f" phone {_describe_profile(me.get('profile') or {})}")+ if not me.get("can_rent", True):+ print(f" access not enabled yet: {me.get('rent_blocked_reason') or 'invite-only'}")+++def _describe_profile(profile):+ state = profile.get("state") or "empty"+ if state == "stored":+ return f"stored, saved {_ago(profile.get('saved_at'))}"+ if state == "running":+ return f"running in session {profile.get('session')}"+ if state == "saving":+ return "saving (a session just ended)"+ return "empty — the first `cloud start` sets it up"+++# --- start / stop ------------------------------------------------------------++def _wait_for_profile():+ """-> the profile id once the saved phone is free to start, or+ {"id", "session"} when a live session already holds it. A phone that was+ just stopped is `running` (its session `closing`) and then `saving` for a+ few seconds; starting it again should simply wait that out."""+ deadline = time.monotonic() + SAVE_WAIT+ told = False+ while True:+ profile = _api("GET", "/me").get("profile") or {}+ state = profile.get("state")+ if state == "running" and profile.get("session"):+ try:+ live = _api("GET", f"/sessions/{profile['session']}")+ except CloudError:+ live = None+ if live and live["state"] in ("provisioning", "ready"):+ print(f"Your phone is already running (session {live['id']}). Attaching to it.")+ return {"id": profile.get("id"), "session": _wait_ready(live["id"])}+ elif state != "saving":+ return profile.get("id")+ if time.monotonic() >= deadline:+ sys.exit("Your phone is still shutting down from its last session. "+ "Try again in a few seconds.")+ if not told:+ print("Your phone is still saving from its last session…")+ told = True+ time.sleep(3)++++def _start(args):+ temp = _flag(args, "--temp")+ minutes = _option(args, "--minutes", "-m")+ if args:+ sys.exit(CLI_USAGE)+ from .android import _adb_bin+ if not shutil.which(_adb_bin()):+ sys.exit("adb is not installed, and it is how the helpers reach the phone. Install "+ "Android platform-tools first (macOS: brew install android-platform-tools; "+ "`phone-harness --doctor android` names it for this OS).")+ cap = int(config.get("cloud.max_minutes"))+ minutes = _int(minutes, "--minutes") if minutes else int(config.get("cloud.minutes"))+ if not 1 <= minutes <= cap:+ sys.exit(f"--minutes must be between 1 and {cap} "+ f"(raise the cap with `phone-harness config set cloud.max_minutes N`).")++ current = attached()+ if current:+ try:+ live = _api("GET", f"/sessions/{current['sid']}")+ except CloudError:+ live = None+ if live and live["state"] in ("provisioning", "ready"):+ print(f"Already attached to session {live['id']}; reusing it.")+ return _report(_wait_ready(live["id"]))+ _detach()++ body = {"timeout_seconds": minutes * 60}+ profile_id = None+ if not temp:+ profile_id = _wait_for_profile()+ if isinstance(profile_id, dict): # it is already up: use it+ return _report(profile_id["session"], profile_id["id"])+ if profile_id:+ body["profile_id"] = profile_id++ request_key = uuid.uuid4().hex+ print("Starting a temporary phone…" if "profile_id" not in body+ else "Starting your phone…")+ try:+ created = _api("POST", "/sessions", body, headers={"Idempotency-Key": request_key})+ except CloudError as e:+ if e.code == "profile_running":+ sys.exit("Your phone is still shutting down from its last session. "+ "Try again in a few seconds.")+ raise+ except OSError:+ # The request may have been admitted even though the answer was lost.+ created = _api("GET", f"/sessions/requests/{request_key}")+ if created.get("cleanup_complete") or not created.get("id"):+ raise+ return _report(_wait_ready(created["id"]), profile_id)+++def _report(session, profile_id=None):+ serial = _attach(session, profile_id)+ how = (session.get("startup") or {}).get("startup")+ note = {"exact": " Resumed exactly where you left it.",+ "rebooted": " Rebooted from saved storage: apps and logins kept, the screen is not."}+ print(f"✓ ready.{note.get(how, '')}")+ print(f" session {session['id']} ({'your phone' if session.get('profile') else 'temporary'})")+ print(f" adb {serial} (connected, unlocked)")+ print(f" expires in {_left(session.get('expires_at'))} — `phone-harness cloud stop` "+ "before then" + (" to keep the running state" if session.get("profile") else ""))+ print(" watch phone-harness cloud watch")+ return 0+++def _stop(args):+ everything = _flag(args, "--all")+ watch_save = _flag(args, "--wait")+ if everything:+ sids = [s["id"] for s in _api("GET", "/sessions")]+ if not sids:+ print("Nothing is running.")+ _detach()+ return 0+ else:+ sids = [_resolve_sid(args[0] if args else None)]+ held_profile = False+ for sid in sids:+ try:+ before = _api("GET", f"/sessions/{sid}")+ held_profile = held_profile or bool(before.get("profile"))+ _api("DELETE", f"/sessions/{sid}")+ print(f"✓ Session {sid} ended; billing stopped.")+ except CloudError as e:+ if e.status != 404:+ raise+ print(f"Session {sid} was already gone.")+ _detach(sid)+ if not held_profile:+ return 0+ # Billing ended with the DELETE. The save runs on the service for another+ # half minute and needs nothing from here, so waiting on it is opt-in;+ # `cloud start` waits out a save that is still going.+ if not watch_save:+ print(" Your phone is being saved (about 30s); `phone-harness cloud phone` shows when.")+ return 0+ print(" Saving your phone…", end="", flush=True)+ deadline = time.monotonic() + SAVE_WAIT+ state = "saving"+ while time.monotonic() < deadline:+ time.sleep(3)+ state = (_api("GET", "/me").get("profile") or {}).get("state")+ if state not in ("saving", "running"):+ break+ print(f" {state}.")+ return 0+++# --- looking -----------------------------------------------------------------++def _status(args):+ if not _bearer(required=False):+ print("Not signed in. Run: phone-harness cloud login")+ return 1+ me = _api("GET", "/me")+ if os.environ.get("PHONE_HARNESS_CLOUD_API"):+ print(f"api {_target('API')}")+ print(f"signed in {me.get('email') or me.get('uid')} · {_money(me.get('balance_cents'))} credit")+ print(f"phone {_describe_profile(me.get('profile') or {})}")+ sess = attached()+ if not sess:+ running = me.get("active_session_count") or 0+ print("session none attached" + (f" ({running} running: `phone-harness cloud ls`)"+ if running else " — `phone-harness cloud start`"))+ return 0+ try:+ live = _api("GET", f"/sessions/{sess['sid']}")+ except CloudError:+ print(f"session {sess['sid']} is gone; detaching")+ _detach()+ return 0+ print(f"session {live['id']} · {live['state']} · {_left(live.get('expires_at'))} left"+ f" · {'your phone' if live.get('profile') else 'temporary'}")+ print(f"adb {serial_of(sess)}")+ return 0+++def _ls(args):+ as_json = _flag(args, "--json")+ limit = _option(args, "-n", "--limit")+ sessions = _api("GET", "/sessions")+ if limit:+ sessions = sessions[:_int(limit, "-n")]+ if as_json:+ print(json.dumps(sessions, indent=2))+ return 0+ if not sessions:+ print("Nothing is running.")+ return 0+ mine = (attached() or {}).get("sid")+ print(f" {'SESSION':<14} {'STATE':<13} {'PHONE':<10} {'LEFT':<8} ADB")+ for s in sessions:+ adb = s.get("adb") or {}+ print(f"{'*' if s['id'] == mine else ' '} {s['id']:<14} {s['state']:<13} "+ f"{'yours' if s.get('profile') else 'temporary':<10} "+ f"{_left(s.get('expires_at')):<8} "+ f"{adb.get('host', '-')}{':' + str(adb['port']) if adb.get('port') else ''}")+ return 0+++def _show(args):+ as_json = _flag(args, "--json")+ session = _api("GET", f"/sessions/{_resolve_sid(args[0] if args else None)}")+ if as_json:+ print(json.dumps(session, indent=2))+ return 0+ adb = session.pop("adb", None) or {}+ session.pop("watch_url", None) # a credential; `cloud watch` opens it+ for k, v in session.items():+ if v not in (None, "", {}):+ print(f"{k:<16} {json.dumps(v) if isinstance(v, (dict, list)) else v}")+ if adb.get("host"):+ print(f"{'adb':<16} {adb['host']}:{adb['port']}")+ return 0+++def _use(args):+ if len(args) != 1:+ sys.exit("Usage: phone-harness cloud use SID")+ session = _wait_ready(_resolve_sid(args[0]))+ serial = _attach(session)+ print(f"✓ attached to {session['id']} at {serial}")+ return 0+++def _watch(args):+ show = _flag(args, "--print")+ url = _api("GET", f"/sessions/{_resolve_sid(args[0] if args else None)}").get("watch_url")+ if not url:+ sys.exit("This session has no live view.")+ if show or not webbrowser.open(url):+ print(url)+ return 0+++def _whoami(args):+ me = _api("GET", "/me")+ if _flag(args, "--json"):+ print(json.dumps(me, indent=2))+ return 0+ print(f"{me.get('email') or me.get('uid')}")+ _print_account(me)+ print(f" sessions {me.get('active_session_count', 0)} of {me.get('session_limit', '?')} running")+ return 0+++def _phone(args):+ if args[:1] == ["reset"]:+ if "--yes" not in args:+ sys.exit("This forgets your saved phone — its apps, logins and data — and cannot "+ "be undone.\nRun: phone-harness cloud phone reset --yes")+ _api("POST", "/me/profile/reset")+ print("Your saved phone was reset. The next `cloud start` begins fresh.")+ return 0+ profile = _api("GET", "/me").get("profile") or {}+ print(json.dumps(profile, indent=2) if _flag(args, "--json") else _describe_profile(profile))+ return 0+++def _keys(args):+ if args[:1] == ["create"]:+ minted = _api("POST", "/me/keys", {"label": " ".join(args[1:]) or None})+ print(minted["key"])+ print("Shown once; store it now.", file=sys.stderr)+ return 0+ if args[:1] == ["revoke"] and len(args) == 2:+ keys = [k for k in _api("GET", "/me/keys") if k["key_hash"].startswith(args[1])]+ if len(keys) != 1:+ sys.exit(f"{args[1]!r} matches {len(keys)} keys")+ _api("POST", "/me/keys/revoke", {"key_hash": keys[0]["key_hash"]})+ print(f"Revoked {keys[0].get('hint')}")+ return 0+ keys = _api("GET", "/me/keys")+ if _flag(args, "--json"):+ print(json.dumps(keys, indent=2))+ return 0+ print(f"{'HASH':<14} {'KEY':<16} {'CREATED':<14} LABEL")+ for k in keys:+ print(f"{k['key_hash'][:12]:<14} "+ f"{k.get('hint') or '':<16} {_ago(k.get('created')):<14} {k.get('label') or ''}")+ return 0+++def _history(args):+ as_json = _flag(args, "--json")+ limit = _int(_option(args, "-n", "--limit") or 20, "-n")+ items, cursor = [], None+ while len(items) < limit:+ q = {"limit": min(100, limit - len(items)), **({"cursor": cursor} if cursor else {})}+ page = _api("GET", "/history/page?" + urllib.parse.urlencode(q))+ items += page.get("items") or []+ cursor = page.get("next_cursor")+ if not cursor:+ break+ if as_json:+ print(json.dumps(items, indent=2))+ return 0+ if not items:+ print("No finished sessions yet.")+ return 0+ print(f"{'SESSION':<14} {'ENDED':<14} {'MIN':>4} {'COST':>7} REASON")+ for h in items:+ print(f"{h.get('sid', ''):<14} {_ago(h.get('ended')):<14} "+ f"{h.get('usage_minutes', 0):>4} {_money(h.get('cost_cents')):>7} "+ f"{h.get('end_reason') or ''}")+ return 0+++# --- CLI (phone-harness cloud ...) -------------------------------------------++CLI_USAGE = """Usage:+ phone-harness cloud who is signed in, what is attached+ phone-harness cloud login [--no-browser] sign in through the browser+ phone-harness cloud logout | whoami+ phone-harness cloud start [--temp] [--minutes N]+ start your saved phone (or a throwaway one) and connect+ phone-harness cloud stop [SID|--all] [--wait]+ end it; your phone is saved for next time+ (--wait watches the save finish)+ phone-harness cloud ls [-n NUM] running sessions (* = attached)+ phone-harness cloud show [SID] one session in full+ phone-harness cloud use SID attach the helpers to another running session+ phone-harness cloud watch [SID] [--print] open the live view+ phone-harness cloud phone [reset --yes] your saved phone+ phone-harness cloud keys [create [LABEL] | revoke HASH] API keys, for CI+ phone-harness cloud history [-n NUM]+ls, show, whoami, phone, keys and history take --json. SID may be a unique prefix.+PHONE_HARNESS_CLOUD_API, _OAUTH_ISSUER, _OAUTH_CLIENT_ID and _PROXY_TOKEN point the CLI+at a Phone Harness instance of your own (or a gated one); unset, it is the public cloud.+They may live in a .env file at the repo root or in the agent workspace (never committed).+"""++_COMMANDS = {"login": _login, "logout": _logout, "whoami": _whoami, "start": _start,+ "stop": _stop, "ls": _ls, "show": _show, "use": _use, "watch": _watch,+ "phone": _phone, "keys": _keys, "history": _history}+++def cli(args):+ args = list(args)+ fn = _status if not args else _COMMANDS.get(args[0])+ if fn is None:+ print(CLI_USAGE)+ return 2+ try:+ return fn(args[1:])+ except CloudError as e:+ print(_explain(e), file=sys.stderr)+ return 1+ except OSError as e:+ print(f"Could not reach {_target('API')}: {e}", file=sys.stderr)+ return 1diff --git a/src/phone_harness/config.py b/src/phone_harness/config.pyindex 8a862d7..0254ca5 100644--- a/src/phone_harness/config.py+++ b/src/phone_harness/config.py@@ -5,10 +5,13 @@ Two kinds of thing, kept apart because they live differently:config intent — the default platform, the adb binary, how often to pokea phone awake. Hand-editable, small, worth putting in dotfiles.~/.config/phone-harness/config.json+ The cloud sign-in sits beside it, private to the user:+ ~/.config/phone-harness/auth.jsonstate what the harness learned — remembered phones and which is- primary, the pid of a running awake session. Machine-managed,- rebuildable, never worth backing up.+ primary, the attached cloud phone, the pid of a running awake+ session. Machine-managed, rebuildable, never worth backing up.~/.local/state/phone-harness/devices.json+ ~/.local/state/phone-harness/cloud.json~/.local/state/phone-harness/telemetry.json~/.local/state/phone-harness/run/awake.pid@@ -16,7 +19,10 @@ XDG_CONFIG_HOME / XDG_STATE_HOME are honoured; PHONE_HARNESS_HOME moves bothroots under one directory (tests, sandboxes).One rule for every setting: explicit argument, else environment variable,-else config file, else built-in default. `get("android.poke_every")` looks+else config file, else built-in default. A `.env` file at the repo root or+in the agent workspace is read once at import and fills in environment+variables that are not already set (the same as browser-harness): a place+for per-machine overrides such as PHONE_HARNESS_CLOUD_API, never committed. `get("android.poke_every")` looksat PHONE_HARNESS_ANDROID_POKE_EVERY, then config.json, then DEFAULTS. Envvars are per-call overrides; nothing requires them.@@ -32,6 +38,29 @@ from pathlib import PathVERSION = 1+_REPO_ROOT = Path(__file__).resolve().parent.parent.parent+++def _load_env_files():+ """KEY=value lines from <repo>/.env and <agent-workspace>/.env into the+ environment, without overriding what is already set. No dependency; a+ `#` line is a comment, quotes around a value are stripped."""+ workspace = Path(os.environ.get("PH_AGENT_WORKSPACE", _REPO_ROOT / "agent-workspace"))+ for path in (_REPO_ROOT / ".env", workspace / ".env"):+ try:+ text = path.read_text(encoding="utf-8-sig")+ except OSError:+ continue+ for line in text.splitlines():+ line = line.strip()+ if not line or line.startswith("#") or "=" not in line:+ continue+ key, value = line.split("=", 1)+ os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))+++_load_env_files()+DEFAULTS = {"platform": "ios" if sys.platform == "darwin" else "android", # iPhone needs a Mac"telemetry": True, # anonymous usage events; `config set telemetry false`@@ -40,6 +69,10 @@ DEFAULTS = {"poke_every": 25, # seconds between keep-awake pokes"mirror": True, # open scrcpy during `android awake` if installed},+ "cloud": {+ "minutes": 15, # how long `cloud start` rents a phone for+ "max_minutes": 30, # the most one `cloud start` may ask for+ },"ios": {"restore_clipboard": False, # put the old clipboard back after a paste"paste_settle": 2.0, # ...after this many seconds, if so@@ -77,7 +110,9 @@ def run_dir():def paths():return {"config": config_dir() / "config.json",+ "auth": config_dir() / "auth.json","devices": state_dir() / "devices.json",+ "cloud": state_dir() / "cloud.json","telemetry": state_dir() / "telemetry.json","run": run_dir()}diff --git a/src/phone_harness/run.py b/src/phone_harness/run.pyindex 0f89ddc..7a40c78 100644--- a/src/phone_harness/run.py+++ b/src/phone_harness/run.py@@ -16,6 +16,7 @@ Commands:phone-harness --doctor [ios|android] diagnose the phone the helpers would drivephone-harness skill print the phone-harness skill textphone-harness android ... pair/connect/choose an Android phone+ phone-harness cloud ... rent a cloud phone: `cloud login`, `cloud start`, `cloud stop`phone-harness config ... settings: `config set platform android`"""@@ -79,7 +80,7 @@ class _StreamTail:def write(self, s):self.length += len(s)- self.tail = (self.tail + s)[-self._limit:]+ self.tail = (self.tail + s)[-self._limit:] if self._limit else ""return self._wrapped.write(s)def __getattr__(self, name):@@ -94,7 +95,7 @@ def _telemetry_command(args):return "help"if first in {"--doctor", "doctor"}:return "doctor"- if first in {"android", "config", "skill"}:+ if first in {"android", "cloud", "config", "skill"}:return firstreturn "usage"@@ -140,8 +141,10 @@ def main():if not args and not sys.stdin.isatty():task = sys.stdin.read()sys.stdin = io.StringIO(task)- stderr_tail = _StreamTail(sys.stderr)- stdout_tail = _StreamTail(sys.stdout)+ # `cloud` prints account keys and viewer links; none of it is telemetry.+ tail_limit = 0 if command == "cloud" else _MAX_OUTPUT_LENGTH+ stderr_tail = _StreamTail(sys.stderr, tail_limit)+ stdout_tail = _StreamTail(sys.stdout, tail_limit)sys.stderr = stderr_tailsys.stdout = stdout_tailtry:@@ -208,6 +211,9 @@ def _run(args):if args and args[0] == "android":from .android import clisys.exit(cli(args[1:]))+ if args and args[0] == "cloud":+ from .cloud import cli+ sys.exit(cli(args[1:]))if args and args[0] == "config":from .config import clisys.exit(cli(args[1:]))diff --git a/src/phone_harness/transport.py b/src/phone_harness/transport.pyindex e27dac5..cefc73e 100644--- a/src/phone_harness/transport.py+++ b/src/phone_harness/transport.py@@ -136,7 +136,15 @@ def connect(platform=None, **kw):helpers.py binds one of these as its default."""from . import config- platform = (platform or config.get("platform")).lower()+ if platform is None:+ platform, source = config.lookup("platform")+ if not source.startswith("env:"):+ # A phone rented with `cloud start` is the one meant, even on a+ # Mac whose default is the iPhone. An explicit platform still wins.+ from . import cloud+ if cloud.attached():+ platform = "android"+ platform = platform.lower()if platform in ("ios", "iphone", "ipad"):if sys.platform != "darwin":raise RuntimeError("iPhone control needs macOS (it drives the iPhone Mirroring app); "diff --git a/tests/test_android.py b/tests/test_android.pynew file mode 100644index 0000000..d005486--- /dev/null+++ b/tests/test_android.py@@ -0,0 +1,78 @@+"""Android backend behaviour that needs no phone: the commands it would send."""+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))+from phone_harness.android import Android # noqa: E402+++class Recorded(Android):+ """An Android whose adb shell is a list."""++ def __init__(self, installed=(), fail_motionevent=False):+ super().__init__()+ self.sent, self.installed, self.fail_motionevent = [], list(installed), fail_motionevent+ self._bounds = {"x": 0, "y": 0, "w": 720, "h": 1280, "id": "fake"}++ def _gate(self):+ pass++ def _sh(self, cmd, timeout=60):+ self.sent.append(cmd)+ if self.fail_motionevent and "motionevent" in cmd:+ raise RuntimeError("Error: Unknown command: motionevent")+ if cmd.startswith("pm list packages"):+ return "\n".join(f"package:{p}" for p in self.installed)+ if cmd.startswith("cmd package resolve-activity"):+ return f"priority=0\n{cmd.split()[-1]}/.Main"+ return ""+++class Scroll(unittest.TestCase):+ def test_a_scroll_holds_still_before_lifting_so_it_cannot_fling(self):+ phone = Recorded()+ phone._input_scroll(360, 640, dy=-768, dx=0, steps=10)+ (cmd,) = phone.sent+ self.assertTrue(cmd.startswith("input motionevent DOWN 360 1024"), cmd)+ self.assertIn("sleep 0.2 && input motionevent UP 360 256", cmd)+ self.assertNotIn("input swipe", cmd)++ def test_it_goes_sideways_and_stays_on_the_glass(self):+ phone = Recorded()+ phone._input_scroll(360, 640, dy=0, dx=-2000)+ (cmd,) = phone.sent+ self.assertTrue(cmd.startswith("input motionevent DOWN 676 640"), cmd) # 94% of 720+ self.assertTrue(cmd.endswith("UP 43 640"), cmd) # 6% of 720++ def test_an_old_android_falls_back_to_a_slow_swipe_and_remembers(self):+ phone = Recorded(fail_motionevent=True)+ phone._input_scroll(360, 640, dy=-400)+ phone._input_scroll(360, 640, dy=-400)+ swipes = [c for c in phone.sent if c.startswith("input swipe")]+ self.assertEqual(len(swipes), 2)+ self.assertGreaterEqual(int(swipes[0].split()[-1]), 600)+ self.assertEqual(sum("motionevent" in c for c in phone.sent), 1) # asked once+++class Launch(unittest.TestCase):+ INSTALLED = ["com.android.chrome", "com.android.chrome.helper", "com.facebook.orca",+ "com.facebook.katana", "com.zhiliaoapp.musically", "com.whatsapp"]++ def launched(self, name):+ phone = Recorded(self.INSTALLED)+ return phone._apps_launch(name), phone.sent[-1]++ def test_names_people_say(self):+ for name, pkg in [("TikTok", "com.zhiliaoapp.musically"), ("tik tok", "com.zhiliaoapp.musically"),+ ("Facebook", "com.facebook.katana"), ("Messenger", "com.facebook.orca"),+ ("chrome", "com.android.chrome"), ("WhatsApp", "com.whatsapp"),+ ("com.whatsapp", "com.whatsapp")]:+ with self.subTest(name=name):+ got, last = self.launched(name)+ self.assertEqual(got, pkg)+ self.assertEqual(last, f"am start -W -n {pkg}/.Main")+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_backend_contract.py b/tests/test_backend_contract.pynew file mode 100644index 0000000..a7e8b42--- /dev/null+++ b/tests/test_backend_contract.py@@ -0,0 +1,68 @@+"""Every op the helpers send must be accepted by every backend.++helpers.py is shared; each backend implements the ops on its own. Nothing else+ties the two together, so a keyword added for one phone (`dx` for a sideways+scroll, `keystrokes` for typing) used to break the other with a TypeError the+first time an agent called it. This reads the calls out of helpers.py and+checks each backend's signature against them. No phone needed.++ python -m unittest discover tests+"""+import ast+import importlib+import inspect+import sys+import unittest+from pathlib import Path++SRC = Path(__file__).resolve().parents[1] / "src"+sys.path.insert(0, str(SRC))+++def sent_by_helpers():+ """{op: set of keyword names} for every send("op", kw=...) in helpers.py."""+ ops = {}+ for node in ast.walk(ast.parse((SRC / "phone_harness" / "helpers.py").read_text())):+ if (isinstance(node, ast.Call) and getattr(node.func, "id", None) == "send"+ and node.args and isinstance(node.args[0], ast.Constant)):+ ops.setdefault(node.args[0].value, set()).update(+ k.arg for k in node.keywords if k.arg)+ return ops+++def backends():+ from phone_harness.android import Android+ found = {"android": Android}+ if sys.platform == "darwin":+ try:+ found["ios"] = importlib.import_module("phone_harness.ios").IPhone+ except ImportError:+ pass # no pyobjc here: Android is still checked+ return found+++class BackendContract(unittest.TestCase):+ def test_helpers_send_something(self):+ ops = sent_by_helpers()+ self.assertIn("input.scroll", ops)+ self.assertIn("dx", ops["input.scroll"])++ def test_every_backend_accepts_what_the_helpers_send(self):+ problems = []+ for name, cls in backends().items():+ for op, kwargs in sorted(sent_by_helpers().items()):+ method = getattr(cls, "_" + op.replace(".", "_"), None)+ if method is None:+ continue # Unsupported is an honest answer+ params = inspect.signature(method).parameters+ if any(p.kind is p.VAR_KEYWORD for p in params.values()):+ continue+ missing = kwargs - set(params)+ if missing:+ problems.append(f"{name}: {op} is sent {sorted(missing)} "+ f"but {method.__qualname__} does not take it")+ self.assertEqual(problems, [])+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_cloud.py b/tests/test_cloud.pynew file mode 100644index 0000000..91b9a8a--- /dev/null+++ b/tests/test_cloud.py@@ -0,0 +1,325 @@+"""`phone-harness cloud` against a fake API and a fake adb. No network, no credits.++ python -m unittest discover tests+"""+import json+import os+import stat+import subprocess+import sys+import tempfile+import threading+import time+import unittest+import urllib.parse+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path++SRC = str(Path(__file__).resolve().parents[1] / "src")++FAKE_ADB = r'''#!/bin/sh+# Locked until `shell unlock CODE`; state is a file next to this script.+DIR="$(dirname "$0")"+echo "$@" >> "$DIR/adb.log"+[ "$1" = "-s" ] && shift 2+case "$1" in+ connect) touch "$DIR/connected"; echo "connected to $2" ;;+ disconnect) rm -f "$DIR/connected" "$DIR/unlocked"; echo "disconnected $2" ;;+ shell)+ [ -f "$DIR/connected" ] || { echo "adb: device not found" >&2; exit 1; }+ if [ "$2" = "unlock" ]; then+ [ "$3" = "ph_code" ] && { touch "$DIR/unlocked"; echo unlocked; } || echo "wrong code"+ elif [ -f "$DIR/unlocked" ]; then shift; sh -c "$*"+ else echo locked; fi ;;+esac+'''+++class FakeCloud(BaseHTTPRequestHandler):+ sessions, profile, polls, posts = {}, {}, {}, []+ valid, token_polls, refreshes, revoked = set(), 0, 0, []+ closing_reads = 0+ seen_headers = []++ def _oauth(self, path, form):+ c = FakeCloud+ if path == "/oauth/device_authorization":+ assert form["client_id"] == "cli-client" and "offline_access" in form["scope"]+ return self._send(200, {"device_code": "dev-1", "user_code": "BCDF-GHJK",+ "verification_uri": "https://accounts.example/device",+ "expires_in": 600, "interval": 0})+ if path == "/oauth/token/revoke":+ c.revoked.append(form["token"])+ c.valid.discard(form["token"])+ return self._send(200, {})+ if form["grant_type"] == "refresh_token":+ if form["refresh_token"] != "rt-1":+ return self._send(400, {"error": "invalid_grant"})+ c.refreshes += 1+ token = f"at-refreshed-{c.refreshes}"+ else:+ c.token_polls += 1+ if c.token_polls < 2: # the user has not clicked yet+ return self._send(400, {"error": "authorization_pending"})+ token = "at-1"+ c.valid.add(token)+ return self._send(200, {"access_token": token, "refresh_token": "rt-1",+ "expires_in": 86400})++ def log_message(self, *a):+ pass++ def _send(self, status, body):+ raw = json.dumps(body).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(raw)))+ self.end_headers()+ self.wfile.write(raw)++ def _handle(self):+ c = FakeCloud+ n = int(self.headers.get("Content-Length") or 0)+ raw = self.rfile.read(n) if n else b""+ path, m = self.path.split("?")[0], self.command+ if path.startswith("/oauth/"):+ return self._oauth(path, dict(urllib.parse.parse_qsl(raw.decode())))+ c.seen_headers.append(dict(self.headers))+ if self.headers.get("Authorization", "")[7:] not in c.valid:+ return self._send(401, {"error": "unauthorized"})+ body = json.loads(raw) if raw else {}+ if (m, path) == ("GET", "/me"):+ if c.closing_reads:+ c.closing_reads -= 1+ if not c.closing_reads:+ c.sessions.pop(c.profile["session"], None)+ c.profile.update(state="stored", session=None)+ return self._send(200, {"uid": "u1", "email": "[email protected]", "balance_cents": 425,+ "price_cents_per_minute": 5, "can_rent": True,+ "active_session_count": len(c.sessions),+ "session_limit": 3, "profile": c.profile})+ if (m, path) == ("POST", "/sessions"):+ c.posts.append(body)+ if body.get("profile_id") and c.profile["state"] == "running":+ return self._send(409, {"error": "held", "code": "profile_running",+ "session": c.profile["session"]})+ sid = f"sid{len(c.posts):03d}"+ c.sessions[sid] = {"id": sid, "state": "provisioning",+ "profile": body.get("profile_id"),+ "expires_at": time.time() + body["timeout_seconds"],+ "watch_url": "https://watch.example/secret"}+ if body.get("profile_id"):+ c.profile.update(state="running", session=sid)+ return self._send(202, c.sessions[sid])+ if (m, path) == ("GET", "/sessions"):+ return self._send(200, list(c.sessions.values()))+ sid = path.rsplit("/", 1)[-1]+ if path.startswith("/sessions/") and sid in c.sessions:+ if m == "GET":+ c.polls[sid] = c.polls.get(sid, 0) + 1+ if c.polls[sid] >= 2:+ c.sessions[sid].update(state="ready", startup={"startup": "exact"}, adb={+ "host": "live.example", "port": 22220, "code": "ph_code"})+ return self._send(200, c.sessions[sid])+ if m == "DELETE":+ if c.sessions.pop(sid).get("profile"):+ c.profile.update(state="stored", session=None, saved_at=time.time())+ return self._send(200, {"released": True})+ return self._send(404, {"error": "not found"})++ do_GET = do_POST = do_DELETE = _handle+++class CloudCli(unittest.TestCase):+ def setUp(self):+ self.home = tempfile.TemporaryDirectory()+ self.addCleanup(self.home.cleanup)+ adb = Path(self.home.name) / "adb"+ adb.write_text(FAKE_ADB)+ adb.chmod(adb.stat().st_mode | stat.S_IEXEC)+ FakeCloud.sessions, FakeCloud.polls, FakeCloud.posts = {}, {}, []+ FakeCloud.valid, FakeCloud.token_polls = set(), 0+ FakeCloud.refreshes, FakeCloud.revoked, FakeCloud.closing_reads = 0, [], 0+ FakeCloud.profile = {"id": "prof-1", "state": "stored", "session": None,+ "saved_at": time.time() - 7200}+ self.server = ThreadingHTTPServer(("127.0.0.1", 0), FakeCloud)+ threading.Thread(target=self.server.serve_forever, daemon=True).start()+ self.addCleanup(self.server.server_close)+ self.addCleanup(self.server.shutdown)+ self.env = {**os.environ, "PYTHONPATH": SRC, "PHONE_HARNESS_HOME": self.home.name,+ "PHONE_HARNESS_ADB": str(adb), "PHONE_HARNESS_TELEMETRY": "0",+ "PHONE_HARNESS_CLOUD_API": f"http://127.0.0.1:{self.server.server_port}",+ "PHONE_HARNESS_CLOUD_OAUTH_ISSUER": f"http://127.0.0.1:{self.server.server_port}",+ "PHONE_HARNESS_CLOUD_OAUTH_CLIENT_ID": "cli-client"}+ for name in ("PHONE_HARNESS_API_KEY", "ANDROID_SERIAL", "PHONE_HARNESS_PLATFORM"):+ self.env.pop(name, None)++ def run_cli(self, *args, stdin=None, env=None):+ return subprocess.run([sys.executable, "-m", "phone_harness.run", *args], input=stdin,+ capture_output=True, text=True, env={**self.env, **(env or {})})++ def login(self):+ r = self.run_cli("cloud", "login", "--no-browser")+ self.assertEqual(r.returncode, 0, r.stderr)+ return r++ def adb_log(self):+ return (Path(self.home.name) / "adb.log").read_text()++ def test_needs_login(self):+ r = self.run_cli("cloud", "start")+ self.assertEqual(r.returncode, 1)+ self.assertIn("phone-harness cloud login", r.stderr)++ def auth(self):+ return json.loads((Path(self.home.name) / "config" / "auth.json").read_text())++ def test_login_is_a_device_flow_and_the_tokens_stay_private(self):+ r = self.login()+ self.assertIn("BCDF-GHJK", r.stdout)+ self.assertIn("https://accounts.example/device", r.stdout)+ self.assertIn("Signed in as [email protected]", r.stdout)+ self.assertNotIn("at-1", r.stdout)+ self.assertEqual(self.auth()["access_token"], "at-1")+ path = Path(self.home.name) / "config" / "auth.json"+ self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o600)++ def test_an_expired_or_refused_token_is_refreshed_silently(self):+ self.login()+ record = {**self.auth(), "expires_at": time.time() - 5}+ (Path(self.home.name) / "config" / "auth.json").write_text(json.dumps(record))+ self.assertIn("[email protected]", self.run_cli("cloud", "whoami").stdout)+ self.assertEqual(self.auth()["access_token"], "at-refreshed-1")+ FakeCloud.valid.clear() # refused before its expiry+ self.assertIn("[email protected]", self.run_cli("cloud", "whoami").stdout)+ self.assertEqual(FakeCloud.refreshes, 2)++ def test_logout_revokes_and_forgets(self):+ self.login()+ self.assertEqual(self.run_cli("cloud", "logout").returncode, 0)+ self.assertEqual(FakeCloud.revoked, ["rt-1", "at-1"])+ self.assertIn("cloud login", self.run_cli("cloud", "whoami").stderr)++ def test_a_dotenv_in_the_agent_workspace_fills_in_unset_variables(self):+ FakeCloud.valid.add("pck_ci")+ ws = Path(self.home.name) / "workspace"+ ws.mkdir()+ (ws / ".env").write_text("# per-machine overrides\n"+ "PHONE_HARNESS_API_KEY=pck_ci\n"+ "PHONE_HARNESS_CLOUD_API='http://127.0.0.1:1'\n") # loses to the real env+ r = self.run_cli("cloud", "whoami", env={"PH_AGENT_WORKSPACE": str(ws)})+ self.assertIn("[email protected]", r.stdout, r.stderr)++ def test_a_proxy_token_rides_along_as_the_gate_header(self):+ FakeCloud.valid.add("pck_ci")+ FakeCloud.seen_headers = []+ r = self.run_cli("cloud", "whoami", env={"PHONE_HARNESS_API_KEY": "pck_ci",+ "PHONE_HARNESS_CLOUD_PROXY_TOKEN": "gate-1"})+ self.assertIn("[email protected]", r.stdout)+ self.assertIn("Bearer gate-1", [h.get("X-Exedev-Authorization") for h in FakeCloud.seen_headers])+ self.assertNotIn("gate-1", r.stdout)++ def test_an_api_key_in_the_environment_is_used_for_ci(self):+ FakeCloud.valid.add("pck_ci")+ r = self.run_cli("cloud", "whoami", env={"PHONE_HARNESS_API_KEY": "pck_ci"})+ self.assertIn("[email protected]", r.stdout)++ def test_start_uses_the_saved_phone_and_connects(self):+ self.login()+ r = self.run_cli("cloud", "start", "--minutes", "5")+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertEqual(FakeCloud.posts, [{"timeout_seconds": 300, "profile_id": "prof-1"}])+ self.assertIn("Resumed exactly", r.stdout)+ self.assertNotIn("ph_code", r.stdout)+ self.assertNotIn("watch.example", r.stdout)+ log = self.adb_log()+ self.assertIn("connect live.example:22220", log)+ self.assertIn("shell unlock ph_code", log)++ again = self.run_cli("cloud", "start") # idempotent: no second phone+ self.assertEqual(again.returncode, 0, again.stderr)+ self.assertEqual(len(FakeCloud.posts), 1)++ ls = self.run_cli("cloud", "ls")+ self.assertIn("* sid001", ls.stdout)++ def test_temp_phone_and_minutes_cap(self):+ self.login()+ self.assertEqual(self.run_cli("cloud", "start", "--temp").returncode, 0)+ self.assertEqual(FakeCloud.posts, [{"timeout_seconds": 900}])+ over = self.run_cli("cloud", "start", "--minutes", "999")+ self.assertEqual(over.returncode, 1)+ self.assertIn("between 1 and 30", over.stderr)++ def test_attaches_when_the_phone_already_runs_elsewhere(self):+ self.login()+ FakeCloud.sessions["dash01"] = {+ "id": "dash01", "state": "ready", "profile": "prof-1",+ "expires_at": time.time() + 600,+ "adb": {"host": "live.example", "port": 22220, "code": "ph_code"}}+ FakeCloud.profile.update(state="running", session="dash01")+ r = self.run_cli("cloud", "start")+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertIn("already running", r.stdout)+ self.assertEqual(FakeCloud.posts, [])++ def test_helpers_drive_the_rented_phone_and_relock_is_healed(self):+ self.login()+ self.run_cli("cloud", "start")+ home = self.home.name+ script = ("import os\n"+ "from phone_harness import transport\n"+ "p = transport.connect()\n"+ "print(p.name, p._sh('echo hello').strip())\n"+ f"os.unlink({home!r} + '/unlocked')\n" # relocked mid-script+ "print(p._sh('echo again').strip())\n"+ f"os.unlink({home!r} + '/connected')\n" # dropped mid-script+ "print(p._sh('echo back').strip())\n")+ r = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True,+ env=self.env)+ self.assertEqual(r.stdout.split(), ["android", "hello", "again", "back"], r.stderr)+ (Path(home) / "unlocked").unlink() # and between two runs+ r = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True,+ env=self.env)+ self.assertEqual(r.stdout.split()[:2], ["android", "hello"], r.stderr)++ def test_start_waits_out_a_phone_that_is_still_closing(self):+ self.login()+ FakeCloud.sessions["old001"] = {"id": "old001", "state": "closing", "profile": "prof-1",+ "expires_at": time.time() + 600}+ FakeCloud.profile.update(state="running", session="old001")+ FakeCloud.closing_reads = 2 # then it is saved+ r = self.run_cli("cloud", "start")+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertIn("still saving", r.stdout)+ self.assertEqual(FakeCloud.posts, [{"timeout_seconds": 900, "profile_id": "prof-1"}])++ def test_stop_returns_at_once_and_detaches(self):+ self.login()+ self.run_cli("cloud", "start")+ started = time.monotonic()+ r = self.run_cli("cloud", "stop")+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertLess(time.monotonic() - started, 2.5) # no polling for the save+ self.assertIn("billing stopped", r.stdout)+ self.assertIn("being saved", r.stdout)+ self.assertEqual(FakeCloud.sessions, {})+ state = json.loads((Path(self.home.name) / "state" / "cloud.json").read_text())+ self.assertNotIn("session", state)+ self.assertIn("none attached", self.run_cli("cloud").stdout)++ def test_stop_wait_watches_the_save(self):+ self.login()+ self.run_cli("cloud", "start")+ r = self.run_cli("cloud", "stop", "--wait")+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertIn("stored", r.stdout)++ def test_a_temporary_phone_has_nothing_to_save(self):+ self.login()+ self.run_cli("cloud", "start", "--temp")+ r = self.run_cli("cloud", "stop")+ self.assertNotIn("saved", r.stdout)++if __name__ == "__main__":+ unittest.main()