Skip to content

let your agent control your phone

Make Hermes telemetry detection more robust (also check HERMES_REAL_HOME, honor DO_NOT_TRACK) (#172)

shawn pana9da3387b54ad
diff --git a/install.md b/install.md
index 6ed679f..bd78bd4 100644
--- a/install.md
+++ b/install.md
@@ -122,7 +122,9 @@ 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. A
cloud iPhone is a third path: HTTPS ops, covered in the skill.
-`phone-harness config set telemetry false` turns off usage telemetry. Once you
+`phone-harness config set telemetry false` turns off usage telemetry, and so does
+`DO_NOT_TRACK=1` or `PHONE_HARNESS_TELEMETRY=0` in the environment. Under Hermes it
+is off unless you opt in with `phone-harness config set telemetry true`. Once you
sign in to Phone Harness Cloud, it is linked to your account.
## If It Fails
diff --git a/integrations/hermes/__init__.py b/integrations/hermes/__init__.py
index dc0cbb9..1772dbd 100644
--- a/integrations/hermes/__init__.py
+++ b/integrations/hermes/__init__.py
@@ -459,17 +459,19 @@ def _env(workspace: Path) -> dict:
Starts from Hermes's scrubbed subprocess env when that module imports, otherwise
from the process env minus ``*_API_KEY`` / ``*_TOKEN`` / ``*_SECRET``. Then sets
- the workspace and client, and puts back any ``PHONE_HARNESS_*`` the user exported.
- Telemetry stays off unless the user explicitly opted in.
+ the workspace and client, and puts back any ``PHONE_HARNESS_*`` the user exported,
+ and ``DO_NOT_TRACK``.
+
+ Telemetry stays off unless the user explicitly opted in. The child is told the answer
+ either way: Hermes can start it under another HOME, away from the config.json read here.
"""
env = _base_child_env()
for key, value in os.environ.items():
- if key.startswith("PHONE_HARNESS_"):
+ if key.startswith("PHONE_HARNESS_") or key == "DO_NOT_TRACK":
env[key] = value
env["PH_AGENT_WORKSPACE"] = str(workspace)
env["PH_CLIENT"] = "hermes"
- if not _telemetry_opted_in():
- env["PHONE_HARNESS_TELEMETRY"] = "0"
+ env["PHONE_HARNESS_TELEMETRY"] = "1" if _telemetry_opted_in() else "0"
return env
# ---------------------------------------------------------------------------------------------
diff --git a/integrations/openclaw/README.md b/integrations/openclaw/README.md
index 971d7cc..26a576b 100644
--- a/integrations/openclaw/README.md
+++ b/integrations/openclaw/README.md
@@ -29,6 +29,10 @@ OpenClaw shows what the plugin can do and asks you to accept it. A running
Gateway picks the plugin up straight away, so there is nothing to restart. The
first script fetches Phone Harness through uv, which takes a moment once.
+Phone Harness sends usage telemetry by default, including your script text and
+what scripts print. [Telemetry](#telemetry) says what is sent and how to turn it
+off.
+
Until the plugin is on ClawHub, install it from a checkout:
```bash
@@ -93,8 +97,7 @@ prompts, so a sender it knows is not the owner is refused before any prompt.
internals, runs an adb shell command, or calls `send("raw", ...)`. What to do on
the phone itself (sending, posting, buying, deleting, changing settings) is still
the skill's consent rule: the agent asks you first.
-- Telemetry is off for plugin runs unless you opt in with
- `phone-harness config set telemetry true`.
+- Telemetry is on by default. See [Telemetry](#telemetry).
- `PHONE_HARNESS_PLATFORM`, when you have exported it, is passed through.
- The agent workspace is `phone-harness/agent-workspace` in OpenClaw's state
directory, or `PH_AGENT_WORKSPACE` if that is set.
@@ -122,6 +125,42 @@ prompts, so a sender it knows is not the owner is refused before any prompt.
- A cloud phone streams its screen to Phone Harness Cloud and uses Phone Harness's
own cloud sign-in. A rented cloud Android bills by the minute.
+## Telemetry
+
+Telemetry is on by default. Phone Harness sends usage telemetry to PostHog
+(`us.i.posthog.com`). One event goes out after each `phone_exec` call and each
+`phone-harness` command. It holds:
+
+- The script text, up to 20,000 characters, including its `# task:` and `# step:` comments.
+- What the script printed, up to the last 20,000 characters. If a script prints
+ text from the phone's screen, that text is sent.
+- Each helper call and its arguments, up to 500 calls. Text a script types on the
+ phone is one of those arguments.
+- The command line, errors, exit code and run time.
+- A random install id, the Phone Harness, Python and OS versions, the kind of phone,
+ and the client (`openclaw`).
+- Once you sign in to Phone Harness Cloud: your account id and the cloud session id.
+ Calls to Phone Harness Cloud also carry the Phone Harness version and the client.
+
+Screenshots are not sent.
+
+To turn it off, use either of these on the machine that runs the Gateway:
+
+- `phone-harness config set telemetry false`. If `phone-harness` is not on your
+ PATH, run `uvx phone-harness config set telemetry false`. The setting is per
+ user, so run it as the user the Gateway runs as.
+- `DO_NOT_TRACK=1` in the Gateway's own environment. `PHONE_HARNESS_TELEMETRY=0`
+ does the same. A Gateway running as a service needs it set in the service, not
+ in your shell.
+
+With either one, Phone Harness sends no event and adds nothing to its calls to the
+cloud.
+
+A cloud phone is the one exception. Phone Harness Cloud keeps its own activity log
+of cloud sessions, tied to your account: each action and what it was asked to do,
+such as the text typed, the app or the URL. These settings do not change that log.
+Local phones are not in it.
+
## Limits
- The approval covers `phone_exec`. An agent that also has OpenClaw's `exec` tool
diff --git a/integrations/openclaw/package.json b/integrations/openclaw/package.json
index 24183c3..0d4f440 100644
--- a/integrations/openclaw/package.json
+++ b/integrations/openclaw/package.json
@@ -1,7 +1,7 @@
{
"name": "phone-harness",
"version": "0.1.0",
- "description": "Drive a real phone from OpenClaw with one phone_exec tool",
+ "description": "Drive a real phone from OpenClaw with one phone_exec tool. Sends usage telemetry, including script text and output, by default; DO_NOT_TRACK=1 turns it off.",
"type": "module",
"license": "MIT",
"homepage": "https://phone-harness.com",
diff --git a/integrations/openclaw/src/phone-exec.test.ts b/integrations/openclaw/src/phone-exec.test.ts
index 2e0793a..4f9466b 100644
--- a/integrations/openclaw/src/phone-exec.test.ts
+++ b/integrations/openclaw/src/phone-exec.test.ts
@@ -13,7 +13,6 @@ import {
PHONE_HARNESS_VERSION,
PhoneLock,
pinnedCommand,
- telemetryOptedIn,
type Env,
type ToolResult,
} from "./phone-exec.ts";
@@ -251,44 +250,19 @@ describe("the script's environment", () => {
});
describe("telemetry", () => {
- let home: string;
- const config = (body: string) => {
- mkdirSync(join(home, "config"), { recursive: true });
- writeFileSync(join(home, "config", "config.json"), body);
- };
- beforeEach(() => {
- home = mkdtempSync(join(tmpdir(), "ph-home-"));
- });
-
- it("stays off with no config", () => {
- assert.equal(telemetryOptedIn({ PHONE_HARNESS_HOME: home }), false);
- assert.equal(childEnv({ PHONE_HARNESS_HOME: home }, "/w").PHONE_HARNESS_TELEMETRY, "0");
- });
-
- it("stays off for a stored false, a broken file and a config without the key", () => {
- for (const body of ['{"telemetry": false}', "not json", '{"platform": "android"}', "[1]"]) {
- config(body);
- assert.equal(telemetryOptedIn({ PHONE_HARNESS_HOME: home }), false, body);
- }
- });
-
- it("follows an explicit opt-in", () => {
- config('{"telemetry": true}');
- assert.equal(telemetryOptedIn({ PHONE_HARNESS_HOME: home }), true);
- assert.equal(childEnv({ PHONE_HARNESS_HOME: home }, "/w").PHONE_HARNESS_TELEMETRY, undefined);
+ it("leaves the decision to Phone Harness, which defaults to on", () => {
+ assert.equal(childEnv({ PATH: "/usr/bin" }, "/w").PHONE_HARNESS_TELEMETRY, undefined);
});
- it("lets the variable win over the file, both ways", () => {
- config('{"telemetry": true}');
- assert.equal(telemetryOptedIn({ PHONE_HARNESS_HOME: home, PHONE_HARNESS_TELEMETRY: "0" }), false);
- config('{"telemetry": false}');
- assert.equal(telemetryOptedIn({ PHONE_HARNESS_HOME: home, PHONE_HARNESS_TELEMETRY: "true" }), true);
+ it("passes every opt-out through", () => {
+ const env = childEnv({ DO_NOT_TRACK: "1", PHONE_HARNESS_TELEMETRY: "0", PHONE_HARNESS_HOME: "/h" }, "/w");
+ assert.equal(env.DO_NOT_TRACK, "1");
+ assert.equal(env.PHONE_HARNESS_TELEMETRY, "0");
+ assert.equal(env.PHONE_HARNESS_HOME, "/h");
});
- it("reads the same folder phone-harness does", () => {
- mkdirSync(join(home, "phone-harness"));
- writeFileSync(join(home, "phone-harness", "config.json"), '{"telemetry": true}');
- assert.equal(telemetryOptedIn({ XDG_CONFIG_HOME: home }), true);
+ it("does not depend on the config file: Phone Harness reads it", () => {
+ assert.equal(childEnv({ XDG_CONFIG_HOME: "/nowhere" }, "/w").PHONE_HARNESS_TELEMETRY, undefined);
});
});
diff --git a/integrations/openclaw/src/phone-exec.ts b/integrations/openclaw/src/phone-exec.ts
index 5605abf..f10baed 100644
--- a/integrations/openclaw/src/phone-exec.ts
+++ b/integrations/openclaw/src/phone-exec.ts
@@ -7,7 +7,8 @@
* call is a fresh interpreter; the phone and the agent workspace persist.
*
* Safety that lives here:
- * - The child environment drops credentials, and telemetry stays off unless the user opted in.
+ * - The child environment drops credentials. Telemetry is Phone Harness's own, on by default
+ * like the CLI's, and DO_NOT_TRACK or `config set telemetry false` reach it unchanged.
* - One script drives the phone at a time, across subagents in this process.
* - A script past its timeout, or a cancelled call, is killed with everything it started.
*/
@@ -59,28 +60,6 @@ export function truthy(value: unknown): boolean {
return typeof value === "string" ? TRUTHY.has(value.trim().toLowerCase()) : Boolean(value);
}
-/** config.json, using the same directory rules as phone_harness.config.config_dir. */
-function configJson(env: Env): string {
- if (env.PHONE_HARNESS_HOME) return join(env.PHONE_HARNESS_HOME, "config", "config.json");
- return join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "phone-harness", "config.json");
-}
-
-/**
- * True only for an explicit opt-in: `phone-harness config set telemetry true` (a value stored in
- * config.json), or PHONE_HARNESS_TELEMETRY set to an enabling value. The built-in default is on
- * for the CLI and is not an opt-in. An explicit false stays off.
- */
-export function telemetryOptedIn(env: Env): boolean {
- const raw = env.PHONE_HARNESS_TELEMETRY;
- if (raw !== undefined) return truthy(raw);
- try {
- const data: unknown = JSON.parse(readFileSync(configJson(env), "utf8"));
- return typeof data === "object" && data !== null && "telemetry" in data && truthy(data.telemetry);
- } catch {
- return false;
- }
-}
-
/**
* Environment for the Phone Harness child.
*
@@ -100,7 +79,6 @@ export function childEnv(base: Env, workspace: string): Env {
env[pathKey] = [env[pathKey], join(homedir(), ".local", "bin")].filter(Boolean).join(delimiter);
env.PH_AGENT_WORKSPACE = workspace;
env.PH_CLIENT = "openclaw";
- if (!telemetryOptedIn(base)) env.PHONE_HARNESS_TELEMETRY = "0";
return env;
}
diff --git a/src/phone_harness/config.py b/src/phone_harness/config.py
index 293a36d..172eb9e 100644
--- a/src/phone_harness/config.py
+++ b/src/phone_harness/config.py
@@ -175,6 +175,16 @@ def save(data):
_write(paths()["config"], data)
+def config_unreadable():
+ """config.json exists and cannot be read, so what it says is unknown."""
+ try:
+ return not isinstance(json.loads(paths()["config"].read_text()), dict)
+ except FileNotFoundError:
+ return False
+ except (OSError, ValueError):
+ return True
+
+
# --- settings ----------------------------------------------------------------
def _dig(d, key):
@@ -211,6 +221,8 @@ def lookup(key, default=None):
return _coerce(os.environ[name], built_in), f"env:{name}"
v = _dig(load(), key)
if v is not None:
+ if isinstance(built_in, bool) and isinstance(v, str):
+ v = _coerce(v, built_in)
return v, "file"
if built_in is not None:
return built_in, "default"
@@ -224,13 +236,17 @@ def get(key, default=None):
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."""
+ built_in = _dig(DEFAULTS, key)
if isinstance(value, str):
- try:
- parsed = json.loads(value)
- if isinstance(parsed, (bool, int, float)) or parsed is None:
- value = parsed
- except ValueError:
- pass
+ if isinstance(built_in, bool):
+ value = _coerce(value, built_in)
+ else:
+ 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(".")
diff --git a/src/phone_harness/telemetry.py b/src/phone_harness/telemetry.py
index 808f9a9..0a614ae 100644
--- a/src/phone_harness/telemetry.py
+++ b/src/phone_harness/telemetry.py
@@ -12,9 +12,11 @@ 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. 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.
+Off: DO_NOT_TRACK=1, `phone-harness config set telemetry false`, or
+PHONE_HARNESS_TELEMETRY=0 for one call. Off sends no event, links no account
+and adds no header. Under Hermes it is off until the user opts in, whether the
+run came through phone_exec or a shell. The install id and the linked uid live
+in the state dir; see config.py.
"""
from __future__ import annotations
@@ -42,10 +44,6 @@ def _version() -> str:
return ""
-def is_enabled() -> bool:
- return bool(_config.get("telemetry"))
-
-
# Env markers each coding agent injects into subprocesses
_AGENT_ENV_MARKERS: tuple[tuple[str, str], ...] = (
("AGENT=amp", "amp"),
@@ -56,7 +54,9 @@ _AGENT_ENV_MARKERS: tuple[tuple[str, str], ...] = (
("COPILOT_CLI", "copilot-cli"),
("COPILOT_AGENT_SESSION_ID", "copilot-cli"),
("OPENCLAW_CLI", "openclaw"),
- ("HERMES_SESSION_ID", "hermes"),
+ ("HERMES_SESSION_ID", "hermes"), # only while a session is bound
+ ("HERMES_REAL_HOME", "hermes"), # on what it starts on its own machine
+ ("HERMES_AGENT", "hermes"), # on each command, also in a Docker or SSH backend
("CURSOR_AGENT", "cursor"),
("CURSOR_TRACE_ID", "cursor"),
("OPENCODE", "opencode"),
@@ -72,6 +72,27 @@ def _detect_agent_client() -> str | None:
return None
+def _do_not_track() -> bool:
+ return os.environ.get("DO_NOT_TRACK", "").strip().lower() not in ("", "0", "false", "no", "off")
+
+
+def _under_hermes() -> bool:
+ """Every marker counts, not the first that matches: another agent's can come first."""
+ return os.environ.get("PH_CLIENT") == "hermes" or any(
+ marker in os.environ for marker, client in _AGENT_ENV_MARKERS if client == "hermes")
+
+
+def is_enabled() -> bool:
+ """DO_NOT_TRACK, then the setting. A setting nobody chose is on, except under
+ Hermes, which is opt-in, and when config.json is unreadable: it may hold a no."""
+ if _do_not_track():
+ return False
+ value, source = _config.lookup("telemetry")
+ if source == "default":
+ return not (_under_hermes() or _config.config_unreadable())
+ return bool(value)
+
+
def _client() -> str | None:
"""Who drives this CLI: the integration that launched it (PH_CLIENT), else
the coding agent its environment names."""
diff --git a/tests/support/network_watch/sitecustomize.py b/tests/support/network_watch/sitecustomize.py
new file mode 100644
index 0000000..196441c
--- /dev/null
+++ b/tests/support/network_watch/sitecustomize.py
@@ -0,0 +1,36 @@
+"""Loaded into every Python process of a watched test (PYTHONPATH lists this folder), so the
+detached sender and any child a script starts are watched too.
+
+Logs each network attempt and process start to NETWORK_WATCH_LOG, and refuses anything off this
+machine: a stray send fails the test and reaches nobody. Never logs a payload, a header or the environment.
+"""
+import json
+import os
+import sys
+
+LOG = os.environ.get("NETWORK_WATCH_LOG")
+LOOPBACK = {"127.0.0.1", "::1", "localhost"}
+
+
+def note(kind, **fields):
+ if LOG:
+ with open(LOG, "a") as f:
+ f.write(json.dumps({"kind": kind, "pid": os.getpid(), **fields}) + "\n")
+
+
+def watch(event, args):
+ if event == "socket.connect" and isinstance(args[1], tuple):
+ note("connect", host=str(args[1][0]))
+ if args[1][0] not in LOOPBACK:
+ raise PermissionError("network_watch: off this machine")
+ elif event == "socket.getaddrinfo":
+ note("connect", host=str(args[0]))
+ if args[0] not in LOOPBACK:
+ raise PermissionError("network_watch: off this machine")
+ elif event == "subprocess.Popen":
+ argv = [str(a) for a in args[1] or []]
+ note("spawn", sender=len(argv) > 2 and argv[1] == "-c" and "urllib.request" in argv[2])
+
+
+sys.addaudithook(watch)
+note("start")
diff --git a/tests/test_cli.py b/tests/test_cli.py
index dab8f61..79fc1f3 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -474,7 +474,9 @@ class TelemetryDefault(unittest.TestCase):
from phone_harness.telemetry import is_enabled
with mock.patch.dict(os.environ, {"PHONE_HARNESS_HOME": home.name}, clear=False):
- os.environ.pop("PHONE_HARNESS_TELEMETRY", None)
+ for name in ("PHONE_HARNESS_TELEMETRY", "DO_NOT_TRACK", "PH_CLIENT",
+ "HERMES_SESSION_ID", "HERMES_REAL_HOME", "HERMES_AGENT"):
+ os.environ.pop(name, None)
# GitHub Actions sets CI=true, and this repo's workflow sets
# PHONE_HARNESS_TELEMETRY=0. This test is the ordinary default.
os.environ.pop("CI", None)
diff --git a/tests/test_cloud.py b/tests/test_cloud.py
index 97fe253..c8785a2 100644
--- a/tests/test_cloud.py
+++ b/tests/test_cloud.py
@@ -1316,7 +1316,7 @@ class CloudCli(unittest.TestCase):
self.addCleanup(server.server_close)
self.addCleanup(server.shutdown)
FakePostHog.events = []
- for name in AGENT_MARKERS:
+ for name in AGENT_MARKERS + ["DO_NOT_TRACK"]:
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}"})
@@ -1432,6 +1432,19 @@ class CloudCli(unittest.TestCase):
(script, "say hi", "through the pin", "42\n"))
self.assertEqual((ran["session_id"], ran["argv"]), (sid, None))
+ def test_do_not_track_sends_no_event_no_link_and_no_cloud_header(self):
+ self.posthog(client="openclaw") # telemetry forced on: DO_NOT_TRACK still wins
+ dnt = {"DO_NOT_TRACK": "1", "PHONE_HARNESS_ADB": "/nonexistent/adb"}
+ self.assertEqual(self.run_cli("cloud", "login", "--no-browser", env=dnt).returncode, 0)
+ self.assertEqual(self.run_cli("cloud", "ls", env=dnt).returncode, 0)
+ self.assertTrue(FakeCloud.requests)
+ for _, path, headers in FakeCloud.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())
+
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()
diff --git a/tests/test_config.py b/tests/test_config.py
new file mode 100644
index 0000000..8d0749b
--- /dev/null
+++ b/tests/test_config.py
@@ -0,0 +1,69 @@
+import json
+import os
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+SRC = str(Path(__file__).resolve().parents[1] / "src")
+if SRC not in sys.path:
+ sys.path.insert(0, SRC)
+
+from phone_harness import config, telemetry # noqa: E402
+
+
+class ConfigSetBooleanTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.config_dir = Path(self.tmp.name)
+ self.config_file = self.config_dir / "config.json"
+ patcher = patch.object(config, "config_dir", return_value=self.config_dir)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ env = patch.dict(os.environ) # CI sets PHONE_HARNESS_TELEMETRY=0
+ env.start()
+ self.addCleanup(env.stop)
+ for name in ("PHONE_HARNESS_TELEMETRY", "DO_NOT_TRACK", "PH_CLIENT",
+ "HERMES_SESSION_ID", "HERMES_REAL_HOME", "HERMES_AGENT"):
+ os.environ.pop(name, None)
+
+ def test_set_telemetry_off_coerces_to_boolean_false(self):
+ for off_val in ("off", "no", "false", "0"):
+ with self.subTest(value=off_val):
+ res = config.set("telemetry", off_val)
+ self.assertIs(res, False)
+ self.assertIs(config.get("telemetry"), False)
+ self.assertFalse(telemetry.is_enabled())
+ data = json.loads(self.config_file.read_text(encoding="utf-8"))
+ self.assertIs(data["telemetry"], False)
+
+ def test_set_telemetry_on_coerces_to_boolean_true(self):
+ for on_val in ("on", "yes", "true", "1"):
+ with self.subTest(value=on_val):
+ res = config.set("telemetry", on_val)
+ self.assertIs(res, True)
+ self.assertIs(config.get("telemetry"), True)
+ self.assertTrue(telemetry.is_enabled())
+ data = json.loads(self.config_file.read_text(encoding="utf-8"))
+ self.assertIs(data["telemetry"], True)
+
+ def test_lookup_coerces_stale_string_in_config_file(self):
+ self.config_file.write_text(json.dumps({"telemetry": "off"}), encoding="utf-8")
+ val, source = config.lookup("telemetry")
+ self.assertIs(val, False)
+ self.assertEqual(source, "file")
+ self.assertFalse(telemetry.is_enabled())
+
+ def test_cli_set_telemetry_prints_boolean(self):
+ out = []
+ with patch("builtins.print", side_effect=out.append):
+ code = config.cli(["set", "telemetry", "off"])
+ self.assertEqual(code, 0)
+ self.assertEqual(out, ["telemetry = false"])
+ self.assertIs(config.get("telemetry"), False)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_hermes_plugin.py b/tests/test_hermes_plugin.py
index 952e3df..73432c2 100644
--- a/tests/test_hermes_plugin.py
+++ b/tests/test_hermes_plugin.py
@@ -462,7 +462,9 @@ class TelemetryOptIn(Base):
super().setUp()
self.saved = dict(os.environ)
os.environ["PHONE_HARNESS_HOME"] = str(self.data)
- os.environ.pop("PHONE_HARNESS_TELEMETRY", None)
+ for name in ("PHONE_HARNESS_TELEMETRY", "DO_NOT_TRACK", "PH_CLIENT",
+ "HERMES_SESSION_ID", "HERMES_REAL_HOME", "HERMES_AGENT"):
+ os.environ.pop(name, None)
# GitHub Actions sets CI=true, and this repo's workflow sets
# PHONE_HARNESS_TELEMETRY=0. These checks are the ordinary opt-in rules,
# including the child process.
@@ -503,9 +505,36 @@ class TelemetryOptIn(Base):
set_config("telemetry", "true")
env = self.plugin._env(self.data / "ws")
- self.assertNotIn("PHONE_HARNESS_TELEMETRY", env)
+ self.assertEqual(env["PHONE_HARNESS_TELEMETRY"], "1")
self.assertTrue(self.child_enabled())
+ def test_a_stored_true_reaches_a_child_with_another_home(self):
+ from phone_harness.config import set as set_config
+
+ set_config("telemetry", "true")
+ env = self.plugin._env(self.data / "ws")
+ env.pop("PHONE_HARNESS_HOME")
+ env["HOME"] = str(self.data / "profile-home")
+ env["PYTHONPATH"] = str(SRC)
+ proc = subprocess.run(
+ [sys.executable, "-c", "from phone_harness.telemetry import is_enabled; print(is_enabled())"],
+ capture_output=True, text=True, env=env, check=True,
+ )
+ self.assertEqual(proc.stdout.strip(), "True")
+
+ def test_do_not_track_reaches_the_child_and_beats_a_stored_true(self):
+ from phone_harness.config import set as set_config
+
+ set_config("telemetry", "true")
+ os.environ["DO_NOT_TRACK"] = "1"
+ self.assertEqual(self.plugin._env(self.data / "ws")["DO_NOT_TRACK"], "1")
+ self.assertFalse(self.child_enabled())
+
+ def test_do_not_track_survives_the_hermes_env_helper(self):
+ sys.modules["tools.environments.local"].hermes_subprocess_env = lambda: {"PATH": "/from-hermes"}
+ os.environ["DO_NOT_TRACK"] = "1"
+ self.assertEqual(self.plugin._env(self.data / "ws")["DO_NOT_TRACK"], "1")
+
def test_an_explicit_stored_false_is_off(self):
from phone_harness.config import set as set_config
from phone_harness.telemetry import is_enabled
@@ -519,7 +548,7 @@ class TelemetryOptIn(Base):
def test_an_enabling_env_var_is_on(self):
os.environ["PHONE_HARNESS_TELEMETRY"] = "true"
env = self.plugin._env(self.data / "ws")
- self.assertEqual(env["PHONE_HARNESS_TELEMETRY"], "true")
+ self.assertEqual(env["PHONE_HARNESS_TELEMETRY"], "1")
self.assertTrue(self.child_enabled())
def test_a_disabling_env_var_is_off(self):
diff --git a/tests/test_openclaw_plugin.py b/tests/test_openclaw_plugin.py
index 53f1bb4..73854ec 100644
--- a/tests/test_openclaw_plugin.py
+++ b/tests/test_openclaw_plugin.py
@@ -208,8 +208,23 @@ class Readme(unittest.TestCase):
self.assertIn("heuristic", text)
self.assertIn("bypassed", text)
- def test_says_telemetry_is_opt_in(self):
- self.assertIn("phone-harness config set telemetry true", (PLUGIN / "README.md").read_text(encoding="utf-8"))
+ def test_says_what_telemetry_sends_and_how_to_turn_it_off(self):
+ text = (PLUGIN / "README.md").read_text(encoding="utf-8")
+ for phrase in ("on by default", "us.i.posthog.com", "script text", "printed", "arguments",
+ "`phone-harness config set telemetry false`",
+ "`uvx phone-harness config set telemetry false`", "`DO_NOT_TRACK=1`",
+ "Gateway's own environment"):
+ self.assertIn(phrase, text)
+
+ def test_the_listing_summary_names_telemetry_and_the_way_out(self):
+ summary = json.loads((PLUGIN / "package.json").read_text(encoding="utf-8"))["description"]
+ self.assertIn("telemetry", summary)
+ self.assertIn("DO_NOT_TRACK=1", summary)
+
+ def test_no_posthog_key_ships_in_the_plugin(self):
+ for path in PLUGIN.rglob("*"):
+ if path.is_file() and "node_modules" not in path.parts:
+ self.assertNotIn(b"phc_", path.read_bytes(), path.name)
class NodeSuite(unittest.TestCase):
diff --git a/tests/test_telemetry.py b/tests/test_telemetry.py
index 3337a8c..e05ac91 100644
--- a/tests/test_telemetry.py
+++ b/tests/test_telemetry.py
@@ -30,7 +30,7 @@ class Telemetry(unittest.TestCase):
"PHONE_HARNESS_TELEMETRY": "1"})
env.start()
self.addCleanup(env.stop)
- for name in AGENT_MARKERS + ["PH_CLIENT", "PH_CLIENT_VERSION"]:
+ for name in AGENT_MARKERS + ["PH_CLIENT", "PH_CLIENT_VERSION", "DO_NOT_TRACK"]:
os.environ.pop(name, None)
self.sent = []
sender = mock.patch.object(telemetry, "_send_detached", self.sent.append)
@@ -44,14 +44,15 @@ class Telemetry(unittest.TestCase):
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())
+ for off in ({"PHONE_HARNESS_TELEMETRY": "0"}, {"DO_NOT_TRACK": "1"}):
+ with self.subTest(off), mock.patch.dict(os.environ, off):
+ 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()
diff --git a/tests/test_telemetry_network.py b/tests/test_telemetry_network.py
new file mode 100644
index 0000000..7b9d2c1
--- /dev/null
+++ b/tests/test_telemetry_network.py
@@ -0,0 +1,369 @@
+"""Opted out means nothing leaves the machine.
+
+The real CLI, in a process tree watched by tests/support/network_watch: every network attempt
+and every process start is logged, and anything off this machine is refused, so a stray send
+fails a test here and never reaches PostHog. A fake PostHog takes what is allowed through.
+
+ python -m unittest tests.test_telemetry_network
+"""
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+import unittest
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+SRC = str(ROOT / "src")
+if SRC not in sys.path:
+ sys.path.insert(0, SRC)
+
+from phone_harness.telemetry import POSTHOG_HOST # noqa: E402
+
+WATCH = str(ROOT / "tests" / "support" / "network_watch")
+HERMES_PLUGIN = ROOT / "integrations" / "hermes" / "__init__.py"
+OPENCLAW_PHONE_EXEC = ROOT / "integrations" / "openclaw" / "src" / "phone-exec.ts"
+
+# One of each way a run can end. Each sends one cli_event when telemetry is on.
+RUNS = (
+ ([], "print('hello')\n"),
+ ([], "raise RuntimeError('boom')\n"),
+ ([], "import sys; sys.exit(3)\n"),
+ (["--version"], None),
+ (["config"], None),
+ (["no-such-command"], None),
+)
+OFF_ENV = (
+ {"PHONE_HARNESS_TELEMETRY": "0"},
+ {"PHONE_HARNESS_TELEMETRY": "false"},
+ {"PHONE_HARNESS_TELEMETRY": "no"},
+ {"PHONE_HARNESS_TELEMETRY": "off"},
+ {"PHONE_HARNESS_TELEMETRY": ""},
+ {"PHONE_HARNESS_TELEMETRY": "junk"},
+ {"DO_NOT_TRACK": "1"},
+ {"DO_NOT_TRACK": "true"},
+ {"DO_NOT_TRACK": "yes"},
+ {"DO_NOT_TRACK": "1", "PHONE_HARNESS_TELEMETRY": "1"},
+)
+HERMES_MARKS = (
+ {"HERMES_SESSION_ID": "s1"},
+ {"HERMES_SESSION_ID": ""},
+ {"HERMES_REAL_HOME": "/home/me"},
+ {"HERMES_AGENT": "true"}, # all a Docker or SSH backend carries
+ {"PH_CLIENT": "hermes"},
+ {"HERMES_REAL_HOME": "/home/me", "CLAUDECODE": "1"}, # another agent's marker comes first
+)
+
+
+def node_major():
+ node = shutil.which("node")
+ if not node:
+ return None
+ version = subprocess.run([node, "--version"], capture_output=True, text=True, check=False).stdout
+ return int(version.strip().lstrip("v").split(".")[0] or 0)
+
+
+class FakePostHog(BaseHTTPRequestHandler):
+ def log_message(self, *a):
+ pass
+
+ def do_POST(self):
+ body = self.rfile.read(int(self.headers.get("Content-Length") or 0))
+ self.server.events.append(json.loads(body or b"{}"))
+ self.send_response(200)
+ self.send_header("Content-Length", "0")
+ self.end_headers()
+
+ do_GET = do_POST # where a feature flag call would land
+
+
+class Watched(unittest.TestCase):
+ def setUp(self):
+ self.server = ThreadingHTTPServer(("127.0.0.1", 0), FakePostHog)
+ threading.Thread(target=self.server.serve_forever, daemon=True).start()
+ self.addCleanup(self.server.server_close)
+ self.addCleanup(self.server.shutdown)
+ self.fresh_machine()
+
+ def fresh_machine(self):
+ tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(tmp.cleanup)
+ self.home = Path(tmp.name)
+ self.log = self.home / "network-watch.jsonl"
+ self.server.events = []
+
+ def env(self, **extra):
+ return {"PATH": os.environ.get("PATH", ""), "HOME": str(self.home), "LANG": "C.UTF-8",
+ "PYTHONPATH": WATCH + os.pathsep + SRC, "NETWORK_WATCH_LOG": str(self.log),
+ "PH_POSTHOG_HOST": f"http://127.0.0.1:{self.server.server_port}",
+ "PHONE_HARNESS_PLATFORM": "android", "PHONE_HARNESS_ADB": "/nonexistent/adb", **extra}
+
+ def run_cli(self, *args, stdin=None, **extra):
+ return subprocess.run([sys.executable, "-m", "phone_harness.run", *args], input=stdin,
+ capture_output=True, text=True, timeout=60, env=self.env(**extra))
+
+ def run_each_way(self, **extra):
+ for args, stdin in RUNS:
+ self.run_cli(*args, stdin=stdin, **extra)
+
+ def stored(self, body):
+ path = self.home / ".config" / "phone-harness" / "config.json"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(body)
+
+ def choose(self, word):
+ """What the user typed, with its own run left out of what a test watches."""
+ result = self.run_cli("config", "set", "telemetry", word, PHONE_HARNESS_TELEMETRY="0",
+ NETWORK_WATCH_LOG=os.devnull)
+ self.assertEqual(result.returncode, 0, result.stderr)
+
+ def watched(self, *kinds):
+ lines = self.log.read_text().splitlines() if self.log.exists() else []
+ return [w for w in map(json.loads, lines) if w["kind"] in kinds]
+
+ def sent(self, count):
+ """The events that reached PostHog, once `count` have or the deadline passes."""
+ deadline = time.monotonic() + 15
+ while len(self.server.events) < count and time.monotonic() < deadline:
+ time.sleep(0.05)
+ return self.server.events
+
+ def assert_nothing_left(self):
+ """A sender is started before the CLI exits, so this needs no wait for a detached one."""
+ self.assertTrue(self.watched("start"), "the watch did not load")
+ self.assertEqual([w for w in self.watched("spawn") if w["sender"]], [])
+ self.assertEqual(self.watched("connect"), [])
+ self.assertEqual(self.server.events, [])
+ self.assertFalse((self.home / ".local" / "state" / "phone-harness" / "telemetry.json").exists(),
+ "an install id was minted")
+
+
+class Cli(Watched):
+ def test_the_default_sends_which_is_what_gives_every_zero_here_its_meaning(self):
+ self.run_each_way()
+ events = self.sent(len(RUNS))
+ self.assertEqual([e["event"] for e in events], ["cli_event"] * len(RUNS))
+ self.assertEqual(sum(w["sender"] for w in self.watched("spawn")), len(RUNS))
+ self.assertTrue(self.watched("connect"))
+
+ def test_the_watch_sees_the_real_host_and_stops_it(self):
+ env = self.env()
+ env.pop("PH_POSTHOG_HOST")
+ subprocess.run([sys.executable, "-m", "phone_harness.run", "--version"], env=env, capture_output=True)
+ host = POSTHOG_HOST.split("://")[1]
+ deadline = time.monotonic() + 15
+ while time.monotonic() < deadline and not any(w["host"] == host for w in self.watched("connect")):
+ time.sleep(0.05)
+ self.assertIn(host, [w["host"] for w in self.watched("connect")])
+
+ def test_each_opt_out_in_the_environment_sends_nothing(self):
+ for off in OFF_ENV:
+ with self.subTest(off):
+ self.fresh_machine()
+ self.run_each_way(**off)
+ self.assert_nothing_left()
+
+ def test_each_way_of_saying_no_to_config_set_sends_nothing(self):
+ for word in ("false", "False", "off", "no", "0", "disabled"):
+ with self.subTest(word):
+ self.fresh_machine()
+ self.choose(word)
+ self.run_each_way()
+ self.assert_nothing_left()
+
+ def test_the_opt_out_command_sends_nothing_itself(self):
+ self.assertEqual(self.run_cli("config", "set", "telemetry", "false").returncode, 0)
+ self.assert_nothing_left()
+
+ def test_a_no_already_stored_as_text_sends_nothing(self):
+ for body in ('{"telemetry": "false"}', '{"telemetry": "off"}'):
+ with self.subTest(body):
+ self.fresh_machine()
+ self.stored(body)
+ self.run_each_way()
+ self.assert_nothing_left()
+
+ def test_a_config_file_that_cannot_be_read_sends_nothing(self):
+ for body in ('{"telemetry": false,}', "[1]", "not json"):
+ with self.subTest(body):
+ self.fresh_machine()
+ self.stored(body)
+ self.run_each_way()
+ self.assert_nothing_left()
+
+ def test_do_not_track_beats_a_stored_yes(self):
+ self.choose("true")
+ self.run_each_way(DO_NOT_TRACK="1")
+ self.assert_nothing_left()
+
+ def test_do_not_track_in_the_workspace_env_file_counts(self):
+ workspace = self.home / "workspace"
+ workspace.mkdir()
+ (workspace / ".env").write_text("DO_NOT_TRACK=1\n")
+ self.run_each_way(PH_AGENT_WORKSPACE=str(workspace))
+ self.assert_nothing_left()
+
+ def test_a_do_not_track_of_zero_or_nothing_is_no_opt_out(self):
+ for value in ("0", ""):
+ with self.subTest(value):
+ self.fresh_machine()
+ self.run_cli("--version", DO_NOT_TRACK=value)
+ self.assertEqual(len(self.sent(1)), 1)
+
+ def test_a_child_a_script_starts_inherits_the_opt_out(self):
+ script = ("import subprocess, sys\n"
+ "subprocess.run([sys.executable, '-m', 'phone_harness.run', '--version'], check=True)\n"
+ "subprocess.run([sys.executable, '-m', 'phone_harness.run', 'config'], check=True)\n"
+ "print('children done')\n")
+ for off in ({"DO_NOT_TRACK": "1"}, {"PHONE_HARNESS_TELEMETRY": "0"}):
+ with self.subTest(off):
+ self.fresh_machine()
+ result = self.run_cli(stdin=script, **off)
+ self.assertIn("children done", result.stdout, result.stderr)
+ self.assert_nothing_left()
+
+ def test_importing_the_cli_starts_nothing(self):
+ probe = ("import atexit, sys, threading\n"
+ "hooks = sys.excepthook, threading.excepthook\n"
+ "exits = atexit._ncallbacks()\n"
+ "import phone_harness.run, phone_harness.cloud, phone_harness.remote, phone_harness.helpers\n"
+ "assert atexit._ncallbacks() == exits, 'an atexit flush'\n"
+ "assert (sys.excepthook, threading.excepthook) == hooks, 'exception autocapture'\n"
+ "assert threading.active_count() == 1, 'a background thread'\n"
+ "assert not [m for m in sys.modules if 'posthog' in m.lower()], 'an analytics client'\n")
+ result = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True, env=self.env())
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(self.watched("connect", "spawn"), [])
+
+
+class Hermes(Watched):
+ """Opt-in, however the CLI was reached."""
+
+ def phone_exec(self, code, child_home=None, **extra):
+ driver = ("import importlib.util, os, sys, types\n"
+ f"child_home = {child_home!r}\n"
+ "if child_home:\n"
+ " local = types.ModuleType('tools.environments.local')\n"
+ " local.hermes_subprocess_env = lambda: {**os.environ, 'HOME': child_home}\n"
+ " sys.modules.update({'tools': types.ModuleType('tools'),\n"
+ " 'tools.environments': types.ModuleType('tools.environments'),\n"
+ " 'tools.environments.local': local})\n"
+ f"spec = importlib.util.spec_from_file_location('ph_hermes', {str(HERMES_PLUGIN)!r})\n"
+ "plugin = importlib.util.module_from_spec(spec)\n"
+ "sys.modules['ph_hermes'] = plugin\n"
+ "spec.loader.exec_module(plugin)\n"
+ f"print(plugin.phone_exec({{'code': {code!r}}}))\n")
+ result = subprocess.run([sys.executable, "-c", driver], capture_output=True, text=True, timeout=60,
+ env=self.env(**extra))
+ self.assertIn("ran", result.stdout, result.stderr)
+
+ def test_a_shell_call_sends_nothing_until_the_user_opts_in(self):
+ for marks in HERMES_MARKS:
+ with self.subTest(marks):
+ self.fresh_machine()
+ self.run_each_way(**marks)
+ self.assert_nothing_left()
+
+ def test_a_shell_call_sends_once_the_user_opted_in(self):
+ for marks in ({"HERMES_SESSION_ID": "s1"}, {"HERMES_REAL_HOME": "/home/me"}, {"HERMES_AGENT": "true"}):
+ with self.subTest(marks):
+ self.fresh_machine()
+ self.choose("true")
+ self.run_cli("--version", **marks)
+ [event] = self.sent(1)
+ self.assertEqual(event["properties"]["client"], "hermes")
+
+ def test_a_stored_no_and_do_not_track_hold_after_marks_too(self):
+ self.choose("false")
+ self.run_each_way(HERMES_REAL_HOME="/home/me")
+ self.fresh_machine()
+ self.choose("true")
+ self.run_each_way(HERMES_REAL_HOME="/home/me", DO_NOT_TRACK="1")
+ self.assert_nothing_left()
+
+ def test_phone_exec_sends_nothing_by_default(self):
+ self.phone_exec("print('ran')\n")
+ self.assert_nothing_left()
+
+ def test_phone_exec_sends_after_an_opt_in(self):
+ self.choose("true")
+ self.phone_exec("print('ran')\n")
+ [event] = self.sent(1)
+ self.assertEqual(event["properties"]["client"], "hermes")
+ self.assertEqual(event["properties"]["task"], "print('ran')\n")
+
+ def test_phone_exec_keeps_the_opt_in_when_hermes_moves_the_childs_home(self):
+ moved = self.home / "profile-home"
+ moved.mkdir()
+ self.choose("true")
+ self.phone_exec("print('ran')\n", child_home=str(moved))
+ self.assertEqual(len(self.sent(1)), 1)
+
+ def test_do_not_track_beats_an_opt_in_in_phone_exec(self):
+ self.choose("true")
+ self.phone_exec("print('ran')\n", DO_NOT_TRACK="1")
+ self.assert_nothing_left()
+
+ def test_a_child_of_a_phone_exec_script_inherits_the_no(self):
+ script = ("import subprocess, sys\n"
+ "subprocess.run([sys.executable, '-m', 'phone_harness.run', '--version'], check=True)\n"
+ "print('ran')\n")
+ self.phone_exec(script)
+ self.assert_nothing_left()
+
+
+class OnByDefault(Watched):
+ """The Claude and Codex skills, and OpenClaw, are opt-out like the plain CLI."""
+
+ def test_the_skills_and_openclaw_send_by_default_and_honour_an_opt_out(self):
+ for client, marks in (("claude-code", {"CLAUDECODE": "1"}), ("codex", {"CODEX_THREAD_ID": "t"}),
+ ("openclaw", {"PH_CLIENT": "openclaw"}), ("openclaw", {"OPENCLAW_CLI": "1"})):
+ with self.subTest(client=client, marks=marks):
+ self.fresh_machine()
+ self.run_cli("--version", **marks)
+ [event] = self.sent(1)
+ self.assertEqual(event["properties"]["client"], client)
+ self.fresh_machine()
+ self.choose("false")
+ self.run_each_way(**marks)
+ self.fresh_machine()
+ self.run_each_way(DO_NOT_TRACK="1", **marks)
+ self.assert_nothing_left()
+
+ @unittest.skipUnless((node_major() or 0) >= 24, "needs Node 24 or newer")
+ def test_the_openclaw_plugin_sends_by_default_and_honours_an_opt_out(self):
+ driver = (f"import {{ phoneExec }} from {json.dumps(str(OPENCLAW_PHONE_EXEC))};\n"
+ "const command = { file: process.env.PY, args: ['-m', 'phone_harness.run'] };\n"
+ "const result = await phoneExec({ code: \"print('ran')\\n\" },\n"
+ " { env: { ...process.env }, workspace: process.env.HOME + '/ws', command });\n"
+ "console.log(JSON.stringify(result.content));\n")
+
+ def phone_exec(**extra):
+ result = subprocess.run(["node", "--no-warnings", "--input-type=module", "-e", driver],
+ capture_output=True, text=True, timeout=60,
+ env=self.env(PY=sys.executable, **extra))
+ self.assertIn("ran", result.stdout, result.stderr)
+
+ phone_exec()
+ [event] = self.sent(1)
+ self.assertEqual((event["properties"]["client"], event["properties"]["task"]), ("openclaw", "print('ran')\n"))
+ self.fresh_machine()
+ phone_exec(DO_NOT_TRACK="1")
+ self.assert_nothing_left()
+ self.fresh_machine()
+ self.choose("false")
+ phone_exec()
+ self.assert_nothing_left()
+ self.fresh_machine()
+ self.choose("true")
+ phone_exec(DO_NOT_TRACK="1")
+ self.assert_nothing_left()
+
+
+if __name__ == "__main__":
+ unittest.main()