let your agent control your phone
A dead cloud phone no longer falls through to another phone (#117)
shawn pana21bfb8e88949
diff --git a/SKILL.md b/SKILL.mdindex 32075b2..9d81ffa 100644--- a/SKILL.md+++ b/SKILL.md@@ -183,6 +183,20 @@ phone-harness cloud open # the dashboard: the user takes the- **`cloud phone` is the saved Android only** (`GET /me/profile`).`cloud phone reset --yes` wipes that phone's stored state: apps, logins,and data. The CLI has no iPhone reset; that is the operator's.+- **A cloud session that ends does not hand you another phone.** If the+ session attached to this script expires, the error says `session <sid> expired`.+ If the service loses it, the error says the cloud phone failed and is+ unreachable. Either way the script stops. It does not drive the personal+ phone, and the CLI does not rent a replacement. Start the same catalog+ phone again with a longer duration and continue the task:+ `phone-harness cloud start <same phone> --for <longer>`. `<same phone>` is+ that phone's id or label (or `ios` / `android` when only one entry has that+ platform). `<longer>` is a duration longer than the session that just+ ended (`90s`, `15m`, or a number of minutes). A `--session` pin whose+ session expired is the same error, naming that sid. A missing cloud state+ file still means no cloud phone was attached, and the personal phone is+ used as today. An unreadable state file is an error, not a cue to switch+ phones. `cloud stop` clears the failure; a new `cloud start` does too.- The adb address the CLI shows is not a secret; the unlock code is. Do notlook for it, print it, or ask the user for it.@@ -340,6 +354,11 @@ PY- Connecting a desk phone is the user's job (USB debugging + Allow, orWireless debugging + `phone-harness android pair CODE`); on `no-device` theerror names the missing step - relay it, don't retry-loop.+- **A saved primary that is unreachable is a failure, not a different phone.**+ If `phone-harness android use` has named a primary and that phone cannot+ be reached, the error says the primary is unreachable. Do not expect the+ harness to connect some other paired or mDNS phone instead. When no+ primary is configured, a USB phone that is plugged in is still used.## iPhone (iPhone Mirroring)diff --git a/src/phone_harness/android.py b/src/phone_harness/android.pyindex f0efb38..9b5b41e 100644--- a/src/phone_harness/android.py+++ b/src/phone_harness/android.py@@ -13,10 +13,13 @@ Connecting is the phone's own developer path, over USB or Wi-Fi:Wireless Developer options > Wireless debugging > Pair device withpairing code, then: phone-harness android pair CODE-The agent never picks a device. session.require — which every helper passes-through — resolves one: a USB phone if one is plugged in, else a live-wireless link (the saved primary first), else a paired phone found on the-LAN over mDNS and connected on the spot, else a message naming the physical+The agent never picks a device. session.require, which every helper passes+through, resolves one: an explicit ANDROID_SERIAL, else a cloud phone from+`cloud start`, else the saved primary and only that phone. If a primary is+set and cannot be reached, this fails and says it is unreachable instead of+connecting a different paired or mDNS phone. When no primary is configured,+a USB phone that is plugged in is used, else a live wireless link, else a+paired phone found on the LAN over mDNS, else a message naming the physicalstep that is missing. Paired phones areremembered (see config.py: the devices state file) under a friendly name andmatched by hardware serial, so a phone whose Wi-Fi port changed overnight is@@ -110,6 +113,21 @@ def _prop(adb_id, name):return _run("-s", adb_id, "shell", "getprop", name, timeout=15).strip()+def _ready_id_for_serial(serial):+ """The adb id of a device that is already up and has this hardware serial."""+ if not serial:+ return None+ for adb_id, state, _transport in _attached():+ if state != "device":+ continue+ try:+ if _prop(adb_id, "ro.serialno") == serial:+ return adb_id+ except RuntimeError:+ pass+ return None++def _mdns(kind="connect"):"""Phones announcing themselves on the LAN: [{serial, host, port, addr}]for _adb-tls-connect services (paired phones with Wireless debugging on)@@ -170,6 +188,10 @@ class TreeUnavailable(RuntimeError):"""uiautomator would not dump this screen; retrying will not change that."""+class PrimaryUnreachable(RuntimeError):+ """The saved primary phone is not reachable. Not a cue to use another."""++class Android(Backend):name = "android"@@ -212,15 +234,16 @@ class Android(Backend):# --- choosing the phone -------------------------------------------------def _resolve(self):- """Pin ANDROID_SERIAL to one ready device, connecting a paired phone- over Wi-Fi if nothing is attached. Returns the adb id or None.+ """Pin ANDROID_SERIAL to one ready device. Returns the adb id, or+ None when no phone is configured and none is plugged in.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 (wired- always wins — it is right there); then a live Wi-Fi link, the saved- primary first; then mDNS — the primary if it is on the LAN, else the- first known phone, else any paired phone."""+ `phone-harness cloud start`; then, when a primary is saved, only that+ phone. A different paired or mDNS phone is not a stand-in: if the+ primary cannot be reached this raises. When no primary is configured,+ a USB phone wins, then a live Wi-Fi link, then any paired phone mDNS+ can see.+ """if os.environ.get("ANDROID_SERIAL"):self._resolved = Truereturn os.environ["ANDROID_SERIAL"]@@ -232,46 +255,61 @@ class Android(Backend):self._resolved = Truereturn os.environ["ANDROID_SERIAL"]cfg = _load()- primary = (cfg.get("phones") or {}).get(cfg.get("primary") or "", {})+ primary_name = cfg.get("primary") or ""+ primary = (cfg.get("phones") or {}).get(primary_name, {}) if primary_name else {}known = {p.get("serial") for p in (cfg.get("phones") or {}).values()}+ def finish(chosen):+ os.environ["ANDROID_SERIAL"] = chosen+ self._resolved = True+ try:+ _remember(cfg, _prop(chosen, "ro.serialno"),+ _prop(chosen, "ro.product.model"),+ host=chosen.rpartition(":")[0] if ":" in chosen else None)+ except RuntimeError:+ pass+ return chosen++ if primary_name:+ serial = primary.get("serial")+ chosen = _ready_id_for_serial(serial) if serial else None+ if chosen is None and serial:+ for service in _mdns():+ if service.get("serial") != serial:+ continue+ out = _run("connect", service["addr"], timeout=15, check=False)+ if "connected" in out and "cannot" not in out:+ break+ chosen = _ready_id_for_serial(serial)+ if chosen is None:+ raise PrimaryUnreachable(+ f"The primary Android phone {primary_name!r} is unreachable. "+ "This did not connect to another phone.")+ return finish(chosen)+def pick(ready):usb = [r for r in ready if r[2] == "usb"]if usb:return usb[0][0]wifi = [r for r in ready if r[2] == "wifi"]- if primary.get("serial"):- for adb_id, _, _ in wifi:- try:- if _prop(adb_id, "ro.serialno") == primary["serial"]:- return adb_id- except RuntimeError:- passreturn wifi[0][0] if wifi else Noneready = [r for r in _attached() if r[1] == "device"]chosen = pick(ready)if chosen is None:- wanted = [primary.get("serial")] + sorted(known - {primary.get("serial")})+ wanted = sorted(s for s in known if s)services = _mdns()services.sort(key=lambda s: (wanted.index(s["serial"])if s["serial"] in wanted else len(wanted)))- for s in services:- out = _run("connect", s["addr"], timeout=15, check=False)+ for service in services:+ out = _run("connect", service["addr"], timeout=15, check=False)if "connected" in out and "cannot" not in out:breakready = [r for r in _attached() if r[1] == "device"]chosen = pick(ready)if chosen is not None:- os.environ["ANDROID_SERIAL"] = chosen- self._resolved = True- try:- _remember(cfg, _prop(chosen, "ro.serialno"),- _prop(chosen, "ro.product.model"),- host=chosen.rpartition(":")[0] if ":" in chosen else None)- except RuntimeError:- pass- return chosen+ return finish(chosen)+ return None# --- awake and unlocked? -----------------------------------------------@@ -545,6 +583,7 @@ class Android(Backend):def _session_state(self):"""'ready' | 'locked' | 'unauthorized' | 'offline' | 'no-device' | 'no-adb'."""+ from .cloud import CloudPhoneErrortry:if self._resolve() is not None:try:@@ -555,6 +594,8 @@ class Android(Backend):raisereturn "ready"states = [st for _, st, _ in _attached()]+ except (PrimaryUnreachable, CloudPhoneError):+ raiseexcept (RuntimeError, FileNotFoundError):return "no-adb"if "unauthorized" in states:diff --git a/src/phone_harness/cloud.py b/src/phone_harness/cloud.pyindex 42d3c3d..af47cc5 100644--- a/src/phone_harness/cloud.py+++ b/src/phone_harness/cloud.py@@ -38,6 +38,14 @@ LOW_TIME = 120 # warn the script when the session has less than this leftUSER_AGENT = "phone-harness-cli"+class CloudPhoneError(RuntimeError):+ """A cloud phone was attached and cannot be driven.++ Callers must surface this. Returning None would look like no cloud phone+ was ever attached, and the next line of code would drive a different one.+ """++class CloudError(RuntimeError):def __init__(self, status, body, headers=None):self.status = status@@ -88,7 +96,31 @@ def _state_path():def _load_state():- return config._read(_state_path(), {})+ """The cloud state file, or {} when this machine has never had one.++ A file that exists but cannot be read is an error. Treating it as empty+ would drop the attached session and let a script drive some other phone.+ """+ path = _state_path()+ try:+ text = path.read_text()+ except FileNotFoundError:+ return {}+ except OSError as e:+ raise CloudPhoneError(+ f"the cloud state file {path} is unreadable ({e}). "+ "This did not fall back to another phone.") from None+ try:+ data = json.loads(text)+ except ValueError as e:+ raise CloudPhoneError(+ f"the cloud state file {path} is unreadable ({e}). "+ "This did not fall back to another phone.") from None+ if not isinstance(data, dict):+ raise CloudPhoneError(+ f"the cloud state file {path} is unreadable (not an object). "+ "This did not fall back to another phone.")+ return datadef _save_state(state):@@ -285,6 +317,93 @@ def _find_recorded(state, pin):return hits[0] if len(hits) == 1 else None+def _expired(sess):+ return bool(sess and sess.get("expires_at") and time.time() >= sess["expires_at"])+++def _pin_hits(sid, pin):+ return bool(sid and pin and (sid == pin or str(sid).startswith(pin)))+++def _quote_arg(name):+ if name and all(c.isalnum() or c in "_.:+@-" for c in name):+ return name+ return '"' + str(name).replace('"', "") + '"'+++def _start_target(rec):+ """The catalog name a later `cloud start` uses for this same phone.++ None means a bare `cloud start` (the unnamed choice). A label or id is+ what the catalog command accepts; `ios` / `android` only when that is+ all we still know.+ """+ rec = rec or {}+ sel = rec.get("selector") or ""+ if sel == "unnamed":+ return None+ label = str(rec.get("label") or "").strip()+ if label:+ return _quote_arg(label)+ device = str(rec.get("device_id") or "").strip()+ if device:+ return _quote_arg(device)+ if sel.startswith("id:") and sel[3:].strip():+ return _quote_arg(sel[3:].strip())+ if sel.startswith("label:") and sel[6:].strip():+ return _quote_arg(sel[6:].strip())+ if sel == "temporary":+ return None+ platform = rec.get("platform")+ if platform in ("ios", "android"):+ return platform+ return None+++def restart_command(rec):+ """`cloud start` of the same phone, for a longer duration than the one that ended."""+ target = _start_target(rec)+ if target:+ return f"phone-harness cloud start {target} --for <longer>"+ return "phone-harness cloud start --for <longer>"+++def _ended_record(rec, cause, at=None):+ rec = rec or {}+ return {+ "sid": rec.get("sid"),+ "platform": rec.get("platform"),+ "label": rec.get("label"),+ "device_id": rec.get("device_id"),+ "selector": rec.get("selector"),+ "expires_at": rec.get("expires_at"),+ "cause": cause,+ "at": time.time() if at is None else at,+ }+++def ended_message(rec):+ """What a script should show, and the one next command.++ Expiry is named `expired`. Anything else (the service lost the session,+ the state file says it is gone) is named `failed` and `unreachable`.+ The CLI does not rent a replacement itself.+ """+ rec = rec or {}+ cause = "expired" if rec.get("cause") == "expired" or _expired(rec) else "unreachable"+ sid = rec.get("sid") or "unknown"+ if cause == "expired":+ lead = f"session {sid} expired"+ else:+ lead = f"session {sid} failed: the cloud phone is unreachable"+ cmd = restart_command(rec)+ return (f"{lead}. This script did not switch to another phone. "+ f"Start the same phone again for longer and continue the task: `{cmd}`. "+ "Replace <longer> with a duration longer than the session that just ended "+ "(`90s`, `15m`, or a number of minutes). "+ "The CLI does not rent a phone by itself.")++def attached(kind=None):"""The session the helpers should drive, or None; with `kind`, only asession reached that way.@@ -292,28 +411,34 @@ def attached(kind=None):`PHONE_HARNESS_SESSION` (or `--session`, which sets it) pins one sessionfor this process, so parallel agents do not share the state file'sfallback. With neither, the fallback is the attached session a person at- a terminal last started or `cloud use`d. The unpinned read does no- network and never raises. A pin that is not on disk is fetched once."""- try:- state = _load_state()- except Exception:- state = {}+ a terminal last started or `cloud use`d. A pin that is not on disk is+ fetched once.++ None means no cloud phone was attached. A pin whose session has expired+ raises `session <sid> expired` instead of returning None, and an+ unreadable state file raises too: both used to look like "no cloud phone"+ and the next call drove a different device. An unpinned session whose+ clock has run out still returns None; `lost()` tells `connect` to raise.+ """+ state = _load_state()pin = os.environ.get("PHONE_HARNESS_SESSION")if pin:raw = _find_recorded(state, pin)sess = _as_linked(raw)if sess is None:+ gone = state.get("gone")+ if isinstance(gone, dict) and _pin_hits(gone.get("sid"), pin):+ raise CloudPhoneError(ended_message(gone))sess = _pull_pinned(pin)+ if _expired(sess):+ raise CloudPhoneError(ended_message(_ended_record(sess, "expired")))else:- try:- sess = _as_linked(state.get("session"))- except Exception:- return None+ sess = _as_linked(state.get("session"))if sess is None:return Noneif kind not in (None, sess["link"]["kind"]):return None- if sess.get("expires_at") and time.time() >= sess["expires_at"]:+ if _expired(sess):return Nonereturn sess@@ -426,7 +551,8 @@ def _session_record(session, selector=None, label=None):def _store_session(record, make_attached=True):"""Remember a session. `make_attached` updates the terminal fallback.Every remembered session stays addressable by `--session`, so a later- start does not forget the previous phone."""+ start does not forget the previous phone. Storing one clears a previous+ "gone" mark: the user has a phone again."""state = _load_state()sessions = _known_sessions(state)sessions[record["sid"]] = record@@ -435,6 +561,7 @@ def _store_session(record, make_attached=True):state["session"] = recordif make_attached and record.get("profile"):state["profile_id"] = record["profile"]+ state.pop("gone", None)_save_state(state)if record["link"]["kind"] == "adb":ensure_connected(record, quiet=True)@@ -469,7 +596,15 @@ def _pull_pinned(pin):return _store_session(_session_record(session), make_attached=False)-def _detach(sid=None):+def _detach(sid=None, gone=False):+ """Forget a remembered session.++ `gone=True` means the service lost the attached one (it failed, or it+ expired) rather than the user ending it. That session is remembered+ under "gone" so the helpers refuse to run instead of driving the phone+ on this machine. A plain detach (the user's `cloud stop`) clears that+ too. Other remembered sessions stay addressable by `--session`.+ """state = _load_state()sessions = _known_sessions(state)current = state.get("session") if isinstance(state.get("session"), dict) else None@@ -478,6 +613,7 @@ def _detach(sid=None):sids = [targeted["sid"]] if targeted and targeted.get("sid") else []else:sids = [sid]+ removed_attached = Nonefor target in sids:rec = _as_linked(sessions.get(target))if rec is None and current and current.get("sid") == target:@@ -490,15 +626,38 @@ def _detach(sid=None):passsessions.pop(target, None)if current and current.get("sid") == target:+ if gone:+ removed_attached = rec or currentstate.pop("session", None)current = Noneif sessions:state["sessions"] = sessionselse:state.pop("sessions", None)+ if gone and removed_attached:+ cause = "expired" if _expired(removed_attached) else "unreachable"+ state["gone"] = _ended_record(removed_attached, cause)+ if not gone:+ state.pop("gone", None)_save_state(state)+def lost():+ """A session that was attached and is no longer usable, or None.++ Either the service said it was gone, or its expiry passed while it was+ still attached. `cause` is `expired` or `unreachable`. No network. An+ unreadable state file raises; it is not "no session"."""+ state = _load_state()+ gone = state.get("gone")+ if isinstance(gone, dict) and gone.get("sid"):+ return gone+ sess = state.get("session") if isinstance(state.get("session"), dict) else None+ if _expired(sess):+ return _ended_record(sess, "expired", at=sess.get("expires_at"))+ return None++# --- small things ------------------------------------------------------------def _flag(args, name):@@ -852,6 +1011,8 @@ def _reusable(selector):still provisioning or ready. None when this start should create one."""try:state = _load_state()+ except CloudPhoneError:+ raiseexcept Exception:return Noneseen = set()@@ -948,6 +1109,8 @@ def _start(args):# Another session may keep running. Say so, and how to aim at it again.try:previous = _as_linked(_load_state().get("session"))+ except CloudPhoneError:+ raiseexcept Exception:previous = Noneif previous and previous.get("selector") != selector:@@ -1068,7 +1231,11 @@ def _status(args):print(f"signed in {me.get('email') or me.get('uid')}")print(f"credit {_credit(me)}")profile = me.get("profile") or {}- sess = attached()+ try:+ sess = attached()+ except CloudPhoneError as e:+ print(e)+ return 1live = Noneif sess:try:@@ -1082,14 +1249,19 @@ def _status(args):profile = {**profile, "state": "saving"}print(f"phone {_describe_profile(profile)}")if not sess:+ lost_rec = lost()+ if lost_rec:+ print(ended_message(lost_rec))+ return 1running = me.get("active_session_count") or 0print("session none attached" + (f" ({running} running: `phone-harness cloud ls`)"if running else " — `phone-harness cloud start`"))return 0if live is None:- print(f"session {sess['sid']} is gone; detaching")- _detach()- return 0+ cause = "expired" if _expired(sess) else "unreachable"+ print(ended_message(_ended_record(sess, cause)))+ _detach(gone=True)+ return 1state = ("closing — saving the phone"if live["state"] == "closing" and _keeps_state(live)else live["state"])diff --git a/src/phone_harness/transport.py b/src/phone_harness/transport.pyindex 25f5802..fe4aaf0 100644--- a/src/phone_harness/transport.py+++ b/src/phone_harness/transport.py@@ -148,6 +148,14 @@ def connect(platform=None, **kw):return Remote(rented["link"]["url"], rented["link"]["token"])if rented:platform = "android"+ else:+ # The agent was driving a cloud phone and it ended. Falling+ # through would run the next script on whatever phone is on+ # this desk. Say so, and name the command that starts the+ # same catalog phone again. This does not rent one itself.+ lost = cloud.lost()+ if lost:+ raise cloud.CloudPhoneError(cloud.ended_message(lost))platform = platform.lower()if platform in ("ios", "iphone", "ipad"):if sys.platform != "darwin":diff --git a/tests/test_android.py b/tests/test_android.pyindex 4455ad8..cf5376e 100644--- a/tests/test_android.py+++ b/tests/test_android.py@@ -1,4 +1,5 @@"""Android backend behaviour that needs no phone: the commands it would send."""+import osimport sysimport unittestimport unittest.mock@@ -136,5 +137,122 @@ class Launch(unittest.TestCase):self.assertEqual(last, f"am start -W -n {pkg}/.Main")+class ResolvePrimary(unittest.TestCase):+ """A saved primary that is gone is a failure. Another paired phone is not a substitute."""++ def setUp(self):+ self._saved = os.environ.pop("ANDROID_SERIAL", None)++ def tearDown(self):+ os.environ.pop("ANDROID_SERIAL", None)+ if self._saved is not None:+ os.environ["ANDROID_SERIAL"] = self._saved++ def phone(self):+ phone = Android.__new__(Android)+ phone._resolved = False+ return phone++ def test_an_unreachable_primary_does_not_connect_another_phone(self):+ phone = self.phone()+ cfg = {"primary": "pixel", "phones": {"pixel": {"serial": "PRIMARY"}}}+ with unittest.mock.patch.object(android_mod, "_load", return_value=cfg), \+ unittest.mock.patch.object(android_mod, "_attached", return_value=[+ ("USB1", "device", "usb"), ("10.0.0.8:5555", "device", "wifi")]), \+ unittest.mock.patch.object(android_mod, "_prop", return_value="OTHER"), \+ unittest.mock.patch.object(android_mod, "_mdns", return_value=[+ {"serial": "OTHER", "addr": "10.0.0.8:5555"}]), \+ unittest.mock.patch.object(android_mod, "_run") as run, \+ unittest.mock.patch.object(android_mod, "_remember"), \+ unittest.mock.patch("phone_harness.cloud.attached", return_value=None):+ with self.assertRaises(android_mod.PrimaryUnreachable) as cm:+ phone._resolve()+ self.assertIn("unreachable", str(cm.exception))+ self.assertIn("pixel", str(cm.exception))+ run.assert_not_called()+ self.assertNotIn("ANDROID_SERIAL", os.environ)++ def test_the_primary_is_used_when_it_is_already_up(self):+ phone = self.phone()+ cfg = {"primary": "pixel", "phones": {"pixel": {"serial": "PRIMARY"}}}++ def prop(adb_id, name):+ if name == "ro.serialno":+ return "PRIMARY" if adb_id == "10.0.0.5:5555" else "OTHER"+ return "Pixel"++ with unittest.mock.patch.object(android_mod, "_load", return_value=cfg), \+ unittest.mock.patch.object(android_mod, "_attached", return_value=[+ ("USB1", "device", "usb"), ("10.0.0.5:5555", "device", "wifi")]), \+ unittest.mock.patch.object(android_mod, "_prop", side_effect=prop), \+ unittest.mock.patch.object(android_mod, "_mdns") as mdns, \+ unittest.mock.patch.object(android_mod, "_run") as run, \+ unittest.mock.patch.object(android_mod, "_remember"), \+ unittest.mock.patch("phone_harness.cloud.attached", return_value=None):+ chosen = phone._resolve()+ self.assertEqual(chosen, "10.0.0.5:5555")+ mdns.assert_not_called()+ run.assert_not_called()++ def test_mdns_connects_only_the_primary(self):+ phone = self.phone()+ cfg = {"primary": "pixel", "phones": {"pixel": {"serial": "PRIMARY"}}}+ ready = []++ def attached():+ return list(ready)++ def run(*args, **_kw):+ if args and args[0] == "connect":+ ready.append((args[1], "device", "wifi"))+ return "connected to " + args[1]+ return ""++ def prop(adb_id, name):+ return "PRIMARY" if name == "ro.serialno" else "Pixel"++ services = [+ {"serial": "OTHER", "addr": "10.0.0.6:5555"},+ {"serial": "PRIMARY", "addr": "10.0.0.5:5555"},+ ]+ with unittest.mock.patch.object(android_mod, "_load", return_value=cfg), \+ unittest.mock.patch.object(android_mod, "_attached", side_effect=attached), \+ unittest.mock.patch.object(android_mod, "_prop", side_effect=prop), \+ unittest.mock.patch.object(android_mod, "_mdns", return_value=services), \+ unittest.mock.patch.object(android_mod, "_run", side_effect=run) as run_mock, \+ unittest.mock.patch.object(android_mod, "_remember"), \+ unittest.mock.patch("phone_harness.cloud.attached", return_value=None):+ chosen = phone._resolve()+ self.assertEqual(chosen, "10.0.0.5:5555")+ connects = [c.args[1] for c in run_mock.call_args_list if c.args and c.args[0] == "connect"]+ self.assertEqual(connects, ["10.0.0.5:5555"])++ def test_usb_is_used_when_no_primary_is_configured(self):+ phone = self.phone()+ cfg = {"phones": {"pixel": {"serial": "AAA"}}}+ with unittest.mock.patch.object(android_mod, "_load", return_value=cfg), \+ unittest.mock.patch.object(android_mod, "_attached", return_value=[+ ("USB1", "device", "usb")]), \+ unittest.mock.patch.object(android_mod, "_prop", return_value="AAA"), \+ unittest.mock.patch.object(android_mod, "_mdns") as mdns, \+ unittest.mock.patch.object(android_mod, "_run") as run, \+ unittest.mock.patch.object(android_mod, "_remember"), \+ unittest.mock.patch("phone_harness.cloud.attached", return_value=None):+ chosen = phone._resolve()+ self.assertEqual(chosen, "USB1")+ mdns.assert_not_called()+ run.assert_not_called()++ def test_session_state_does_not_hide_an_unreachable_primary(self):+ phone = self.phone()+ phone._resolve = unittest.mock.Mock(+ side_effect=android_mod.PrimaryUnreachable(+ "The primary Android phone 'pixel' is unreachable"))+ with self.assertRaises(android_mod.PrimaryUnreachable) as cm:+ phone._session_state()+ self.assertIn("unreachable", str(cm.exception))+ self.assertNotIn("no-adb", str(cm.exception))++if __name__ == "__main__":unittest.main()diff --git a/tests/test_cloud.py b/tests/test_cloud.pyindex 5ee1c6a..4ec3cc4 100644--- a/tests/test_cloud.py+++ b/tests/test_cloud.py@@ -566,6 +566,114 @@ class CloudCli(unittest.TestCase):self.assertIn("live.example", r.stdout)self.assertNotEqual(r.stdout.strip(), "None", r.stderr)+ def _expire_attached(self):+ path = Path(self.home.name) / "state" / "cloud.json"+ state = json.loads(path.read_text())+ sid = state["session"]["sid"]+ when = time.time() - 30+ state["session"]["expires_at"] = when+ for rec in (state.get("sessions") or {}).values():+ if isinstance(rec, dict) and rec.get("sid") == sid:+ rec["expires_at"] = when+ path.write_text(json.dumps(state))+ return sid++ def _connect_script(self, also_attached=False):+ lines = ["from phone_harness import cloud, transport"]+ if also_attached:+ lines += ["try:",+ " print('ATTACHED', cloud.attached())",+ "except RuntimeError as e:",+ " print('REFUSED', e)"]+ lines += ["try:",+ " transport.connect()",+ " print('RAN')",+ "except RuntimeError as e:",+ " print('CONNECT', e)"]+ return "\n".join(lines) + "\n"++ def test_no_cloud_state_file_still_means_no_cloud_phone(self):+ r = subprocess.run([sys.executable, "-c",+ "from phone_harness import cloud\n"+ "print('ATTACHED', cloud.attached())\n"+ "print('LOST', cloud.lost())\n"],+ capture_output=True, text=True, env=self.env)+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertIn("ATTACHED None", r.stdout)+ self.assertIn("LOST None", r.stdout)++ def test_an_unreadable_cloud_state_file_does_not_fall_back(self):+ state = Path(self.home.name) / "state"+ state.mkdir(parents=True)+ (state / "cloud.json").write_text("{not json")+ r = subprocess.run([sys.executable, "-c", self._connect_script(also_attached=True)],+ capture_output=True, text=True, env=self.env)+ self.assertIn("REFUSED", r.stdout, r.stderr)+ self.assertIn("unreadable", r.stdout)+ self.assertIn("CONNECT", r.stdout)+ self.assertNotIn("RAN", r.stdout)+ self.assertNotIn("expired", r.stdout)++ def test_an_expired_session_pin_does_not_fall_back_to_a_local_phone(self):+ self.login()+ started = self.run_cli("cloud", "start", "Saved phone", "--no-watch")+ self.assertEqual(started.returncode, 0, started.stderr)+ sid = self._expire_attached()+ r = subprocess.run([sys.executable, "-c", self._connect_script(also_attached=True)],+ capture_output=True, text=True,+ env={**self.env, "PHONE_HARNESS_SESSION": sid})+ self.assertIn("REFUSED", r.stdout, r.stderr)+ self.assertIn(f"session {sid} expired", r.stdout)+ self.assertIn('cloud start "Saved phone"', r.stdout)+ self.assertIn("--for", r.stdout)+ self.assertIn("<longer>", r.stdout)+ self.assertNotIn("RAN", r.stdout)+ self.assertNotIn("unreachable", r.stdout)++ def test_an_expired_attached_session_does_not_fall_back(self):+ self.login()+ started = self.run_cli("cloud", "start", "Saved phone", "--no-watch")+ self.assertEqual(started.returncode, 0, started.stderr)+ sid = self._expire_attached()+ r = subprocess.run([sys.executable, "-c", self._connect_script(also_attached=True)],+ capture_output=True, text=True, env=self.env)+ self.assertIn("ATTACHED None", r.stdout, r.stderr)+ self.assertIn("CONNECT", r.stdout)+ self.assertIn(f"session {sid} expired", r.stdout)+ self.assertIn('cloud start "Saved phone"', r.stdout)+ self.assertIn("--for", r.stdout)+ self.assertNotIn("RAN", r.stdout)++ def test_a_session_that_dies_does_not_fall_back_to_a_local_phone(self):+ self.login()+ started = self.run_cli("cloud", "start", "Saved phone", "--no-watch")+ self.assertEqual(started.returncode, 0, started.stderr)+ FakeCloud.sessions.clear()+ status = self.run_cli("cloud")+ self.assertIn("unreachable", status.stdout, status.stderr)+ self.assertIn("failed", status.stdout)+ self.assertIn('cloud start "Saved phone"', status.stdout)+ self.assertIn("--for", status.stdout)+ self.assertNotIn("expired", status.stdout)+ r = subprocess.run([sys.executable, "-c", self._connect_script()],+ capture_output=True, text=True, env=self.env)+ self.assertIn("CONNECT", r.stdout, r.stderr)+ self.assertIn("unreachable", r.stdout)+ self.assertIn("failed", r.stdout)+ self.assertIn('cloud start "Saved phone"', r.stdout)+ self.assertNotIn("RAN", r.stdout)+ self.assertNotIn("expired", r.stdout)+ still = subprocess.run(+ [sys.executable, "-c", "from phone_harness import cloud; print(cloud.lost() is not None)"],+ capture_output=True, text=True, env={**self.env, "PHONE_HARNESS_PLATFORM": "android"})+ self.assertEqual(still.stdout.strip(), "True", still.stderr)+ stopped = self.run_cli("cloud", "stop", "--all")+ self.assertEqual(stopped.returncode, 0, stopped.stderr)+ cleared = subprocess.run(+ [sys.executable, "-c", "from phone_harness import cloud; print(cloud.lost())"],+ capture_output=True, text=True, env=self.env)+ self.assertEqual(cleared.stdout.strip(), "None", cleared.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",