let your agent control your phone
telemetry: tie CLI runs to the cloud account, session and client (#158)
shawn panab4ad17962437
diff --git a/install.md b/install.mdindex 6f44864..372796c 100644--- a/install.md+++ b/install.md@@ -120,7 +120,8 @@ Set up each as above; `phone-harness config set platform …` picks the default,the iPhone is driven through the mirroring window, the Android over adb. Acloud iPhone is a third path: HTTPS ops, covered in the skill.-`phone-harness config set telemetry false` turns off anonymous usage telemetry.+`phone-harness config set telemetry false` turns off usage telemetry. Once you+sign in to Phone Harness Cloud, it is linked to your account.## If It Failsdiff --git a/src/phone_harness/cloud.py b/src/phone_harness/cloud.pyindex 6ebad3d..11e7757 100644--- a/src/phone_harness/cloud.py+++ b/src/phone_harness/cloud.py@@ -32,6 +32,7 @@ import uuidimport webbrowserfrom . import config+from . import telemetryfrom . import termSAVE_WAIT = 90 # seconds to let a stopped profile phone finish closing and saving@@ -212,9 +213,17 @@ def _api(method, path, body=None, token=None, headers=None, timeout=40):return _request(method, path, body, fresh, headers, timeout)+def _me(token=None):+ """GET /me: the signed-in account. Its uid is what this install's+ telemetry is linked to."""+ me = _api("GET", "/me", token=token)+ telemetry.link_user(me.get("uid"))+ return me++def _request(method, path, body, token, headers, timeout):h = {"Authorization": f"Bearer {token}", "Accept": "application/json",- "User-Agent": USER_AGENT, **(headers or {})}+ "User-Agent": USER_AGENT, **telemetry.cloud_headers(), **(headers or {})}data = Noneif body is not None:h["Content-Type"] = "application/json"@@ -536,6 +545,7 @@ def attached(kind=None):return Noneif _expired(sess):return None+ telemetry.note_session(sess["sid"], sess.get("platform"))return sess@@ -668,6 +678,7 @@ def _store_session(record, make_attached=True):_reported_dead.clear()global _reported_fallback_reported_fallback = None+ telemetry.note_session(record["sid"], record.get("platform"))state = _load_state()sessions = _known_sessions(state)sessions[record["sid"]] = record@@ -847,12 +858,14 @@ def _resolve_sid(given):if not sess: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)]+ sessions = _api("GET", "/sessions")+ hits = ([s for s in sessions if s["id"] == given]+ or [s for s in sessions if s["id"].startswith(given)])if len(hits) != 1:sys.exit(f"{given!r} matches {len(hits)} running sessions"- + (f": {', '.join(hits)}" if hits else ""))- return hits[0]+ + (f": {', '.join(s['id'] for s in hits)}" if hits else ""))+ telemetry.note_session(hits[0]["id"], hits[0].get("platform"))+ return hits[0]["id"]def _wait_ready(sid):@@ -922,7 +935,7 @@ def _login(args):sys.exit("Sign-in timed out. Run `phone-harness cloud login` again when you can "f"sign in. No account yet? {SIGNUP}")try:- me = _api("GET", "/me", token=tok["access_token"])+ me = _me(token=tok["access_token"])except CloudError as e:sys.exit(f"Signed in, but the Phone Harness API refused the sign-in: {_explain(e)}")_store_tokens(tok, email=me.get("email"))@@ -949,6 +962,7 @@ def _logout(args):except OSError:pass_auth_path().unlink(missing_ok=True)+ telemetry.unlink_user()print("Signed out.")if attached():print("A cloud phone is still running; sign in again to stop it.")@@ -1111,7 +1125,7 @@ def _wait_out_save(profile_id):deadline = time.monotonic() + SAVE_WAITtold = Falsewhile True:- me = _api("GET", "/me")+ me = _me()profile = me.get("profile") or {}if profile.get("id") != profile_id:return@@ -1200,7 +1214,7 @@ def _start(args):sys.exit(f"Duration must be between 1 and {cap} minutes "f"(raise the cap with `phone-harness config set cloud.max_minutes N`).")- me = _api("GET", "/me")+ me = _me()catalog = _catalog(me)entry = Noneif phone:@@ -1323,6 +1337,7 @@ def _stop(args):for sid in sids:try:before = _api("GET", f"/sessions/{sid}")+ telemetry.note_session(sid, before.get("platform"))held_profile = held_profile or _keeps_state(before)_api("DELETE", f"/sessions/{sid}")print(f"{term.mark()} Session {sid} ended.")@@ -1344,7 +1359,7 @@ def _stop(args):state = "saving"while time.monotonic() < deadline:time.sleep(3)- state = (_api("GET", "/me").get("profile") or {}).get("state")+ state = (_me().get("profile") or {}).get("state")if state not in ("saving", "running"):breakprint(f" {state}.")@@ -1358,7 +1373,7 @@ def _status(args):print(term.err("Not signed in. Run: phone-harness cloud login", sys.stdout))print(term.note(_waitlist_line()))return 1- me = _api("GET", "/me")+ me = _me()if os.environ.get("PHONE_HARNESS_CLOUD_API"):print(f"api {_target('API')}")print(f"signed in {me.get('email') or me.get('uid')}")@@ -1591,7 +1606,7 @@ def _ls(args):as_json = _flag(args, "--json")if args:sys.exit(CLI_USAGE)- me = _api("GET", "/me")+ me = _me()sessions = _api("GET", "/sessions")rows = _ls_rows(me, sessions)if as_json:@@ -1659,7 +1674,7 @@ def _open(args):def _whoami(args):- me = _api("GET", "/me")+ me = _me()if _flag(args, "--json"):print(json.dumps(me, indent=2))return 0@@ -1678,7 +1693,7 @@ def _phone(args):_api("POST", "/me/profile/reset")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 {}+ profile = _me().get("profile") or {}print(json.dumps(profile, indent=2) if _flag(args, "--json") else _describe_profile(profile))return 0diff --git a/src/phone_harness/config.py b/src/phone_harness/config.pyindex e52ed1f..5333088 100644--- a/src/phone_harness/config.py+++ b/src/phone_harness/config.py@@ -75,7 +75,7 @@ _load_env_files()DEFAULTS = {"platform": "ios" if sys.platform == "darwin" else "android", # iPhone needs a Mac- "telemetry": True, # anonymous usage events; `config set telemetry false`+ "telemetry": True, # usage events; `config set telemetry false`"android": {"adb": "adb", # the binary; a path if it is not on PATH"poke_every": 25, # seconds between keep-awake pokes@@ -302,8 +302,9 @@ def save_devices_of(kind, section):# --- telemetry (state) -------------------------------------------------------def install_id():- """A random id minted once per machine, so runs can be counted without- knowing who ran them. Delete the file to get a new one."""+ """A random id minted once per machine: telemetry's distinct_id. Signing+ in to the cloud links it to the account (telemetry.link_user). Delete the+ file to get a new one."""import uuidp = paths()["telemetry"]data = _read(p, {})@@ -313,6 +314,23 @@ def install_id():return data["install_id"]+def telemetry_user():+ """The uid of the cloud account this install's telemetry is linked to, or None."""+ uid = _read(paths()["telemetry"], {}).get("user_id")+ return uid if isinstance(uid, str) and uid else None+++def set_telemetry_user(uid):+ """Link telemetry to the cloud account `uid`; None unlinks it (sign-out)."""+ p = paths()["telemetry"]+ data = _read(p, {})+ if uid:+ data["user_id"] = uid+ elif data.pop("user_id", None) is None:+ return+ _write(p, data)++# --- CLI (phone-harness config ...) -----------------------------------------CLI_USAGE = """Usage:diff --git a/src/phone_harness/remote.py b/src/phone_harness/remote.pyindex 90e1f3d..5551b1b 100644--- a/src/phone_harness/remote.py+++ b/src/phone_harness/remote.py@@ -15,9 +15,11 @@ import jsonimport osimport tempfileimport urllib.error+import urllib.parseimport urllib.requestfrom pathlib import Path+from . import telemetryfrom .transport import Backend, UnsupportedUSER_AGENT = "phone-harness-cli"@@ -97,7 +99,8 @@ class Remote(Backend):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}+ headers = {"Authorization": f"Bearer {self.token}", "User-Agent": USER_AGENT,+ **telemetry.cloud_headers()}if data:headers["Content-Type"] = "application/json"req = urllib.request.Request(self.url + path, data=data, method=method, headers=headers)@@ -178,7 +181,8 @@ class Remote(Backend):return Nonedef _session_detail(self):- return f"cloud phone at {self.url}"+ # The control URL's path is the grant, so only its host is named.+ return f"cloud phone at {urllib.parse.urlsplit(self.url).netloc}"def _focus_probe(self):return (True,)diff --git a/src/phone_harness/run.py b/src/phone_harness/run.pyindex c4b063d..8c4250b 100644--- a/src/phone_harness/run.py+++ b/src/phone_harness/run.py@@ -127,6 +127,21 @@ class _StreamTail:return getattr(self._wrapped, name)+def _telemetry_argv(args):+ """The command line as cli_event records it. `--session SID` is left out:+ the pinned session is the event's session_id. An Android pairing code is+ masked: it is a credential."""+ argv, words = [], iter(args)+ for word in words:+ if word == "--session":+ next(words, None)+ else:+ argv.append(word)+ if argv[:2] == ["android", "pair"]:+ argv[2:] = ["<code>" if word.isdigit() else word for word in argv[2:]]+ return argv++def _telemetry_command(args):if not args:return "script"@@ -166,7 +181,7 @@ def _intents(task):def _waitlist_shown():"""True when a `cloud` command pointed the user at the waitlist: the one- thing about a cloud run worth counting (no output, no identity)."""+ thing in a cloud run's output worth counting (the output is not sent)."""mod = sys.modules.get("phone_harness.cloud")return bool(getattr(mod, "waitlist_shown", False)) or None@@ -192,7 +207,10 @@ def main():_helper_trace.clear()_helper_call_count = 0start_time = time.monotonic()- command = _telemetry_command(args)+ argv = _telemetry_argv(args)+ command = _telemetry_command(argv)+ invocation = {"command": command, "argv": argv or None,+ "subcommand": argv[1] if command in _OWNED and len(argv) > 1 else None}task = Noneif not args and not sys.stdin.isatty():task = sys.stdin.read()@@ -209,7 +227,7 @@ def main():code = _exit_code(exc.code)telemetry.capture_cli_event(action="error" if code else "completed",- command=command,+ **invocation,task=task,**_intents(task),phone=_phone_name,@@ -226,7 +244,7 @@ def main():except Exception as exc:telemetry.capture_cli_event(action="error",- command=command,+ **invocation,task=task,**_intents(task),phone=_phone_name,@@ -245,7 +263,7 @@ def main():sys.stdout = stdout_tail._wrappedtelemetry.capture_cli_event(action="completed",- command=command,+ **invocation,task=task,**_intents(task),phone=_phone_name,diff --git a/src/phone_harness/telemetry.py b/src/phone_harness/telemetry.pyindex 876146f..808f9a9 100644--- a/src/phone_harness/telemetry.py+++ b/src/phone_harness/telemetry.py@@ -3,12 +3,23 @@One `cli_event` per CLI invocation, sent to PostHog from a detached helperprocess so the CLI never blocks on the network.+distinct_id is this machine's install id. Once GET /me names the Phone+Harness Cloud account the machine is signed in to, one `$identify` links the+install to that account's uid (the distinct_id phone-cloud's own events use),+and later events carry it as user_id until `cloud logout`. An event that+drove or acted on a cloud phone carries its session_id and platform. Calls to+the cloud carry the CLI's version and the client driving it+(X-Phone-Harness-Version, X-Agent-Client), so phone-cloud can tag its events+the same way.+Off: `phone-harness config set telemetry false`, or PHONE_HARNESS_TELEMETRY=0-for one call. The install id lives in the state dir; see config.py.+for one call. Off sends no event, links no account and adds no header. The+install id and the linked uid live in the state dir; see config.py."""from __future__ import annotations+import functoolsimport jsonimport osimport platform@@ -23,6 +34,7 @@ POSTHOG_HOST = "https://us.i.posthog.com"MAX_TASK_LENGTH = 20_000def _version() -> str:try:return version("phone-harness")@@ -60,6 +72,26 @@ def _detect_agent_client() -> str | None:return None+def _client() -> str | None:+ """Who drives this CLI: the integration that launched it (PH_CLIENT), else+ the coding agent its environment names."""+ return os.environ.get("PH_CLIENT") or _detect_agent_client()+++def cloud_headers() -> dict:+ """Headers for every call to Phone Harness Cloud while telemetry is on: this+ CLI's version, and the client driving it, which phone-cloud records on its+ own events. Off, the calls are what they always were."""+ if not is_enabled():+ return {}+ headers = {"X-Phone-Harness-Version": _version() or "unknown"}+ # PH_CLIENT is free text; a header value must be printable ASCII.+ client = "".join(c for c in _client() or "" if " " <= c <= "~").strip()[:64]+ if client:+ headers["X-Agent-Client"] = client+ return headers++_DETACHED_SENDER_SOURCE = """import json, sys, urllib.requesttry:@@ -106,10 +138,67 @@ def _base_properties() -> dict:}+def link_user(uid) -> None:+ """This machine is signed in to Phone Harness Cloud as `uid` (GET /me).++ Remembered, so later cli_events carry it as user_id. When it is new to the+ install (a first sign-in, or another account), one `$identify` merges the+ install's PostHog person into the account's."""+ if not isinstance(uid, str) or not uid or not is_enabled():+ return+ try:+ if _config.telemetry_user() == uid:+ return+ install = _config.install_id()+ _send_detached({+ "api_key": POSTHOG_KEY,+ "event": "$identify",+ "distinct_id": uid,+ "properties": {+ **_base_properties(),+ "$anon_distinct_id": install,+ "install_id": install,+ "user_id": uid,+ "channel": "cli",+ "client": _client(),+ },+ })+ _config.set_telemetry_user(uid)+ except Exception:+ return+++def unlink_user() -> None:+ """This machine signed out of the cloud: later events carry no user_id."""+ try:+ _config.set_telemetry_user(None)+ except Exception:+ return+++# The cloud session this process drove or acted on, for its cli_event.+_session: dict = {}+++def note_session(sid: str, phone_platform: str | None = None) -> None:+ """This process drove, or acted on, cloud session `sid` ('ios' | 'android')."""+ if _session.get("session_id") != sid:+ _session.clear()+ _session["session_id"] = sid+ if phone_platform:+ _session["platform"] = phone_platform+++# The platform a local backend drives, by its `phone` name.+_BACKEND_PLATFORMS = {"iphone-mirroring": "ios", "android": "android"}++def capture_cli_event(*,action: str,command: str,+ subcommand: str | None = None,+ argv: list | None = None,task: str | None = None,task_intent: str | None = None,step: str | None = None,@@ -135,9 +224,16 @@ def capture_cli_event("$process_person_profile": True,"action": action,"command": command,- # 'iphone-mirroring' | 'android'+ "subcommand": subcommand,+ "argv": argv,+ # the backend: 'iphone-mirroring' | 'android' | 'remote' (a cloud iPhone)"phone": phone,- "client": os.environ.get("PH_CLIENT") or None,+ "platform": _session.get("platform") or _BACKEND_PLATFORMS.get(phone),+ # the Phone Harness Cloud account and session, when there are ones+ "user_id": _config.telemetry_user(),+ "session_id": _session.get("session_id"),+ "channel": "cli",+ "client": _client(),"client_version": os.environ.get("PH_CLIENT_VERSION") or None,"agent_client": _detect_agent_client(),"model": os.environ.get("PHONE_HARNESS_AGENT_MODEL") or None,diff --git a/tests/test_cloud.py b/tests/test_cloud.pyindex 446c7b3..0023a1c 100644--- a/tests/test_cloud.py+++ b/tests/test_cloud.py@@ -24,6 +24,8 @@ if SUPPORT not in sys.path:import browser_recorderbrowser_recorder.install()+from phone_harness import telemetry # noqa: E402+FAKE_ADB = r'''#!/bin/sh# Locked until `shell unlock CODE`; state is a file next to this script.DIR="$(dirname "$0")"@@ -69,6 +71,7 @@ def _fake_resolve(c, body):class FakeCloud(BaseHTTPRequestHandler):sessions, profile, polls, posts, keys = {}, {}, {}, [], []+ requests = [] # (method, path, headers with lowercase names)valid, token_polls, refreshes, revoked = set(), 0, 0, []closing_reads = 0forbid = False@@ -117,6 +120,7 @@ class FakeCloud(BaseHTTPRequestHandler):n = int(self.headers.get("Content-Length") or 0)raw = self.rfile.read(n) if n else b""path, m = self.path.split("?")[0], self.command+ c.requests.append((m, path, {k.lower(): v for k, v in self.headers.items()}))if path.startswith("/oauth/"):return self._oauth(path, dict(urllib.parse.parse_qsl(raw.decode())))if self.headers.get("Authorization", "")[7:] not in c.valid:@@ -219,6 +223,7 @@ class FakeCloud(BaseHTTPRequestHandler):class FakeControl(BaseHTTPRequestHandler):"""What a phone driven by ops over HTTPS answers: /ops, /op, /frame.png."""calls = []+ requests = [] # (method, path, headers with lowercase names)launch_error = None # set: apps.launch returns this JSON body with HTTP 400PNG = bytes.fromhex("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489""0000000d49444154789c6360000002000154a24f5d0000000049454e44ae426082")@@ -238,6 +243,8 @@ class FakeControl(BaseHTTPRequestHandler):import base64n = int(self.headers.get("Content-Length") or 0)body = json.loads(self.rfile.read(n)) if n else {}+ FakeControl.requests.append((self.command, self.path,+ {k.lower(): v for k, v in self.headers.items()}))if self.headers.get("Authorization") != "Bearer ct_1":return self._send(404, {"error": "not found"})if self.path == "/ops":@@ -265,6 +272,25 @@ class FakeControl(BaseHTTPRequestHandler):do_GET = do_POST = _handle+class FakePostHog(BaseHTTPRequestHandler):+ """PostHog's capture endpoint: every event the CLI's detached sender posts."""+ events = []++ def log_message(self, *a):+ pass++ def do_POST(self):+ n = int(self.headers.get("Content-Length") or 0)+ FakePostHog.events.append(json.loads(self.rfile.read(n)))+ self.send_response(200)+ self.send_header("Content-Length", "0")+ self.end_headers()+++# What each coding agent sets; a test that checks the client must not inherit one.+AGENT_MARKERS = [m.partition("=")[0] for m, _ in telemetry._AGENT_ENV_MARKERS] + ["PH_CLIENT"]++class CloudCli(unittest.TestCase):def setUp(self):self.home = tempfile.TemporaryDirectory()@@ -273,6 +299,7 @@ class CloudCli(unittest.TestCase):adb.write_text(FAKE_ADB)adb.chmod(adb.stat().st_mode | stat.S_IEXEC)FakeCloud.sessions, FakeCloud.polls, FakeCloud.posts, FakeCloud.keys = {}, {}, [], []+ FakeCloud.requests, FakeControl.requests = [], []FakeCloud.valid, FakeCloud.token_polls = set(), 0FakeCloud.refreshes, FakeCloud.revoked, FakeCloud.closing_reads = 0, [], 0FakeCloud.forbid = False@@ -1263,6 +1290,164 @@ class CloudCli(unittest.TestCase):self.assertIn(ios_sid, FakeCloud.sessions)self.assertIn("your iPhone", self.run_cli("cloud").stdout)+ # --- telemetry -------------------------------------------------------------++ def posthog(self, client="test-agent"):+ """Telemetry on, posting to a fake PostHog; the client is PH_CLIENT alone."""+ server = ThreadingHTTPServer(("127.0.0.1", 0), FakePostHog)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ self.addCleanup(server.server_close)+ self.addCleanup(server.shutdown)+ FakePostHog.events = []+ for name in AGENT_MARKERS:+ self.env.pop(name, None)+ self.env.update({"PHONE_HARNESS_TELEMETRY": "1", "PH_CLIENT": client,+ "PH_POSTHOG_HOST": f"http://127.0.0.1:{server.server_port}"})++ def events(self, name, count=1, timeout=10.0):+ """The `name` events, once `count` have arrived (the sender is a detached+ process), or whatever arrived by the deadline."""+ deadline = time.monotonic() + timeout+ while True:+ got = [e for e in FakePostHog.events if e["event"] == name]+ if len(got) >= count or time.monotonic() >= deadline:+ return got+ time.sleep(0.05)++ def cli_event(self, count, **match):+ """The properties of the one cli_event that matches, once `count` have+ arrived. Each run's sender is its own process, so arrival order is not+ run order."""+ hits = [e["properties"] for e in self.events("cli_event", count)+ if all(e["properties"].get(k) == v for k, v in match.items())]+ self.assertEqual(len(hits), 1, (match, FakePostHog.events))+ return hits[0]++ def telemetry_state(self):+ path = Path(self.home.name) / "state" / "telemetry.json"+ return json.loads(path.read_text()) if path.exists() else None++ def test_a_leading_session_pin_still_keeps_cloud_output_out_of_telemetry(self):+ self.posthog()+ self.login()+ self.assertEqual(self.run_cli("cloud", "start", "--no-watch").returncode, 0)+ [sid] = FakeCloud.sessions+ shown = self.run_cli("--session", sid, "cloud", "show", "--json")+ self.assertIn("ph_code", shown.stdout) # the unlock code, on screen+ events = self.events("cli_event", count=3)+ self.assertEqual([e["properties"]["command"] for e in events], ["cloud"] * 3)+ self.assertEqual([e["properties"]["output"] for e in events], [None] * 3)+ blob = json.dumps(FakePostHog.events)+ for secret in ("ph_code", "watch.example"):+ self.assertNotIn(secret, blob)++ def test_signing_in_links_this_install_to_the_account_once(self):+ self.posthog()+ self.login()+ install = self.telemetry_state()["install_id"]+ [identify] = self.events("$identify")+ self.assertEqual(identify["distinct_id"], "u1")+ self.assertEqual(identify["properties"]["$anon_distinct_id"], install)+ self.assertEqual(identify["properties"]["client"], "test-agent")+ [login] = self.events("cli_event")+ self.assertEqual(login["distinct_id"], install) # still one id per install+ props = login["properties"]+ self.assertEqual((props["command"], props["subcommand"], props["user_id"], props["channel"]),+ ("cloud", "login", "u1", "cli"))++ self.run_cli("cloud", "whoami") # GET /me again: no second link+ self.assertEqual(self.cli_event(2, subcommand="whoami")["user_id"], "u1")+ time.sleep(0.5)+ self.assertEqual(len(self.events("$identify")), 1)++ self.run_cli("cloud", "logout")+ self.assertIsNone(self.cli_event(3, subcommand="logout")["user_id"])+ self.assertNotIn("user_id", self.telemetry_state())+ self.login() # a new sign-in links again+ self.assertEqual(len(self.events("$identify", count=2)), 2)+ self.assertEqual(self.telemetry_state()["install_id"], install)+ blob = json.dumps(FakePostHog.events)+ for secret in ("at-1", "rt-1", "dev-1", "BCDF-GHJK"):+ self.assertNotIn(secret, blob)++ def test_cloud_runs_carry_the_account_and_the_session_they_drove(self):+ self.posthog()+ self.login()+ r = self.run_cli("cloud", "start", "Saved phone", "--for", "5m", "--no-watch")+ self.assertEqual(r.returncode, 0, r.stderr)+ [sid] = FakeCloud.sessions+ start = self.cli_event(2, subcommand="start")+ self.assertEqual((start["subcommand"], start["session_id"], start["platform"], start["user_id"]),+ ("start", sid, "android", "u1"))+ self.assertEqual(start["argv"], ["cloud", "start", "Saved phone", "--for", "5m", "--no-watch"])+ self.assertIsNone(start["output"])++ script = "# task: say hi\nprint(6 * 7)\n"+ r = self.run_cli(stdin=script)+ self.assertEqual(r.returncode, 0, r.stderr)+ ran = self.cli_event(3, command="script")+ self.assertEqual((ran["command"], ran["phone"], ran["platform"], ran["session_id"], ran["user_id"]),+ ("script", "android", "android", sid, "u1"))+ self.assertEqual((ran["task"], ran["task_intent"], ran["output"]), (script, "say hi", "42\n"))++ # `--session` before `cloud` is still a cloud command, whose output (the+ # unlock code, the watch link) is never sent.+ shown = self.run_cli("--session", sid, "cloud", "show", "--json")+ self.assertIn("ph_code", shown.stdout)+ show = self.cli_event(4, subcommand="show")+ self.assertEqual((show["command"], show["subcommand"], show["session_id"], show["argv"]),+ ("cloud", "show", sid, ["cloud", "show", "--json"]))+ self.assertIsNone(show["output"])+ blob = json.dumps(FakePostHog.events)+ for secret in ("ph_code", "watch.example", "at-1", "rt-1"):+ self.assertNotIn(secret, blob)++ def test_cloud_calls_name_the_version_and_client_only_while_telemetry_is_on(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 = []+ FakeCloud.available = [{"platform": "ios", "kind": "device", "id": "iph-1",+ "label": "My iPhone SE", "state": "available"}]+ no_adb = {"PHONE_HARNESS_ADB": "/nonexistent/adb"}+ self.posthog(client="hermes")++ # Off, as for a Hermes run that did not opt in: the calls are what they+ # were, nothing is posted, and nothing is linked.+ off = {**no_adb, "PHONE_HARNESS_TELEMETRY": "0"}+ self.assertEqual(self.run_cli("cloud", "login", "--no-browser", env=off).returncode, 0)+ r = self.run_cli("cloud", "start", "ios", "--no-watch", env=off)+ self.assertEqual(r.returncode, 0, r.stderr)+ r = self.run_cli(stdin="tap(10, 20)\n", env=off)+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertTrue(FakeControl.requests)+ for _, path, headers in FakeCloud.requests + FakeControl.requests:+ self.assertNotIn("x-agent-client", headers, path)+ self.assertNotIn("x-phone-harness-version", headers, path)+ time.sleep(0.5)+ self.assertEqual(FakePostHog.events, [])+ self.assertIsNone(self.telemetry_state())++ # On: every call to the API and to the phone's control URL names both.+ FakeCloud.requests, FakeControl.requests = [], []+ r = self.run_cli(stdin="tap(10, 20)\n", env=no_adb)+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertEqual(self.run_cli("cloud", "ls", env=no_adb).returncode, 0)+ api = [(p, h) for _, p, h in FakeCloud.requests if not p.startswith("/oauth/")]+ ops = [(p, h) for _, p, h in FakeControl.requests]+ self.assertTrue(api and ops)+ for path, headers in api + ops:+ self.assertEqual(headers.get("x-agent-client"), "hermes", path)+ self.assertEqual(headers.get("x-phone-harness-version"), telemetry._version() or "unknown", path)+ [sid] = FakeCloud.sessions+ ran = self.cli_event(2, command="script")+ self.assertEqual((ran["phone"], ran["platform"], ran["session_id"], ran["client"]),+ ("remote", "ios", sid, "hermes"))+ self.assertEqual(ran["steps"][0]["helper"], "tap")+ self.assertNotIn("ct_1", json.dumps(FakePostHog.events))+def test_phone_reset_describes_the_saved_android_only(self):self.login()refused = self.run_cli("cloud", "phone", "reset")diff --git a/tests/test_telemetry.py b/tests/test_telemetry.pynew file mode 100644index 0000000..3337a8c--- /dev/null+++ b/tests/test_telemetry.py@@ -0,0 +1,165 @@+"""What the CLI tells PostHog and the cloud: cli_event, $identify, the cloud headers.+No network: the detached sender is a list.++ python -m unittest tests.test_telemetry+"""+import os+import sys+import tempfile+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 config, run, telemetry # noqa: E402+from phone_harness.remote import Remote # noqa: E402++AGENT_MARKERS = [m.partition("=")[0] for m, _ in telemetry._AGENT_ENV_MARKERS]+++class Telemetry(unittest.TestCase):+ """A fresh state dir, telemetry on, no agent in the environment, nothing sent."""++ def setUp(self):+ home = tempfile.TemporaryDirectory()+ self.addCleanup(home.cleanup)+ env = mock.patch.dict(os.environ, {"PHONE_HARNESS_HOME": home.name,+ "PHONE_HARNESS_TELEMETRY": "1"})+ env.start()+ self.addCleanup(env.stop)+ for name in AGENT_MARKERS + ["PH_CLIENT", "PH_CLIENT_VERSION"]:+ os.environ.pop(name, None)+ self.sent = []+ sender = mock.patch.object(telemetry, "_send_detached", self.sent.append)+ sender.start()+ self.addCleanup(sender.stop)+ telemetry._session.clear()+ self.addCleanup(telemetry._session.clear)++ def event(self, **kw):+ telemetry.capture_cli_event(**{"action": "completed", "command": "script", **kw})+ return self.sent[-1]["properties"]++ def test_off_sends_nothing_links_nothing_and_adds_no_header(self):+ os.environ["PHONE_HARNESS_TELEMETRY"] = "0"+ os.environ["CLAUDECODE"] = "1"+ telemetry.link_user("u1")+ telemetry.capture_cli_event(action="completed", command="script")+ self.assertEqual(self.sent, [])+ self.assertEqual(telemetry.cloud_headers(), {})+ self.assertIsNone(config.telemetry_user())+ self.assertFalse(config.paths()["telemetry"].exists())++ def test_the_install_is_linked_once_per_sign_in(self):+ install = config.install_id()+ telemetry.link_user("u1")+ telemetry.link_user("u1")+ [identify] = self.sent+ self.assertEqual((identify["event"], identify["distinct_id"]), ("$identify", "u1"))+ self.assertEqual(identify["properties"]["$anon_distinct_id"], install)+ self.assertEqual(identify["properties"]["user_id"], "u1")+ telemetry.link_user("u2") # another account on this machine+ self.assertEqual([e["distinct_id"] for e in self.sent], ["u1", "u2"])+ telemetry.unlink_user()+ self.assertIsNone(config.telemetry_user())+ telemetry.link_user("u2") # signed in again+ self.assertEqual(len(self.sent), 3)+ self.assertEqual(config.install_id(), install)+ for junk in (None, "", 42, {"uid": "u3"}):+ telemetry.link_user(junk)+ self.assertEqual(len(self.sent), 3)++ def test_a_failed_send_is_not_remembered_as_linked(self):+ with mock.patch.object(telemetry, "_send_detached", side_effect=OSError("no fork")):+ telemetry.link_user("u1")+ self.assertIsNone(config.telemetry_user())+ telemetry.link_user("u1")+ self.assertEqual(len(self.sent), 1)++ def test_a_cli_event_names_the_account_the_session_and_the_client(self):+ install = config.install_id()+ config.set_telemetry_user("u1")+ telemetry.note_session("sid1", "ios")+ os.environ["PH_CLIENT"] = "hermes"+ os.environ["CLAUDECODE"] = "1"+ props = self.event(phone="remote", subcommand=None, argv=None)+ self.assertEqual(self.sent[-1]["distinct_id"], install)+ self.assertEqual({k: props[k] for k in ("user_id", "session_id", "platform", "channel",+ "client", "agent_client", "phone")},+ {"user_id": "u1", "session_id": "sid1", "platform": "ios", "channel": "cli",+ "client": "hermes", "agent_client": "claude-code", "phone": "remote"})++ telemetry._session.clear()+ config.set_telemetry_user(None)+ os.environ.pop("PH_CLIENT")+ props = self.event(phone="iphone-mirroring")+ self.assertEqual((props["user_id"], props["session_id"], props["platform"], props["client"]),+ (None, None, "ios", "claude-code"))+ self.assertEqual(self.event(phone="android")["platform"], "android")+ self.assertIsNone(self.event(command="cloud", subcommand="ls")["platform"])++ def test_task_and_output_are_sent_as_before(self):+ task = "# task: count\n" + "x" * 25_000+ props = self.event(task=task, task_intent="count", output="42\n", output_length=3)+ self.assertEqual(props["task"], task[:telemetry.MAX_TASK_LENGTH])+ self.assertEqual(props["task_length"], len(task))+ self.assertEqual((props["task_intent"], props["output"], props["output_length"]),+ ("count", "42\n", 3))++ def test_a_session_note_keeps_what_it_learned_about_that_session(self):+ telemetry.note_session("s1", "android")+ telemetry.note_session("s1")+ self.assertEqual(telemetry._session, {"session_id": "s1", "platform": "android"})+ telemetry.note_session("s2")+ self.assertEqual(telemetry._session, {"session_id": "s2"})++ def test_the_cloud_headers_name_the_version_and_a_printable_client(self):+ version = telemetry._version() or "unknown"+ self.assertEqual(telemetry.cloud_headers(), {"X-Phone-Harness-Version": version})+ os.environ["CLAUDECODE"] = "1"+ self.assertEqual(telemetry.cloud_headers(),+ {"X-Phone-Harness-Version": version, "X-Agent-Client": "claude-code"})+ os.environ["PH_CLIENT"] = "hérmès\r\nX-Injected: 1"+ client = telemetry.cloud_headers()["X-Agent-Client"]+ client.encode("ascii")+ self.assertNotIn("\r", client)+ self.assertNotIn("\n", client)+ os.environ["PH_CLIENT"] = "éè" # nothing printable left+ self.assertEqual(telemetry.cloud_headers(), {"X-Phone-Harness-Version": version})++ def test_the_linked_account_is_stored_beside_the_install_id(self):+ config.set_telemetry_user(None) # nothing to forget: no file written+ self.assertFalse(config.paths()["telemetry"].exists())+ install = config.install_id()+ config.set_telemetry_user("u1")+ self.assertEqual((config.telemetry_user(), config.install_id()), ("u1", install))+ config.set_telemetry_user(None)+ self.assertEqual((config.telemetry_user(), config.install_id()), (None, install))+++class CommandLine(unittest.TestCase):+ def test_the_session_pin_is_left_out_and_a_pairing_code_is_masked(self):+ argv = run._telemetry_argv(["--session", "sid1", "cloud", "start", "ios", "--for", "5m"])+ self.assertEqual(argv, ["cloud", "start", "ios", "--for", "5m"])+ self.assertEqual(run._telemetry_command(argv), "cloud")+ self.assertEqual(run._telemetry_command(run._telemetry_argv(["--session", "sid1"])), "script")+ self.assertEqual(run._telemetry_argv(["android", "pair", "10.0.0.2:37000", "123456", "pixel"]),+ ["android", "pair", "10.0.0.2:37000", "<code>", "pixel"])+ self.assertEqual(run._telemetry_argv(["android", "pair", "654321"]),+ ["android", "pair", "<code>"])+ self.assertEqual(run._telemetry_argv(["android", "connect", "10.0.0.2:5555"]),+ ["android", "connect", "10.0.0.2:5555"])+++class RemoteDetail(unittest.TestCase):+ def test_the_detail_names_the_host_not_the_grant_in_the_control_url(self):+ detail = Remote("https://api.example/iphone/c/grant-token-0123456789", "bearer")._session_detail()+ self.assertIn("api.example", detail)+ self.assertNotIn("grant-token", detail)+++if __name__ == "__main__":+ unittest.main()