Skip to content

let your agent control your phone

cloud: start a phone from the account catalog, drive a cloud iPhone over HTTPS (#105)

shawn panab21bc0123634
diff --git a/README.md b/README.md
index d2f687b..72fc468 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,8 @@
Connect Claude Code, Codex, or any agent to your real phone. **iPhone** through
the Mac's iPhone Mirroring window, **Android** over adb from macOS, Linux or
-Windows. No jailbreak, no
+Windows, or a Phone Harness Cloud phone — an Android over adb, or an iPhone
+over HTTPS. No jailbreak, no
Xcode, nothing installed on the phone. The agent sees the screen, taps, types,
and reads the result.
@@ -60,18 +61,26 @@ guide; [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 cloud login # once: approve in your browser
+phone-harness cloud ls # phones on the account, and any live session
+phone-harness cloud start # cloud.phone if set, else a temporary Android; 15 min (--for 90s, 15m)
+phone-harness cloud start ios # the account's iPhone, when only one is listed
phone-harness <<'PY'
print(screenshot())
PY
-phone-harness cloud stop # billing stops, the phone is saved
+phone-harness cloud stop # billing stops; a saved Android is written back
```
-[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.
+`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
+starts this machine's `cloud.phone` setting if one is set, else what the
+service 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)
+is reached over adb, so every helper works on it unchanged. A cloud iPhone has
+no shell: the helpers POST ops over HTTPS, OCR runs on the host, and driving
+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.
## How it works
@@ -84,8 +93,13 @@ HID-level events for taps, swipes, and typing.
accessibility tree is the text source, `input` is the hands. Works over USB or
Wi‑Fi, no window needed.
-Same helpers on both. `phone-harness config set platform ios|android` picks
-the default.
+**Cloud iPhone.** `phone-harness cloud start` with that phone's catalog id,
+label, or `ios` when it is the only one, drives it over HTTPS from any OS.
+The host runs OCR; taps use the phone's screen points. No adb and no
+accessibility tree. Day-to-day steps are in [SKILL.md](SKILL.md).
+
+Same helpers throughout. `phone-harness config set platform ios|android` picks
+the desk default.
## Limits
diff --git a/SKILL.md b/SKILL.md
index 7e6788c..8108b73 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -1,13 +1,13 @@
---
name: phone-harness
-description: "Control the user's phone — an iPhone through the Mac's iPhone Mirroring window, an Android over adb, or a rented cloud Android: open apps, tap, type, swipe, read the screen."
+description: "Control the user's phone - an iPhone through the Mac's iPhone Mirroring window, an Android over adb, a rented cloud Android, or a cloud iPhone over HTTPS: open apps, tap, type, swipe, read the screen."
---
# phone-harness
-Direct control of a phone from Python scripts. The same helpers drive three
-kinds of phone; what differs is how each one sees and touches the screen, and
-that is what the per-phone sections below are for. Read **Which phone**, the
+Direct control of a phone from Python scripts. The same helpers drive every
+kind of phone below; what differs is how each one sees and touches the screen,
+and that is what the per-phone sections below are for. Read **Which phone**, the
shared **Working method**, and then only the section for the phone in front
of you.
@@ -15,17 +15,19 @@ of you.
| Phone | How it is reached | Eyes | Hands | Read |
| --- | --- | --- | --- | --- |
-| **Cloud Android** — rented from Phone Harness Cloud, the user's own saved phone | `phone-harness cloud start` connects it; nothing to export | accessibility tree (exact), Vision OCR fallback on a Mac | adb `input` | Working method, then **Cloud phones** and **Android** |
-| **Android on the desk** — USB or paired Wi-Fi | the harness finds it | accessibility tree (exact), Vision OCR fallback on a Mac | adb `input` | Working method, then **Android** |
-| **iPhone** — through the Mac's iPhone Mirroring window | the user connects it | screenshots + Vision OCR | HID-level CGEvents into the window | Working method, then **iPhone** |
+| **Cloud Android** - rented from Phone Harness Cloud, the user's own saved phone | `phone-harness cloud start` connects it; nothing to export | accessibility tree (exact), Vision OCR fallback on a Mac | adb `input` | Working method, then **Cloud phones** and **Android** |
+| **Cloud iPhone** - an iOS entry in the account catalog | `phone-harness cloud start` with its id, label, or `ios` when that is the only one | server-side OCR (`source: "pixels"`), from any OS | ops over HTTPS | Working method, then **Cloud iPhone** |
+| **Android on the desk** - USB or paired Wi-Fi | the harness finds it | accessibility tree (exact), Vision OCR fallback on a Mac | adb `input` | Working method, then **Android** |
+| **iPhone** - through the Mac's iPhone Mirroring window | the user connects it | screenshots + Vision OCR | HID-level CGEvents into the window | Working method, then **iPhone** |
`phone-harness config` shows the default platform (`ios` on a Mac, `android`
elsewhere) and every other setting. `phone-harness cloud` shows whether a cloud
-phone is attached; while one is, scripts drive it regardless of the default.
-`PHONE_HARNESS_PLATFORM=android` overrides per call.
+phone is attached; while one is, scripts drive it regardless of the config
+default. `PHONE_HARNESS_PLATFORM=android` overrides per call. On a cloud
+iPhone any explicit platform selects a local backend; see **Cloud iPhone**.
-**When not to use any of them:** if the task is doable on the Mac or the web —
-a website, an API, an app with a web equivalent — do it there and leave the
+**When not to use any of them:** if the task is doable on the Mac or the web -
+a website, an API, an app with a web equivalent - do it there and leave the
phone alone. Use a phone when the task genuinely needs one: phone-only apps,
things tied to a phone number or 2FA, checking how something looks on a phone.
@@ -46,16 +48,16 @@ PY
- **Tell the user what you are doing as you go.** A phone task is many short
scripts and the user sees none of them: one line before each script (what
you are about to do), one line after (what you saw). Never run two scripts
- in a row in silence. The `# task:`/`# step:` comments are not this — the user
+ in a row in silence. The `# task:`/`# step:` comments are not this - the user
cannot see them.
- **Read with `ocr()`, not by eyeballing screenshots.** Every visible string
comes back with a tap-ready centre: `[{text, confidence, source, x, y, w, h}]`.
Filter in Python before printing. `tap_text("Weather")` taps by label and,
- on failure, raises with what IS visible — read the exception before retrying.
+ on failure, raises with what IS visible - read the exception before retrying.
`screenshot()` costs more but shows what OCR cannot: icons, images, state.
- **Act, verify, adapt.** There is no DOM to assert against and no return value
that means "it worked", so:
- 1. Name what should change before you act — a title, a row, a field's
+ 1. Name what should change before you act - a title, a row, a field's
contents. Most phone failures are silent no-ops; if you cannot name the
expected change you cannot tell success from one.
2. Do one thing, then check that one thing: `wait_for_text("Got it")`,
@@ -68,17 +70,17 @@ PY
5. Keep what you learn in `agent-workspace/agent_helpers.py`.
- **The harness reports, you decide.** Helpers return observations, never a
verdict on your intent. Diff two `ocr()` sets, watch one label, count rows,
- poll until something appears — whatever matches what you asked for.
+ poll until something appears - whatever matches what you asked for.
- **Navigation:** `home()`, `back()`, `app_switcher()`, `open_app("Notes")`,
`type_text("...")`, `press("enter")`, `long_press(x, y)`, `tap(x, y)`.
- **`scroll` says what you want to SEE; `swipe` says which way the finger
- goes.** English disagrees the same way — "scroll down the page" and "swipe
+ goes.** English disagrees the same way - "scroll down the page" and "swipe
up for the next video" describe the same motion. `scroll("down")` reveals
what is further down; `swipe("up")` is a thumb flick, the phrasing everyone
uses for "next". `scroll`, `scroll_screen`, `scroll_until` and
`scroll_collect` take the content direction; only `swipe` takes finger
motion. `"left"`/`"right"` work on both. Which one moves what differs per
- phone — see each section.
+ phone - see each section.
- **Walking a list:** `scroll_until(done)` stops when your predicate on the
visible boxes is met; `scroll_collect(extract, key=...)` walks and de-dupes,
returning `{items, stop, scrolls}` with `stop` of `'reached-end'` or
@@ -97,58 +99,183 @@ PY
- **Connection is the user's job.** Pairing, unlocking, tapping Allow,
locking an iPhone that says "iPhone in Use", approving a cloud sign-in in
the browser: when the harness says the phone is not reachable, relay its
- message and ask — never tap through a Connect screen and never loop-poll.
+ message and ask - never tap through a Connect screen and never loop-poll.
Retry once after the user says it is done.
## 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.
+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 temporary
+phone. 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.
+
+`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
+no `platform` or `kind` and gets the service's rule for an unnamed start
+(`GET /me` -> `unnamed`): a temporary Android. A name is a catalog id
+or label, or `ios` / `android` when only one entry has that platform. Several
+matches print the catalog and stop (a terminal may ask which one). The CLI
+turns the chosen row into `platform` and `kind`, plus `device_id` for an
+iPhone or `profile_id` for the saved Android. The temporary row sends neither
+id.
+
+What the helpers do next follows the session's link, not the platform name.
+An adb link is the Android section. A control link (`{url, token}`) is
+**Cloud iPhone**.
```bash
-phone-harness cloud # signed in? a phone attached? minutes left?
-phone-harness cloud start # ~15s; opens the live view; safe to run twice (reattaches)
-phone-harness cloud start --minutes 25 # default 15, cap 30 (config: cloud.minutes, cloud.max_minutes)
-phone-harness cloud start --temp # a throwaway phone that keeps nothing
-phone-harness cloud ls # every running session (* = attached)
-phone-harness cloud phone # the saved phone: stored / running / saving
-phone-harness cloud watch # reopen the read-only live view (--print to share the link)
-phone-harness cloud open # the dashboard: the user takes the controls (their sign-in)
-phone-harness cloud stop # ends billing and saves the phone; returns at once
+phone-harness cloud # signed in? which session is attached? time left?
+phone-harness cloud ls # catalog, live sessions inlined; --json for the rows
+phone-harness cloud start # cloud.phone if set, else a temporary Android; opens the live view
+phone-harness cloud start ios --for 15m # one iPhone, fifteen minutes
+phone-harness cloud start "Temporary phone" --for 90s
+phone-harness --session SID <<'PY' # this process only; or PHONE_HARNESS_SESSION
+print(screen_info())
+PY
+phone-harness cloud stop # ends billing; returns at once
+phone-harness cloud phone # the saved Android's stored state
+phone-harness cloud watch # reopen the read-only live view (--print to share)
+phone-harness cloud open # the dashboard: the user takes the controls
```
+- **Pin a session when more than one can be up.** `--session SID` or
+ `PHONE_HARNESS_SESSION` selects one phone for this process, and every
+ `cloud` command and helper honours it. With neither, a person at a terminal
+ gets the attached session: the last `cloud start`, or `cloud use SID`.
+ `cloud use` rewrites that shared fallback. Parallel agents should pass
+ `--session` and leave `cloud use` alone, or they will steal the fallback
+ from each other.
- **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.
+ whole conversation. Stop it when the user is done, and say that you did.
+ `--for` is the length: `90s`, `15m` / `15min`, or a bare number of minutes.
+ Default 15, cap 30 (`cloud.minutes`, `cloud.max_minutes`).
- **Stop before the deadline; 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 under two minutes; `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 it running unless
- they ask you to stop it.
+ runs out keeps a saved Android's data but not its running state. The harness
+ warns on stderr under two minutes; `phone-harness cloud` shows the time left.
+ `cloud stop` returns at once. Stopping an adb phone that has a profile saves
+ it; `cloud start` of that phone waits out a save still in progress. A
+ control link keeps its data on the phone, so there is nothing to wait for.
+- **Already running.** Starting a phone this machine already holds for the
+ same catalog choice reuses that session. If the service says it is held
+ elsewhere (`409` `profile_running`), the message names the SID and says to
+ attach with `--session SID`. Do that; do not start a second one. `409`
+ `device_unavailable` means the phone is granted but not on its host.
+ `409` `session_limit` names how many sessions are in use. `503`
+ `phones_busy` includes `Retry-After`. `403` `account_blocked` means rentals
+ are blocked; a `403` about credit or balance means add credit. A `400` that
+ names no such phone reprints the catalog.
- **`Not signed in`** means the user runs `phone-harness cloud login` and
- approves it in a browser. Relay that; you cannot do it for them. A user
- without an account is pointed at phone-harness.com by the CLI itself.
-- **Watching versus controlling.** `cloud start` opens the phone's live view
- in the user's browser so they can watch you work; it is read-only and
- `cloud watch` reopens it. When the user wants to drive themselves — a
- password, a 2FA prompt, or just to take over — run `phone-harness cloud open`
- (the dashboard, behind their own sign-in) and wait for them to say they are
- done before you touch the phone again.
-- 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.
+ approves it in a browser. Relay that; you cannot do it for them.
+- **Watching versus controlling.** `cloud start` opens the live view so the
+ user can watch. `cloud watch` reopens it. For a password, a 2FA prompt, or
+ the user taking over, run `phone-harness cloud open` and wait until they say
+ they are done.
+- **`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.
+- The adb address the CLI shows is not a secret; the unlock code is. Do not
+ look for it, print it, or ask the user for it.
+
+## Cloud iPhone
+
+Start it from the catalog: `phone-harness cloud start ios` when that is
+unambiguous, or the entry's id or label (`cloud ls`). The create body is
+`platform: "ios"`, `kind: "device"`, and `device_id` set to that entry's id.
+A ready session carries `control: {url, token, expires_at}` and no `adb`.
+From then on the helpers drive it over HTTPS. This machine needs no adb, no
+shell, and no Mac. `cloud stop` ends billing and returns at once; the phone
+keeps its own data. There is no Android-style disk save, and nothing on this
+phone for `cloud phone` to wipe.
+
+An Android session can stay up beside it. Target one with `--session SID`.
+`cloud use SID` only changes the terminal fallback.
+
+Length, billing, `ls`, `watch`, and `stop` are the **Cloud phones** commands
+above. An iPhone session reports `billing_mode: disabled`. Run scripts as
+plain `phone-harness` (with `--session` when you must pin one).
+`PHONE_HARNESS_PLATFORM=...` selects a local backend and skips the attached
+cloud phone.
+
+The mirroring section describes a Mac window. This phone is the HTTPS path.
+
+The client posts `{"op", "kw"}` to `<control url>/op` and reads the host's
+list from `GET <control url>/ops` (`remote.py`). `supports(op)` is that list.
+`send` of an op the host did not list raises `Unsupported` before the POST
+(`this cloud phone cannot '...'`). The op names and the shapes below are the
+client vocabulary in `transport.py`. Result shapes are what this repo
+documents or decodes.
+
+| Op | Arguments | Result this client uses |
+| --- | --- | --- |
+| `screen.capture` | `path` optional | `(png_path, bounds)`. On the wire the host returns `png_b64` and `bounds`; the client writes the PNG. Timeout 60s. |
+| `screen.bounds` | | `{x, y, w, h, id}` or None |
+| `screen.require` | | bounds, or raise |
+| `screen.text` | `min_confidence` | `[{text, confidence, source, x, y, w, h}]`. `source` is `"pixels"` or `"tree"`. |
+| `screen.text_pixels` | `min_confidence` | same, forced through pixel OCR |
+| `input.tap` | `x, y` | host result, passed through |
+| `input.press` | `x, y, duration` | host result. Long press. |
+| `input.drag` | `x1, y1, x2, y2, duration, steps` | host result |
+| `input.scroll` | `x, y, dy, dx, steps` | host result. Content-space deltas. |
+| `input.keys` | `combo` | host result |
+| `input.text` | `s, delay, keystrokes` | host result. Timeout `max(60, 0.2 * len(s) + 30)` seconds. |
+| `nav.home` / `nav.back` / `nav.recents` | | host result, or `Unsupported` when the host says `unsupported` |
+| `apps.launch` | `name`, `fresh` | app id. Timeout 90s. |
+| `apps.current` | | app id or None |
+| `apps.list` | `include_system` | `[app id]`. Timeout 90s. |
+| `session.state` | | backend-defined string; `'ready'` when usable |
+| `session.require` | | bounds, or raise telling the user what to do |
+| `session.refocus` | | `None` here. The client does not call the host. |
+| `session.detail` | | a string. Local. |
+| `focus.probe` | | an opaque snapshot. Local: `(True,)`. |
+| `focus.diff` | `before, after` | `{raised, stole_focus}`. Local: both false. |
+| `tree` | | `[node]` where the device has one |
+| `raw` | backend-specific | host result |
+
+Trust `GET /ops` when the host's list is shorter than this table.
+
+- **Coordinates are `screen.bounds`.** `tap(x, y)`, `find_window()`,
+ `send("screen.require")`, and OCR centres all use that space:
+ `{x, y, w, h, id}`. A point read off the PNG goes through
+ `tap_image_point()` once `screen_info()` returns `img_px`. Otherwise tap
+ an OCR centre.
+- **`screen_info()`, `image_point()`, and `tap_image_point()` measure the
+ PNG** so a point you read off a screenshot can become a tap. If
+ `screen_info()` raises `ModuleNotFoundError: No module named 'Quartz'`,
+ that helper imported the macOS Vision module to read the PNG's pixel size.
+ `ocr()` sends `screen.text` to the host and still works - keep using
+ `tap_text()`. If `screen_info()` returns `img_px`, those three helpers work
+ on any OS. [PR #108](https://github.com/ShawnPana/phone-harness/pull/108)
+ ("screen_info() no longer needs macOS") is the change that reads the PNG
+ header instead of importing Quartz; until `screen_info()` returns `img_px`
+ off a Mac, treat the Quartz error as those three helpers only.
+- **`type_text()` types into the focused field.** Tap the field first. Text
+ sent before the field has focus goes nowhere, so check with `ocr()`
+ afterwards.
+- **Act, then look.** One action, then `ocr()` or `screenshot()`, then the
+ next. Do not `wait(n)` for a screen to load. The client allows
+ `screen.capture` 60s, `apps.launch` and `apps.list` 90s, and `input.text`
+ the timeout in the table.
+- **Errors the client raises.** HTTP 400 with `unsupported: true` raises
+ `Unsupported` (retrying will not help). HTTP 404 raises `RuntimeError`:
+ the session is gone or the grant expired. Any other HTTP status raises
+ `RuntimeError` with the host's `error` string. Create-time
+ `device_unavailable`, `profile_running`, and `phones_busy` happen on
+ `cloud start`, before any op, and are described under **Cloud phones**.
+- **`ui()`, `back()`, and `current_app()` raise Unsupported** when the host
+ does not list `tree`, `nav.back`, and `apps.current`. `home()` is the Home
+ button. `shell()` is Unsupported.
+- **Confirm `open_app`.** It sends `apps.launch` and can return with the app
+ still not in front. Check with `ocr()` or a screenshot. If it missed,
+ `home()` and tap the icon. `tap_icon()` in
+ `agent-workspace/agent_helpers.py` aims 35 points above the label for the
+ mirroring window, so measure this phone's icon yourself.
## Android
-The phone is reached over adb — a USB phone if plugged in, else the paired
-Wi-Fi phone, else the attached cloud phone — so there is nothing to select.
+The phone is reached over adb - a USB phone if plugged in, else the paired
+Wi-Fi phone, else the attached cloud Android - so there is nothing to select.
`phone-harness android` shows known phones and what is attached.
```bash
@@ -159,11 +286,11 @@ PY
```
- **Coordinates are device pixels;** the screenshot is 1:1 with `tap(x, y)`.
-- **`ocr()` is the accessibility tree** (`source: "tree"`) — exact, no
+- **`ocr()` is the accessibility tree** (`source: "tree"`) - exact, no
misreads. Prefer `ui()` / `find_nodes()` / `tap_ui()`: they also see
elements with no visible text (icons with a content-description, fields by
resource-id like `tap_ui("url_bar")`).
-- **Some screens never give up their tree** — a playing video, some Settings
+- **Some screens never give up their tree** - a playing video, some Settings
pages. On a Mac, `ocr()` then reads the screenshot with Vision instead
(`source: "pixels"`, fuzzier, still tap-ready; the first read costs ~12s
while uiautomator gives up, later reads are fast). Elsewhere it raises
@@ -174,12 +301,12 @@ PY
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 are one-line wrappers over the same
- commands — use whichever you think in. What the harness adds: finding and
+ commands - use whichever you think in. What the harness adds: finding and
reconnecting the phone, and the screen as a short list instead of XML.
- **`scroll` and `swipe` are different gestures here.** `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
+ `swipe` is a flick and coasts past whatever was next - right for "next
video" or changing pages, wrong for reading a list.
- `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,
@@ -188,7 +315,7 @@ PY
- `press()` takes single keys only (`"enter"`, `"back"`, `"tab"`); chords
raise Unsupported. `type_text` types ASCII: adb cannot type emoji or
accented letters.
-- **Verify cheaply, then read.** adb reports nothing about outcomes — a tap on
+- **Verify cheaply, then read.** adb reports nothing about outcomes - a tap on
empty space "succeeds". After an action: `wait_for_app(...)` (~0.1s a poll)
or `wait_for_text(...)` (returns the box or None), then `ui()`/`ocr()` once.
The tree costs ~2-3s a call on a slow phone and a screenshot ~0.5s, so
@@ -198,13 +325,13 @@ PY
`interruption(before, after)` always reports nothing disturbed.
- **A desk phone locks itself** after its screen timeout. `connection_state()`
reports `locked`; taps and `ocr()` refuse with the same message. Ask the user
- to unlock — never type a PIN. `screenshot()` still works locked, so you can
+ to unlock - never type a PIN. `screenshot()` still works locked, so you can
show them what you see. For a task longer than a minute, ask the user, then
`phone-harness android awake --bg` keeps it awake without changing any phone
setting; `phone-harness android rest` ends that. Cloud phones do not lock.
- Connecting a desk phone is the user's job (USB debugging + Allow, or
Wireless debugging + `phone-harness android pair CODE`); on `no-device` the
- error names the missing step — relay it, don't retry-loop.
+ error names the missing step - relay it, don't retry-loop.
## iPhone (iPhone Mirroring)
@@ -215,7 +342,7 @@ events into it for hands. All coordinates are global macOS screen points.
- `ensure_mirroring()` launches the window and gates on connection. The
default build works the phone **without taking the user's focus**: capture
is by window id and taps and keystrokes are event records delivered straight
- to the app. Scrolling is the exception — macOS routes a scroll to whichever
+ to the app. Scrolling is the exception - macOS routes a scroll to whichever
window sits under the pointer, so a scroll raises the mirroring window for
the length of the gesture and hands focus straight back. Expect a brief
flicker on scrolls and nothing on anything else. `PHONE_HARNESS_BACKGROUND=0`
@@ -227,7 +354,7 @@ events into it for hands. All coordinates are global macOS screen points.
from the current `screen_info()`; never estimate the window offset.
- **Use `scroll` for anything scrollable.** On macOS 26 a vertical touch-drag
is dropped, so `swipe("up")`/`swipe("down")` move nothing in a list or a
- feed — measured on Settings and on TikTok. Horizontal still works, so
+ feed - measured on Settings and on TikTok. Horizontal still works, so
`swipe("left")` / `swipe("right")` remain the way to flip Home Screen pages
and carousels, which a scroll cannot do. (Breaking change: `scroll` used to
take finger motion too, so the old `scroll("up")` is today's
@@ -248,12 +375,12 @@ events into it for hands. All coordinates are global macOS screen points.
Never tap `Connect` / `Continue` and never loop-poll: tapping Connect while
the phone is unlocked does nothing, and the only fix is the user locking or
connecting the phone. **Unlocking the physical phone pauses the session**
- ("iPhone in Use") — do not tap through the resume screen.
-- **Unfocused input is swallowed silently — for events you post yourself.**
+ ("iPhone in Use") - do not tap through the resume screen.
+- **Unfocused input is swallowed silently - for events you post yourself.**
The helpers are immune in the background build, but raw CGEvents and the
`PHONE_HARNESS_BACKGROUND=0` path need the window frontmost: `activate()`
before posting, and re-activate if a click steals focus. The failure looks
- exactly like "scrolling is broken" or "the list already ended" — when a
+ exactly like "scrolling is broken" or "the list already ended" - when a
gesture changes nothing on screen, check focus before inventing another
theory.
- **The window is a video stream.** macOS accessibility sees nothing inside
@@ -263,7 +390,7 @@ events into it for hands. All coordinates are global macOS screen points.
- Mouse taps map to touches 1:1, but there is no multi-touch: no pinch, no
two-finger gestures.
- Raw Quartz is the escape hatch: `import Quartz` in your script for anything
- the helpers don't cover — but raw CGEvents don't ride the helpers' delivery
+ the helpers don't cover - but raw CGEvents don't ride the helpers' delivery
path, and where they land is its own question per event type. Check what
actually happened on screen rather than assuming the event arrived.
diff --git a/install.md b/install.md
index f5a50a6..c60345a 100644
--- a/install.md
+++ b/install.md
@@ -1,9 +1,12 @@
# phone-harness install
-phone-harness drives a real phone from a Mac (first-run flow for agents:
-`onboarding.md`; day-to-day usage: `SKILL.md`). It works with an **iPhone** through the macOS
-iPhone Mirroring app, or an **Android** over adb (USB or Wi‑Fi). Same helpers
-either way; you choose a default and can switch per call.
+phone-harness drives a real phone (first-run flow for agents: `onboarding.md`;
+day-to-day usage: `SKILL.md`). It works with an **iPhone** through the macOS
+iPhone Mirroring app, an **Android** over adb (USB or Wi‑Fi), or a phone from
+Phone Harness Cloud — an Android over adb, or an iPhone the helpers drive over
+HTTPS (`phone-harness cloud start` with that phone's name from `cloud ls`).
+Same helpers either way; you
+choose a default and can switch per call.
## Common
@@ -19,7 +22,8 @@ mkdir -p "${CODEX_HOME:-$HOME/.codex}/skills/phone-harness"
phone-harness skill > "${CODEX_HOME:-$HOME/.codex}/skills/phone-harness/SKILL.md"
```
-- Python 3.10+, any OS. **iPhone needs a Mac** (it drives iPhone Mirroring);
+- Python 3.10+, any OS. **iPhone Mirroring needs a Mac.** A cloud iPhone
+ (`cloud start` of the iOS catalog entry) is driven over HTTPS from any OS.
**Android works on macOS, Linux and Windows** and is the default off a Mac.
Only the CLI? `pip install phone-harness` works too; the
checkout is what makes the harness editable (`agent-workspace/agent_helpers.py`).
@@ -31,9 +35,13 @@ phone-harness skill > "${CODEX_HOME:-$HOME/.codex}/skills/phone-harness/SKILL.md
Re-run the `phone-harness skill > …/SKILL.md` lines after pulling updates so
the agent's copy matches the code.
-- **No phone on your desk?** `phone-harness cloud login` then
- `phone-harness cloud start` rents your own Android in the cloud; new accounts
- get $5 of credit (100 minutes). It needs only adb (below) — nothing to pair.
+- **No phone on your desk?** `phone-harness cloud login`, then
+ `phone-harness cloud ls` and `phone-harness cloud start` (the account
+ default) or `phone-harness cloud start PHONE` for a catalog id, label, or
+ `ios` / `android` when that names one phone. An Android needs adb, below.
+ An iPhone needs no adb and no Mac; driving it is **Cloud iPhone** in
+ `SKILL.md`. A start lasts 15 minutes unless you pass `--for` (`90s`, `15m`,
+ or a number of minutes). New accounts get $5 of credit (100 minutes).
## iPhone
@@ -78,8 +86,9 @@ the agent's copy matches the code.
## Both
Set up each as above; `phone-harness config set platform …` picks the default,
-`PHONE_HARNESS_PLATFORM=…` picks per call. The two never interfere — the
-iPhone is driven through the mirroring window, the Android over adb.
+`PHONE_HARNESS_PLATFORM=…` picks per call. The desk phones never interfere —
+the iPhone is driven through the mirroring window, the Android over adb. A
+cloud iPhone is a third path: HTTPS ops, covered in `SKILL.md`.
`phone-harness config set telemetry false` turns off anonymous usage telemetry.
diff --git a/pyproject.toml b/pyproject.toml
index 8b9065b..da94e33 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,7 +1,7 @@
[project]
name = "phone-harness"
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"
+description = "Let an agent drive a real phone: an iPhone through macOS iPhone Mirroring, an Android over adb, a rented cloud Android, or a cloud iPhone over HTTPS"
readme = "README.md"
license = "MIT"
license-files = ["LICENSE"]
diff --git a/src/phone_harness/android.py b/src/phone_harness/android.py
index 5081519..f0efb38 100644
--- a/src/phone_harness/android.py
+++ b/src/phone_harness/android.py
@@ -191,7 +191,7 @@ class Android(Backend):
if not self._resolved and self._resolve() is None:
self._session_require() # raises with the physical step
from . import cloud
- rented = cloud.attached()
+ rented = cloud.attached("adb")
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
@@ -225,7 +225,7 @@ class Android(Backend):
self._resolved = True
return os.environ["ANDROID_SERIAL"]
from . import cloud
- rented = cloud.attached()
+ rented = cloud.attached("adb")
if rented:
# Not remembered below: its address is reused by other phones.
os.environ["ANDROID_SERIAL"] = cloud.ensure_connected(rented)
@@ -690,7 +690,7 @@ CLI_USAGE = """Usage:
phone-harness android forget NAME
phone-harness android awake [--bg] [--no-mirror]
keep the phone awake for a session (and mirror it if scrcpy is
- installed); changes no phone settings — ends with rest, Ctrl-C, or
+ installed); changes no phone settings - ends with rest, Ctrl-C, or
closing the mirror. --bg detaches.
phone-harness android rest end the session; the phone sleeps
"""
diff --git a/src/phone_harness/cloud.py b/src/phone_harness/cloud.py
index 3b0a5bf..42d3c3d 100644
--- a/src/phone_harness/cloud.py
+++ b/src/phone_harness/cloud.py
@@ -1,9 +1,12 @@
-"""Phone Harness Cloud: rent an Android phone, then drive it like any other.
+"""Phone Harness Cloud: rent a 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.
+one. `cloud start` picks an entry from the account catalog (`GET /me` →
+`available`) and the service returns a session. The session carries one link:
+an Android phone is adb at host:port (`adb connect` and `unlock` live here),
+and a phone with no shell carries a control URL that remote.py drives over
+HTTPS. Which link it is, not the platform name, is what the rest of the CLI
+branches on.
auth.json (config dir, 0600) this machine's sign-in: OAuth tokens from
`cloud login`, refreshed here as they expire
@@ -36,10 +39,11 @@ USER_AGENT = "phone-harness-cli"
class CloudError(RuntimeError):
- def __init__(self, status, body):
+ def __init__(self, status, body, headers=None):
self.status = status
self.body = body if isinstance(body, dict) else {}
self.code = self.body.get("code")
+ self.headers = headers
super().__init__(self.body.get("error") or f"HTTP {status}")
@@ -176,10 +180,6 @@ def _api(method, path, body=None, token=None, headers=None, timeout=40):
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"
@@ -195,7 +195,7 @@ def _request(method, path, body, token, headers, timeout):
parsed = json.loads(raw)
except ValueError:
parsed = {"error": raw.decode(errors="replace")[:200]}
- raise CloudError(e.code, parsed) from None
+ raise CloudError(e.code, parsed, e.headers) from None
return json.loads(raw) if raw.strip() else {}
@@ -203,29 +203,115 @@ 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"{_waitlist_line()}")
- if e.status == 402 or "balance_cents" in e.body:
+ if e.status == 403 and e.code == "account_blocked":
+ return f"Rentals are blocked on this account ({e})."
+ if e.status in (402, 403) and (
+ e.code in ("insufficient_balance", "balance") or "balance_cents" in e.body
+ or "credit" in str(e).lower() or "balance" in str(e).lower()):
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 e.status == 403:
+ # beta_access_required keeps the waitlist line the older CLI printed.
+ return (f"Your account isn't enabled for phones yet ({e}). "
+ f"{_waitlist_line()}")
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.")
+ if e.code == "session_limit":
+ count, limit = e.body.get("active_session_count"), e.body.get("session_limit")
+ extra = f" ({count} of {limit})" if count is not None and limit is not None else ""
+ return f"Session limit reached{extra}. `phone-harness cloud ls` shows them."
+ if e.code == "phones_busy":
+ retry = _retry_after(e)
+ when = f" Try again in {retry}s." if retry else " Try again shortly."
+ return f"Every phone is busy right now.{when}"
+ if e.code == "device_unavailable":
+ return ("That phone is granted to this account but not on its host right now. "
+ "Try again once it is connected.")
return f"{e} (HTTP {e.status})"
+def _retry_after(e):
+ raw = e.headers.get("Retry-After") if getattr(e, "headers", None) else None
+ if raw is None:
+ raw = e.body.get("retry_after_seconds")
+ try:
+ return int(raw)
+ except (TypeError, ValueError):
+ return None
+
+
# --- 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."""
+# A saved session reaches its phone through exactly one link:
+# {"kind": "adb", "host", "port", "code"} an Android: adb connect + unlock
+# {"kind": "control", "url", "token"} no shell (a real iPhone): ops over HTTPS
+LINK_KINDS = ("adb", "control")
+
+
+def _as_linked(sess):
+ """A session record the helpers can drive, or None.
+
+ Current files store `link`. A file written by the Android-only CLI stores
+ host/port/code on the session itself; that is an adb link, so an upgrade
+ mid-session keeps driving the phone that is already running.
+ """
+ if not isinstance(sess, dict):
+ return None
+ link = sess.get("link")
+ if isinstance(link, dict) and link.get("kind") in LINK_KINDS:
+ return sess
+ if sess.get("host") and sess.get("code"):
+ return {**sess, "link": {"kind": "adb", "host": sess["host"],
+ "port": sess.get("port"), "code": sess["code"]}}
+ return None
+
+
+def _known_sessions(state):
+ """sid -> record, including the single attached session older files store."""
+ sessions = dict(state.get("sessions") or {})
+ current = state.get("session")
+ if isinstance(current, dict) and current.get("sid") and current["sid"] not in sessions:
+ sessions[current["sid"]] = current
+ return sessions
+
+
+def _find_recorded(state, pin):
+ sessions = _known_sessions(state)
+ if pin in sessions:
+ return sessions[pin]
+ hits = [s for sid, s in sessions.items() if sid.startswith(pin)]
+ return hits[0] if len(hits) == 1 else None
+
+
+def attached(kind=None):
+ """The session the helpers should drive, or None; with `kind`, only a
+ session reached that way.
+
+ `PHONE_HARNESS_SESSION` (or `--session`, which sets it) pins one session
+ for this process, so parallel agents do not share the state file's
+ fallback. 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:
- sess = _load_state().get("session")
+ state = _load_state()
except Exception:
+ state = {}
+ pin = os.environ.get("PHONE_HARNESS_SESSION")
+ if pin:
+ raw = _find_recorded(state, pin)
+ sess = _as_linked(raw)
+ if sess is None:
+ sess = _pull_pinned(pin)
+ else:
+ try:
+ sess = _as_linked(state.get("session"))
+ except Exception:
+ return None
+ if sess is None:
return None
- if not isinstance(sess, dict) or not sess.get("host") or not sess.get("code"):
+ if kind not in (None, sess["link"]["kind"]):
return None
if sess.get("expires_at") and time.time() >= sess["expires_at"]:
return None
@@ -233,7 +319,54 @@ def attached():
def serial_of(sess):
- return f"{sess['host']}:{sess['port']}"
+ """The adb serial of an adb-linked session."""
+ return f"{sess['link']['host']}:{sess['link']['port']}"
+
+
+def _describe_link(sess):
+ if sess["link"]["kind"] == "control":
+ return "no shell on this phone; the helpers drive it over HTTPS"
+ return serial_of(sess)
+
+
+def _link_kind(session):
+ """adb or control, from a saved record or from the API session. None when
+ the session has not said yet (still provisioning, no block)."""
+ if not isinstance(session, dict):
+ return None
+ link = session.get("link")
+ if isinstance(link, dict) and link.get("kind") in LINK_KINDS:
+ return link["kind"]
+ if (session.get("control") or {}).get("url"):
+ return "control"
+ if (session.get("adb") or {}).get("host") or session.get("host"):
+ return "adb"
+ return None
+
+
+def _keeps_state(session):
+ """Whether stopping saves the phone. A control link keeps its data on the
+ phone, even when the session also names a profile. An adb link with a
+ profile is written to storage after the session ends."""
+ if _link_kind(session) == "control":
+ return False
+ return bool(session.get("profile"))
+
+
+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"
+
+
+def _adb_present():
+ 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).")
def ensure_connected(sess, quiet=False):
@@ -251,7 +384,7 @@ def ensure_connected(sess, quiet=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)
+ _run("-s", serial, "shell", "unlock", sess["link"]["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 "
@@ -264,35 +397,106 @@ def ensure_connected(sess, quiet=False):
return serial
-def _attach(session, profile_id=None):
- """Remember a ready session and connect to it."""
+def _link(session):
+ """How the helpers reach a ready session (see LINK_KINDS)."""
+ control = session.get("control") or {}
+ if control.get("url") and control.get("token"):
+ return {"kind": "control", "url": control["url"], "token": control["token"]}
+ _adb_present()
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"),
+ return {"kind": "adb", "host": adb["host"], "port": adb["port"], "code": adb["code"]}
+
+
+def _session_record(session, selector=None, label=None):
+ phone = session.get("phone")
+ return {
+ "sid": session["id"], "platform": session.get("platform"),
+ "kind": session.get("kind"),
+ "device_id": session.get("device_id") or (phone if isinstance(phone, str) else None),
+ "label": label or session.get("label"),
+ "profile": session.get("profile"), "expires_at": session.get("expires_at"),
+ "watch_url": session.get("watch_url"), "selector": selector,
+ "link": _link(session),
}
- if profile_id:
- state["profile_id"] = profile_id
+
+
+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."""
+ state = _load_state()
+ sessions = _known_sessions(state)
+ sessions[record["sid"]] = record
+ state["sessions"] = sessions
+ if make_attached or not isinstance(state.get("session"), dict):
+ state["session"] = record
+ if make_attached and record.get("profile"):
+ state["profile_id"] = record["profile"]
_save_state(state)
- return ensure_connected(state["session"], quiet=True)
+ if record["link"]["kind"] == "adb":
+ ensure_connected(record, quiet=True)
+ return record
+
+
+def _attach(session, profile_id=None, selector=None, label=None):
+ """Remember a ready session and connect to it."""
+ record = _session_record(session, selector=selector, label=label)
+ if profile_id and not record.get("profile"):
+ record["profile"] = profile_id
+ return _store_session(record, make_attached=True)
+
+
+def _pull_pinned(pin):
+ """A pinned sid that this machine has not remembered yet. Raises when it
+ does not name one running session, so a helper does not fall through to
+ the phone on the desk."""
+ try:
+ sessions = _api("GET", "/sessions")
+ except CloudError as e:
+ raise RuntimeError(f"could not resolve --session {pin}: {_explain(e)}") from None
+ except OSError as e:
+ raise RuntimeError(f"could not resolve --session {pin}: {e}") from None
+ hits = [s for s in sessions if s.get("id") == pin] or [s for s in sessions if str(s.get("id", "")).startswith(pin)]
+ if len(hits) != 1:
+ raise RuntimeError(f"{pin!r} matches {len(hits)} running sessions"
+ + (f": {', '.join(s['id'] for s in hits)}" if hits else ""))
+ session = hits[0]
+ if session.get("state") != "ready":
+ session = _wait_ready(session["id"])
+ return _store_session(_session_record(session), make_attached=False)
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)
+ sessions = _known_sessions(state)
+ current = state.get("session") if isinstance(state.get("session"), dict) else None
+ if sid is None:
+ targeted = _as_linked(current)
+ sids = [targeted["sid"]] if targeted and targeted.get("sid") else []
+ else:
+ sids = [sid]
+ for target in sids:
+ rec = _as_linked(sessions.get(target))
+ if rec is None and current and current.get("sid") == target:
+ rec = _as_linked(current)
+ if rec and rec["link"]["kind"] == "adb":
+ try:
+ from .android import _run
+ _run("disconnect", serial_of(rec), timeout=10, check=False)
+ except Exception:
+ pass
+ sessions.pop(target, None)
+ if current and current.get("sid") == target:
+ state.pop("session", None)
+ current = None
+ if sessions:
+ state["sessions"] = sessions
+ else:
+ state.pop("sessions", None)
+ _save_state(state)
# --- small things ------------------------------------------------------------
@@ -350,7 +554,7 @@ def _resolve_sid(given):
if given is None:
sess = attached()
if not sess:
- sys.exit("No cloud phone attached. `phone-harness cloud ls` lists running ones.")
+ sys.exit("No cloud phone attached. Pass --session SID, or `phone-harness cloud ls`.")
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)]
@@ -486,26 +690,154 @@ def _describe_profile(profile):
# --- 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."""
+def _catalog(me):
+ available = me.get("available") if isinstance(me, dict) else None
+ return list(available) if isinstance(available, list) else []
+
+
+def _unnamed(me):
+ """What the service gives a start that names nothing: its own rule
+ (`GET /me` → `unnamed`), a temporary Android. Never a preference."""
+ rule = me.get("unnamed") if isinstance(me, dict) else None
+ if isinstance(rule, dict) and rule.get("platform"):
+ return {**rule, "temporary": bool(rule.get("temporary", True))}
+ return {"platform": "android", "kind": "emulator", "temporary": True}
+
+
+def _entry_selector(entry):
+ """What a later `cloud start` of the same phone matches against."""
+ if entry is None:
+ return "unnamed"
+ if entry.get("id"):
+ return "id:" + entry["id"]
+ if entry.get("temporary"):
+ return "temporary"
+ return "label:" + (entry.get("label") or "")
+
+
+def _match_catalog(catalog, query):
+ """Catalog entries named by id, label, or `ios`/`android` when only one
+ entry has that platform. Exact, case-insensitive. No partial matches."""
+ q = query.strip().lower()
+ by_id = [e for e in catalog if str(e.get("id") or "").lower() == q]
+ if by_id:
+ return by_id
+ by_label = [e for e in catalog if str(e.get("label") or "").lower() == q]
+ if by_label:
+ return by_label
+ if q in ("ios", "android"):
+ return [e for e in catalog if e.get("platform") == q]
+ return []
+
+
+def _format_catalog(catalog):
+ if not catalog:
+ return " (nothing in this account's catalog)"
+ lines = []
+ for e in catalog:
+ note = "temporary" if e.get("temporary") else ""
+ lines.append(f" {e.get('label') or 'phone':<18} {e.get('platform') or '':<8} "
+ f"{e.get('id') or '-':<14} {e.get('state') or '-':<12} {note}".rstrip())
+ return "\n".join(lines)
+
+
+def _create_body(entry, timeout):
+ """The POST /sessions body for one catalog entry. A bare start (entry is
+ None) names nothing: the service applies GET /me → default. This is the
+ only place the CLI looks at platform, and only to choose device_id or
+ profile_id."""
+ body = {"timeout_seconds": timeout}
+ if entry is None:
+ return body
+ body["platform"] = entry.get("platform")
+ body["kind"] = entry.get("kind")
+ if entry.get("temporary"):
+ return body
+ if entry.get("platform") == "ios":
+ if entry.get("id"):
+ body["device_id"] = entry["id"]
+ elif entry.get("id"):
+ body["profile_id"] = entry["id"]
+ return body
+
+
+def _needs_adb(entry, me):
+ """An emulator link is adb. A device link is not. A bare start gets
+ what the service gives an unnamed start."""
+ chosen = entry if entry is not None else _unnamed(me)
+ return chosen.get("kind") != "device"
+
+
+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 ''}…"
+ if shown and shown.get("temporary"):
+ return "Starting a temporary phone…"
+ if shown and shown.get("label"):
+ return f"Starting {shown['label']}…"
+ return "Starting your phone…"
+
+
+def _parse_for(text):
+ """Seconds. A bare number is minutes. `90s` is seconds. `15m` / `15min`
+ is minutes."""
+ t = str(text).strip().lower()
+ as_minutes = True
+ if t.endswith("min"):
+ t = t[:-3]
+ elif t.endswith("m"):
+ t = t[:-1]
+ elif t.endswith("s"):
+ t, as_minutes = t[:-1], False
+ n = _int(t, "--for")
+ return n * 60 if as_minutes else n
+
+
+def _already_running(session):
+ sid = (session or {}).get("id") or (session or {}).get("session") or "SID"
+ sys.exit(f"That phone is already running (session {sid}). "
+ f"Attach with `--session {sid}`.")
+
+
+def _saved_holder(entry, me):
+ """The profile id this start will occupy, when it is the saved Android.
+ None for a temporary phone, an iPhone, or a bare start whose default is
+ not that profile."""
+ shown = entry if entry is not None else _unnamed(me)
+ profile = (me.get("profile") or {}).get("id")
+ if not shown or not profile or shown.get("temporary") or shown.get("platform") == "ios":
+ return None
+ if shown.get("id") == profile:
+ return profile
+ return None
+
+
+def _wait_out_save(profile_id):
+ """The saved Android can be `saving` for a few seconds after stop. Wait
+ that out. If a ready session already holds it, say so and exit. -> None
+ when the phone is free to start."""
deadline = time.monotonic() + SAVE_WAIT
told = False
while True:
- profile = _api("GET", "/me").get("profile") or {}
+ me = _api("GET", "/me")
+ profile = me.get("profile") or {}
+ if profile.get("id") != profile_id:
+ return
state = profile.get("state")
+ live = None
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 live and live.get("state") in ("provisioning", "ready"):
+ _already_running(live)
+ if state not in ("saving", "running"):
+ return
+ if live and live.get("state") not in ("closing", None):
+ return
if time.monotonic() >= deadline:
sys.exit("Your phone is still shutting down from its last session. "
"Try again in a few seconds.")
@@ -515,72 +847,153 @@ def _wait_for_profile():
time.sleep(3)
+def _reusable(selector):
+ """A session this machine already started for the same catalog choice,
+ still provisioning or ready. None when this start should create one."""
+ try:
+ state = _load_state()
+ except Exception:
+ return None
+ seen = set()
+ for rec in _known_sessions(state).values():
+ rec = _as_linked(rec)
+ if not rec or rec.get("sid") in seen or rec.get("selector") != selector:
+ continue
+ seen.add(rec["sid"])
+ try:
+ live = _api("GET", f"/sessions/{rec['sid']}")
+ except CloudError:
+ continue
+ if live.get("state") in ("provisioning", "ready"):
+ return live, rec
+ return None
+
+
+def _reject_removed(args):
+ gone = {
+ "--iphone": "name the phone instead: `cloud start ios` when that is unambiguous, or an id or label from `cloud ls`",
+ "--device": "pass the catalog id: `cloud start ID`",
+ "--temp": "start the temporary entry: `cloud start` with its label (see `cloud ls`)",
+ "--timeout": "pass the length with `--for` (`90s`, `15m`, or a number of minutes)",
+ }
+ for flag, hint in gone.items():
+ if flag in args:
+ sys.exit(f"{flag} was removed. {hint}.")
+
def _start(args):
- temp = _flag(args, "--temp")
+ args = list(args)
+ _reject_removed(args)
watch = not _flag(args, "--no-watch")
- minutes = _option(args, "--minutes", "-m")
- if args:
+ for_opt = _option(args, "--for")
+ minutes_opt = _option(args, "--minutes", "-m")
+ if any(a.startswith("-") for a in 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).")
+ if len(args) > 1:
+ sys.exit(CLI_USAGE)
+ # No name: this machine's own preference (`config set cloud.phone ...`),
+ # else whatever the service gives an unnamed start (a temporary Android).
+ configured = str(config.get("cloud.phone") or "").strip()
+ phone = args[0] if args else (configured or None)
+ if for_opt and minutes_opt:
+ sys.exit("Pass --for or --minutes, not both.")
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} "
+ if for_opt:
+ timeout = _parse_for(for_opt)
+ elif minutes_opt:
+ timeout = _int(minutes_opt, "--minutes") * 60
+ else:
+ timeout = int(config.get("cloud.minutes")) * 60
+ if timeout < 1 or timeout > cap * 60:
+ sys.exit(f"Duration must be between 1 and {cap} minutes "
f"(raise the cap with `phone-harness config set cloud.max_minutes N`).")
- current = attached()
- if current:
+ me = _api("GET", "/me")
+ catalog = _catalog(me)
+ entry = None
+ if phone:
+ matches = _match_catalog(catalog, phone)
+ if not matches:
+ where = (" (from `config set cloud.phone`; clear it with `config unset cloud.phone`)"
+ if not args else "")
+ sys.exit(f"No phone named {phone!r} is in this account's catalog{where}.\n"
+ f"{_format_catalog(catalog)}")
+ if len(matches) > 1:
+ print(_format_catalog(matches))
+ if not sys.stdin.isatty():
+ sys.exit(f"{phone!r} matches {len(matches)} phones. "
+ "Pass a catalog id or label.")
+ choice = input("Id or label: ").strip()
+ narrowed = _match_catalog(matches, choice)
+ if len(narrowed) != 1:
+ sys.exit(f"{choice!r} matches {len(narrowed)} phones.")
+ matches = narrowed
+ entry = matches[0]
+
+ if _needs_adb(entry, me):
+ _adb_present()
+
+ selector = _entry_selector(entry)
+ reused = _reusable(selector)
+ if reused:
+ live, rec = reused
+ print(f"Already attached to session {live['id']}; reusing it.")
+ return _report(_wait_ready(live["id"]), selector=selector,
+ label=rec.get("label"), watch=False)
+
+ holder = _saved_holder(entry, me)
+ if holder:
+ _wait_out_save(holder)
+
+ # Another session may keep running. Say so, and how to aim at it again.
+ try:
+ previous = _as_linked(_load_state().get("session"))
+ except Exception:
+ previous = None
+ if previous and previous.get("selector") != selector:
try:
- live = _api("GET", f"/sessions/{current['sid']}")
+ still = _api("GET", f"/sessions/{previous['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"]), watch=False) # its view is already open
- _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"], watch)
- if profile_id:
- body["profile_id"] = profile_id
+ still = None
+ if still and still.get("state") in ("provisioning", "ready"):
+ print(f"Session {previous['sid']} stays up. `--session {previous['sid']}` targets it.")
+ body = _create_body(entry, timeout)
+ label = (entry or {}).get("label")
request_key = uuid.uuid4().hex
- print("Starting a temporary phone…" if "profile_id" not in body
- else "Starting your phone…")
+ print(_starting_line(entry, me))
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.")
+ _already_running({"id": e.body.get("session")})
+ if e.code == "device_unavailable":
+ sys.exit(_explain(e))
+ if e.status == 400:
+ sys.exit(f"{_explain(e)}\n{_format_catalog(catalog)}")
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, watch)
+ return _report(_wait_ready(created["id"]), selector=selector, label=label, watch=watch)
-def _report(session, profile_id=None, watch=True):
- serial = _attach(session, profile_id)
+
+
+def _report(session, profile_id=None, watch=True, selector=None, label=None):
+ attached_now = _attach(session, profile_id, selector=selector, label=label)
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."}
+ words = _kind_of_phone({**session, "link": attached_now["link"]}, label or attached_now.get("label"))
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" session {session['id']} ({words})")
+ link = attached_now["link"]["kind"]
+ print(f" {link:<8} {_describe_link(attached_now)}" + (" (connected, unlocked)" if link == "adb" else ""))
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 ""))
+ "before then" + (" to keep the running state" if _keeps_state(session) else ""))
# The user asked for a phone; show it to them. Fails quietly where there
# is no browser (an SSH box, CI), and the command is one line away.
if watch and session.get("watch_url") and _open_browser(session["watch_url"]):
@@ -614,7 +1027,7 @@ def _stop(args):
for sid in sids:
try:
before = _api("GET", f"/sessions/{sid}")
- held_profile = held_profile or bool(before.get("profile"))
+ held_profile = held_profile or _keeps_state(before)
_api("DELETE", f"/sessions/{sid}")
print(f"✓ Session {sid} ended; billing stopped.")
except CloudError as e:
@@ -664,7 +1077,8 @@ def _status(args):
live = None
# Just after `stop`, the API still says the profile is `running` while its
# session is `closing`; the truth for the user is that it is being saved.
- if live and live.get("state") == "closing" and live.get("profile"):
+ # A control link keeps its data on the phone, so closing it is not a save.
+ if live and live.get("state") == "closing" and _keeps_state(live):
profile = {**profile, "state": "saving"}
print(f"phone {_describe_profile(profile)}")
if not sess:
@@ -676,33 +1090,109 @@ def _status(args):
print(f"session {sess['sid']} is gone; detaching")
_detach()
return 0
- state = "closing — saving the phone" if live["state"] == "closing" else live["state"]
+ state = ("closing — saving the phone"
+ if live["state"] == "closing" and _keeps_state(live)
+ else live["state"])
+ label = sess.get("label")
print(f"session {live['id']} · {state} · {_left(live.get('expires_at'))} left"
- f" · {'your phone' if live.get('profile') else 'temporary'}")
- print(f"adb {serial_of(sess)}")
+ f" · {_kind_of_phone({**live, 'link': sess['link']}, label)}")
+ print(f"{sess['link']['kind']:<12}{_describe_link(sess)}")
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 _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)
+
+
+def _ls_rows(me, sessions):
+ """One row per catalog entry, with a live session inlined when it is that
+ phone. Sessions that match nothing still appear, after the catalog."""
+ catalog = _catalog(me)
+ mine = (attached() or {}).get("sid")
+ used = set()
+
+ def session_blob(s):
+ return {"id": s.get("id"), "state": s.get("state"),
+ "left": _left(s.get("expires_at")), "expires_at": s.get("expires_at")}
+
+ rows = []
+ for entry in catalog:
+ match = None
+ for s in sessions:
+ if s.get("id") in used:
+ continue
+ if _session_on_entry(entry, s):
+ match = s
+ used.add(s["id"])
+ break
+ rows.append({
+ "label": entry.get("label") or "",
+ "platform": entry.get("platform"),
+ "id": entry.get("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),
+ })
+ for s in sessions:
+ if s.get("id") in used:
+ continue
+ 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",
+ "session": session_blob(s),
+ "targeted": s.get("id") == mine,
+ "unmatched": True,
+ })
+ return rows
+
+
def _ls(args):
as_json = _flag(args, "--json")
- limit = _option(args, "-n", "--limit")
+ if args:
+ sys.exit(CLI_USAGE)
+ me = _api("GET", "/me")
sessions = _api("GET", "/sessions")
- if limit:
- sessions = sessions[:_int(limit, "-n")]
+ rows = _ls_rows(me, sessions)
if as_json:
- print(json.dumps(sessions, indent=2))
+ print(json.dumps(rows, indent=2))
return 0
- if not sessions:
- print("Nothing is running.")
+ if not rows:
+ print("No phones in this account's catalog.")
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 ''}")
+ print(f"{'':1} {'LABEL':<18} {'PLATFORM':<8} {'ID':<14} {'STATE':<12} {'NOTE':<10} "
+ f"{'SESSION':<14} LEFT")
+ for row in rows:
+ sess = row.get("session") or {}
+ note = "temporary" if row.get("temporary") else ""
+ print(f"{'*' if row.get('targeted') else ' '} {row.get('label') or '':<18} "
+ f"{row.get('platform') or '':<8} {row.get('id') or '-':<14} "
+ f"{row.get('state') or '-':<12} {note:<10} "
+ f"{sess.get('id') or '-':<14} {sess.get('left') or ''}".rstrip())
return 0
@@ -713,12 +1203,15 @@ def _show(args):
print(json.dumps(session, indent=2))
return 0
adb = session.pop("adb", None) or {}
+ control = session.pop("control", 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']}")
+ if control.get("url"):
+ print(f"{'control':<16} {control['url']}")
return 0
@@ -726,8 +1219,9 @@ 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}")
+ sess = _attach(session)
+ print(f"✓ attached to {session['id']}; {_describe_link(sess)}")
+ print("Helpers with no --session and no PHONE_HARNESS_SESSION follow this one.")
return 0
@@ -743,7 +1237,11 @@ def _watch(args):
def _open(args):
"""The dashboard: the interactive viewer, behind the user's own sign-in.
- `watch` is for looking; this is for taking the controls."""
+ `watch` is for looking; this is for taking the controls. An optional SID
+ checks that the session exists; the page is still the account dashboard."""
+ if args and args[0] != "--print":
+ _resolve_sid(args[0])
+ args = args[1:]
url = _dashboard()
if _flag(args, "--print") or not _open_browser(url):
print(url)
@@ -766,10 +1264,11 @@ def _whoami(args):
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")
+ sys.exit("This wipes the saved Android's stored state — its apps, logins and "
+ "data — and cannot be undone. The CLI has no iPhone reset; that is "
+ "the operator's.\nRun: phone-harness cloud phone reset --yes")
_api("POST", "/me/profile/reset")
- print("Your saved phone was reset. The next `cloud start` begins fresh.")
+ print("Wiped the saved Android's stored state. The next start of that phone 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))
@@ -828,26 +1327,36 @@ def _history(args):
# --- CLI (phone-harness cloud ...) -------------------------------------------
CLI_USAGE = """Usage:
- phone-harness cloud who is signed in, what is attached
+ phone-harness cloud [--session SID] 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] [--no-watch]
- start your saved phone (or a throwaway one), connect,
- and open its live view (config: cloud.watch)
+ phone-harness cloud ls [--json] the account catalog, with live sessions inlined
+ (* = the session this process targets)
+ phone-harness cloud start [PHONE] [--for DURATION] [--no-watch]
+ PHONE is a catalog id or label, or ios/android
+ when only one entry has that platform. No PHONE
+ starts cloud.phone (config set cloud.phone NAME),
+ else a temporary Android, the service's rule for an
+ unnamed start. --for is 90s, 15m, or
+ minutes (default 15, cap cloud.max_minutes).
+ --minutes N is the same thing, deprecated.
+ Opens the live view (cloud.watch)
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
+ end it. An adb phone with a saved profile is saved;
+ a control link (an iPhone) keeps its own data
+ (--wait watches an Android save finish)
+ phone-harness cloud show [SID] [--json] one session in full
+ phone-harness cloud use SID point the terminal fallback at a running session
phone-harness cloud watch [SID] [--print] the read-only live view (no sign-in; shareable)
- phone-harness cloud open [--print] the dashboard: control the phone yourself (sign-in)
- phone-harness cloud phone [reset --yes] your saved phone
+ phone-harness cloud open [SID] [--print] the dashboard: control the phone yourself (sign-in)
+ phone-harness cloud phone [reset --yes] the saved Android. reset --yes wipes its stored state
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.
+ phone-harness cloud history [-n NUM] [--json]
+Every command takes --session SID, or PHONE_HARNESS_SESSION, and so do helper
+scripts: that pins one phone for this process. With neither, helpers follow the
+attached session (the last start, or cloud use). SID may be a unique prefix.
+PHONE_HARNESS_CLOUD_API, _OAUTH_ISSUER and _OAUTH_CLIENT_ID point the CLI
+at a Phone Harness instance of your own; unset, it is the public cloud.
They may live in a .env file at the repo root or in the agent workspace (never committed).
"""
@@ -858,6 +1367,9 @@ _COMMANDS = {"login": _login, "logout": _logout, "whoami": _whoami, "start": _st
def cli(args):
args = list(args)
+ pinned = _option(args, "--session")
+ if pinned:
+ os.environ["PHONE_HARNESS_SESSION"] = pinned
fn = _status if not args else _COMMANDS.get(args[0])
if fn is None:
print(CLI_USAGE)
diff --git a/src/phone_harness/config.py b/src/phone_harness/config.py
index f9bbe09..fb0f240 100644
--- a/src/phone_harness/config.py
+++ b/src/phone_harness/config.py
@@ -73,6 +73,7 @@ DEFAULTS = {
"minutes": 15, # how long `cloud start` rents a phone for
"max_minutes": 30, # the most one `cloud start` may ask for
"watch": True, # `cloud start` opens the phone's live view in the browser
+ "phone": "", # what a bare `cloud start` names: a catalog id or label; empty = the service's unnamed start
},
"ios": {
"restore_clipboard": False, # put the old clipboard back after a paste
diff --git a/src/phone_harness/remote.py b/src/phone_harness/remote.py
new file mode 100644
index 0000000..396a832
--- /dev/null
+++ b/src/phone_harness/remote.py
@@ -0,0 +1,112 @@
+"""A cloud phone driven by ops over HTTPS, not by ADB.
+
+Some cloud phones have no shell to connect to: a real iPhone behind a Mac is
+one. Its session carries a `control` grant instead of an `adb` block: a URL
+and a token. Every op in the vocabulary becomes one POST to `<url>/op`, and
+the answer is the op's value. Screenshots arrive as PNG bytes and are written
+where a local backend would have written them, so helpers.py never learns
+where the phone is.
+
+What the far side cannot do comes back as `unsupported`, which is raised as
+Unsupported here, exactly as a local backend would.
+"""
+import base64
+import json
+import tempfile
+import urllib.error
+import urllib.request
+from pathlib import Path
+
+from .transport import Backend, Unsupported
+
+TMP = Path(tempfile.gettempdir()) / "phone-harness"
+USER_AGENT = "phone-harness-cli"
+
+
+class Remote(Backend):
+ name = "remote"
+
+ def __init__(self, url, token):
+ self.url = url.rstrip("/")
+ self.token = token
+ self._ops = None
+
+ # --- the wire -----------------------------------------------------------
+
+ def _call(self, method, path, body=None, timeout=60):
+ data = json.dumps(body).encode() if body is not None else None
+ headers = {"Authorization": f"Bearer {self.token}", "User-Agent": USER_AGENT}
+ if data:
+ headers["Content-Type"] = "application/json"
+ req = urllib.request.Request(self.url + path, data=data, method=method, headers=headers)
+ try:
+ with urllib.request.urlopen(req, timeout=timeout) as r:
+ raw = r.read()
+ return json.loads(raw) if r.headers.get("Content-Type", "").startswith("application/json") else raw
+ except urllib.error.HTTPError as e:
+ try:
+ err = json.loads(e.read())
+ except ValueError:
+ err = {}
+ message = err.get("error") or f"the cloud phone answered {e.code}"
+ if err.get("unsupported"):
+ raise Unsupported(message) from None
+ if 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
+ except urllib.error.URLError as e:
+ raise RuntimeError(f"could not reach the cloud phone: {e.reason}") from None
+
+ def _op(self, op, timeout=60, **kw):
+ return self._call("POST", "/op", {"op": op, "kw": kw}, timeout=timeout)["result"]
+
+ # --- capabilities -------------------------------------------------------
+
+ def _known(self):
+ if self._ops is None:
+ self._ops = set(self._call("GET", "/ops")["ops"])
+ return self._ops
+
+ def supports(self, op):
+ # What the far side offers, plus the local bookkeeping ops (focus,
+ # refocus) that mean nothing for a phone nobody's screen shows.
+ return op in self._known() or getattr(self, self._slot(op), None) is not None
+
+ def send(self, op, **kw):
+ if not self.supports(op):
+ raise Unsupported(f"this cloud phone cannot {op!r}")
+ fn = getattr(self, self._slot(op), None)
+ if fn is not None:
+ return fn(**kw)
+ return self._op(op, **kw)
+
+ # --- the ops whose shape is local -----------------------------------------
+
+ def _screen_capture(self, path=None):
+ r = self._op("screen.capture", timeout=60)
+ TMP.mkdir(exist_ok=True)
+ path = Path(path or TMP / "remote.png")
+ path.write_bytes(base64.b64decode(r["png_b64"]))
+ return str(path), r["bounds"]
+
+ def _input_text(self, s, delay=0.03, keystrokes=False):
+ return self._op("input.text", timeout=max(60, 0.2 * len(s) + 30), s=s, delay=delay, keystrokes=keystrokes)
+
+ def _apps_launch(self, name, fresh=False):
+ return self._op("apps.launch", timeout=90, name=name, fresh=fresh)
+
+ def _apps_list(self, include_system=False):
+ return self._op("apps.list", timeout=90, include_system=include_system)
+
+ def _session_refocus(self):
+ return None
+
+ def _session_detail(self):
+ return f"cloud phone at {self.url}"
+
+ def _focus_probe(self):
+ return (True,)
+
+ def _focus_diff(self, before, after):
+ return {"raised": False, "stole_focus": False}
diff --git a/src/phone_harness/run.py b/src/phone_harness/run.py
index dd172cd..488d271 100644
--- a/src/phone_harness/run.py
+++ b/src/phone_harness/run.py
@@ -1,6 +1,7 @@
"""The phone-harness CLI: exec Python from stdin with helpers pre-imported."""
import functools
import io
+import os
import sys
import time
from pathlib import Path
@@ -13,14 +14,47 @@ USAGE = """Usage:
PY
Commands:
+ phone-harness --session SID <<'PY' pin one cloud phone for this process
phone-harness --doctor [ios|android] diagnose the phone the helpers would drive
phone-harness skill print the phone-harness skill text
phone-harness android ... pair/connect/choose an Android phone
- phone-harness cloud ... rent a cloud phone: `cloud login`, `cloud start`, `cloud stop`
+ phone-harness cloud ... rent a catalog phone: `cloud login`, `cloud ls`, `cloud start [PHONE]`
phone-harness config ... settings: `config set platform android`
+
+--session SID (or PHONE_HARNESS_SESSION) selects one rented phone. With neither,
+a script follows the attached session.
"""
+def _write_utf8(text):
+ """Write text as UTF-8.
+
+ Windows pipes and consoles often use cp1252 (`phone-harness skill > file`).
+ Reconfigure the text stream when it allows it; if that still cannot encode
+ the text, write UTF-8 bytes to the buffer.
+ """
+ out = sys.stdout
+ try:
+ out.reconfigure(encoding="utf-8", errors="replace")
+ except (AttributeError, OSError, ValueError):
+ pass
+ try:
+ out.write(text)
+ out.flush()
+ return
+ except UnicodeEncodeError:
+ pass
+ data = text.encode("utf-8", errors="replace")
+ buf = getattr(out, "buffer", None)
+ if buf is not None:
+ buf.write(data)
+ buf.flush()
+ return
+ encoding = getattr(out, "encoding", None) or "ascii"
+ out.write(data.decode(encoding, errors="replace"))
+ out.flush()
+
+
def _skill_text():
"""SKILL.md: packaged alongside the code in a wheel; at the repo root in
a checkout (where the launcher runs the working tree)."""
@@ -210,8 +244,27 @@ def main():
)
+def _take_session(args):
+ """Pull `--session SID` off the front of any command, including a script.
+ The flag wins over PHONE_HARNESS_SESSION already in the environment."""
+ out, i, pinned = [], 0, None
+ while i < len(args):
+ if args[i] == "--session":
+ if i + 1 >= len(args):
+ sys.exit("--session needs a SID")
+ pinned = args[i + 1]
+ i += 2
+ continue
+ out.append(args[i])
+ i += 1
+ if pinned:
+ os.environ["PHONE_HARNESS_SESSION"] = pinned
+ return out
+
+
def _run(args):
global _phone_name
+ args = _take_session(args)
if args and args[0] in {"-h", "--help"}:
print(USAGE)
return
@@ -228,7 +281,7 @@ def _run(args):
from .config import cli
sys.exit(cli(args[1:]))
if args and args[0] == "skill":
- print(_skill_text(), end="")
+ _write_utf8(_skill_text())
return
if args or sys.stdin.isatty():
sys.exit(USAGE)
diff --git a/src/phone_harness/transport.py b/src/phone_harness/transport.py
index cefc73e..25f5802 100644
--- a/src/phone_harness/transport.py
+++ b/src/phone_harness/transport.py
@@ -142,7 +142,11 @@ def connect(platform=None, **kw):
# 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():
+ rented = cloud.attached()
+ if rented and rented["link"]["kind"] == "control":
+ from .remote import Remote
+ return Remote(rented["link"]["url"], rented["link"]["token"])
+ if rented:
platform = "android"
platform = platform.lower()
if platform in ("ios", "iphone", "ipad"):
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000..13951aa
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,22 @@
+"""Pytest loads this on its own. Unittest does not; test_cloud installs the
+same recorder at import, and its CLI subprocesses load tests/support/sitecustomize.py.
+"""
+import sys
+from pathlib import Path
+
+_SUPPORT = Path(__file__).resolve().parent / "support"
+if str(_SUPPORT) not in sys.path:
+ sys.path.insert(0, str(_SUPPORT))
+
+import browser_recorder
+import pytest
+
+browser_recorder.install()
+
+
[email protected](autouse=True)
+def block_real_browser(monkeypatch):
+ """No test may launch a browser. `recorder.urls()` is what was opened."""
+ browser_recorder.install(monkeypatch)
+ browser_recorder.recorder.reset()
+ yield browser_recorder.recorder
diff --git a/tests/support/browser_recorder.py b/tests/support/browser_recorder.py
new file mode 100644
index 0000000..906fdb4
--- /dev/null
+++ b/tests/support/browser_recorder.py
@@ -0,0 +1,68 @@
+"""A stand-in for webbrowser that records URLs and never launches anything.
+
+The CLI under test is a fresh Python process, so the patch has to be installed
+there too (see sitecustomize.py). Both processes share the log file.
+"""
+import sys
+import tempfile
+import webbrowser
+from pathlib import Path
+
+LOG = Path(tempfile.gettempdir()) / "phone-harness-tests-browser.log"
+
+
+class Recorder:
+ def urls(self):
+ if not LOG.exists():
+ return []
+ return [line for line in LOG.read_text().splitlines() if line]
+
+ def reset(self):
+ LOG.write_text("")
+
+ def open(self, url, new=0, autoraise=True):
+ with LOG.open("a") as fh:
+ fh.write(f"{url}\n")
+ return True
+
+ def open_new(self, url):
+ return self.open(url, new=1)
+
+ def open_new_tab(self, url):
+ return self.open(url, new=2)
+
+
+recorder = Recorder()
+
+
+def _patched_open_browser(url):
+ """Same gate as phone_harness.cloud._open_browser, pointed at the recorder."""
+ from phone_harness import config
+ if not config.get("cloud.watch"):
+ return False
+ try:
+ return bool(recorder.open(url))
+ except Exception:
+ return False
+
+
+def install(monkeypatch=None):
+ """Replace webbrowser.open/open_new/open_new_tab and the cloud wrapper."""
+ src = str(Path(__file__).resolve().parents[2] / "src")
+ if src not in sys.path:
+ sys.path.insert(0, src)
+
+ def set_(obj, name, value):
+ if monkeypatch is not None:
+ monkeypatch.setattr(obj, name, value)
+ else:
+ setattr(obj, name, value)
+
+ set_(webbrowser, "open", recorder.open)
+ set_(webbrowser, "open_new", recorder.open_new)
+ set_(webbrowser, "open_new_tab", recorder.open_new_tab)
+ from phone_harness import cloud
+ set_(cloud.webbrowser, "open", recorder.open)
+ set_(cloud.webbrowser, "open_new", recorder.open_new)
+ set_(cloud.webbrowser, "open_new_tab", recorder.open_new_tab)
+ set_(cloud, "_open_browser", _patched_open_browser)
diff --git a/tests/support/sitecustomize.py b/tests/support/sitecustomize.py
new file mode 100644
index 0000000..6469f17
--- /dev/null
+++ b/tests/support/sitecustomize.py
@@ -0,0 +1,8 @@
+"""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.
+"""
+import browser_recorder
+
+browser_recorder.install()
diff --git a/tests/test_cloud.py b/tests/test_cloud.py
index d437703..5ee1c6a 100644
--- a/tests/test_cloud.py
+++ b/tests/test_cloud.py
@@ -16,6 +16,13 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
SRC = str(Path(__file__).resolve().parents[1] / "src")
+SUPPORT = str(Path(__file__).resolve().parent / "support")
+if SRC not in sys.path:
+ sys.path.insert(0, SRC)
+if SUPPORT not in sys.path:
+ sys.path.insert(0, SUPPORT)
+import browser_recorder
+browser_recorder.install()
FAKE_ADB = r'''#!/bin/sh
# Locked until `shell unlock CODE`; state is a file next to this script.
@@ -35,12 +42,39 @@ esac
'''
+def _fake_catalog(c):
+ """The account catalog. Tests that leave `available` unset get the saved
+ Android plus a temporary phone, which is what a normal account holds."""
+ if c.available is not None:
+ return c.available
+ return [
+ {"platform": "android", "kind": "emulator", "id": c.profile["id"],
+ "label": "Saved phone", "state": c.profile.get("state") or "stored"},
+ {"platform": "android", "kind": "emulator", "temporary": True,
+ "label": "Temporary phone"},
+ ]
+
+
+UNNAMED = {"platform": "android", "kind": "emulator", "temporary": True}
+
+
+def _fake_resolve(c, body):
+ """What the service makes of a create body. `posts` keeps the raw body.
+ A body that names nothing gets the service's rule: a temporary Android,
+ never anyone's saved phone."""
+ if "platform" in body or "kind" in body:
+ return dict(body)
+ return {**body, "platform": "android", "kind": "emulator"}
+
+
class FakeCloud(BaseHTTPRequestHandler):
- sessions, profile, polls, posts = {}, {}, {}, []
+ sessions, profile, polls, posts, keys = {}, {}, {}, [], []
valid, token_polls, refreshes, revoked = set(), 0, 0, []
closing_reads = 0
- seen_headers = []
forbid = False
+ control_url = None # set: an iPhone's control grant points here
+ available = None # set: replaces the synthesized catalog
+ fail = None # set: POST /sessions returns this instead
def _oauth(self, path, form):
c = FakeCloud
@@ -85,7 +119,6 @@ class FakeCloud(BaseHTTPRequestHandler):
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 {}
@@ -97,21 +130,66 @@ class FakeCloud(BaseHTTPRequestHandler):
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})
+ me = {"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,
+ "unnamed": dict(UNNAMED),
+ "available": _fake_catalog(c)}
+ return self._send(200, me)
if (m, path) == ("POST", "/sessions"):
+ c.keys.append(self.headers.get("Idempotency-Key"))
c.posts.append(body)
- if body.get("profile_id") and c.profile["state"] == "running":
+ if c.fail:
+ status, payload, extra = c.fail
+ if extra:
+ self.send_response(status)
+ raw = json.dumps(payload).encode()
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(raw)))
+ for k, v in extra.items():
+ self.send_header(k, v)
+ self.end_headers()
+ self.wfile.write(raw)
+ return
+ return self._send(status, payload)
+ if "provider" in body:
+ return self._send(400, {"error": "provider was replaced by platform and kind"})
+ if ("platform" in body) ^ ("kind" in body):
+ return self._send(400, {"error": "platform and kind go together"})
+ resolved = _fake_resolve(c, body)
+ iphone = resolved.get("platform") == "ios" and resolved.get("kind") == "device"
+ if resolved.get("profile_id") and c.profile["state"] == "running":
return self._send(409, {"error": "held", "code": "profile_running",
"session": c.profile["session"]})
+ if iphone and isinstance(c.available, list):
+ phones = [p for p in c.available
+ if p.get("platform") == "ios" and p.get("kind") == "device"]
+ if not phones:
+ return self._send(400, {"error": "no phone of that platform and kind "
+ "available to this account"})
+ chosen = body.get("device_id")
+ match = [p for p in phones if p.get("id") == chosen] if chosen else phones[:1]
+ if chosen and not match:
+ return self._send(400, {"error": "no grant for that phone"})
+ phone = match[0]
+ if phone.get("state") == "unavailable":
+ return self._send(409, {"error": "not on its host", "code": "device_unavailable"})
+ if phone.get("state") == "running":
+ return self._send(409, {"error": "held", "code": "profile_running",
+ "session": phone.get("session") or "liveiphone"})
sid = f"sid{len(c.posts):03d}"
c.sessions[sid] = {"id": sid, "state": "provisioning",
- "profile": body.get("profile_id"),
+ "platform": "ios" if iphone else (resolved.get("platform") or "android"),
+ "kind": "device" if iphone else (resolved.get("kind") or "emulator"),
+ "device": "iPhone" if iphone else "Android emulator",
+ "billing_mode": "disabled" if iphone else "metered",
+ "profile": resolved.get("profile_id"),
+ "device_id": resolved.get("device_id"),
+ "phone": resolved.get("device_id"),
"expires_at": time.time() + body["timeout_seconds"],
"watch_url": "https://watch.example/secret"}
- if body.get("profile_id"):
+ if resolved.get("profile_id"):
c.profile.update(state="running", session=sid)
return self._send(202, c.sessions[sid])
if (m, path) == ("GET", "/sessions"):
@@ -121,8 +199,13 @@ class FakeCloud(BaseHTTPRequestHandler):
if m == "GET":
c.polls[sid] = c.polls.get(sid, 0) + 1
if c.polls[sid] >= 2 and c.sessions[sid]["state"] == "provisioning":
- c.sessions[sid].update(state="ready", startup={"startup": "exact"}, adb={
- "host": "live.example", "port": 22220, "code": "ph_code"})
+ c.sessions[sid].update(state="ready", startup={"startup": "exact"})
+ if c.sessions[sid].get("platform") == "ios":
+ c.sessions[sid]["control"] = {
+ "url": c.control_url or "http://127.0.0.1:1", "token": "ct_1",
+ "expires_at": c.sessions[sid]["expires_at"]}
+ else:
+ c.sessions[sid]["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"):
@@ -133,6 +216,52 @@ class FakeCloud(BaseHTTPRequestHandler):
do_GET = do_POST = do_DELETE = _handle
+class FakeControl(BaseHTTPRequestHandler):
+ """What a phone driven by ops over HTTPS answers: /ops, /op, /frame.png."""
+ calls = []
+ PNG = bytes.fromhex("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489"
+ "0000000d49444154789c6360000002000154a24f5d0000000049454e44ae426082")
+
+ 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):
+ import base64
+ n = int(self.headers.get("Content-Length") or 0)
+ body = json.loads(self.rfile.read(n)) if n else {}
+ if self.headers.get("Authorization") != "Bearer ct_1":
+ return self._send(404, {"error": "not found"})
+ if self.path == "/ops":
+ # nav.back is advertised so the client actually POSTs it; the op
+ # answer below is the unsupported 400 the live iPhone returns.
+ return self._send(200, {"ops": ["screen.capture", "screen.bounds", "input.tap",
+ "nav.home", "nav.back"]})
+ if self.path == "/op":
+ FakeControl.calls.append(body)
+ op = body["op"]
+ if op == "screen.capture":
+ return self._send(200, {"result": {"png_b64": base64.b64encode(self.PNG).decode(),
+ "bounds": {"x": 0, "y": 0, "w": 750, "h": 1334, "id": "udid1"}}})
+ if op == "screen.bounds":
+ return self._send(200, {"result": {"x": 0, "y": 0, "w": 750, "h": 1334, "id": "udid1"}})
+ if op == "input.tap":
+ return self._send(200, {"result": True})
+ if op == "nav.back":
+ return self._send(400, {"error": "iOS has no back", "unsupported": True})
+ return self._send(400, {"error": f"cannot {op}", "unsupported": True})
+ return self._send(404, {"error": "not found"})
+
+ do_GET = do_POST = _handle
+
+
class CloudCli(unittest.TestCase):
def setUp(self):
self.home = tempfile.TemporaryDirectory()
@@ -140,23 +269,29 @@ class CloudCli(unittest.TestCase):
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.sessions, FakeCloud.polls, FakeCloud.posts, FakeCloud.keys = {}, {}, [], []
FakeCloud.valid, FakeCloud.token_polls = set(), 0
FakeCloud.refreshes, FakeCloud.revoked, FakeCloud.closing_reads = 0, [], 0
FakeCloud.forbid = False
+ FakeCloud.control_url = None
+ FakeCloud.available = None
+ FakeCloud.fail = None
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,
+ 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_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"):
+ for name in ("PHONE_HARNESS_API_KEY", "ANDROID_SERIAL", "PHONE_HARNESS_PLATFORM",
+ "PHONE_HARNESS_SESSION", "BROWSER"):
self.env.pop(name, None)
+ browser_recorder.recorder.reset()
def run_cli(self, *args, stdin=None, env=None):
return subprocess.run([sys.executable, "-m", "phone_harness.run", *args], input=stdin,
@@ -214,15 +349,6 @@ class CloudCli(unittest.TestCase):
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"})
@@ -230,9 +356,11 @@ class CloudCli(unittest.TestCase):
def test_start_uses_the_saved_phone_and_connects(self):
self.login()
- r = self.run_cli("cloud", "start", "--minutes", "5")
+ r = self.run_cli("cloud", "start", "Saved phone", "--minutes", "5")
self.assertEqual(r.returncode, 0, r.stderr)
- self.assertEqual(FakeCloud.posts, [{"timeout_seconds": 300, "profile_id": "prof-1"}])
+ self.assertEqual(FakeCloud.posts, [{"timeout_seconds": 300, "platform": "android",
+ "kind": "emulator", "profile_id": "prof-1"}])
+ self.assertRegex(FakeCloud.keys[0] or "", r"^[A-Za-z0-9_-]{16,128}$")
self.assertIn("Resumed exactly", r.stdout)
self.assertNotIn("ph_code", r.stdout)
self.assertNotIn("watch.example", r.stdout)
@@ -240,35 +368,33 @@ class CloudCli(unittest.TestCase):
self.assertIn("connect live.example:22220", log)
self.assertIn("shell unlock ph_code", log)
- again = self.run_cli("cloud", "start") # idempotent: no second phone
+ again = self.run_cli("cloud", "start", "Saved phone") # same catalog choice: no second phone
self.assertEqual(again.returncode, 0, again.stderr)
+ self.assertIn("reusing", again.stdout)
self.assertEqual(len(FakeCloud.posts), 1)
ls = self.run_cli("cloud", "ls")
- self.assertIn("* sid001", ls.stdout)
+ line = next(l for l in ls.stdout.splitlines() if "sid001" in l)
+ self.assertTrue(line.startswith("*"), ls.stdout)
+ self.assertIn("Saved phone", line)
def test_start_opens_the_live_view_unless_told_not_to(self):
self.login()
- opened = Path(self.home.name) / "opened-urls"
- # a fake browser: `webbrowser` honours $BROWSER, so point it at a script that records the url
- fake = Path(self.home.name) / "browser"
- fake.write_text(f'#!/bin/sh\necho "$1" >> "{opened}"\n')
- fake.chmod(0o755)
- r = self.run_cli("cloud", "start", env={"BROWSER": str(fake)})
+ r = self.run_cli("cloud", "start")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("opened in your browser", r.stdout)
- self.assertEqual(opened.read_text().strip(), "https://watch.example/secret")
+ self.assertEqual(browser_recorder.recorder.urls(), ["https://watch.example/secret"])
self.assertNotIn("watch.example", r.stdout) # the url itself is never printed
- again = self.run_cli("cloud", "start", env={"BROWSER": str(fake)}) # reattach: no second tab
- self.assertEqual(len(opened.read_text().split()), 1, again.stdout)
+ again = self.run_cli("cloud", "start") # reattach: no second tab
+ self.assertEqual(browser_recorder.recorder.urls(), ["https://watch.example/secret"], again.stdout)
self.run_cli("cloud", "stop")
- r = self.run_cli("cloud", "start", "--no-watch", env={"BROWSER": str(fake)})
+ r = self.run_cli("cloud", "start", "--no-watch")
self.assertIn("phone-harness cloud watch", r.stdout)
- self.assertEqual(len(opened.read_text().split()), 1)
+ self.assertEqual(browser_recorder.recorder.urls(), ["https://watch.example/secret"])
self.run_cli("cloud", "stop")
- r = self.run_cli("cloud", "start", env={"BROWSER": str(fake), "PHONE_HARNESS_CLOUD_WATCH": "0"})
+ r = self.run_cli("cloud", "start", env={"PHONE_HARNESS_CLOUD_WATCH": "0"})
self.assertIn("phone-harness cloud watch", r.stdout)
- self.assertEqual(len(opened.read_text().split()), 1)
+ self.assertEqual(browser_recorder.recorder.urls(), ["https://watch.example/secret"])
def test_open_is_the_dashboard_not_the_watch_link(self):
self.login()
@@ -290,7 +416,7 @@ class CloudCli(unittest.TestCase):
def test_status_says_saving_while_the_session_closes(self):
self.login()
- self.run_cli("cloud", "start")
+ self.run_cli("cloud", "start", "Saved phone")
sid = json.loads((Path(self.home.name) / "state" / "cloud.json").read_text())["session"]["sid"]
FakeCloud.sessions[sid]["state"] = "closing"
FakeCloud.profile.update(state="running", session=sid)
@@ -299,10 +425,46 @@ class CloudCli(unittest.TestCase):
self.assertIn("closing — saving the phone", r.stdout)
self.assertNotIn("running in session", r.stdout)
+ def test_a_closing_temporary_android_stays_plain_closing(self):
+ """A temp session has no profile, so closing it must not look like a save
+ and must not relabel the stored phone."""
+ self.login()
+ self.assertEqual(self.run_cli("cloud", "start", "Temporary phone").returncode, 0)
+ sid = json.loads((Path(self.home.name) / "state" / "cloud.json").read_text())["session"]["sid"]
+ self.assertFalse(FakeCloud.sessions[sid].get("profile"))
+ FakeCloud.sessions[sid]["state"] = "closing"
+ r = self.run_cli("cloud")
+ self.assertIn("· closing ·", r.stdout)
+ self.assertNotIn("saving", r.stdout)
+ self.assertIn("phone stored", r.stdout)
+ self.assertIn("temporary", r.stdout)
+
+ def test_a_closing_iphone_is_not_a_save(self):
+ """An iPhone session can name a profile; closing it still is not a save."""
+ self.login()
+ FakeCloud.available = [
+ {"platform": "ios", "kind": "device", "id": "iph-1", "label": "My iPhone SE",
+ "state": "available"}]
+ started = self.run_cli("cloud", "start", "ios", "--no-watch",
+ env={"PHONE_HARNESS_ADB": "/nonexistent/adb"})
+ self.assertEqual(started.returncode, 0, started.stderr)
+ sid = json.loads((Path(self.home.name) / "state" / "cloud.json").read_text())["session"]["sid"]
+ # A control session may name a profile; closing it is still not a save.
+ FakeCloud.sessions[sid]["profile"] = "prof-1"
+ FakeCloud.sessions[sid]["state"] = "closing"
+ r = self.run_cli("cloud")
+ self.assertIn("· closing ·", r.stdout)
+ self.assertIn("your iPhone", r.stdout)
+ self.assertNotIn("saving", r.stdout)
+ self.assertIn("phone stored", r.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}])
+ self.assertEqual(self.run_cli("cloud", "start", "Temporary phone").returncode, 0)
+ self.assertEqual(FakeCloud.posts, [{"timeout_seconds": 900, "platform": "android",
+ "kind": "emulator"}])
+ self.assertNotIn("profile_id", FakeCloud.posts[0])
+ self.assertNotIn("device_id", FakeCloud.posts[0])
over = self.run_cli("cloud", "start", "--minutes", "999")
self.assertEqual(over.returncode, 1)
self.assertIn("between 1 and 30", over.stderr)
@@ -314,9 +476,11 @@ class CloudCli(unittest.TestCase):
"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)
+ r = self.run_cli("cloud", "start", "Saved phone")
+ self.assertNotEqual(r.returncode, 0)
+ self.assertIn("already running", r.stderr)
+ self.assertIn("--session", r.stderr)
+ self.assertIn("dash01", r.stderr)
self.assertEqual(FakeCloud.posts, [])
def test_helpers_drive_the_rented_phone_and_relock_is_healed(self):
@@ -339,20 +503,85 @@ class CloudCli(unittest.TestCase):
env=self.env)
self.assertEqual(r.stdout.split()[:2], ["android", "hello"], r.stderr)
+ def test_a_control_session_needs_no_adb_and_the_helpers_drive_it_over_https(self):
+ 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.calls = []
+ self.login()
+ FakeCloud.available = [
+ {"platform": "ios", "kind": "device", "id": "iph-1", "label": "My iPhone SE",
+ "state": "available"}]
+ r = self.run_cli("cloud", "start", "ios", "--no-watch", env={"PHONE_HARNESS_ADB": "/nonexistent/adb"})
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertEqual(FakeCloud.posts[0]["platform"], "ios")
+ self.assertEqual(FakeCloud.posts[0]["kind"], "device")
+ self.assertEqual(FakeCloud.posts[0]["device_id"], "iph-1")
+ self.assertEqual(FakeCloud.posts[0]["timeout_seconds"], 900)
+ self.assertNotIn("provider", FakeCloud.posts[0])
+ self.assertNotIn("profile_id", FakeCloud.posts[0])
+ self.assertIn("Starting your iPhone", r.stdout)
+ self.assertIn("control", r.stdout)
+ self.assertNotIn("adb", r.stdout)
+ self.assertFalse((Path(self.home.name) / "adb.log").exists()) # never touched
+ status = self.run_cli("cloud")
+ self.assertIn("your iPhone", status.stdout)
+ self.assertIn("drive it over HTTPS", status.stdout)
+ self.assertNotIn("ct_1", status.stdout + r.stdout) # the grant stays private
+
+ script = ("from phone_harness import transport\n"
+ "from phone_harness.helpers import tap, Unsupported\n"
+ "p = transport.connect()\n"
+ "print(p.name)\n"
+ "tap(10, 20)\n"
+ "path, win = p.send('screen.capture')\n"
+ "print(open(path, 'rb').read()[:4] == b'\\x89PNG', win['w'])\n"
+ "try:\n"
+ " p.send('nav.back')\n"
+ "except Unsupported:\n"
+ " print('unsupported')\n"
+ "print(p.supports('tree'), p.supports('apps.current'))\n")
+ r = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, env=self.env)
+ self.assertEqual(r.stdout.split(), ["remote", "True", "750", "unsupported", "False", "False"], r.stderr)
+ self.assertEqual([c["op"] for c in FakeControl.calls][:2], ["input.tap", "screen.capture"])
+ self.assertIn("nav.back", [c["op"] for c in FakeControl.calls])
+
+ stop = self.run_cli("cloud", "stop")
+ self.assertEqual(stop.returncode, 0, stop.stderr)
+ self.assertNotIn("saved", stop.stdout) # an iPhone keeps its data
+ self.assertIn("none attached", self.run_cli("cloud").stdout)
+
+ def test_a_session_saved_by_the_android_cli_still_attaches(self):
+ """main writes host/port/code and no link. An upgrade keeps that phone."""
+ state = Path(self.home.name) / "state"
+ state.mkdir(parents=True, exist_ok=True)
+ (state / "cloud.json").write_text(json.dumps({"session": {
+ "sid": "sid009", "host": "live.example", "port": 22220, "code": "ph_code",
+ "expires_at": time.time() + 600}}))
+ r = subprocess.run([sys.executable, "-c", "from phone_harness import cloud; print(cloud.attached())"],
+ capture_output=True, text=True, env=self.env)
+ self.assertIn("'kind': 'adb'", r.stdout)
+ self.assertIn("live.example", r.stdout)
+ self.assertNotEqual(r.stdout.strip(), "None", 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")
+ # One read builds the catalog; the wait then sees the phone still closing.
+ FakeCloud.closing_reads = 3
+ r = self.run_cli("cloud", "start", "Saved phone")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("still saving", r.stdout)
- self.assertEqual(FakeCloud.posts, [{"timeout_seconds": 900, "profile_id": "prof-1"}])
+ self.assertEqual(FakeCloud.posts, [{"timeout_seconds": 900, "platform": "android",
+ "kind": "emulator", "profile_id": "prof-1"}])
def test_stop_returns_at_once_and_detaches(self):
self.login()
- self.run_cli("cloud", "start")
+ self.run_cli("cloud", "start", "Saved phone")
started = time.monotonic()
r = self.run_cli("cloud", "stop")
self.assertEqual(r.returncode, 0, r.stderr)
@@ -366,16 +595,272 @@ class CloudCli(unittest.TestCase):
def test_stop_wait_watches_the_save(self):
self.login()
- self.run_cli("cloud", "start")
+ self.run_cli("cloud", "start", "Saved phone")
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")
+ self.run_cli("cloud", "start", "Temporary phone")
r = self.run_cli("cloud", "stop")
self.assertNotIn("saved", r.stdout)
+ def test_a_bare_start_names_nothing_and_gets_the_service_s_unnamed_phone(self):
+ self.login()
+ r = self.run_cli("cloud", "start", "--no-watch")
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertIn("Starting a temporary phone", r.stdout)
+ self.assertNotIn("Saved phone", r.stdout)
+ self.assertEqual(FakeCloud.posts, [{"timeout_seconds": 900}]) # no platform, no kind, no profile
+ self.assertEqual(FakeCloud.sessions[next(iter(FakeCloud.sessions))].get("profile"), None)
+
+ def test_this_machine_may_prefer_a_phone_for_bare_starts(self):
+ self.login()
+ self.assertEqual(self.run_cli("config", "set", "cloud.phone", "Saved phone").returncode, 0)
+ r = self.run_cli("cloud", "start", "--no-watch")
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertIn("Starting Saved phone", r.stdout)
+ self.assertEqual(FakeCloud.posts[-1], {"timeout_seconds": 900, "platform": "android",
+ "kind": "emulator", "profile_id": "prof-1"})
+ # a stale preference says where it came from
+ self.run_cli("cloud", "stop")
+ self.assertEqual(self.run_cli("config", "set", "cloud.phone", "Old phone").returncode, 0)
+ gone = self.run_cli("cloud", "start", "--no-watch")
+ self.assertNotEqual(gone.returncode, 0)
+ self.assertIn("cloud.phone", gone.stderr)
+ self.assertIn("Saved phone", gone.stderr)
+
+ def test_removed_flags_are_not_phone_names(self):
+ self.login()
+ for flag in ("--iphone", "--device", "--temp", "--timeout"):
+ r = self.run_cli("cloud", "start", flag)
+ self.assertNotEqual(r.returncode, 0, flag)
+ self.assertIn(flag, r.stderr)
+ self.assertEqual(FakeCloud.posts, [])
+
+ def test_catalog_start_is_exact_and_an_ambiguous_name_stops(self):
+ self.login()
+ FakeCloud.available = [
+ {"platform": "ios", "kind": "device", "id": "iph-a", "label": "SE", "state": "available"},
+ {"platform": "ios", "kind": "device", "id": "iph-b", "label": "Pro", "state": "unavailable"},
+ ]
+ many = self.run_cli("cloud", "start", "ios", "--no-watch")
+ self.assertNotEqual(many.returncode, 0)
+ shown = many.stdout + many.stderr
+ self.assertIn("SE", shown)
+ self.assertIn("Pro", shown)
+ self.assertIn("iph-a", shown)
+ self.assertEqual(FakeCloud.posts, [])
+
+ missing = self.run_cli("cloud", "start", "nope", "--no-watch")
+ self.assertIn("nope", missing.stderr)
+ self.assertIn("catalog", missing.stderr)
+ self.assertEqual(FakeCloud.posts, [])
+
+ down = self.run_cli("cloud", "start", "iph-b", "--no-watch",
+ env={"PHONE_HARNESS_ADB": "/nonexistent/adb"})
+ self.assertNotEqual(down.returncode, 0)
+ self.assertIn("not on its host", down.stderr)
+
+ FakeCloud.available = [
+ {"platform": "ios", "kind": "device", "id": "iph-a", "label": "SE",
+ "state": "running", "session": "live1"}]
+ held = self.run_cli("cloud", "start", "SE", "--no-watch",
+ env={"PHONE_HARNESS_ADB": "/nonexistent/adb"})
+ self.assertNotEqual(held.returncode, 0)
+ self.assertIn("--session", held.stderr)
+ self.assertIn("live1", held.stderr)
+ self.assertNotIn("cloud use", held.stderr)
+
+ FakeCloud.available = [
+ {"platform": "android", "kind": "emulator", "label": "Temporary phone", "temporary": True}]
+ before = len(FakeCloud.posts)
+ none = self.run_cli("cloud", "start", "ios", "--no-watch")
+ self.assertIn("catalog", none.stderr)
+ self.assertEqual(len(FakeCloud.posts), before)
+
+ def test_create_errors_name_the_next_step(self):
+ self.login()
+ FakeCloud.fail = (400, {"error": "no phone of that platform and kind available to this account"}, None)
+ hinted = self.run_cli("cloud", "start", "Saved phone", "--no-watch")
+ self.assertIn("no phone of that platform and kind", hinted.stderr)
+ self.assertIn("Saved phone", hinted.stderr)
+ FakeCloud.fail = (409, {"error": "limit", "code": "session_limit",
+ "active_session_count": 2, "session_limit": 2}, None)
+ limited = self.run_cli("cloud", "start", "--no-watch")
+ self.assertIn("2 of 2", limited.stderr)
+ FakeCloud.fail = (503, {"error": "busy", "code": "phones_busy"}, {"Retry-After": "12"})
+ busy = self.run_cli("cloud", "start", "--no-watch")
+ self.assertIn("Try again in 12s", busy.stderr)
+ FakeCloud.fail = (403, {"error": "blocked", "code": "account_blocked"}, None)
+ blocked = self.run_cli("cloud", "start", "--no-watch")
+ self.assertIn("Rentals are blocked", blocked.stderr)
+ self.assertNotIn("isn't enabled", blocked.stderr)
+ FakeCloud.fail = (403, {"error": "not enough credit", "balance_cents": 0}, None)
+ broke = self.run_cli("cloud", "start", "--no-watch")
+ self.assertIn("Not enough credit", broke.stderr)
+ self.assertNotIn("isn't enabled", broke.stderr)
+
+ def test_one_iphone_starts_by_platform_or_id_and_for_sets_the_length(self):
+ self.login()
+ FakeCloud.available = [
+ {"platform": "ios", "kind": "device", "id": "iph-a", "label": "SE", "state": "available"}]
+ r = self.run_cli("cloud", "start", "ios", "--for", "2m", "--no-watch",
+ env={"PHONE_HARNESS_ADB": "/nonexistent/adb"})
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertEqual(FakeCloud.posts[-1]["timeout_seconds"], 120)
+ self.assertEqual(FakeCloud.posts[-1]["device_id"], "iph-a")
+ self.assertEqual(FakeCloud.posts[-1]["platform"], "ios")
+ self.assertEqual(FakeCloud.posts[-1]["kind"], "device")
+ named = self.run_cli("cloud", "start", "iph-a", "--for", "45s", "--no-watch",
+ env={"PHONE_HARNESS_ADB": "/nonexistent/adb"})
+ self.assertEqual(named.returncode, 0, named.stderr)
+ self.assertIn("reusing", named.stdout)
+ self.assertEqual(len(FakeCloud.posts), 1)
+ self.run_cli("cloud", "stop")
+ posted = self.run_cli("cloud", "start", "SE", "--for", "45s", "--no-watch",
+ env={"PHONE_HARNESS_ADB": "/nonexistent/adb"})
+ self.assertEqual(posted.returncode, 0, posted.stderr)
+ self.assertEqual(FakeCloud.posts[-1]["device_id"], "iph-a")
+ self.assertEqual(FakeCloud.posts[-1]["timeout_seconds"], 45)
+ over = self.run_cli("cloud", "start", "--for", "90m", "--no-watch")
+ self.assertNotEqual(over.returncode, 0)
+ self.assertIn("between 1 and 30", over.stderr)
+ clash = self.run_cli("cloud", "start", "--minutes", "5", "--for", "90s")
+ self.assertIn("not both", clash.stderr)
+
+ def test_for_accepts_seconds_minutes_and_a_bare_number(self):
+ self.login()
+ for text, seconds in (("90s", 90), ("15m", 900), ("2", 120), ("15min", 900)):
+ if FakeCloud.sessions:
+ stopped = self.run_cli("cloud", "stop")
+ self.assertEqual(stopped.returncode, 0, stopped.stderr)
+ r = self.run_cli("cloud", "start", "Temporary phone", "--for", text, "--no-watch")
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertEqual(FakeCloud.posts[-1]["timeout_seconds"], seconds, text)
+ self.assertNotIn("profile_id", FakeCloud.posts[-1])
+
+ def test_android_timeout_keeps_the_profile_body(self):
+ self.login()
+ r = self.run_cli("cloud", "start", "Saved phone", "--for", "120s", "--no-watch")
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertEqual(FakeCloud.posts, [{"timeout_seconds": 120, "platform": "android",
+ "kind": "emulator", "profile_id": "prof-1"}])
+
+ def test_an_iphone_and_an_android_can_run_together(self):
+ self.login()
+ FakeCloud.available = [
+ {"platform": "android", "kind": "emulator", "id": "prof-1", "label": "Saved phone",
+ "state": "stored"},
+ {"platform": "ios", "kind": "device", "id": "iph-1", "label": "My iPhone SE",
+ "state": "available"},
+ ]
+ first = self.run_cli("cloud", "start", "Saved phone", "--minutes", "5", "--no-watch")
+ self.assertEqual(first.returncode, 0, first.stderr)
+ self.assertEqual(FakeCloud.posts[0], {"timeout_seconds": 300, "platform": "android",
+ "kind": "emulator", "profile_id": "prof-1"})
+ second = self.run_cli("cloud", "start", "ios", "--no-watch",
+ env={"PHONE_HARNESS_ADB": "/nonexistent/adb"})
+ self.assertEqual(second.returncode, 0, second.stderr)
+ self.assertIn("stays up", second.stdout)
+ self.assertEqual(FakeCloud.posts[1]["platform"], "ios")
+ self.assertEqual(FakeCloud.posts[1]["kind"], "device")
+ self.assertEqual(FakeCloud.posts[1]["device_id"], "iph-1")
+ self.assertEqual(len(FakeCloud.sessions), 2)
+ back = self.run_cli("cloud", "start", "Saved phone", "--no-watch")
+ self.assertEqual(back.returncode, 0, back.stderr)
+ self.assertIn("reusing", back.stdout)
+ self.assertEqual(len(FakeCloud.posts), 2)
+ self.assertIn("your phone", back.stdout)
+ self.assertNotIn("your iPhone", back.stdout)
+
+ def test_ls_merges_the_catalog_with_a_session_that_matches_nothing(self):
+ self.login()
+ FakeCloud.available = [
+ {"platform": "android", "kind": "emulator", "id": "prof-1", "label": "Saved phone",
+ "state": "stored"},
+ {"platform": "ios", "kind": "device", "id": "iph-1", "label": "My iPhone SE",
+ "state": "available"},
+ {"platform": "android", "kind": "emulator", "temporary": True, "label": "Temporary phone"},
+ ]
+ self.assertEqual(self.run_cli("cloud", "start", "Saved phone", "--no-watch").returncode, 0)
+ FakeCloud.sessions["orphan"] = {
+ "id": "orphan", "state": "ready", "platform": "android", "profile": "prof-other",
+ "expires_at": time.time() + 600,
+ "adb": {"host": "live.example", "port": 22220, "code": "ph_code"}}
+ raw = self.run_cli("cloud", "ls", "--json")
+ self.assertEqual(raw.returncode, 0, raw.stderr)
+ rows = json.loads(raw.stdout)
+ self.assertEqual([row["label"] for row in rows[:3]],
+ ["Saved phone", "My iPhone SE", "Temporary phone"])
+ self.assertNotIn("default", rows[0]) # the service keeps no preference, so neither does ls
+ self.assertFalse(rows[0]["temporary"])
+ self.assertEqual(rows[0]["id"], "prof-1")
+ self.assertEqual(rows[0]["platform"], "android")
+ self.assertEqual(rows[0]["state"], "stored")
+ self.assertEqual(rows[0]["session"]["id"], "sid001")
+ self.assertTrue(rows[0]["targeted"])
+ self.assertIsNone(rows[1]["session"])
+ self.assertFalse(rows[1]["targeted"])
+ self.assertTrue(rows[-1]["unmatched"])
+ self.assertEqual(rows[-1]["session"]["id"], "orphan")
+ text = self.run_cli("cloud", "ls")
+ self.assertIn("orphan", text.stdout)
+ self.assertTrue(any(line.startswith("*") and "sid001" in line
+ for line in text.stdout.splitlines()))
+
+ def test_a_session_pin_targets_one_phone_for_commands_and_helpers(self):
+ self.login()
+ FakeCloud.available = [
+ {"platform": "android", "kind": "emulator", "id": "prof-1", "label": "Saved phone",
+ "state": "stored"},
+ {"platform": "ios", "kind": "device", "id": "iph-1", "label": "My iPhone SE",
+ "state": "available"},
+ ]
+ self.assertEqual(self.run_cli("cloud", "start", "--no-watch").returncode, 0)
+ self.assertEqual(self.run_cli("cloud", "start", "ios", "--no-watch",
+ env={"PHONE_HARNESS_ADB": "/nonexistent/adb"}).returncode, 0)
+ state = json.loads((Path(self.home.name) / "state" / "cloud.json").read_text())
+ android_sid = next(s["sid"] for s in state["sessions"].values() if s["link"]["kind"] == "adb")
+ ios_sid = next(s["sid"] for s in state["sessions"].values() if s["link"]["kind"] == "control")
+
+ def starred(result, sid):
+ line = next(l for l in result.stdout.splitlines() if sid in l)
+ return line.startswith("*")
+
+ plain = self.run_cli("cloud", "ls")
+ self.assertTrue(starred(plain, ios_sid), plain.stdout)
+ self.assertFalse(starred(plain, android_sid), plain.stdout)
+ pinned = self.run_cli("cloud", "ls", "--session", android_sid)
+ self.assertTrue(starred(pinned, android_sid), pinned.stdout)
+ self.assertFalse(starred(pinned, ios_sid), pinned.stdout)
+ via_env = self.run_cli("cloud", "ls", env={"PHONE_HARNESS_SESSION": android_sid})
+ self.assertTrue(starred(via_env, android_sid), via_env.stdout)
+
+ script = "from phone_harness import transport\nprint(transport.connect().name)\n"
+ remote = self.run_cli("--session", ios_sid, stdin=script)
+ self.assertEqual(remote.stdout.strip(), "remote", remote.stderr)
+ android = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True,
+ env={**self.env, "PHONE_HARNESS_SESSION": android_sid})
+ self.assertEqual(android.stdout.strip(), "android", android.stderr)
+
+ stopped = self.run_cli("cloud", "stop", "--session", android_sid)
+ self.assertEqual(stopped.returncode, 0, stopped.stderr)
+ self.assertIn(android_sid, stopped.stdout)
+ self.assertNotIn(android_sid, FakeCloud.sessions)
+ self.assertIn(ios_sid, FakeCloud.sessions)
+ self.assertIn("your iPhone", self.run_cli("cloud").stdout)
+
+ def test_phone_reset_describes_the_saved_android_only(self):
+ self.login()
+ refused = self.run_cli("cloud", "phone", "reset")
+ self.assertNotEqual(refused.returncode, 0)
+ self.assertIn("saved Android", refused.stderr)
+ self.assertIn("no iPhone reset", refused.stderr)
+ help_text = self.run_cli("cloud", "nope")
+ self.assertIn("wipes its stored state", help_text.stdout)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_skill.py b/tests/test_skill.py
new file mode 100644
index 0000000..ef38623
--- /dev/null
+++ b/tests/test_skill.py
@@ -0,0 +1,59 @@
+"""`phone-harness skill` is printed on Windows CI, where stdout is cp1252."""
+import io
+import os
+import subprocess
+import sys
+import unittest
+from pathlib import Path
+
+SRC = Path(__file__).resolve().parents[1] / "src"
+sys.path.insert(0, str(SRC))
+
+from phone_harness.run import _skill_text, _write_utf8 # noqa: E402
+from phone_harness.android import CLI_USAGE as ANDROID_USAGE # noqa: E402
+from phone_harness.cloud import CLI_USAGE as CLOUD_USAGE # noqa: E402
+from phone_harness.config import CLI_USAGE as CONFIG_USAGE # noqa: E402
+from phone_harness.run import USAGE # noqa: E402
+
+
+class SkillOutput(unittest.TestCase):
+ def test_printed_docs_and_help_are_ascii(self):
+ for text in (_skill_text(), USAGE, ANDROID_USAGE, CLOUD_USAGE, CONFIG_USAGE):
+ text.encode("ascii")
+
+ def test_skill_command_survives_cp1252_stdout(self):
+ env = os.environ.copy()
+ env["PYTHONIOENCODING"] = "cp1252:strict"
+ env["PYTHONPATH"] = str(SRC) + os.pathsep + env.get("PYTHONPATH", "")
+ env.pop("BROWSER", None)
+ r = subprocess.run(
+ [sys.executable, "-m", "phone_harness.run", "skill"],
+ capture_output=True, env=env)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertIn(b"phone-harness", r.stdout)
+ r.stdout.decode("ascii")
+
+ def test_write_utf8_uses_the_buffer_when_the_text_stream_refuses(self):
+ class Stdout:
+ encoding = "cp1252"
+
+ def __init__(self):
+ self.buffer = io.BytesIO()
+
+ def reconfigure(self, **_kw):
+ raise OSError("cannot reconfigure")
+
+ def write(self, s):
+ s.encode(self.encoding)
+
+ def flush(self):
+ pass
+
+ out = Stdout()
+ old = sys.stdout
+ sys.stdout = out
+ try:
+ _write_utf8("a \u2192 b")
+ finally:
+ sys.stdout = old
+ self.assertEqual(out.buffer.getvalue(), "a \u2192 b".encode("utf-8"))