Skip to content

let your agent control your phone

feat: config.py owns what the user chose and what the harness learned

ShawnPana773b88706b5f
diff --git a/SKILL.md b/SKILL.md
index a5cb384..c0def55 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -60,9 +60,10 @@ PY
## Android
-Same helpers, different phone. `phone-harness use android` makes Android the
-default (`phone-harness use` shows the current one); until then, or to
-override per call, prefix with `PHONE_HARNESS_PLATFORM=android`. The harness
+Same helpers, different phone. `phone-harness config set platform android`
+makes Android the default (`phone-harness config` shows every setting and
+where it came from); until then, or to override per call, prefix with
+`PHONE_HARNESS_PLATFORM=android`. The harness
finds the phone itself — a USB phone if plugged in, else the paired Wi-Fi
phone — so there is nothing to select.
diff --git a/src/phone_harness/android.py b/src/phone_harness/android.py
index d677d38..b29483b 100644
--- a/src/phone_harness/android.py
+++ b/src/phone_harness/android.py
@@ -18,13 +18,12 @@ through — resolves one: a USB phone if one is plugged in, else a live
wireless link (the saved primary first), else a paired phone found on the
LAN over mDNS and connected on the spot, else a message naming the physical
step that is missing. Paired phones are
-remembered in ~/.config/phone-harness/android.json under a friendly name and
+remembered (see config.py: the devices state file) under a friendly name and
matched by hardware serial, so a phone whose Wi-Fi port changed overnight is
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 json
import os
import re
import shlex
@@ -36,13 +35,13 @@ import tempfile
import time
import xml.etree.ElementTree as ET
from datetime import datetime, timezone
-from pathlib import Path
+from . import config
from .transport import Backend, Unsupported
-ADB = os.environ.get("PHONE_HARNESS_ADB", "adb")
-CONFIG = Path(os.environ.get("PHONE_HARNESS_CONFIG_DIR",
- Path.home() / ".config" / "phone-harness")) / "android.json"
+
+def _adb_bin():
+ return str(config.get("android.adb"))
# input.keys names -> Android keycodes. Modifier chords are not a thing
# `input keyevent` can express, so combos raise rather than half-work.
@@ -59,7 +58,7 @@ _KEYS = {
# --- adb, without a device yet -----------------------------------------------
def _run(*args, binary=False, timeout=60, check=True):
- r = subprocess.run([ADB, *args], capture_output=True, timeout=timeout)
+ r = subprocess.run([_adb_bin(), *args], capture_output=True, timeout=timeout)
if check and r.returncode != 0:
err = (r.stderr or r.stdout).decode(errors="replace").strip()
raise RuntimeError(f"adb {' '.join(args)} failed: {err}")
@@ -100,15 +99,11 @@ def _mdns(kind="connect"):
# --- the registry: phones we know, and which one is primary -----------------
def _load():
- try:
- return json.loads(CONFIG.read_text())
- except (OSError, ValueError):
- return {"primary": None, "phones": {}}
+ return config.devices_of("android")
def _store(cfg):
- CONFIG.parent.mkdir(parents=True, exist_ok=True)
- CONFIG.write_text(json.dumps(cfg, indent=2) + "\n")
+ config.save_devices_of("android", cfg)
def _now():
@@ -538,8 +533,12 @@ CLI_USAGE = """Usage:
phone-harness android rest end the session; the phone sleeps
"""
-PIDFILE = CONFIG.with_name("awake.pid")
-POKE_EVERY = 25 # seconds; a phone's shortest screen timeout is 15s
+def _pidfile():
+ return config.run_dir() / "awake.pid"
+
+
+def _poke_every():
+ return max(5, int(config.get("android.poke_every"))) # shortest phone timeout is 15s
POKE = "input keyevent KEYCODE_UNKNOWN" # counts as user activity; no app sees it
@@ -557,7 +556,7 @@ def _phone_label(adb_id):
def _awake(mirror=True):
"""The session companion. Wakes the phone; waits for the user to unlock
- if it is locked; then every POKE_EVERY seconds sends a keypress no app
+ if it is locked; then every android.poke_every seconds sends a keypress no app
reacts to, which the phone counts as user activity — so it never
reaches its screen timeout while this runs, on USB or Wi-Fi, charging
or not, and reverts to normal the instant this stops. No setting is
@@ -612,12 +611,12 @@ def _awake(mirror=True):
print("unlocked — keeping awake", flush=True)
was_locked = False
phone._sh(POKE)
- time.sleep(POKE_EVERY if not locked else 3)
+ time.sleep(_poke_every() if not locked else 3)
finally:
if proc and proc.poll() is None:
proc.terminate()
try:
- PIDFILE.unlink()
+ _pidfile().unlink()
except OSError:
pass
@@ -625,7 +624,7 @@ def _awake(mirror=True):
def _awake_pid():
"""pid of a running awake session (not ourselves), else None."""
try:
- pid = int(PIDFILE.read_text().strip())
+ pid = int(_pidfile().read_text().strip())
if pid == os.getpid():
return None
os.kill(pid, 0)
@@ -655,7 +654,7 @@ def cli(args):
if cmd is None:
live = {a: (st, tr) for a, st, tr in _attached()}
- print(f"primary: {cfg.get('primary') or '(none)'} config: {CONFIG}")
+ print(f"primary: {cfg.get('primary') or '(none)'} devices: {config.paths()['devices']}")
for name, p in phones.items():
mark = "*" if name == cfg.get("primary") else " "
print(f" {mark} {name:<16} {p.get('model') or '?':<18} serial {p.get('serial')}"
@@ -674,21 +673,21 @@ def cli(args):
if _awake_pid():
print(f"already awake (pid {_awake_pid()}); phone-harness android rest to end")
return 0
- mirror = "--no-mirror" not in args
+ mirror = "--no-mirror" not in args and bool(config.get("android.mirror"))
if "--bg" in args:
child = subprocess.Popen(
[sys.executable, "-m", "phone_harness.run", "android", "awake",
"--fg"] + (["--no-mirror"] if not mirror else []),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
start_new_session=True)
- CONFIG.parent.mkdir(parents=True, exist_ok=True)
- PIDFILE.write_text(str(child.pid))
+ _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")
return 0 if child.poll() is None else 1
- CONFIG.parent.mkdir(parents=True, exist_ok=True)
- PIDFILE.write_text(str(os.getpid()))
+ _pidfile().parent.mkdir(parents=True, exist_ok=True)
+ _pidfile().write_text(str(os.getpid()))
return _awake(mirror=mirror)
if cmd == "rest":
@@ -765,10 +764,9 @@ def cli(args):
cfg = _load()
print(f"paired and connected: {model} as '{key}' ({adb_id})"
+ (" — now the primary" if cfg.get("primary") == key else ""))
- from . import transport
- if transport.default_platform() != "android":
- print("tip: `phone-harness use android` makes Android the default, "
- "so nothing needs PHONE_HARNESS_PLATFORM=android")
+ if config.get("platform") != "android":
+ print("tip: `phone-harness config set platform android` makes Android "
+ "the default, so nothing needs PHONE_HARNESS_PLATFORM=android")
return 0
if cmd == "connect":
diff --git a/src/phone_harness/config.py b/src/phone_harness/config.py
new file mode 100644
index 0000000..c8c8dc2
--- /dev/null
+++ b/src/phone_harness/config.py
@@ -0,0 +1,275 @@
+"""Where phone-harness keeps what the user chose and what it learned.
+
+Two kinds of thing, kept apart because they live differently:
+
+ config intent — the default platform, the adb binary, how often to poke
+ a phone awake. Hand-editable, small, worth putting in dotfiles.
+ ~/.config/phone-harness/config.json
+ state what the harness learned — remembered phones and which is
+ primary, the pid of a running awake session. Machine-managed,
+ rebuildable, never worth backing up.
+ ~/.local/state/phone-harness/devices.json
+ ~/.local/state/phone-harness/run/awake.pid
+
+XDG_CONFIG_HOME / XDG_STATE_HOME are honoured; PHONE_HARNESS_HOME moves both
+roots under one directory (tests, sandboxes).
+
+One rule for every setting: explicit argument, else environment variable,
+else config file, else built-in default. `get("android.poke_every")` looks
+at PHONE_HARNESS_ANDROID_POKE_EVERY, then config.json, then DEFAULTS. Env
+vars are per-call overrides; nothing requires them.
+
+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 json
+import os
+import sys
+import tempfile
+from pathlib import Path
+
+VERSION = 1
+
+DEFAULTS = {
+ "platform": "ios",
+ "android": {
+ "adb": "adb", # the binary; a path if it is not on PATH
+ "poke_every": 25, # seconds between keep-awake pokes
+ "mirror": True, # open scrcpy during `android awake` if installed
+ },
+}
+
+# Settings that historically had their own environment variable.
+_ENV_ALIASES = {
+ "platform": ["PHONE_HARNESS_PLATFORM"],
+ "android.adb": ["PHONE_HARNESS_ADB"],
+}
+
+
+# --- where -------------------------------------------------------------------
+
+def config_dir():
+ home = os.environ.get("PHONE_HARNESS_HOME")
+ if home:
+ return Path(home) / "config"
+ base = os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config"
+ return Path(base) / "phone-harness"
+
+
+def state_dir():
+ home = os.environ.get("PHONE_HARNESS_HOME")
+ if home:
+ return Path(home) / "state"
+ base = os.environ.get("XDG_STATE_HOME") or Path.home() / ".local" / "state"
+ return Path(base) / "phone-harness"
+
+
+def run_dir():
+ return state_dir() / "run"
+
+
+def paths():
+ return {"config": config_dir() / "config.json",
+ "devices": state_dir() / "devices.json",
+ "run": run_dir()}
+
+
+# --- files -------------------------------------------------------------------
+
+def _read(path, empty):
+ try:
+ data = json.loads(path.read_text())
+ if not isinstance(data, dict):
+ raise ValueError("not an object")
+ return data
+ except FileNotFoundError:
+ return dict(empty)
+ except (OSError, ValueError) as e:
+ print(f"phone-harness: ignoring unreadable {path} ({e}); using defaults",
+ file=sys.stderr)
+ return dict(empty)
+
+
+def _write(path, data):
+ """Atomic: a crash mid-write leaves the old file, not half a new one."""
+ path.parent.mkdir(parents=True, exist_ok=True)
+ data = {"version": VERSION, **{k: v for k, v in data.items() if k != "version"}}
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=path.name, suffix=".tmp")
+ with os.fdopen(fd, "w") as f:
+ json.dump(data, f, indent=2)
+ f.write("\n")
+ os.replace(tmp, path)
+
+
+def load():
+ return _read(paths()["config"], {})
+
+
+def save(data):
+ _write(paths()["config"], data)
+
+
+# --- settings ----------------------------------------------------------------
+
+def _dig(d, key):
+ for part in key.split("."):
+ if not isinstance(d, dict) or part not in d:
+ return None
+ d = d[part]
+ return d
+
+
+def _coerce(text, like):
+ """An env-var string, shaped like the default it overrides."""
+ if isinstance(like, bool):
+ return text.strip().lower() in ("1", "true", "yes", "on")
+ if isinstance(like, int):
+ try:
+ return int(text)
+ except ValueError:
+ return like
+ return text
+
+
+def _env_names(key):
+ return _ENV_ALIASES.get(key, []) + [
+ "PHONE_HARNESS_" + key.upper().replace(".", "_")]
+
+
+def lookup(key, default=None):
+ """(value, source) for a dotted key; source is 'env:NAME', 'file',
+ 'default' or 'unset'."""
+ built_in = _dig(DEFAULTS, key)
+ for name in _env_names(key):
+ if name in os.environ:
+ return _coerce(os.environ[name], built_in), f"env:{name}"
+ v = _dig(load(), key)
+ if v is not None:
+ return v, "file"
+ if built_in is not None:
+ return built_in, "default"
+ return default, "unset"
+
+
+def get(key, default=None):
+ return lookup(key, default)[0]
+
+
+def set(key, value):
+ """Set a dotted key in config.json. Strings that look like JSON scalars
+ ('true', '25') become that value, so the CLI can pass text through."""
+ if isinstance(value, str):
+ try:
+ parsed = json.loads(value)
+ if isinstance(parsed, (bool, int, float)) or parsed is None:
+ value = parsed
+ except ValueError:
+ pass
+ data = load()
+ d = data
+ parts = key.split(".")
+ for part in parts[:-1]:
+ if not isinstance(d.get(part), dict):
+ d[part] = {}
+ d = d[part]
+ d[parts[-1]] = value
+ save(data)
+ return value
+
+
+def unset(key):
+ data = load()
+ d = data
+ parts = key.split(".")
+ for part in parts[:-1]:
+ d = d.get(part) if isinstance(d, dict) else None
+ if d is None:
+ return
+ d.pop(parts[-1], None)
+ save(data)
+
+
+def known_keys():
+ out = []
+ def walk(d, prefix=""):
+ for k, v in d.items():
+ if isinstance(v, dict):
+ walk(v, prefix + k + ".")
+ else:
+ out.append(prefix + k)
+ walk(DEFAULTS)
+ return out
+
+
+# --- devices (state) ---------------------------------------------------------
+
+def devices():
+ """The remembered-devices file, whole: {"version", "<kind>": {...}}.
+ Migrates the pre-config android.json once, if it is found."""
+ p = paths()["devices"]
+ data = _read(p, {})
+ if not data.get("android"):
+ legacy = config_dir() / "android.json"
+ if legacy.exists():
+ old = _read(legacy, {})
+ if old.get("phones") or old.get("primary"):
+ data["android"] = {"primary": old.get("primary"),
+ "phones": old.get("phones") or {}}
+ _write(p, data)
+ legacy.rename(legacy.with_suffix(".json.migrated"))
+ return data
+
+
+def devices_of(kind):
+ """The section for one backend, always shaped {"primary", "phones"}."""
+ sect = devices().get(kind) or {}
+ return {"primary": sect.get("primary"), "phones": sect.get("phones") or {}}
+
+
+def save_devices_of(kind, section):
+ data = devices()
+ data[kind] = {"primary": section.get("primary"),
+ "phones": section.get("phones") or {}}
+ _write(paths()["devices"], data)
+
+
+# --- CLI (phone-harness config ...) -----------------------------------------
+
+CLI_USAGE = """Usage:
+ phone-harness config every setting, its value, and where it came from
+ phone-harness config get KEY
+ phone-harness config set KEY VALUE e.g. config set platform android
+ phone-harness config unset KEY
+ phone-harness config path where the files live
+"""
+
+
+def cli(args):
+ cmd = args[0] if args else None
+ if cmd is None:
+ for key in known_keys():
+ value, source = lookup(key)
+ print(f"{key:<22} {json.dumps(value):<10} ({source})")
+ for k, v in load().items():
+ 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")
+ 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"):
+ 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}")
+ return 0
+ print(CLI_USAGE)
+ return 2
diff --git a/src/phone_harness/run.py b/src/phone_harness/run.py
index 75a8bcc..755c518 100644
--- a/src/phone_harness/run.py
+++ b/src/phone_harness/run.py
@@ -11,7 +11,7 @@ Commands:
phone-harness --doctor diagnose permissions, app, and session state
phone-harness skill print the phone-harness skill text
phone-harness android ... pair/connect/choose an Android phone
- phone-harness use ios|android which phone helpers drive by default
+ phone-harness config ... settings: `config set platform android`
"""
@@ -26,15 +26,9 @@ def main():
if args and args[0] == "android":
from .android import cli
sys.exit(cli(args[1:]))
- if args and args[0] == "use":
- from . import transport
- if len(args) < 2 or args[1] not in ("ios", "android"):
- print(f"default platform: {transport.default_platform()}\n"
- "usage: phone-harness use ios|android")
- sys.exit(0 if len(args) < 2 else 2)
- transport.set_default_platform(args[1])
- print(f"default platform: {args[1]}")
- return
+ if args and args[0] == "config":
+ from .config import cli
+ sys.exit(cli(args[1:]))
if args and args[0] == "skill":
repo_root = Path(__file__).resolve().parent.parent.parent
print((repo_root / "SKILL.md").read_text(encoding="utf-8"), end="")
diff --git a/src/phone_harness/transport.py b/src/phone_harness/transport.py
index e92a9fb..81a8672 100644
--- a/src/phone_harness/transport.py
+++ b/src/phone_harness/transport.py
@@ -67,9 +67,7 @@ Anything a backend genuinely cannot do raises Unsupported. Callers gate on
supports(op) rather than guessing.
"""
import importlib
-import json
import os
-from pathlib import Path
class Unsupported(RuntimeError):
@@ -121,42 +119,17 @@ class Backend:
return [op for op in OP_NAMES if self.supports(op)]
-CONFIG_DIR = Path(os.environ.get("PHONE_HARNESS_CONFIG_DIR",
- Path.home() / ".config" / "phone-harness"))
-
-
-def default_platform():
- """The platform to use when nothing says otherwise: the one saved by
- `phone-harness use <platform>`, else ios."""
- try:
- return json.loads((CONFIG_DIR / "config.json").read_text()).get(
- "platform") or "ios"
- except (OSError, ValueError):
- return "ios"
-
-
-def set_default_platform(platform):
- CONFIG_DIR.mkdir(parents=True, exist_ok=True)
- path = CONFIG_DIR / "config.json"
- try:
- cfg = json.loads(path.read_text())
- except (OSError, ValueError):
- cfg = {}
- cfg["platform"] = platform
- path.write_text(json.dumps(cfg, indent=2) + "\n")
-
-
def connect(platform=None, **kw):
"""Build a backend. Explicit argument, else PHONE_HARNESS_PLATFORM, else
- the default saved by `phone-harness use <platform>`, else ios.
+ `platform` in the config file (`phone-harness config set platform …`),
+ else ios.
Returns an object rather than installing a module global, so a script can
hold two devices at once instead of being limited to one per process.
helpers.py binds one of these as its default.
"""
- platform = (platform
- or os.environ.get("PHONE_HARNESS_PLATFORM")
- or default_platform()).lower()
+ from . import config
+ platform = (platform or config.get("platform")).lower()
if platform in ("ios", "iphone", "ipad"):
return importlib.import_module(".ios", __package__).IPhone(**kw)
if platform == "android":