let your agent control your phone
Fix cloud ls rows, start wording, and add an update check (#116)
shawn pana629aefea62e1
diff --git a/README.md b/README.mdindex 9227d3a..9abe502 100644--- a/README.md+++ b/README.md@@ -77,7 +77,13 @@ phone-harness cloud stop # billing stops; a saved Android is written````cloud ls` is the catalog (`GET /me` → `available`): each phone's label,-platform, and id, with a live session on that row. `cloud start` with no name+platform, and id, with a live session on that row (matched by device id,+profile id, or the temporary row). A cloud iPhone session does not echo its+catalog id (`device` is the word "iPhone", and `profile` is an `iphone-…` id+that matches no catalog row). That session is written on the one catalog row+of the same platform and kind whose `state` is `running`, when that is the+only such row and the only unmatched session of that platform and kind. A+session that matches nothing is its own row. `cloud start` with no namestarts this machine's `cloud.phone` setting if one is set, else what theservice gives an unnamed start, a temporary Android. A name is a catalog id or label, or `ios` /`android` when only one entry has that platform. A [cloud Android](https://phone-harness.com/cloud)@@ -87,6 +93,15 @@ it is in [SKILL.md](SKILL.md). `phone-harness cloud` lists the rest, including`watch`, `open`, `history`, and `phone` for the saved Android. `--session SID`(or `PHONE_HARNESS_SESSION`) pins one rented phone for this process.+## Updates++`phone-harness update` upgrades a [uv](https://docs.astral.sh/uv/) tool+(`uv tool upgrade phone-harness`) or a git checkout (`git pull --ff-only`).+Any other install prints `pip install -U phone-harness` and leaves it for+you to run. The tool never updates itself. On a terminal, once a day, it+prints one line on stderr when PyPI has a newer version. Set+`PHONE_HARNESS_NO_UPDATE_CHECK=1` to silence that notice.+## How it works**iPhone.** iPhone Mirroring renders the phone as a Mac window and forwardsdiff --git a/SKILL.md b/SKILL.mdindex 5665136..37eed9e 100644--- a/SKILL.md+++ b/SKILL.md@@ -129,8 +129,15 @@ There are two things. A **phone** is a row in the account catalog (`GET /me`-> `available`): a label, a platform, an id, and whether it is a temporaryphone. The service keeps no default phone; a preference is the chooser's. A **session** is one of those phones rented right now.`cloud ls` prints one row per catalog phone and writes any live session on-that row (`*` is the session this process targets). A running session that-matches no row is still listed.+that row (`*` is the session this process targets). A session lines up with+the row that has the same device_id or profile_id; a session with neither+lines up with the temporary row. A cloud iPhone session does not echo that+id: its `device` is the word "iPhone", and its `profile` (`iphone-...`) matches+no catalog row. The catalog row's `state` is `running` while a session holds+it. A session whose ids match no row counts as unmatched. When exactly one+row of that platform and kind is `running` and exactly one unmatched session+has that same platform and kind, the session is written on that row. A+session that still matches nothing is listed on its own.`cloud start` with no name starts this machine's `cloud.phone` setting(`config set cloud.phone "Desk phone"`) when one is set; otherwise it sends@@ -460,3 +467,18 @@ overrides that. Installs seed that directory from the packaged defaultswhen it does not exist yet; an existing workspace is left as it is.To get a fresh default, delete the workspace folder; it is recreatedon the next run. For setup or permission problems, read `install.md`.++## Updates++`phone-harness update` brings this install up to date. A uv tool runs+`uv tool upgrade phone-harness`. A git checkout runs `git pull --ff-only`+in that checkout. Anything else prints `pip install -U phone-harness` and+does not run it. The CLI never updates itself. Once a day, on a terminal,+it may print one stderr line when PyPI has a newer version:++```+phone-harness X.Y.Z is available (you have A.B.C): run phone-harness update+```++Relay that line to the user. `PHONE_HARNESS_NO_UPDATE_CHECK=1` turns the+notice off. A network problem never fails the command.diff --git a/install.md b/install.mdindex c813347..78a4543 100644--- a/install.md+++ b/install.md@@ -43,7 +43,12 @@ phone-harness skill > "${CODEX_HOME:-$HOME/.codex}/skills/phone-harness/SKILL.md`--doctor android` checks the other.Re-run the `phone-harness skill > …/SKILL.md` lines after pulling updates so-the agent's copy matches the code.+the agent's copy matches the code. `phone-harness update` does the upgrade:+`uv tool upgrade phone-harness` when this is a uv tool, `git pull --ff-only`+in a checkout, otherwise it prints `pip install -U phone-harness` and does+not run it. It never updates on its own. A newer PyPI release is one stderr+line, at most once a day, and only on a terminal;+`PHONE_HARNESS_NO_UPDATE_CHECK=1` skips the check.- **No phone on your desk?** `phone-harness cloud login`, then`phone-harness cloud ls` and `phone-harness cloud start` (the accountdefault) or `phone-harness cloud start PHONE` for a catalog id, label, ordiff --git a/src/phone_harness/cloud.py b/src/phone_harness/cloud.pyindex af47cc5..a53b366 100644--- a/src/phone_harness/cloud.py+++ b/src/phone_harness/cloud.py@@ -19,6 +19,7 @@ is no one to click Approve.Stdlib only. API reference: https://phone-harness.com/docs"""import json+import mathimport osimport shutilimport sys@@ -478,12 +479,26 @@ def _keeps_state(session):return bool(session.get("profile"))+def _iphone_words(label):+ """'your iPhone', plus a label only when the label is not itself 'iPhone'.++ The catalog name for the one phone on an account is often just iPhone, and+ 'your iPhone, iPhone' says the same thing twice."""+ text = " ".join(str(label).split()) if label else ""+ if text.lower() in {"", "iphone", "your iphone"}:+ return "your iPhone"+ return f"your iPhone, {text}"++def _kind_of_phone(session, label=None):"""Wording for a session, from its link. A control link is an iPhone."""if _link_kind(session) == "control":- label = label or session.get("label")- return f"your iPhone, {label}" if label else "your iPhone"- return "your phone" if session.get("profile") else "temporary"+ if label is None:+ label = session.get("label")+ return _iphone_words(label)+ if session.get("profile") or session.get("profile_id"):+ return "your phone"+ return "temporary"def _adb_present():@@ -691,10 +706,20 @@ def _money(cents):def _left(expires_at):+ """How long the session has left, for a person reading it.++ Minutes round up. `cloud start --for 6` still says 6 min after the phone+ spends part of that first minute booting; flooring made it say 5. Under+ two minutes the exact seconds stay.+ """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"+ remaining = expires_at - time.time()+ if remaining <= 0:+ return "expired"+ if remaining < 120:+ return f"{int(remaining)}s"+ return f"{math.ceil(remaining / 60)} min"def _ago(ts):@@ -930,8 +955,7 @@ def _needs_adb(entry, me):def _starting_line(entry, me):shown = entry if entry is not None else _unnamed(me)if shown and shown.get("platform") == "ios":- label = shown.get("label") or shown.get("id") or ""- return f"Starting your iPhone{', ' + label if label else ''}…"+ return "Starting " + _iphone_words(shown.get("label") or shown.get("id") or "") + "…"if shown and shown.get("temporary"):return "Starting a temporary phone…"if shown and shown.get("label"):@@ -1272,29 +1296,100 @@ def _status(args):return 0-def _session_key(session):- """The catalog id a live session belongs to: its device id or its profile."""- phone = session.get("phone")- if session.get("device_id"):- return session["device_id"]- if isinstance(phone, str) and phone:- return phone- return session.get("profile") or None+def _text_id(value):+ """An id string, or the id inside a small object. Display text is not an id."""+ if isinstance(value, str):+ text = value.strip()+ return text or None+ if isinstance(value, dict):+ for key in ("id", "device_id", "profile_id"):+ found = _text_id(value.get(key))+ if found:+ return found+ return None+++def _id_set(mapping, keys):+ found = set()+ if not isinstance(mapping, dict):+ return found+ for key in keys:+ text = _text_id(mapping.get(key))+ if text:+ found.add(text)+ return found+++# `phone` used to be a saved-phone id. The live API also puts a display name+# there ("iPhone", "Android emulator"); those are not catalog ids.+_PHONE_DISPLAY_NAMES = {"iphone", "android", "android emulator", "your iphone", "your phone"}+++def _session_ids(session):+ """device ids and profile ids this session holds.++ `profile` is the older name for `profile_id`. A string `phone` counts only+ when it is an id, not the display name."""+ devices = _id_set(session, ("device_id",))+ profiles = _id_set(session, ("profile_id", "profile"))+ phone = _text_id(session.get("phone"))+ if phone and phone.lower() not in _PHONE_DISPLAY_NAMES and phone not in devices:+ profiles.add(phone)+ return devices, profilesdef _session_on_entry(entry, session):"""True when this live session is that catalog phone.- An entry with an id matches the session's device id or profile. A- temporary entry has no id; a session with no device and no profile, on- the same platform, is that throwaway phone."""- key = _session_key(session)- if entry.get("id"):- return key == entry["id"]- if not entry.get("temporary") or key is not None or _link_kind(session) == "control":- return False- platform = entry.get("platform")- return not platform or session.get("platform") in (None, platform)+ Match by device_id or profile_id (a catalog row keeps that id on `id`,+ `device_id`, or `profile_id`). A temporary row, which names neither, is+ the session that also names neither. Anything else is not this row.+ An iPhone session does not carry the catalog id: `device` is the display+ word "iPhone". That case is decided in `_inline_running`."""+ devices, profiles = _session_ids(session)+ entry_ids = _id_set(entry, ("id", "device_id", "profile_id"))+ if (devices | profiles) & entry_ids:+ return True+ if entry.get("temporary") and not entry_ids and not devices and not profiles:+ if _link_kind(session) == "control" or session.get("platform") == "ios":+ return False+ platform = entry.get("platform")+ return not platform or session.get("platform") in (None, platform)+ return False+++def _inline_running(entries, rows, sessions, used, blob, mine):+ """Put one unmatched live session on the one catalog phone that is running.++ A cloud iPhone session does not echo the catalog id. It carries+ `platform`, `kind`, `device` set to the word "iPhone", and a `profile`+ like `iphone-…` that matches no catalog row. Any session whose+ device_id or profile matched no row is unmatched, even when those fields+ are set. When exactly one entry of that platform and kind is `running`,+ and exactly one unmatched session has that same platform and kind, the+ session is that row.+ """+ for entry, row in zip(entries, rows):+ if row.get("session") or entry.get("state") != "running":+ continue+ platform, kind = entry.get("platform"), entry.get("kind")+ if not platform or not kind:+ continue+ running = [e for e in entries+ if e.get("platform") == platform and e.get("kind") == kind+ and e.get("state") == "running"]+ if len(running) != 1:+ continue+ candidates = [s for s in sessions+ if s.get("id") not in used+ and s.get("platform") == platform+ and s.get("kind") == kind]+ if len(candidates) != 1:+ continue+ match = candidates[0]+ used.add(match["id"])+ row["session"] = blob(match)+ row["targeted"] = match.get("id") == minedef _ls_rows(me, sessions):@@ -1321,21 +1416,23 @@ def _ls_rows(me, sessions):rows.append({"label": entry.get("label") or "","platform": entry.get("platform"),- "id": entry.get("id"),+ "id": entry.get("id") or entry.get("device_id") or entry.get("profile_id"),"state": entry.get("state"),"temporary": bool(entry.get("temporary")),"session": session_blob(match) if match else None,"targeted": bool(match and match.get("id") == mine),})+ _inline_running(catalog, rows, sessions, used, session_blob, mine)for s in sessions:if s.get("id") in used:continue+ named, _profiles = _session_ids(s)rows.append({"label": s.get("device") or s.get("label") or "session","platform": s.get("platform"),"id": None,"state": s.get("state"),- "temporary": not s.get("profile") and _link_kind(s) != "control",+ "temporary": not named and not _profiles and _link_kind(s) != "control","session": session_blob(s),"targeted": s.get("id") == mine,"unmatched": True,diff --git a/src/phone_harness/config.py b/src/phone_harness/config.pyindex cc22903..a390def 100644--- a/src/phone_harness/config.py+++ b/src/phone_harness/config.py@@ -1,6 +1,6 @@"""Where phone-harness keeps what the user chose and what it learned.-Two kinds of thing, kept apart because they live differently:+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.@@ -14,9 +14,12 @@ Two kinds of thing, kept apart because they live differently:~/.local/state/phone-harness/cloud.json~/.local/state/phone-harness/telemetry.json~/.local/state/phone-harness/run/awake.pid+ cache the once-a-day update check: when it last looked, and the latest+ version it saw.+ ~/.cache/phone-harness/update.json-XDG_CONFIG_HOME / XDG_STATE_HOME are honoured; PHONE_HARNESS_HOME moves both-roots under one directory (tests, sandboxes).+XDG_CONFIG_HOME / XDG_STATE_HOME / XDG_CACHE_HOME are honoured;+PHONE_HARNESS_HOME moves all three roots under one directory (tests, sandboxes).One rule for every setting: explicit argument, else environment variable,else config file, else built-in default. A `.env` file at the repo root or@@ -114,6 +117,14 @@ def state_dir():return Path(base) / "phone-harness"+def cache_dir():+ home = os.environ.get("PHONE_HARNESS_HOME")+ if home:+ return Path(home) / "cache"+ base = os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache"+ return Path(base) / "phone-harness"++def run_dir():return state_dir() / "run"@@ -124,6 +135,7 @@ def paths():"devices": state_dir() / "devices.json","cloud": state_dir() / "cloud.json","telemetry": state_dir() / "telemetry.json",+ "update": cache_dir() / "update.json","run": run_dir()}diff --git a/src/phone_harness/remote.py b/src/phone_harness/remote.pyindex 396a832..2aeaee8 100644--- a/src/phone_harness/remote.py+++ b/src/phone_harness/remote.py@@ -23,6 +23,68 @@ TMP = Path(tempfile.gettempdir()) / "phone-harness"USER_AGENT = "phone-harness-cli"+def _cloud_phone_error():+ from .cloud import CloudPhoneError+ return CloudPhoneError+++def _runtime_prefixes():+ """Type prefixes a host may put on a RuntimeError-family message.++ CloudPhoneError is a RuntimeError. The traceback printer qualifies it+ (`phone_harness.cloud.CloudPhoneError:`), and a host may also send the+ bare class name or `RuntimeError:`.+ """+ cloud = _cloud_phone_error()+ qualified = f"{cloud.__module__}.{cloud.__qualname__}: "+ return (qualified, "CloudPhoneError: ", "RuntimeError: ")+++def _plain_error(message, exc_type):+ """Drop a leading `TypeName:` that repeats the exception about to be raised.++ Raising RuntimeError while a CloudPhoneError prefix is still on the text+ (or the reverse) prints both types.+ """+ if not isinstance(message, str):+ message = str(message)+ prefixes = [exc_type.__name__ + ": "]+ if exc_type.__name__ in ("RuntimeError", "CloudPhoneError"):+ for prefix in _runtime_prefixes():+ if prefix not in prefixes:+ prefixes.append(prefix)+ while True:+ for prefix in prefixes:+ if message.startswith(prefix):+ message = message[len(prefix):]+ break+ else:+ break+ return message or exc_type.__name__+++def _host_error(message):+ """The exception the host named. A CloudPhoneError stays a CloudPhoneError."""+ text = message if isinstance(message, str) else str(message)+ cloud = _cloud_phone_error()+ qualified = f"{cloud.__module__}.{cloud.__qualname__}: "+ named = RuntimeError+ while True:+ if text.startswith(qualified):+ named = cloud+ text = text[len(qualified):]+ continue+ if text.startswith("CloudPhoneError: "):+ named = cloud+ text = text[len("CloudPhoneError: "):]+ continue+ if text.startswith("RuntimeError: "):+ text = text[len("RuntimeError: "):]+ continue+ break+ return named(_plain_error(message, named))++class Remote(Backend):name = "remote"@@ -50,11 +112,16 @@ class Remote(Backend):err = {}message = err.get("error") or f"the cloud phone answered {e.code}"if err.get("unsupported"):- raise Unsupported(message) from None+ raise Unsupported(_plain_error(message, Unsupported)) from Noneif e.code == 404:raise RuntimeError("the cloud phone session is gone or its grant expired; ""`phone-harness cloud` shows whether it is still running") from None- raise RuntimeError(message) from None+ # The host's `error` already includes its exception type+ # ("RuntimeError: no installed app matches 'Notes'", or+ # "CloudPhoneError: session … expired"). Raising that string+ # as-is would print the type twice. A CloudPhoneError stays one,+ # so a dead cloud phone is not reported as a plain RuntimeError.+ raise _host_error(message) from Noneexcept urllib.error.URLError as e:raise RuntimeError(f"could not reach the cloud phone: {e.reason}") from Nonediff --git a/src/phone_harness/run.py b/src/phone_harness/run.pyindex 488d271..3b921ca 100644--- a/src/phone_harness/run.py+++ b/src/phone_harness/run.py@@ -20,6 +20,7 @@ Commands:phone-harness android ... pair/connect/choose an Android phonephone-harness cloud ... rent a catalog phone: `cloud login`, `cloud ls`, `cloud start [PHONE]`phone-harness config ... settings: `config set platform android`+ phone-harness update update this install: uv tool upgrade, git pull, or the pip command--session SID (or PHONE_HARNESS_SESSION) selects one rented phone. With neither,a script follows the attached session.@@ -129,7 +130,7 @@ def _telemetry_command(args):return "help"if first in {"--doctor", "doctor"}:return "doctor"- if first in {"android", "cloud", "config", "skill"}:+ if first in {"android", "cloud", "config", "skill", "update"}:return firstreturn "usage"@@ -174,6 +175,13 @@ def _exit_code(code):def main():global _helper_call_countargs = sys.argv[1:]+ # Once a day, on a terminal. Never delays or fails the command.+ if args[:1] != ["update"]:+ try:+ from .update import maybe_notify+ maybe_notify()+ except Exception:+ pass_helper_trace.clear()_helper_call_count = 0start_time = time.monotonic()@@ -280,6 +288,9 @@ def _run(args):if args and args[0] == "config":from .config import clisys.exit(cli(args[1:]))+ if args and args[0] == "update":+ from .update import cmd_update+ sys.exit(cmd_update(args[1:]))if args and args[0] == "skill":_write_utf8(_skill_text())returndiff --git a/src/phone_harness/update.py b/src/phone_harness/update.pynew file mode 100644index 0000000..b77581e--- /dev/null+++ b/src/phone_harness/update.py@@ -0,0 +1,213 @@+"""Tell the user when a newer phone-harness is out, and update when they ask.++The check runs at most once a day. It stores the time and the latest version+it saw under the cache dir (see config.py) and prints one stderr line. It+never upgrades by itself, and a network failure never fails the command.++`phone-harness update` is the only thing that changes an install: `uv tool+upgrade` for a uv tool, `git pull --ff-only` for a checkout, otherwise the+pip command printed for the user to run.+"""+import json+import os+import subprocess+import sys+import time+import urllib.request+from pathlib import Path++from . import config++CHECK_INTERVAL = 24 * 60 * 60+FETCH_TIMEOUT = 2+PYPI_URL = "https://pypi.org/pypi/phone-harness/json"+_TRUTHY = {"1", "true", "yes", "on"}+++def installed_version():+ try:+ from importlib.metadata import version+ return version("phone-harness")+ except Exception:+ return ""+++def _parse(value):+ nums = []+ for part in str(value).split("."):+ digits = ""+ for ch in part:+ if not ch.isdigit():+ break+ digits += ch+ if digits:+ nums.append(int(digits))+ return tuple(nums)+++def is_newer(latest, current):+ """True when `latest` is a higher version than `current`."""+ a, b = _parse(latest), _parse(current)+ width = max(len(a), len(b))+ a += (0,) * (width - len(a))+ b += (0,) * (width - len(b))+ return a > b+++def _load():+ data = config._read(config.paths()["update"], {})+ latest = data.get("latest") if isinstance(data.get("latest"), str) else None+ try:+ checked = float(data.get("checked_at") or 0)+ except (TypeError, ValueError):+ checked = 0.0+ return {"checked_at": checked, "latest": latest}+++def _store(checked_at, latest):+ config._write(config.paths()["update"], {"checked_at": checked_at, "latest": latest})+++def fetch_latest(opener=None, timeout=FETCH_TIMEOUT):+ opener = opener or urllib.request.urlopen+ req = urllib.request.Request(+ PYPI_URL,+ headers={"Accept": "application/json", "User-Agent": "phone-harness-cli"},+ )+ with opener(req, timeout=timeout) as resp:+ payload = json.loads(resp.read().decode())+ version = (payload.get("info") or {}).get("version")+ if not isinstance(version, str) or not version.strip():+ raise ValueError("PyPI returned no version")+ return version.strip()+++def _try_fetch(opener=None):+ try:+ return fetch_latest(opener=opener)+ except Exception:+ return None+++def announce(*, opener=None, version=None, now=None, stderr=None):+ """Compare the installed version to PyPI and print the one-line notice.++ Network errors are swallowed. A fresh cache (younger than a day) is used+ as-is, so a command does not wait on the network again.+ """+ current = installed_version() if version is None else version+ if not current:+ return+ now = time.time() if now is None else now+ stderr = stderr or sys.stderr+ cached = _load()+ latest = cached["latest"]+ if now - cached["checked_at"] >= CHECK_INTERVAL:+ fetched = _try_fetch(opener)+ latest = fetched or latest+ _store(now, latest)+ if latest and is_newer(latest, current):+ print(+ f"phone-harness {latest} is available (you have {current}): "+ "run phone-harness update",+ file=stderr,+ )+++def under_test():+ """True when this process is a test run, so the suite never calls PyPI.++ Covers `python -m unittest`, pytest, and a `test_*.py` file. Some runners+ put the whole command in argv[0] (`python3 -m unittest`) instead of the+ unittest module path."""+ if os.environ.get("PYTEST_CURRENT_TEST"):+ return True+ argv0 = (sys.argv[0] if sys.argv else "").replace("\\", "/")+ if argv0.endswith(("/unittest/__main__.py", "/pytest/__main__.py", "/pytest.py")):+ return True+ base = argv0.rsplit("/", 1)[-1]+ if base in {"pytest", "py.test", "unittest"}:+ return True+ # `python3 -m unittest` as a single argv[0], not a path that merely+ # contains those letters.+ if " -m unittest" in argv0 or " -m pytest" in argv0:+ return True+ return base.startswith("test_") and base.endswith(".py")+++def suppressed(environ=None, isatty=None, testing=None):+ environ = os.environ if environ is None else environ+ flag = str(environ.get("PHONE_HARNESS_NO_UPDATE_CHECK", "")).strip().lower()+ if flag in _TRUTHY:+ return True+ if isatty is None:+ try:+ isatty = sys.stderr.isatty()+ except Exception:+ isatty = False+ if not isatty:+ return True+ if testing is None:+ testing = under_test()+ return bool(testing)+++def maybe_notify():+ """The CLI's check. Returns without doing work when it should stay quiet."""+ try:+ if suppressed():+ return+ announce()+ except Exception:+ return+++def is_uv_tool_prefix(prefix):+ """A uv tool env lives in `.../uv/tools/<name>`."""+ parts = Path(prefix).parts+ return any(part == "uv" and parts[i + 1] == "tools" for i, part in enumerate(parts[:-1]))+++def git_checkout_root(module_file):+ """The repo root when `module_file` is the checkout, not an installed copy."""+ path = Path(module_file).resolve()+ if "site-packages" in path.parts or "dist-packages" in path.parts:+ return None+ for parent in path.parents:+ if (parent / ".git").exists() and (parent / "pyproject.toml").is_file():+ return parent+ return None+++def install_mode():+ """'uv', 'git', or 'pip' — which install this process is running from."""+ if is_uv_tool_prefix(sys.prefix):+ return "uv"+ if git_checkout_root(Path(__file__).resolve()):+ return "git"+ return "pip"+++def _exec(argv):+ try:+ return subprocess.call(argv)+ except FileNotFoundError:+ print(f"Could not run {argv[0]}. Run this yourself: {' '.join(argv)}", file=sys.stderr)+ return 1+++def cmd_update(args=None):+ args = list(args or [])+ if args:+ print("Usage: phone-harness update", file=sys.stderr)+ return 2+ mode = install_mode()+ if mode == "uv":+ print("Updating phone-harness with uv...")+ return _exec(["uv", "tool", "upgrade", "phone-harness"])+ if mode == "git":+ root = git_checkout_root(Path(__file__).resolve())+ print(f"Updating {root} with git...")+ return _exec(["git", "-C", str(root), "pull", "--ff-only"])+ print("pip install -U phone-harness")+ return 0diff --git a/tests/support/sitecustomize.py b/tests/support/sitecustomize.pyindex 6469f17..63dd2ca 100644--- a/tests/support/sitecustomize.py+++ b/tests/support/sitecustomize.py@@ -1,8 +1,12 @@"""Imported automatically in test subprocesses (PYTHONPATH lists this directory).Installed before phone_harness so `cloud start`, `cloud watch`, and `cloud open`-record the URL instead of calling a real browser.+record the URL instead of calling a real browser. The update check stays off:+a test must not call PyPI, and a failure there must not fail the suite."""+import os+import browser_recorder+os.environ.setdefault("PHONE_HARNESS_NO_UPDATE_CHECK", "1")browser_recorder.install()diff --git a/tests/test_cloud.py b/tests/test_cloud.pyindex 4ec3cc4..792b794 100644--- a/tests/test_cloud.py+++ b/tests/test_cloud.py@@ -219,6 +219,7 @@ class FakeCloud(BaseHTTPRequestHandler):class FakeControl(BaseHTTPRequestHandler):"""What a phone driven by ops over HTTPS answers: /ops, /op, /frame.png."""calls = []+ launch_error = None # set: apps.launch returns this JSON body with HTTP 400PNG = bytes.fromhex("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489""0000000d49444154789c6360000002000154a24f5d0000000049454e44ae426082")@@ -256,6 +257,8 @@ class FakeControl(BaseHTTPRequestHandler):return self._send(200, {"result": True})if op == "nav.back":return self._send(400, {"error": "iOS has no back", "unsupported": True})+ if op == "apps.launch" and FakeControl.launch_error:+ return self._send(400, FakeControl.launch_error)return self._send(400, {"error": f"cannot {op}", "unsupported": True})return self._send(404, {"error": "not found"})@@ -276,6 +279,7 @@ class CloudCli(unittest.TestCase):FakeCloud.control_url = NoneFakeCloud.available = NoneFakeCloud.fail = None+ FakeControl.launch_error = NoneFakeCloud.profile = {"id": "prof-1", "state": "stored", "session": None,"saved_at": time.time() - 7200}self.server = ThreadingHTTPServer(("127.0.0.1", 0), FakeCloud)@@ -285,6 +289,7 @@ class CloudCli(unittest.TestCase):self.env = {**os.environ, "PYTHONPATH": SUPPORT + os.pathsep + SRC,"PHONE_HARNESS_HOME": self.home.name,"PHONE_HARNESS_ADB": str(adb), "PHONE_HARNESS_TELEMETRY": "0",+ "PHONE_HARNESS_NO_UPDATE_CHECK": "1","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"}@@ -523,6 +528,7 @@ class CloudCli(unittest.TestCase):self.assertNotIn("provider", FakeCloud.posts[0])self.assertNotIn("profile_id", FakeCloud.posts[0])self.assertIn("Starting your iPhone", r.stdout)+ self.assertIn("your iPhone, My iPhone SE", r.stdout)self.assertIn("control", r.stdout)self.assertNotIn("adb", r.stdout)self.assertFalse((Path(self.home.name) / "adb.log").exists()) # never touched@@ -918,6 +924,232 @@ class CloudCli(unittest.TestCase):self.assertTrue(any(line.startswith("*") and "sid001" in linefor line in text.stdout.splitlines()))+ def test_ls_inlines_a_live_session_on_its_catalog_row(self):+ """device_id, profile_id, and a temporary session each share their row.++ A live iPhone used to print a second `iPhone ios - ready <sid>` line+ because the list matches `profile` and a display name, not device_id+ or profile_id. A session that matches nothing is still its own row,+ including a control link that names no device."""+ self.login()+ FakeCloud.available = [+ {"platform": "ios", "kind": "device", "device_id": "iph-1", "label": "iPhone",+ "state": "running"},+ {"platform": "android", "kind": "emulator", "id": "prof-1", "label": "Saved phone",+ "state": "running"},+ {"platform": "android", "kind": "emulator", "temporary": True, "label": "Temporary phone"},+ ]+ soon = time.time() + 7 * 60+ control = {"url": "http://127.0.0.1:1", "token": "ct_1"}+ FakeCloud.sessions["liveios"] = {+ "id": "liveios", "state": "ready", "platform": "ios", "kind": "device",+ "device": "iPhone", "label": "iPhone", "device_id": "iph-1",+ "profile_id": None, "profile": None, "phone": None,+ "expires_at": soon, "control": control}+ FakeCloud.sessions["liveand"] = {+ "id": "liveand", "state": "ready", "platform": "android", "kind": "emulator",+ "device": "Android emulator", "profile_id": "prof-1", "profile": None,+ "device_id": None, "phone": None, "expires_at": soon,+ "adb": {"host": "live.example", "port": 22220, "code": "ph_code"}}+ FakeCloud.sessions["livetemp"] = {+ "id": "livetemp", "state": "ready", "platform": "android", "kind": "emulator",+ "device": "Android emulator", "profile_id": None, "profile": None,+ "device_id": None, "phone": None, "expires_at": soon,+ "adb": {"host": "live.example", "port": 22221, "code": "ph_code"}}+ FakeCloud.sessions["orphan"] = {+ "id": "orphan", "state": "ready", "platform": "ios", "kind": "device",+ "device": "iPhone", "device_id": "iph-other", "profile_id": None,+ "expires_at": soon, "control": control}+ FakeCloud.sessions["noid"] = {+ "id": "noid", "state": "ready", "platform": "ios", "device": "iPhone",+ "profile_id": None, "profile": None, "device_id": None, "phone": "iPhone",+ "expires_at": soon, "control": control}+ raw = self.run_cli("cloud", "ls", "--json")+ self.assertEqual(raw.returncode, 0, raw.stderr)+ rows = json.loads(raw.stdout)+ self.assertEqual([row["session"]["id"] for row in rows],+ ["liveios", "liveand", "livetemp", "orphan", "noid"])+ self.assertEqual(rows[0]["id"], "iph-1")+ self.assertEqual(rows[0]["label"], "iPhone")+ self.assertFalse(rows[0].get("unmatched"))+ self.assertEqual(rows[1]["id"], "prof-1")+ self.assertTrue(rows[2]["temporary"])+ self.assertEqual([row["session"]["id"] for row in rows if row.get("unmatched")],+ ["orphan", "noid"])+ text = self.run_cli("cloud", "ls").stdout+ for sid in ("liveios", "liveand", "livetemp", "orphan", "noid"):+ self.assertEqual(text.count(sid), 1, text)+ iphone = next(line for line in text.splitlines() if "liveios" in line)+ self.assertIn("iPhone", iphone)+ self.assertIn("iph-1", iphone)+ self.assertIn("Saved phone", next(line for line in text.splitlines() if "liveand" in line))+ self.assertIn("Temporary", next(line for line in text.splitlines() if "livetemp" in line))++ def test_ls_inlines_a_running_iphone_that_does_not_echo_its_id(self):+ """Live shape: the session's `device` is the word iPhone, not the catalog id.++ GET /me `available` marks that phone `state: running`. GET /sessions+ does not return `device_id`. One running ios device and one ios+ session with no id share the catalog row.+ """+ self.login()+ FakeCloud.available = [+ {"platform": "ios", "kind": "device", "id": "iph-e2eeaed7e6",+ "label": "iPhone", "state": "running"},+ {"platform": "android", "kind": "emulator", "id": "prof-1",+ "label": "Saved phone", "state": "stored"},+ {"platform": "android", "kind": "emulator", "temporary": True,+ "label": "Temporary phone"},+ ]+ soon = time.time() + 117+ FakeCloud.sessions["74f35c02595f"] = {+ "id": "74f35c02595f", "state": "ready", "platform": "ios", "kind": "device",+ "device": "iPhone", "phone": None, "profile": None, "billing_mode": "disabled",+ "expires_at": soon,+ "control": {"url": "http://127.0.0.1:1", "token": "ct_1"}}+ raw = self.run_cli("cloud", "ls", "--json")+ self.assertEqual(raw.returncode, 0, raw.stderr)+ rows = json.loads(raw.stdout)+ self.assertEqual(len(rows), 3)+ self.assertEqual(rows[0]["id"], "iph-e2eeaed7e6")+ self.assertEqual(rows[0]["state"], "running")+ self.assertEqual(rows[0]["session"]["id"], "74f35c02595f")+ self.assertFalse(rows[0].get("unmatched"))+ text = self.run_cli("cloud", "ls").stdout+ self.assertEqual(text.count("74f35c02595f"), 1, text)+ self.assertEqual(sum(1 for line in text.splitlines() if "iPhone" in line), 1, text)++ def test_ls_inlines_the_live_iphone_profile_that_matches_no_catalog_id(self):+ """Captured while a cloud iPhone was running.++ The session's `profile` is `iphone-…`, which is not the catalog id+ `iph-…`. It is still that one running ios device.+ """+ self.login()+ FakeCloud.available = [+ {"platform": "android", "kind": "emulator",+ "id": "prof-948b7471ed7575fc17236906", "label": "Saved phone",+ "state": "stored"},+ {"platform": "android", "kind": "emulator", "temporary": True,+ "label": "Temporary phone"},+ {"platform": "ios", "kind": "device", "id": "iph-e2eeaed7e6",+ "label": "iPhone", "state": "running"},+ ]+ FakeCloud.sessions["61712b99d488"] = {+ "id": "61712b99d488", "state": "ready", "platform": "ios", "kind": "device",+ "device": "iPhone", "phone": None, "profile": "iphone-99d901c34490fbe8bc4b0402",+ "screen": {"w": 750, "h": 1334}, "expires_at": 1791693728.89,+ "timeout_seconds": 120,+ "control": {"url": "http://127.0.0.1:1", "token": "ct_1"}}+ raw = self.run_cli("cloud", "ls", "--json")+ self.assertEqual(raw.returncode, 0, raw.stderr)+ rows = json.loads(raw.stdout)+ self.assertEqual([row.get("unmatched") for row in rows], [None, None, None])+ iphone = rows[2]+ self.assertEqual(iphone["id"], "iph-e2eeaed7e6")+ self.assertEqual(iphone["state"], "running")+ self.assertEqual(iphone["session"]["id"], "61712b99d488")+ text = self.run_cli("cloud", "ls").stdout+ self.assertEqual(text.count("61712b99d488"), 1, text)+ line = next(line for line in text.splitlines() if "61712b99d488" in line)+ self.assertIn("iph-e2eeaed7e6", line)+ self.assertIn("iPhone", line)++ def test_ls_does_not_guess_when_two_iphones_are_running(self):+ self.login()+ FakeCloud.available = [+ {"platform": "ios", "kind": "device", "id": "iph-a", "label": "iPhone",+ "state": "running"},+ {"platform": "ios", "kind": "device", "id": "iph-b", "label": "Other",+ "state": "running"},+ ]+ FakeCloud.sessions["solo"] = {+ "id": "solo", "state": "ready", "platform": "ios", "kind": "device",+ "device": "iPhone", "phone": None, "profile": None,+ "expires_at": time.time() + 600,+ "control": {"url": "http://127.0.0.1:1", "token": "ct_1"}}+ rows = json.loads(self.run_cli("cloud", "ls", "--json").stdout)+ self.assertIsNone(rows[0]["session"])+ self.assertIsNone(rows[1]["session"])+ self.assertEqual(rows[2]["session"]["id"], "solo")+ self.assertTrue(rows[2]["unmatched"])++ def test_start_does_not_repeat_an_iphone_label(self):+ self.login()+ FakeCloud.available = [+ {"platform": "ios", "kind": "device", "id": "iph-1", "label": "iPhone",+ "state": "available"}]+ r = self.run_cli("cloud", "start", "iPhone", "--no-watch",+ env={"PHONE_HARNESS_ADB": "/nonexistent/adb"})+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertNotIn("iPhone, iPhone", r.stdout)+ self.assertRegex(r.stdout, r"Starting your iPhone(?!,)")+ self.assertRegex(r.stdout, r"\(your iPhone\)")++ def test_shown_expiry_rounds_up_to_the_requested_minutes(self):+ from phone_harness.cloud import _left+ self.assertEqual(_left(time.time() + 6 * 60 - 50), "6 min")+ self.assertEqual(_left(time.time() + 5 * 60), "5 min")+ self.assertTrue(_left(time.time() + 90).endswith("s"))+ self.login()+ r = self.run_cli("cloud", "start", "Temporary phone", "--for", "6", "--no-watch")+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertEqual(FakeCloud.posts[-1]["timeout_seconds"], 360)+ self.assertIn("expires in 6 min", r.stdout)++ def test_a_control_error_prints_its_type_once(self):+ from phone_harness.remote import _plain_error+ self.assertEqual(+ _plain_error("RuntimeError: no installed app matches 'Notes'", RuntimeError),+ "no installed app matches 'Notes'")+ self.assertEqual(+ _plain_error("RuntimeError: RuntimeError: no installed app matches 'Notes'", RuntimeError),+ "no installed app matches 'Notes'")+ self.assertEqual(+ _plain_error("CloudPhoneError: session s expired", RuntimeError),+ "session s expired")+ self.assertEqual(+ _plain_error("RuntimeError: CloudPhoneError: session s expired", RuntimeError),+ "session s expired")+ self.assertEqual(+ _plain_error(+ "phone_harness.cloud.CloudPhoneError: RuntimeError: session s expired",+ RuntimeError),+ "session s expired")+ from phone_harness.cloud import CloudPhoneError+ self.assertEqual(+ _plain_error("CloudPhoneError: RuntimeError: session s expired", CloudPhoneError),+ "session s expired")+ control = ThreadingHTTPServer(("127.0.0.1", 0), FakeControl)+ threading.Thread(target=control.serve_forever, daemon=True).start()+ self.addCleanup(control.server_close)+ self.addCleanup(control.shutdown)+ FakeCloud.control_url = f"http://127.0.0.1:{control.server_port}"+ FakeControl.launch_error = {"error": "RuntimeError: no installed app matches 'Notes'"}+ self.login()+ FakeCloud.available = [+ {"platform": "ios", "kind": "device", "id": "iph-1", "label": "iPhone",+ "state": "available"}]+ started = self.run_cli("cloud", "start", "ios", "--no-watch",+ env={"PHONE_HARNESS_ADB": "/nonexistent/adb"})+ self.assertEqual(started.returncode, 0, started.stderr)+ script = "from phone_harness.helpers import open_app\nopen_app('Notes')\n"+ r = self.run_cli(stdin=script)+ self.assertNotEqual(r.returncode, 0)+ last = [line for line in r.stderr.splitlines() if line.strip()][-1]+ self.assertEqual(last, "RuntimeError: no installed app matches 'Notes'")+ self.assertNotIn("RuntimeError: RuntimeError:", r.stderr)+ FakeControl.launch_error = {+ "error": "phone_harness.cloud.CloudPhoneError: session dead1 expired"}+ again = self.run_cli(stdin=script)+ self.assertNotEqual(again.returncode, 0)+ cloud_last = [line for line in again.stderr.splitlines() if line.strip()][-1]+ self.assertEqual(+ cloud_last, "phone_harness.cloud.CloudPhoneError: session dead1 expired")+ self.assertNotIn("RuntimeError: phone_harness.cloud.CloudPhoneError:", again.stderr)+ self.assertNotIn("CloudPhoneError: phone_harness.cloud.CloudPhoneError:", again.stderr)+ self.assertNotIn("CloudPhoneError: RuntimeError:", again.stderr)+def test_a_session_pin_targets_one_phone_for_commands_and_helpers(self):self.login()FakeCloud.available = [diff --git a/tests/test_update.py b/tests/test_update.pynew file mode 100644index 0000000..b1ff835--- /dev/null+++ b/tests/test_update.py@@ -0,0 +1,186 @@+"""The once-a-day update notice, and `phone-harness update`. No network."""+import io+import json+import os+import sys+import tempfile+import unittest+from contextlib import redirect_stderr, redirect_stdout+from pathlib import Path+from unittest.mock import patch++SRC = str(Path(__file__).resolve().parents[1] / "src")+if SRC not in sys.path:+ sys.path.insert(0, SRC)++from phone_harness import update # noqa: E402+from phone_harness.run import USAGE, _skill_text # noqa: E402+++class _Body:+ def __init__(self, payload):+ self.payload = json.dumps(payload).encode()++ def read(self):+ return self.payload++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return False+++class UpdateCheck(unittest.TestCase):+ def setUp(self):+ self.home = tempfile.TemporaryDirectory()+ self.addCleanup(self.home.cleanup)+ self._old_home = os.environ.get("PHONE_HARNESS_HOME")+ os.environ["PHONE_HARNESS_HOME"] = self.home.name++ def tearDown(self):+ if self._old_home is None:+ os.environ.pop("PHONE_HARNESS_HOME", None)+ else:+ os.environ["PHONE_HARNESS_HOME"] = self._old_home++ def _opener(self, version, calls):+ def opener(req, timeout):+ calls.append((req.full_url, timeout))+ return _Body({"info": {"version": version}})+ return opener++ def test_versions_compare_numerically(self):+ self.assertTrue(update.is_newer("0.4.0", "0.3.0"))+ self.assertTrue(update.is_newer("0.3.10", "0.3.9"))+ self.assertTrue(update.is_newer("1.0", "0.9.9"))+ self.assertFalse(update.is_newer("0.3.0", "0.3.0"))+ self.assertFalse(update.is_newer("0.3.0", "0.4.0"))++ def test_a_newer_release_prints_one_line_and_is_cached_for_a_day(self):+ calls = []+ err = io.StringIO()+ update.announce(opener=self._opener("9.9.0", calls), version="0.3.0",+ now=1_000_000, stderr=err)+ self.assertEqual(+ err.getvalue().strip(),+ "phone-harness 9.9.0 is available (you have 0.3.0): run phone-harness update")+ self.assertEqual(calls, [("https://pypi.org/pypi/phone-harness/json", 2)])+ again = io.StringIO()++ def boom(*args, **kwargs):+ raise AssertionError("cache should have covered a day")++ update.announce(opener=boom, version="0.3.0", now=1_000_000 + 10, stderr=again)+ self.assertEqual(again.getvalue().strip(), err.getvalue().strip())+ cached = json.loads((Path(self.home.name) / "cache" / "update.json").read_text())+ self.assertEqual(cached["latest"], "9.9.0")+ self.assertEqual(cached["checked_at"], 1_000_000)++ def test_the_same_version_is_quiet(self):+ err = io.StringIO()+ update.announce(opener=self._opener("0.3.0", []), version="0.3.0",+ now=1_000_000, stderr=err)+ self.assertEqual(err.getvalue(), "")++ def test_a_network_error_does_not_raise_or_retry_until_tomorrow(self):+ calls = []++ def opener(req, timeout):+ calls.append(1)+ raise TimeoutError("timed out")++ err = io.StringIO()+ update.announce(opener=opener, version="0.3.0", now=1_000_000, stderr=err)+ update.announce(opener=opener, version="0.3.0", now=1_000_000 + 60, stderr=err)+ self.assertEqual(calls, [1])+ self.assertEqual(err.getvalue(), "")++ def test_notice_is_skipped_without_a_tty_when_opted_out_and_in_tests(self):+ self.assertTrue(update.suppressed(+ environ={"PHONE_HARNESS_NO_UPDATE_CHECK": "1"}, isatty=True, testing=False))+ self.assertTrue(update.suppressed(environ={}, isatty=False, testing=False))+ self.assertTrue(update.suppressed(environ={}, isatty=True, testing=True))+ self.assertFalse(update.suppressed(environ={}, isatty=True, testing=False))+ self.assertTrue(update.under_test())+ with patch.object(update, "announce", side_effect=AssertionError("should not run")):+ update.maybe_notify()++ def test_maybe_notify_swallows_a_broken_check(self):+ with patch.object(update, "suppressed", return_value=False), \+ patch.object(update, "announce", side_effect=TimeoutError("nope")):+ update.maybe_notify()+++class UpdateCommand(unittest.TestCase):+ def test_uv_tool_and_git_checkout_are_detected_from_the_path(self):+ self.assertTrue(update.is_uv_tool_prefix(+ Path("/home/me/.local/share/uv/tools/phone-harness")))+ self.assertFalse(update.is_uv_tool_prefix(Path("/usr/lib")))+ self.assertIsNone(update.git_checkout_root(+ Path("/tmp/lib/site-packages/phone_harness/update.py")))+ root = update.git_checkout_root(Path(__file__).resolve())+ self.assertEqual(root, Path(__file__).resolve().parents[1])++ def test_uv_tool_runs_uv_tool_upgrade(self):+ with patch.object(update, "install_mode", return_value="uv"), \+ patch.object(update.subprocess, "call", return_value=0) as call:+ out = io.StringIO()+ with redirect_stdout(out):+ code = update.cmd_update([])+ self.assertEqual(code, 0)+ call.assert_called_once_with(["uv", "tool", "upgrade", "phone-harness"])+ self.assertIn("uv", out.getvalue())++ def test_a_missing_uv_prints_the_command_instead_of_raising(self):+ with patch.object(update, "install_mode", return_value="uv"), \+ patch.object(update.subprocess, "call", side_effect=FileNotFoundError):+ err = io.StringIO()+ with redirect_stdout(io.StringIO()), redirect_stderr(err):+ code = update.cmd_update([])+ self.assertEqual(code, 1)+ self.assertIn("uv tool upgrade phone-harness", err.getvalue())++ def test_a_git_checkout_pulls_ff_only(self):+ root = update.git_checkout_root(Path(update.__file__).resolve())+ self.assertIsNotNone(root)+ with patch.object(update, "install_mode", return_value="git"), \+ patch.object(update.subprocess, "call", return_value=0) as call:+ out = io.StringIO()+ with redirect_stdout(out):+ code = update.cmd_update([])+ self.assertEqual(code, 0)+ call.assert_called_once_with(["git", "-C", str(root), "pull", "--ff-only"])+ self.assertIn(str(root), out.getvalue())++ def test_anything_else_prints_the_pip_command_and_does_not_run_it(self):+ with patch.object(update, "install_mode", return_value="pip"), \+ patch.object(update.subprocess, "call") as call:+ out = io.StringIO()+ with redirect_stdout(out):+ code = update.cmd_update([])+ self.assertEqual(code, 0)+ call.assert_not_called()+ self.assertEqual(out.getvalue().strip(), "pip install -U phone-harness")++ def test_extra_arguments_are_refused(self):+ err = io.StringIO()+ with redirect_stderr(err):+ code = update.cmd_update(["--now"])+ self.assertEqual(code, 2)+ self.assertIn("Usage: phone-harness update", err.getvalue())++ def test_help_and_the_skill_mention_update(self):+ self.assertIn("phone-harness update", USAGE)+ USAGE.encode("ascii")+ skill = _skill_text()+ self.assertIn("phone-harness update", skill)+ self.assertIn("PHONE_HARNESS_NO_UPDATE_CHECK=1", skill)+ skill.encode("ascii")+ readme = Path(__file__).resolve().parents[1].joinpath("README.md").read_text(encoding="utf-8")+ self.assertIn("phone-harness update", readme)+ self.assertIn("pip install -U phone-harness", readme)+++if __name__ == "__main__":+ unittest.main()