Skip to content

let your agent control your phone

Polish the CLI: argparse help, fitted ls columns, and --version (#118)

shawn pana697cdd6dc366
diff --git a/README.md b/README.md
index 6fb050e..933071a 100644
--- a/README.md
+++ b/README.md
@@ -56,8 +56,11 @@ tap_text("New Note")
type_text("hello from the harness")
print([o["text"] for o in ocr()][:10])
PY
+phone-harness --version
```
+`phone-harness --version` (or `-V`) prints `phone-harness <version>`.
+
Helpers are pre-imported. [SKILL.md](SKILL.md) is the agent's day-to-day
guide; [helpers.py](src/phone_harness/helpers.py) is the full list.
Task-specific helpers live in `agent-workspace/agent_helpers.py` in a
diff --git a/SKILL.md b/SKILL.md
index 37eed9e..97b76cc 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -470,6 +470,8 @@ on the next run. For setup or permission problems, read `install.md`.
## Updates
+`phone-harness --version` prints `phone-harness <version>`.
+
`phone-harness update` brings this install up to date. A uv tool runs
`uv tool upgrade phone-harness`. A git checkout runs `git pull --ff-only`
in that checkout. Anything else prints `pip install -U phone-harness` and
diff --git a/src/phone_harness/android.py b/src/phone_harness/android.py
index 9b5b41e..d7d0506 100644
--- a/src/phone_harness/android.py
+++ b/src/phone_harness/android.py
@@ -27,6 +27,7 @@ still "pixel-8". The first phone paired over Wi-Fi becomes the primary;
`phone-harness android use NAME` changes that; ANDROID_SERIAL overrides
everything.
"""
+import argparse
import importlib.util
import os
import re
@@ -41,6 +42,7 @@ import xml.etree.ElementTree as ET
from datetime import datetime, timezone
from . import config
+from . import term
from .transport import Backend, Unsupported
# Apple's Vision OCR ships with the iPhone backend; on a Mac it can read an
@@ -781,8 +783,8 @@ def _awake(mirror=True):
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
print("mirror: scrcpy window open (close it to end)", flush=True)
elif mirror:
- print("mirror: scrcpy not installed (brew install scrcpy) — keeping "
- "awake without a window", flush=True)
+ print(term.note("mirror: scrcpy not installed (brew install scrcpy) — keeping "
+ "awake without a window"), flush=True)
def stop(*_):
if proc and proc.poll() is None:
@@ -806,7 +808,7 @@ def _awake(mirror=True):
awake, locked = phone._screen_status()
if locked:
if was_locked is not True:
- print("locked — unlock the phone to continue (pokes paused)",
+ print(term.note("locked — unlock the phone to continue (pokes paused)"),
flush=True)
was_locked = True
else:
@@ -850,8 +852,73 @@ def _connect_serial(serial, timeout=10):
return None
+def _android_parsers():
+ """One argparse parser per subcommand, for --help and unknown flags.
+
+ The command body still reads the original words. `--fg` is how
+ `awake --bg` re-enters this process; it is accepted and not shown.
+ """
+ def make(name, usage, description):
+ return term.Parser(
+ prog=f"phone-harness android {name}",
+ usage=usage,
+ description=description,
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ )
+
+ parsers = {}
+ awake = make("awake", "phone-harness android awake [--bg] [--no-mirror]",
+ "Keep the phone awake for a session, and mirror it when scrcpy "
+ "is installed. Changes no phone settings. Ends with rest, Ctrl-C, "
+ "or closing the mirror.")
+ awake.add_argument("--bg", action="store_true", help="detach and keep running")
+ awake.add_argument("--no-mirror", action="store_true", help="do not open a scrcpy window")
+ awake.add_argument("--fg", action="store_true", help=argparse.SUPPRESS)
+ parsers["awake"] = awake
+
+ parsers["rest"] = make("rest", "phone-harness android rest",
+ "End the awake session and let the phone sleep.")
+
+ parsers["pair"] = make(
+ "pair",
+ "phone-harness android pair [CODE] [NAME] | phone-harness android pair IP:PORT CODE [NAME]",
+ "Wireless debugging. With a 6-digit code, the phone is found over mDNS. "
+ "Pass IP:PORT when mDNS is blocked; both values are on the pairing dialog.")
+
+ parsers["connect"] = make(
+ "connect", "phone-harness android connect [NAME|IP:PORT]",
+ "Connect a paired phone. With no name, connect the primary over mDNS.")
+
+ parsers["use"] = make("use", "phone-harness android use NAME",
+ "Make NAME the primary phone.")
+
+ parsers["forget"] = make("forget", "phone-harness android forget NAME",
+ "Forget a paired phone.")
+ return parsers
+
+
def cli(args):
+ try:
+ return _cli(list(args))
+ except SystemExit as e:
+ if isinstance(e.code, str):
+ print(term.err(e.code), file=sys.stderr)
+ return 1
+ raise
+
+
+def _cli(args):
+ if args[:1] in (["-h"], ["--help"]):
+ print(CLI_USAGE)
+ return 0
cmd = args[0] if args else None
+ if cmd is not None:
+ parser = _android_parsers().get(cmd)
+ if parser is None:
+ _load()
+ print(CLI_USAGE)
+ return 2
+ term.reject_unknown_flags(parser, args[1:])
cfg = _load()
phones = cfg.get("phones") or {}
@@ -886,8 +953,11 @@ def cli(args):
_pidfile().parent.mkdir(parents=True, exist_ok=True)
_pidfile().write_text(str(child.pid))
time.sleep(2)
- print(f"awake in background (pid {child.pid}); phone-harness android rest to end"
- if child.poll() is None else "awake exited at once — is a phone connected? try without --bg")
+ if child.poll() is None:
+ print(f"awake in background (pid {child.pid}); phone-harness android rest to end")
+ else:
+ print(term.err("awake exited at once — is a phone connected? try without --bg",
+ sys.stdout))
return 0 if child.poll() is None else 1
_pidfile().parent.mkdir(parents=True, exist_ok=True)
_pidfile().write_text(str(os.getpid()))
@@ -910,7 +980,7 @@ def cli(args):
phone._sh("input keyevent KEYCODE_SLEEP", timeout=10)
print("phone put to sleep")
except RuntimeError as e:
- print(f"(could not put the phone to sleep: {e})")
+ print(term.err(f"(could not put the phone to sleep: {e})", sys.stdout))
return 0
if cmd == "pair":
@@ -930,7 +1000,7 @@ def cli(args):
code = input("6-digit pairing code shown on the phone: ").strip()
except EOFError:
print(CLI_USAGE); return 2
- print("looking for the phone on this Wi-Fi...", flush=True)
+ print(term.note("looking for the phone on this Wi-Fi..."), flush=True)
addr = None
for _ in range(45): # the dialog advertises itself
hits = _mdns("pairing")
@@ -938,14 +1008,16 @@ def cli(args):
addr = hits[0]["addr"]; break
time.sleep(1)
if addr is None:
- print("no phone is offering to pair on this network. Is Wireless "
- "debugging on, the pairing dialog open, and the phone on the "
- "same Wi-Fi as this Mac? If your network blocks mDNS, use: "
- "phone-harness android pair IP:PORT CODE (both shown in the dialog)")
+ print(term.err("no phone is offering to pair on this network. Is Wireless "
+ "debugging on, the pairing dialog open, and the phone on the "
+ "same Wi-Fi as this Mac? If your network blocks mDNS, use: "
+ "phone-harness android pair IP:PORT CODE (both shown in the dialog)",
+ sys.stdout))
return 1
out = _run("pair", addr, code, timeout=30, check=False)
if "Successfully paired" not in out:
- print(out.strip() or "pairing failed"); return 1
+ print(term.err(out.strip() or "pairing failed", sys.stdout))
+ return 1
host = addr.rpartition(":")[0]
# the connect port differs from the pairing port; find it via mDNS
adb_id = None
@@ -957,10 +1029,10 @@ def cli(args):
adb_id = hit["addr"]; break
time.sleep(1)
if adb_id is None:
- print("paired, but could not find the phone's connect port on this "
- "network yet. Turn Wireless debugging off and on, then: "
- "phone-harness android connect IP:PORT (the port shown on "
- "the Wireless debugging screen)")
+ print(term.err("paired, but could not find the phone's connect port on this "
+ "network yet. Turn Wireless debugging off and on, then: "
+ "phone-harness android connect IP:PORT (the port shown on "
+ "the Wireless debugging screen)", sys.stdout))
return 1
serial, model = _prop(adb_id, "ro.serialno"), _prop(adb_id, "ro.product.model")
key = _remember(cfg, serial, model, host=host, name=name, primary=True)
@@ -968,24 +1040,31 @@ def cli(args):
print(f"paired and connected: {model} as '{key}' ({adb_id})"
+ (" — now the primary" if cfg.get("primary") == key else ""))
if config.get("platform") != "android":
- print("tip: `phone-harness config set platform android` makes Android "
- "the default, so nothing needs PHONE_HARNESS_PLATFORM=android")
+ print(term.note("tip: `phone-harness config set platform android` makes Android "
+ "the default, so nothing needs PHONE_HARNESS_PLATFORM=android"))
return 0
if cmd == "connect":
target = args[1] if len(args) > 1 else cfg.get("primary")
if not target:
- print("no primary phone yet — pair one first"); return 1
+ print(term.err("no primary phone yet — pair one first", sys.stdout))
+ return 1
if ":" in target:
- out = _run("connect", target, timeout=15, check=False); print(out.strip())
- return 0 if "connected" in out and "cannot" not in out else 1
+ out = _run("connect", target, timeout=15, check=False)
+ text = out.strip()
+ ok = "connected" in out and "cannot" not in out
+ print(text if ok else term.err(text, sys.stdout))
+ return 0 if ok else 1
p = phones.get(target)
if not p:
- print(f"unknown phone {target!r}; known: {', '.join(phones) or 'none'}"); return 1
+ print(term.err(f"unknown phone {target!r}; known: {', '.join(phones) or 'none'}",
+ sys.stdout))
+ return 1
adb_id = _connect_serial(p["serial"])
if adb_id is None:
- print(f"'{target}' isn't announcing on this Wi-Fi. Is Wireless "
- "debugging on, and the phone on the same network?"); return 1
+ print(term.err(f"'{target}' isn't announcing on this Wi-Fi. Is Wireless "
+ "debugging on, and the phone on the same network?", sys.stdout))
+ return 1
_remember(cfg, p["serial"], p.get("model"), host=adb_id.rpartition(":")[0],
primary=True)
print(f"connected: {target} ({adb_id})"); return 0
diff --git a/src/phone_harness/cloud.py b/src/phone_harness/cloud.py
index a53b366..1325d62 100644
--- a/src/phone_harness/cloud.py
+++ b/src/phone_harness/cloud.py
@@ -18,6 +18,7 @@ is no one to click Approve.
Stdlib only. API reference: https://phone-harness.com/docs
"""
+import argparse
import json
import math
import os
@@ -31,6 +32,7 @@ import uuid
import webbrowser
from . import config
+from . import term
SAVE_WAIT = 90 # seconds to let a stopped profile phone finish closing and saving
READY_WAIT = 240 # seconds to wait for `ready` before giving the phone back
@@ -532,8 +534,10 @@ def ensure_connected(sess, quiet=False):
f"{sess.get('sid', 'SID')}` to fetch the current one")
left = (sess.get("expires_at") or 0) - time.time()
if not quiet and 0 < left < LOW_TIME:
- print(f"phone-harness: the cloud phone expires in {int(left)}s — run "
- "`phone-harness cloud stop` now to keep its running state", file=sys.stderr)
+ print(term.note(
+ f"phone-harness: the cloud phone expires in {int(left)}s — run "
+ "`phone-harness cloud stop` now to keep its running state",
+ sys.stderr), file=sys.stderr)
return serial
@@ -769,7 +773,7 @@ def _wait_ready(sid):
if prog.get("queue_position"):
line += f", position {prog['queue_position']} in the queue"
if line != shown:
- print(f" … {line}")
+ print(term.note(f" … {line}"))
shown = line
time.sleep(2)
@@ -788,13 +792,13 @@ def _login(args):
f"{start.get('error_description') or start.get('error') or start.get('title') or status}")
print(f"To sign in, open: {start['verification_uri']}\n"
f"and enter code: {start['user_code']}\n\n"
- f"{_waitlist_line()}\n")
+ f"{term.note(_waitlist_line())}\n")
if open_browser:
try:
webbrowser.open(start.get("verification_uri_complete") or start["verification_uri"])
except Exception:
pass
- print("Waiting for you to approve in the browser…", flush=True)
+ print(term.note("Waiting for you to approve in the browser…"), flush=True)
interval = int(start.get("interval", 5))
deadline = time.monotonic() + int(start.get("expires_in") or 600)
tok = None
@@ -822,7 +826,7 @@ def _login(args):
state = _load_state()
state["profile_id"] = (me.get("profile") or {}).get("id")
_save_state(state)
- print(f"✓ Signed in as {me.get('email') or me.get('uid')}")
+ print(f"{term.mark()} Signed in as {me.get('email') or me.get('uid')}")
_print_account(me)
print("\nStart your phone with: phone-harness cloud start")
return 0
@@ -1025,7 +1029,7 @@ def _wait_out_save(profile_id):
sys.exit("Your phone is still shutting down from its last session. "
"Try again in a few seconds.")
if not told:
- print("Your phone is still saving from its last session…")
+ print(term.note("Your phone is still saving from its last session…"))
told = True
time.sleep(3)
@@ -1122,7 +1126,7 @@ def _start(args):
reused = _reusable(selector)
if reused:
live, rec = reused
- print(f"Already attached to session {live['id']}; reusing it.")
+ print(term.note(f"Already attached to session {live['id']}; reusing it."))
return _report(_wait_ready(live["id"]), selector=selector,
label=rec.get("label"), watch=False)
@@ -1143,7 +1147,8 @@ def _start(args):
except CloudError:
still = None
if still and still.get("state") in ("provisioning", "ready"):
- print(f"Session {previous['sid']} stays up. `--session {previous['sid']}` targets it.")
+ print(term.note(
+ f"Session {previous['sid']} stays up. `--session {previous['sid']}` targets it."))
body = _create_body(entry, timeout)
label = (entry or {}).get("label")
@@ -1175,7 +1180,8 @@ def _report(session, profile_id=None, watch=True, selector=None, label=None):
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, '')}")
+ ready_note = note.get(how, "")
+ print(f"{term.mark()} ready.{term.note(ready_note) if ready_note else ''}")
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 ""))
@@ -1216,7 +1222,7 @@ def _stop(args):
before = _api("GET", f"/sessions/{sid}")
held_profile = held_profile or _keeps_state(before)
_api("DELETE", f"/sessions/{sid}")
- print(f"✓ Session {sid} ended; billing stopped.")
+ print(f"{term.mark()} Session {sid} ended; billing stopped.")
except CloudError as e:
if e.status != 404:
raise
@@ -1228,9 +1234,9 @@ def _stop(args):
# half minute and needs nothing from here, so waiting on it is opt-in;
# `cloud start` waits out a save that is still going.
if not watch_save:
- print(" Your phone is being saved (about 30s); `phone-harness cloud phone` shows when.")
+ print(term.note(" Your phone is being saved (about 30s); `phone-harness cloud phone` shows when."))
return 0
- print(" Saving your phone…", end="", flush=True)
+ print(term.note(" Saving your phone…"), end="", flush=True)
deadline = time.monotonic() + SAVE_WAIT
state = "saving"
while time.monotonic() < deadline:
@@ -1246,8 +1252,8 @@ def _stop(args):
def _status(args):
if not _bearer(required=False):
- print("Not signed in. Run: phone-harness cloud login")
- print(_waitlist_line())
+ print(term.err("Not signed in. Run: phone-harness cloud login", sys.stdout))
+ print(term.note(_waitlist_line()))
return 1
me = _api("GET", "/me")
if os.environ.get("PHONE_HARNESS_CLOUD_API"):
@@ -1258,7 +1264,7 @@ def _status(args):
try:
sess = attached()
except CloudPhoneError as e:
- print(e)
+ print(term.err(str(e), sys.stdout))
return 1
live = None
if sess:
@@ -1275,7 +1281,7 @@ def _status(args):
if not sess:
lost_rec = lost()
if lost_rec:
- print(ended_message(lost_rec))
+ print(term.err(ended_message(lost_rec), sys.stdout))
return 1
running = me.get("active_session_count") or 0
print("session none attached" + (f" ({running} running: `phone-harness cloud ls`)"
@@ -1283,7 +1289,7 @@ def _status(args):
return 0
if live is None:
cause = "expired" if _expired(sess) else "unreachable"
- print(ended_message(_ended_record(sess, cause)))
+ print(term.err(ended_message(_ended_record(sess, cause)), sys.stdout))
_detach(gone=True)
return 1
state = ("closing — saving the phone"
@@ -1440,6 +1446,40 @@ def _ls_rows(me, sessions):
return rows
+def _format_ls(rows):
+ """Text table for `cloud ls`. Widths follow the header and the cells.
+
+ A long catalog id stays inside ID; the next column starts after it.
+ The last column is not padded, and trailing space is stripped, matching
+ the previous line shape when every value is short.
+ """
+ header = ["", "LABEL", "PLATFORM", "ID", "STATE", "NOTE", "SESSION", "LEFT"]
+ body = []
+ for row in rows:
+ sess = row.get("session") or {}
+ body.append([
+ "*" if row.get("targeted") else "",
+ str(row.get("label") or ""),
+ str(row.get("platform") or ""),
+ str(row.get("id") or "-"),
+ str(row.get("state") or "-"),
+ "temporary" if row.get("temporary") else "",
+ str(sess.get("id") or "-"),
+ str(sess.get("left") or ""),
+ ])
+ if not body:
+ return ""
+ widths = [max(len(header[i]), *(len(cells[i]) for cells in body)) for i in range(len(header))]
+ widths[0] = max(widths[0], 1)
+
+ def render(cells):
+ padded = [cells[i].ljust(widths[i]) for i in range(len(cells) - 1)]
+ padded.append(cells[-1])
+ return " ".join(padded).rstrip()
+
+ return "\n".join([render(header), *(render(cells) for cells in body)])
+
+
def _ls(args):
as_json = _flag(args, "--json")
if args:
@@ -1453,15 +1493,7 @@ def _ls(args):
if not rows:
print("No phones in this account's catalog.")
return 0
- 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())
+ print(_format_ls(rows))
return 0
@@ -1489,8 +1521,8 @@ def _use(args):
sys.exit("Usage: phone-harness cloud use SID")
session = _wait_ready(_resolve_sid(args[0]))
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.")
+ print(f"{term.mark()} attached to {session['id']}; {_describe_link(sess)}")
+ print(term.note("Helpers with no --session and no PHONE_HARNESS_SESSION follow this one."))
return 0
@@ -1548,7 +1580,7 @@ def _keys(args):
if args[:1] == ["create"]:
minted = _api("POST", "/me/keys", {"label": " ".join(args[1:]) or None})
print(minted["key"])
- print("Shown once; store it now.", file=sys.stderr)
+ print(term.note("Shown once; store it now.", sys.stderr), file=sys.stderr)
return 0
if args[:1] == ["revoke"] and len(args) == 2:
keys = [k for k in _api("GET", "/me/keys") if k["key_hash"].startswith(args[1])]
@@ -1634,20 +1666,140 @@ _COMMANDS = {"login": _login, "logout": _logout, "whoami": _whoami, "start": _st
"phone": _phone, "keys": _keys, "history": _history}
+def _cloud_parsers():
+ """One argparse parser per subcommand, for --help and unknown flags.
+
+ The command functions still read the original words. This layer only
+ rejects a flag they do not have, and prints help for `-h` / `--help`.
+ """
+ also = "Also accepts --session SID, or PHONE_HARNESS_SESSION, to pin one phone."
+
+ def make(name, usage, description):
+ return term.Parser(
+ prog=f"phone-harness cloud {name}",
+ usage=usage,
+ description=description + "\n\n" + also,
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ )
+
+ parsers = {}
+ login = make("login", "phone-harness cloud login [--no-browser]",
+ "Sign in through the browser.")
+ login.add_argument("--no-browser", action="store_true",
+ help="print the link and code without opening a browser")
+ parsers["login"] = login
+
+ parsers["logout"] = make("logout", "phone-harness cloud logout",
+ "Sign out on this machine.")
+
+ whoami = make("whoami", "phone-harness cloud whoami [--json]",
+ "Show the signed-in account.")
+ whoami.add_argument("--json", action="store_true", help="print the account record as JSON")
+ parsers["whoami"] = whoami
+
+ start = make(
+ "start",
+ "phone-harness cloud start [PHONE] [--for DURATION] [--minutes N] [--no-watch]",
+ "PHONE is a catalog id or label, or ios/android when only one entry has that "
+ "platform. With no PHONE, start cloud.phone if it is set, otherwise a temporary "
+ "Android. --for is 90s, 15m, or a number of minutes (default 15, cap "
+ "cloud.max_minutes). --minutes N is the same length. Opens the live view.")
+ start.add_argument("--for", metavar="DURATION",
+ help="how long to keep the phone (90s, 15m, or minutes)")
+ start.add_argument("--minutes", "-m", metavar="N",
+ help="length in minutes; same as --for")
+ start.add_argument("--no-watch", action="store_true", help="do not open the live view")
+ # Accepted so the command can print the removal message itself.
+ for flag in ("--iphone", "--device", "--temp", "--timeout"):
+ start.add_argument(flag, action="store_true", help=argparse.SUPPRESS)
+ parsers["start"] = start
+
+ stop = make("stop", "phone-harness cloud stop [SID] [--all] [--wait]",
+ "End a session. An adb phone with a saved profile is saved; a control "
+ "link keeps its own data. --wait watches an Android save finish.")
+ stop.add_argument("--all", action="store_true", help="end every running session")
+ stop.add_argument("--wait", action="store_true", help="wait until an Android save finishes")
+ parsers["stop"] = stop
+
+ ls = make("ls", "phone-harness cloud ls [--json]",
+ "The account catalog, with a live session inlined on its phone. "
+ "* marks the session this process targets.")
+ ls.add_argument("--json", action="store_true", help="print the rows as JSON")
+ parsers["ls"] = ls
+
+ show = make("show", "phone-harness cloud show [SID] [--json]", "One session in full.")
+ show.add_argument("--json", action="store_true", help="print the session as JSON")
+ parsers["show"] = show
+
+ parsers["use"] = make("use", "phone-harness cloud use SID",
+ "Point the terminal fallback at a running session. "
+ "SID may be a unique prefix.")
+
+ watch = make("watch", "phone-harness cloud watch [SID] [--print]",
+ "The read-only live view. It needs no sign-in, and the link is shareable.")
+ watch.add_argument("--print", action="store_true", help="print the link instead of opening it")
+ parsers["watch"] = watch
+
+ open_ = make("open", "phone-harness cloud open [SID] [--print]",
+ "The dashboard, where you control the phone yourself.")
+ open_.add_argument("--print", action="store_true", help="print the link instead of opening it")
+ parsers["open"] = open_
+
+ phone = make("phone", "phone-harness cloud phone [reset --yes] [--json]",
+ "The saved Android phone. reset --yes wipes its stored state. "
+ "The CLI has no iPhone reset.")
+ phone.add_argument("--json", action="store_true", help="print the profile as JSON")
+ phone.add_argument("--yes", action="store_true", help="confirm phone reset")
+ parsers["phone"] = phone
+
+ keys = make("keys", "phone-harness cloud keys [create [LABEL] | revoke HASH] [--json]",
+ "API keys, for CI. create mints a key and prints it once. "
+ "revoke takes a key hash or a unique prefix of one.")
+ keys.add_argument("--json", action="store_true", help="print the keys as JSON")
+ parsers["keys"] = keys
+
+ history = make("history", "phone-harness cloud history [-n NUM] [--json]",
+ "Finished sessions.")
+ history.add_argument("-n", "--limit", metavar="NUM",
+ help="how many sessions to show (default 20)")
+ history.add_argument("--json", action="store_true", help="print the sessions as JSON")
+ parsers["history"] = history
+ return parsers
+
+
def cli(args):
args = list(args)
+ try:
+ return _dispatch(args)
+ except SystemExit as e:
+ # Command errors raise SystemExit(message), which the interpreter would
+ # print and turn into exit code 1. Print it here so a terminal can
+ # color it, and so the process exit code stays 1.
+ if isinstance(e.code, str):
+ print(term.err(e.code), file=sys.stderr)
+ return 1
+ raise
+
+
+def _dispatch(args):
pinned = _option(args, "--session")
if pinned:
os.environ["PHONE_HARNESS_SESSION"] = pinned
- fn = _status if not args else _COMMANDS.get(args[0])
+ if not args:
+ return _status(args)
+ if args[0] in ("-h", "--help"):
+ print(CLI_USAGE)
+ return 0
+ fn = _COMMANDS.get(args[0])
if fn is None:
print(CLI_USAGE)
return 2
+ term.reject_unknown_flags(_cloud_parsers()[args[0]], args[1:])
try:
return fn(args[1:])
except CloudError as e:
- print(_explain(e), file=sys.stderr)
+ print(term.err(_explain(e)), file=sys.stderr)
return 1
except OSError as e:
- print(f"Could not reach {_target('API')}: {e}", file=sys.stderr)
+ print(term.err(f"Could not reach {_target('API')}: {e}"), file=sys.stderr)
return 1
diff --git a/src/phone_harness/config.py b/src/phone_harness/config.py
index a390def..4d9bb85 100644
--- a/src/phone_harness/config.py
+++ b/src/phone_harness/config.py
@@ -37,6 +37,7 @@ Files are versioned, read forgivingly (a corrupt file is a warning and
defaults, never a crash) and written atomically. Unknown keys survive a
round trip. This module owns the disk; backends ask it.
"""
+import argparse
import json
import os
import sys
@@ -323,9 +324,33 @@ CLI_USAGE = """Usage:
"""
+def _config_parser():
+ from .term import Parser
+ parser = Parser(
+ prog="phone-harness config",
+ description=CLI_USAGE.strip("\n"),
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ )
+ sub = parser.add_subparsers(dest="cmd", required=False, metavar="{get,set,unset,path}")
+ get = sub.add_parser("get", help="print one setting",
+ description="Print one setting as JSON.")
+ get.add_argument("key", metavar="KEY", help="setting name")
+ setp = sub.add_parser("set", help="set one setting",
+ description="Set one setting. platform must be ios or android.")
+ setp.add_argument("key", metavar="KEY", help="setting name")
+ setp.add_argument("value", metavar="VALUE", help="new value")
+ unset = sub.add_parser("unset", help="remove one setting",
+ description="Remove one setting from the config file.")
+ unset.add_argument("key", metavar="KEY", help="setting name")
+ path = sub.add_parser("path", help="where the files live",
+ description="Print where the config, state, and cache files live.")
+ path.add_argument("extra", nargs=argparse.REMAINDER, help=argparse.SUPPRESS)
+ return parser
+
+
def cli(args):
- cmd = args[0] if args else None
- if cmd is None:
+ ns = _config_parser().parse_args(list(args))
+ if ns.cmd is None:
for key in known_keys():
value, source = lookup(key)
print(f"{key:<22} {json.dumps(value):<10} ({source})")
@@ -333,21 +358,21 @@ def cli(args):
if k != "version" and not isinstance(v, dict) and k not in known_keys():
print(f"{k:<22} {json.dumps(v):<10} (file, unknown key)")
return 0
- if cmd == "get" and len(args) == 2:
- value, source = lookup(args[1])
- print(json.dumps(value) if source != "unset" else f"{args[1]}: unset")
+ if ns.cmd == "get":
+ value, source = lookup(ns.key)
+ print(json.dumps(value) if source != "unset" else f"{ns.key}: unset")
return 0 if source != "unset" else 1
- if cmd == "set" and len(args) == 3:
- if args[1] == "platform" and args[2] not in ("ios", "android"):
+ if ns.cmd == "set":
+ if ns.key == "platform" and ns.value not in ("ios", "android"):
print("platform must be ios or android"); return 2
- v = set(args[1], args[2])
- print(f"{args[1]} = {json.dumps(v)}")
- return 0
- if cmd == "unset" and len(args) == 2:
- unset(args[1]); print(f"{args[1]} unset"); return 0
- if cmd == "path":
- for k, v in paths().items():
- print(f"{k:<8} {v}")
+ v = set(ns.key, ns.value)
+ print(f"{ns.key} = {json.dumps(v)}")
return 0
- print(CLI_USAGE)
- return 2
+ if ns.cmd == "unset":
+ unset(ns.key); print(f"{ns.key} unset"); return 0
+ bad = [w for w in ns.extra if str(w).startswith("-")]
+ if bad:
+ _config_parser().error("unrecognized arguments: " + " ".join(bad))
+ for k, v in paths().items():
+ print(f"{k:<8} {v}")
+ return 0
diff --git a/src/phone_harness/run.py b/src/phone_harness/run.py
index 3b921ca..100a97f 100644
--- a/src/phone_harness/run.py
+++ b/src/phone_harness/run.py
@@ -1,4 +1,5 @@
"""The phone-harness CLI: exec Python from stdin with helpers pre-imported."""
+import argparse
import functools
import io
import os
@@ -7,6 +8,7 @@ import time
from pathlib import Path
from . import telemetry
+from .term import Parser
USAGE = """Usage:
phone-harness <<'PY'
@@ -15,7 +17,9 @@ USAGE = """Usage:
Commands:
phone-harness --session SID <<'PY' pin one cloud phone for this process
+ phone-harness --version, -V print phone-harness <version>
phone-harness --doctor [ios|android] diagnose the phone the helpers would drive
+ phone-harness doctor [ios|android] same diagnosis as --doctor
phone-harness skill print the phone-harness skill text
phone-harness android ... pair/connect/choose an Android phone
phone-harness cloud ... rent a catalog phone: `cloud login`, `cloud ls`, `cloud start [PHONE]`
@@ -128,6 +132,8 @@ def _telemetry_command(args):
first = args[0]
if first in {"-h", "--help"}:
return "help"
+ if first in {"-V", "--version"}:
+ return "version"
if first in {"--doctor", "doctor"}:
return "doctor"
if first in {"android", "cloud", "config", "skill", "update"}:
@@ -270,32 +276,96 @@ def _take_session(args):
return out
-def _run(args):
- global _phone_name
- args = _take_session(args)
- if args and args[0] in {"-h", "--help"}:
- print(USAGE)
- return
- if args and args[0] in {"--doctor", "doctor"}:
- from .admin import run_doctor
- sys.exit(run_doctor(args[1] if len(args) > 1 else None))
- if args and args[0] == "android":
+# These three parse their own argv, including --help. A leading --help is
+# the top-level parser, so only a bare command name takes this path.
+# --version is handled before this, in any position.
+_OWNED = {"android", "cloud", "config"}
+
+
+def _version_text():
+ from .update import installed_version
+ return f"phone-harness {installed_version()}"
+
+
+def _build_parser():
+ parser = Parser(
+ prog="phone-harness",
+ description=USAGE.strip("\n"),
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ )
+ parser.add_argument("-V", "--version", action="version", version=_version_text())
+ parser.add_argument(
+ "--session", metavar="SID",
+ help="pin one cloud phone for this process (or set PHONE_HARNESS_SESSION)",
+ )
+ # Hidden alias of `doctor`. Help stays on the `doctor` subcommand.
+ parser.add_argument("--doctor", nargs="?", const="", default=None, metavar="PLATFORM",
+ help=argparse.SUPPRESS)
+ sub = parser.add_subparsers(
+ dest="command", required=False,
+ metavar="{doctor,skill,config,update,cloud,android}",
+ )
+
+ doctor = sub.add_parser(
+ "doctor",
+ help="diagnose the phone the helpers would drive",
+ description="Diagnose the phone the helpers would drive.",
+ )
+ doctor.add_argument("platform", nargs="?", metavar="ios|android",
+ help="ios or android (default: the configured platform)")
+ doctor.add_argument("extra", nargs=argparse.REMAINDER, help=argparse.SUPPRESS)
+
+ skill = sub.add_parser(
+ "skill",
+ help="print the phone-harness skill text",
+ description="Print the phone-harness skill text.",
+ )
+ skill.add_argument("words", nargs=argparse.REMAINDER, help=argparse.SUPPRESS)
+
+ sub.add_parser(
+ "config",
+ help="settings: config set platform android",
+ add_help=False,
+ ).add_argument("rest", nargs=argparse.REMAINDER, help=argparse.SUPPRESS)
+
+ sub.add_parser(
+ "update",
+ help="update this install",
+ description="Update this install: uv tool upgrade, git pull, or the pip command.",
+ )
+
+ sub.add_parser(
+ "cloud",
+ help="rent a catalog phone",
+ add_help=False,
+ ).add_argument("rest", nargs=argparse.REMAINDER, help=argparse.SUPPRESS)
+
+ sub.add_parser(
+ "android",
+ help="pair, connect, or choose an Android phone",
+ add_help=False,
+ ).add_argument("rest", nargs=argparse.REMAINDER, help=argparse.SUPPRESS)
+ return parser, {"doctor": doctor, "skill": skill}
+
+
+def _reject_dashed(subparser, words):
+ bad = [w for w in words if str(w).startswith("-")]
+ if bad:
+ subparser.error("unrecognized arguments: " + " ".join(bad))
+
+
+def _dispatch_owned(name, rest):
+ if name == "android":
from .android import cli
- sys.exit(cli(args[1:]))
- if args and args[0] == "cloud":
+ elif name == "cloud":
from .cloud import cli
- sys.exit(cli(args[1:]))
- if args and args[0] == "config":
+ else:
from .config import cli
- sys.exit(cli(args[1:]))
- if args and args[0] == "update":
- from .update import cmd_update
- sys.exit(cmd_update(args[1:]))
- if args and args[0] == "skill":
- _write_utf8(_skill_text())
- return
- if args or sys.stdin.isatty():
- sys.exit(USAGE)
+ sys.exit(cli(rest))
+
+
+def _exec_script():
+ global _phone_name
code = sys.stdin.read()
if not code.strip():
sys.exit(USAGE)
@@ -312,5 +382,46 @@ def _run(args):
exec(code, g)
+def _run(args):
+ args = _take_session(list(args))
+ if any(tok in {"-V", "--version"} for tok in args):
+ print(_version_text())
+ sys.exit(0)
+ if not args:
+ if sys.stdin.isatty():
+ sys.stderr.write(USAGE)
+ sys.exit(2)
+ _exec_script()
+ return
+ # `--help` on these groups is their own usage text, not the top-level one.
+ if args[0] in _OWNED:
+ _dispatch_owned(args[0], args[1:])
+ return
+ parser, subs = _build_parser()
+ ns = parser.parse_args(args)
+ if ns.session:
+ os.environ["PHONE_HARNESS_SESSION"] = ns.session
+ if ns.command == "doctor" or (ns.command is None and ns.doctor is not None):
+ if ns.command == "doctor":
+ _reject_dashed(subs["doctor"], ns.extra)
+ platform = ns.platform
+ else:
+ platform = ns.doctor or None
+ from .admin import run_doctor
+ sys.exit(run_doctor(platform))
+ if ns.command == "skill":
+ _reject_dashed(subs["skill"], ns.words)
+ _write_utf8(_skill_text())
+ return
+ if ns.command == "update":
+ from .update import cmd_update
+ sys.exit(cmd_update([]))
+ if ns.command in _OWNED:
+ _dispatch_owned(ns.command, list(ns.rest))
+ return
+ sys.stderr.write(USAGE)
+ sys.exit(2)
+
+
if __name__ == "__main__":
main()
diff --git a/src/phone_harness/term.py b/src/phone_harness/term.py
new file mode 100644
index 0000000..60559bc
--- /dev/null
+++ b/src/phone_harness/term.py
@@ -0,0 +1,77 @@
+"""Optional color for CLI text. Standard library only.
+
+Color is on only when the stream being written is a real terminal and
+NO_COLOR is unset. A pipe, a redirect, or NO_COLOR (set to anything, including
+the empty string) stays plain text, so a captured run is byte-for-byte the
+same text an agent already parses.
+"""
+import argparse
+import os
+import sys
+
+_CODES = {"ok": "32", "err": "31", "note": "2"}
+
+
+def enabled(stream=None):
+ """True when this stream should carry ANSI color."""
+ if os.environ.get("NO_COLOR") is not None:
+ return False
+ stream = sys.stdout if stream is None else stream
+ isatty = getattr(stream, "isatty", None)
+ if not callable(isatty):
+ return False
+ try:
+ return bool(isatty())
+ except OSError:
+ return False
+
+
+def paint(text, kind, stream=None):
+ """Wrap text in one color, or return it unchanged."""
+ if not text:
+ return text
+ stream = sys.stdout if stream is None else stream
+ if not enabled(stream):
+ return text
+ return f"\033[{_CODES[kind]}m{text}\033[0m"
+
+
+def mark(char="✓", stream=None):
+ """A green check mark on a terminal, the same character otherwise."""
+ return paint(char, "ok", sys.stdout if stream is None else stream)
+
+
+def err(text, stream=None):
+ """An error line, red on a terminal."""
+ return paint(text, "err", sys.stderr if stream is None else stream)
+
+
+def note(text, stream=None):
+ """Secondary text, dim on a terminal."""
+ return paint(text, "note", sys.stdout if stream is None else stream)
+
+
+class Parser(argparse.ArgumentParser):
+ """argparse that does not accept `--min` as `--minutes`, and colors errors."""
+
+ def __init__(self, *args, **kwargs):
+ kwargs.setdefault("allow_abbrev", False)
+ super().__init__(*args, **kwargs)
+
+ def error(self, message):
+ self.print_usage(sys.stderr)
+ print(err(f"{self.prog}: error: {message}"), file=sys.stderr)
+ self.exit(2)
+
+
+def reject_unknown_flags(parser, argv):
+ """Accept this command's flags. Leave other words for the command itself.
+
+ `--help` prints help and exits 0. An unknown flag is an error that names
+ the flag and exits 2. Positionals are not rejected here: each command
+ already decides how many words it takes.
+ """
+ _ns, unknown = parser.parse_known_args(argv)
+ bad = [tok for tok in unknown if str(tok).startswith("-")]
+ if bad:
+ parser.error("unrecognized arguments: " + " ".join(bad))
diff --git a/tests/test_cli.py b/tests/test_cli.py
new file mode 100644
index 0000000..16aeb22
--- /dev/null
+++ b/tests/test_cli.py
@@ -0,0 +1,448 @@
+"""CLI help, bad flags, column layout, and optional color. No phone, no network."""
+import contextlib
+import io
+import os
+import subprocess
+import sys
+import tempfile
+import time
+import unittest
+from pathlib import Path
+from unittest import mock
+
+SRC = str(Path(__file__).resolve().parents[1] / "src")
+if SRC not in sys.path:
+ sys.path.insert(0, SRC)
+
+from phone_harness import android, cloud, term # noqa: E402
+from phone_harness.run import USAGE, _run as run_main # noqa: E402
+from phone_harness.update import installed_version # noqa: E402
+
+
+def _run(*args, stdin=None, env=None):
+ merged = os.environ.copy()
+ merged["PYTHONPATH"] = SRC + os.pathsep + merged.get("PYTHONPATH", "")
+ merged["PHONE_HARNESS_TELEMETRY"] = "0"
+ merged.pop("NO_COLOR", None)
+ if env:
+ merged.update(env)
+ return subprocess.run([sys.executable, "-m", "phone_harness.run", *args],
+ input=stdin, capture_output=True, text=True, env=merged)
+
+
+class Tty(io.StringIO):
+ def isatty(self):
+ return True
+
+
+class HelpAndFlags(unittest.TestCase):
+ def test_group_help_matches_the_usage_text_and_exits_cleanly(self):
+ top = _run("--help")
+ self.assertEqual(top.returncode, 0, top.stderr)
+ self.assertIn("Commands:", top.stdout)
+ self.assertIn("phone-harness cloud", top.stdout)
+
+ for args, needle in ((["cloud", "--help"], "cloud ls"),
+ (["cloud", "-h"], "cloud start"),
+ (["android", "--help"], "android pair"),
+ (["android", "-h"], "android awake")):
+ got = _run(*args)
+ self.assertEqual(got.returncode, 0, got.stderr)
+ self.assertIn(needle, got.stdout)
+ got.stdout.encode("ascii")
+
+ unknown = _run("cloud", "nope")
+ self.assertEqual(unknown.returncode, 2)
+ self.assertIn("cloud ls", unknown.stdout)
+ self.assertEqual(unknown.stderr, "")
+
+ bogus = _run("--bogus")
+ self.assertEqual(bogus.returncode, 2)
+ self.assertIn("unrecognized arguments: --bogus", bogus.stderr)
+ self.assertNotIn("Commands:", bogus.stdout)
+
+ def test_every_subcommand_has_help_and_rejects_a_bad_flag(self):
+ cloud_cmds = {
+ "login": "--no-browser",
+ "logout": None,
+ "whoami": "--json",
+ "start": "--for",
+ "stop": "--all",
+ "ls": "--json",
+ "show": "--json",
+ "use": "SID",
+ "watch": "--print",
+ "open": "--print",
+ "phone": "--yes",
+ "keys": "--json",
+ "history": "--limit",
+ }
+ for name, flag in cloud_cmds.items():
+ help_out = _run("cloud", name, "--help")
+ self.assertEqual(help_out.returncode, 0, help_out.stderr)
+ self.assertIn(f"phone-harness cloud {name}", help_out.stdout)
+ self.assertIn("--session SID", help_out.stdout)
+ help_out.stdout.encode("ascii")
+ if flag and flag.startswith("-"):
+ self.assertIn(flag, help_out.stdout, name)
+ bad = _run("cloud", name, "--no-such-flag")
+ self.assertEqual(bad.returncode, 2, name)
+ self.assertIn("unrecognized arguments: --no-such-flag", bad.stderr)
+ self.assertIn(f"phone-harness cloud {name}", bad.stderr)
+
+ for name, flag in (("awake", "--bg"), ("rest", None), ("pair", None),
+ ("connect", None), ("use", None), ("forget", None)):
+ help_out = _run("android", name, "--help")
+ self.assertEqual(help_out.returncode, 0, help_out.stderr)
+ self.assertIn(f"phone-harness android {name}", help_out.stdout)
+ help_out.stdout.encode("ascii")
+ if flag:
+ self.assertIn(flag, help_out.stdout)
+ bad = _run("android", name, "--no-such-flag")
+ self.assertEqual(bad.returncode, 2, name)
+ self.assertIn("unrecognized arguments: --no-such-flag", bad.stderr)
+
+ awake_help = _run("android", "awake", "--help")
+ self.assertIn("--no-mirror", awake_help.stdout)
+ self.assertNotIn("--fg", awake_help.stdout)
+ parsed, leftover = android._android_parsers()["awake"].parse_known_args(["--fg", "--bg"])
+ self.assertEqual(leftover, [])
+ self.assertTrue(parsed.fg and parsed.bg)
+
+ def test_removed_flags_aliases_and_session_keep_their_messages(self):
+ removed = _run("cloud", "start", "--iphone")
+ self.assertEqual(removed.returncode, 1)
+ self.assertIn("--iphone was removed", removed.stderr)
+ self.assertNotIn("unrecognized", removed.stderr)
+ self.assertNotIn("\x1b", removed.stderr)
+
+ both = _run("cloud", "start", "--minutes", "5", "--for", "90s")
+ self.assertEqual(both.returncode, 1)
+ self.assertIn("not both", both.stderr)
+
+ use = _run("cloud", "use")
+ self.assertEqual(use.returncode, 1)
+ self.assertIn("Usage: phone-harness cloud use SID", use.stderr)
+
+ missing = _run("--session")
+ self.assertNotEqual(missing.returncode, 0)
+ self.assertIn("--session needs a SID", missing.stderr)
+
+ os.environ.pop("PHONE_HARNESS_SESSION", None)
+ err = io.StringIO()
+ try:
+ with _stderr(err):
+ code = cloud.cli(["--session"])
+ self.assertEqual(code, 1)
+ self.assertIn("--session needs a value", err.getvalue())
+
+ err = io.StringIO()
+ with _stderr(err):
+ code = cloud.cli(["--session", "abc123", "use"])
+ self.assertEqual(code, 1)
+ self.assertEqual(os.environ.get("PHONE_HARNESS_SESSION"), "abc123")
+ self.assertIn("Usage: phone-harness cloud use SID", err.getvalue())
+ finally:
+ os.environ.pop("PHONE_HARNESS_SESSION", None)
+
+ pinned_help = _run("--session", "abc123", "cloud", "ls", "--help")
+ self.assertEqual(pinned_help.returncode, 0, pinned_help.stderr)
+ self.assertIn("phone-harness cloud ls", pinned_help.stdout)
+
+ android_help = _run("android", "awake", "--session", "abc123", "--help")
+ self.assertEqual(android_help.returncode, 0, android_help.stderr)
+ self.assertIn("--bg", android_help.stdout)
+
+ no_primary = _run("android", "connect")
+ self.assertEqual(no_primary.returncode, 1)
+ self.assertIn("no primary phone yet", no_primary.stdout)
+ self.assertNotIn("\x1b", no_primary.stdout)
+
+ start_help = _run("cloud", "start", "--help")
+ self.assertIn("-m", start_help.stdout)
+ self.assertIn("--minutes", start_help.stdout)
+ self.assertNotIn("--iphone", start_help.stdout)
+ history_help = _run("cloud", "history", "--help")
+ self.assertIn("-n", history_help.stdout)
+
+ def test_history_limit_flags_still_reach_the_command(self):
+ with mock.patch.object(cloud, "_api", return_value={"items": []}) as api, \
+ contextlib.redirect_stdout(io.StringIO()):
+ self.assertEqual(cloud.cli(["history", "-n", "3"]), 0)
+ self.assertEqual(cloud.cli(["history", "--limit", "4"]), 0)
+ self.assertIn("limit=3", api.call_args_list[0].args[1])
+ self.assertIn("limit=4", api.call_args_list[1].args[1])
+
+ def test_a_script_on_stdin_is_still_a_script(self):
+ home = Path(self.id().replace(".", "_"))
+ # Keep the script off the checkout's workspace and the real home.
+ env = {"PHONE_HARNESS_HOME": str(Path("/tmp") / home),
+ "PH_AGENT_WORKSPACE": str(Path("/tmp") / home / "ws"),
+ "PHONE_HARNESS_PLATFORM": "android"}
+ got = _run(stdin="print(6 * 7)\n", env=env)
+ self.assertEqual(got.returncode, 0, got.stderr)
+ self.assertIn("42", got.stdout)
+ self.assertNotIn("unrecognized arguments", got.stderr)
+
+
+class _stderr:
+ """Patch sys.stderr for one cloud.cli call."""
+
+ def __init__(self, buf):
+ self.buf = buf
+ self.old = None
+
+ def __enter__(self):
+ self.old = sys.stderr
+ sys.stderr = self.buf
+ return self.buf
+
+ def __exit__(self, *exc):
+ sys.stderr = self.old
+
+
+class Columns(unittest.TestCase):
+ def test_columns_grow_to_fit_and_stay_aligned(self):
+ long_id = "prof-948b7471ed7575fc17236906"
+ long_sid = "sess-948b7471ed7575fc17236906"
+ rows = [
+ {"targeted": True, "label": "Saved phone", "platform": "android",
+ "id": long_id, "state": "stored", "temporary": False,
+ "session": {"id": long_sid, "left": "14 min"}},
+ {"targeted": False, "label": "Temporary", "platform": "android",
+ "id": None, "state": "-", "temporary": True, "session": {}},
+ ]
+ header, saved, temporary = cloud._format_ls(rows).splitlines()
+ for line in (header, saved, temporary):
+ self.assertEqual(line, line.rstrip())
+ id_at = header.index("ID")
+ state_at = header.index("STATE")
+ note_at = header.index("NOTE")
+ session_at = header.index("SESSION")
+ left_at = header.index("LEFT")
+ self.assertEqual(saved.index(long_id), id_at)
+ self.assertEqual(state_at, id_at + len(long_id) + 1)
+ self.assertTrue(saved[state_at:].startswith("stored"))
+ self.assertEqual(saved.index(long_sid), session_at)
+ self.assertEqual(left_at, session_at + len(long_sid) + 1)
+ self.assertTrue(saved[left_at:].startswith("14 min"))
+ self.assertTrue(saved.startswith("*"))
+ self.assertTrue(temporary.startswith(" "))
+ self.assertEqual(temporary.index("android"), header.index("PLATFORM"))
+ self.assertEqual(temporary.index("temporary"), note_at)
+ # A short id still sits under ID, padded out to the header when nothing is longer.
+ short = cloud._format_ls([{
+ "label": "A", "platform": "ios", "id": "iph", "state": "up",
+ "temporary": False, "session": {"id": "s", "left": "1s"},
+ }]).splitlines()
+ self.assertEqual(short[1].index("iph"), short[0].index("ID"))
+ self.assertEqual(short[0].index("STATE"), short[0].index("ID") + max(len("ID"), len("iph")) + 1)
+
+
+class Color(unittest.TestCase):
+ def setUp(self):
+ self._no_color = os.environ.pop("NO_COLOR", None)
+
+ def tearDown(self):
+ if self._no_color is not None:
+ os.environ["NO_COLOR"] = self._no_color
+ else:
+ os.environ.pop("NO_COLOR", None)
+
+ def test_color_follows_the_stream_and_no_color(self):
+ tty = Tty()
+ plain = io.StringIO()
+ self.assertEqual(term.paint("✓", "ok", tty), "\033[32m✓\033[0m")
+ self.assertEqual(term.paint("nope", "err", tty), "\033[31mnope\033[0m")
+ self.assertEqual(term.paint("aside", "note", tty), "\033[2maside\033[0m")
+ self.assertEqual(term.paint("✓", "ok", plain), "✓")
+ self.assertFalse(plain.isatty() if hasattr(plain, "isatty") else False)
+
+ os.environ["NO_COLOR"] = ""
+ self.assertEqual(term.paint("✓", "ok", tty), "✓")
+ self.assertEqual(term.err("boom", tty), "boom")
+ os.environ["NO_COLOR"] = "1"
+ self.assertEqual(term.note("aside", tty), "aside")
+
+ def test_a_terminal_colors_the_check_and_the_error(self):
+ os.environ.pop("NO_COLOR", None)
+ out, err = Tty(), Tty()
+ old_out, old_err = sys.stdout, sys.stderr
+ sys.stdout, sys.stderr = out, err
+ home = tempfile.mkdtemp()
+ try:
+ with mock.patch.dict(os.environ, {"PHONE_HARNESS_HOME": home}, clear=False):
+ os.environ.pop("PHONE_HARNESS_API_KEY", None)
+ code = cloud.cli([])
+ record = {"sid": "sid001", "label": None, "profile": None,
+ "link": {"kind": "adb", "host": "h", "port": 1, "code": "c"}}
+ session = {"id": "sid001", "profile": None, "platform": "android",
+ "expires_at": time.time() + 900, "watch_url": None,
+ "startup": {"startup": "exact"}}
+ with mock.patch.object(cloud, "_attach", return_value=record):
+ cloud._report(session, watch=False)
+ removed = cloud.cli(["start", "--device"])
+ finally:
+ sys.stdout, sys.stderr = old_out, old_err
+ self.assertEqual(code, 1)
+ self.assertEqual(removed, 1)
+ text, errors = out.getvalue(), err.getvalue()
+ self.assertIn("\033[31mNot signed in", text)
+ self.assertIn("\033[0m", text)
+ self.assertIn("\033[2m", text)
+ self.assertIn("\033[32m✓\033[0m ready.", text)
+ self.assertIn("\033[2m Resumed exactly where you left it.\033[0m", text)
+ self.assertIn("\033[31m", errors)
+ self.assertIn("--device was removed", errors)
+
+ os.environ["NO_COLOR"] = "1"
+ out, err = Tty(), Tty()
+ sys.stdout, sys.stderr = out, err
+ try:
+ code = cloud.cli(["start", "--temp"])
+ finally:
+ sys.stdout, sys.stderr = old_out, old_err
+ self.assertEqual(code, 1)
+ self.assertNotIn("\x1b", err.getvalue())
+ self.assertIn("--temp was removed", err.getvalue())
+
+
+class TopLevel(unittest.TestCase):
+ def test_version_prints_the_installed_package_version(self):
+ expected = f"phone-harness {installed_version()}\n"
+ for flag in ("--version", "-V"):
+ got = _run(flag)
+ self.assertEqual(got.returncode, 0, got.stderr)
+ self.assertEqual(got.stdout, expected)
+ self.assertEqual(got.stderr, "")
+ got.stdout.encode("ascii")
+ for args in (["cloud", "--version"], ["android", "-V"], ["config", "--version"],
+ ["update", "-V"], ["skill", "--version"], ["doctor", "-V"]):
+ got = _run(*args)
+ self.assertEqual(got.returncode, 0, (args, got.stderr, got.stdout))
+ self.assertEqual(got.stdout, expected, args)
+
+ def test_unknown_command_and_flag_exit_2_and_name_themselves(self):
+ command = _run("no-such-command")
+ self.assertEqual(command.returncode, 2)
+ self.assertIn("no-such-command", command.stderr)
+ self.assertEqual(command.stdout, "")
+ command.stderr.encode("ascii")
+
+ flag = _run("--no-such-flag")
+ self.assertEqual(flag.returncode, 2)
+ self.assertIn("unrecognized arguments: --no-such-flag", flag.stderr)
+ self.assertEqual(flag.stdout, "")
+ flag.stderr.encode("ascii")
+
+ nested = _run("doctor", "--no-such-flag")
+ self.assertEqual(nested.returncode, 2)
+ self.assertIn("--no-such-flag", nested.stderr)
+
+ def test_every_top_level_command_has_help(self):
+ cases = (
+ (["doctor", "--help"], "ios|android"),
+ (["doctor", "-h"], "ios or android"),
+ (["skill", "--help"], "phone-harness skill"),
+ (["skill", "-h"], "show this help message"),
+ (["config", "--help"], "config get"),
+ (["config", "-h"], "config set"),
+ (["config", "get", "--help"], "KEY"),
+ (["config", "set", "-h"], "VALUE"),
+ (["config", "unset", "--help"], "KEY"),
+ (["config", "path", "--help"], "config, state, and cache"),
+ (["update", "--help"], "uv tool upgrade"),
+ (["update", "-h"], "pip command"),
+ (["cloud", "--help"], "cloud ls"),
+ (["android", "--help"], "android pair"),
+ )
+ for args, needle in cases:
+ got = _run(*args)
+ self.assertEqual(got.returncode, 0, (args, got.stderr, got.stdout))
+ self.assertIn(needle, got.stdout, args)
+ self.assertNotIn("\x1b", got.stdout)
+ got.stdout.encode("ascii")
+ skill_help = _run("skill", "--help")
+ self.assertNotIn("Which phone", skill_help.stdout)
+ skill = _run("skill")
+ self.assertEqual(skill.returncode, 0, skill.stderr)
+ self.assertIn("Which phone", skill.stdout)
+ options = _run("--help").stdout.split("options:", 1)[-1]
+ self.assertNotIn("--doctor", options)
+
+ def test_session_before_the_subcommand_still_pins_the_phone(self):
+ home = Path("/tmp") / "ph-session-place"
+ env = {"PHONE_HARNESS_HOME": str(home),
+ "PH_AGENT_WORKSPACE": str(home / "ws"),
+ "PHONE_HARNESS_PLATFORM": "android"}
+ pinned = _run("--session", "sid-placed",
+ stdin="import os\nprint(os.environ['PHONE_HARNESS_SESSION'])\n",
+ env=env)
+ self.assertEqual(pinned.returncode, 0, pinned.stderr)
+ self.assertIn("sid-placed", pinned.stdout)
+
+ middle = _run("cloud", "--session", "abc123", "ls", "--help")
+ self.assertEqual(middle.returncode, 0, middle.stderr)
+ self.assertIn("phone-harness cloud ls", middle.stdout)
+
+ version = _run("--session", "abc123", "--version")
+ self.assertEqual(version.returncode, 0, version.stderr)
+ self.assertTrue(version.stdout.startswith("phone-harness "))
+
+ def test_no_args_on_a_tty_prints_usage_to_stderr_and_exits_2(self):
+ err = io.StringIO()
+ with mock.patch("sys.stdin", Tty()), mock.patch("sys.stderr", err):
+ with self.assertRaises(SystemExit) as caught:
+ run_main([])
+ self.assertEqual(caught.exception.code, 2)
+ self.assertEqual(err.getvalue(), USAGE)
+ err.getvalue().encode("ascii")
+
+ def test_doctor_alias_still_dispatches_and_help_does_not(self):
+ with mock.patch("phone_harness.admin.run_doctor", return_value=0) as doctor:
+ for argv, platform in ((["--doctor"], None),
+ (["--doctor", "ios"], "ios"),
+ (["doctor", "android"], "android"),
+ (["doctor"], None)):
+ with self.assertRaises(SystemExit) as caught:
+ run_main(argv)
+ self.assertEqual(caught.exception.code, 0, argv)
+ self.assertEqual(doctor.call_args.args[0], platform)
+ help_out = _run("doctor", "--help")
+ self.assertEqual(help_out.returncode, 0, help_out.stderr)
+ self.assertNotIn("all clear", help_out.stdout)
+
+ def test_config_set_output_is_unchanged(self):
+ home = Path("/tmp") / "ph-config-cli"
+ env = {"PHONE_HARNESS_HOME": str(home)}
+ bad = _run("config", "set", "platform", "nope", env=env)
+ self.assertEqual(bad.returncode, 2)
+ self.assertIn("platform must be ios or android", bad.stdout)
+ good = _run("config", "set", "platform", "android", env=env)
+ self.assertEqual(good.returncode, 0, good.stderr)
+ self.assertIn('platform = "android"', good.stdout)
+ got = _run("config", "get", "platform", env=env)
+ self.assertEqual(got.returncode, 0, got.stderr)
+ self.assertEqual(got.stdout.strip(), '"android"')
+
+ def test_docs_mention_version(self):
+ root = Path(__file__).resolve().parents[1]
+ readme = (root / "README.md").read_text(encoding="utf-8")
+ skill = (root / "SKILL.md").read_text(encoding="utf-8")
+ self.assertIn("phone-harness --version", readme)
+ self.assertIn("phone-harness --version", skill)
+ version_line = next(line for line in readme.splitlines() if "phone-harness --version" in line)
+ version_line.encode("ascii")
+ skill.encode("ascii")
+
+
+class SessionAndStdinGuard(unittest.TestCase):
+ """The top-level script path and --session live in run.py; argparse must not take them over."""
+
+ def test_usage_text_stays_the_top_level_help(self):
+ self.assertIn("<<'PY'", USAGE)
+ self.assertNotIn("argparse", USAGE)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_cloud.py b/tests/test_cloud.py
index 792b794..efd040c 100644
--- a/tests/test_cloud.py
+++ b/tests/test_cloud.py
@@ -1201,6 +1201,33 @@ class CloudCli(unittest.TestCase):
help_text = self.run_cli("cloud", "nope")
self.assertIn("wipes its stored state", help_text.stdout)
+ def test_minutes_alias_still_sets_the_length(self):
+ self.login()
+ r = self.run_cli("cloud", "start", "Temporary phone", "-m", "2", "--no-watch")
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertEqual(FakeCloud.posts[-1]["timeout_seconds"], 120)
+
+ def test_ls_columns_fit_a_long_catalog_id(self):
+ self.login()
+ long_id = "prof-948b7471ed7575fc17236906"
+ FakeCloud.available = [
+ {"platform": "android", "kind": "emulator", "id": long_id,
+ "label": "Saved phone", "state": "stored"},
+ {"platform": "android", "kind": "emulator", "temporary": True,
+ "label": "Temporary phone"},
+ ]
+ text = self.run_cli("cloud", "ls")
+ self.assertEqual(text.returncode, 0, text.stderr)
+ self.assertNotIn("\x1b", text.stdout)
+ header, saved, temporary = [ln for ln in text.stdout.splitlines() if ln.strip()]
+ id_at = header.index("ID")
+ state_at = header.index("STATE")
+ self.assertEqual(saved.index(long_id), id_at)
+ self.assertEqual(state_at, id_at + len(long_id) + 1)
+ self.assertTrue(saved[state_at:].startswith("stored"))
+ self.assertEqual(temporary.index("android"), header.index("PLATFORM"))
+ self.assertIn("temporary", temporary[header.index("NOTE"):])
+
if __name__ == "__main__":
unittest.main()