Skip to content

let your agent control your phone

Seed the agent workspace from the wheel without overwriting edits (#114)

shawn panac1baf9a5422f
diff --git a/README.md b/README.md
index 72fc468..9227d3a 100644
--- a/README.md
+++ b/README.md
@@ -57,6 +57,11 @@ PY
Helpers are pre-imported. [SKILL.md](SKILL.md) is the agent's day-to-day
guide; [helpers.py](src/phone_harness/helpers.py) is the full list.
+Task-specific helpers live in `agent-workspace/agent_helpers.py` in a
+checkout. A pip or uv install uses `~/.phone-harness/agent-workspace`
+(see [install.md](install.md)), creates it from the packaged defaults
+when it is missing, and never overwrites an existing one. Delete that
+folder for a fresh default; the next run recreates it.
## No phone on your desk? Rent one
diff --git a/SKILL.md b/SKILL.md
index 8108b73..32075b2 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -67,7 +67,15 @@ PY
faster than a call per turn. Keep one cheap check at the end.
4. When a check fails, isolate: re-run that one action, look at the screen,
form one guess, test it. Do not re-run the batch hoping it lands.
- 5. Keep what you learn in `agent-workspace/agent_helpers.py`.
+ 5. Keep what you learn in the agent workspace's `agent_helpers.py`.
+ A checkout uses `agent-workspace/`. A pip or uv install uses
+ `~/.phone-harness/agent-workspace`, or
+ `~/.local/share/phone-harness/agent-workspace` when
+ `~/.phone-harness` is a git checkout, so an upgrade does not wipe
+ it. `PH_AGENT_WORKSPACE` overrides that path. The directory is
+ created from the defaults only when it is missing. An existing
+ workspace is never overwritten. To get a fresh default, delete the
+ workspace folder; it is recreated on the next run.
- **The harness reports, you decide.** Helpers return observations, never a
verdict on your intent. Diff two `ocr()` sets, watch one label, count rows,
poll until something appears - whatever matches what you asked for.
@@ -394,5 +402,11 @@ events into it for hands. All coordinates are global macOS screen points.
path, and where they land is its own question per event type. Check what
actually happened on screen rather than assuming the event arrived.
-For task-specific edits, use `agent-workspace/agent_helpers.py`. For setup or
-permission problems, read `install.md`.
+For task-specific edits, use the agent workspace's `agent_helpers.py`:
+`agent-workspace/` in a checkout, `~/.phone-harness/agent-workspace` for
+a pip or uv install (or `~/.local/share/phone-harness/agent-workspace`
+when `~/.phone-harness` is a git checkout). `PH_AGENT_WORKSPACE`
+overrides that. Installs seed that directory from the packaged defaults
+when it does not exist yet; an existing workspace is left as it is.
+To get a fresh default, delete the workspace folder; it is recreated
+on the next run. For setup or permission problems, read `install.md`.
diff --git a/install.md b/install.md
index c60345a..c813347 100644
--- a/install.md
+++ b/install.md
@@ -25,8 +25,17 @@ phone-harness skill > "${CODEX_HOME:-$HOME/.codex}/skills/phone-harness/SKILL.md
- Python 3.10+, any OS. **iPhone Mirroring needs a Mac.** A cloud iPhone
(`cloud start` of the iOS catalog entry) is driven over HTTPS from any OS.
**Android works on macOS, Linux and Windows** and is the default off a Mac.
- Only the CLI? `pip install phone-harness` works too; the
- checkout is what makes the harness editable (`agent-workspace/agent_helpers.py`).
+ Only the CLI? `pip install phone-harness` works too. Helpers you add
+ live outside the install, so an upgrade does not wipe them. The
+ directory is `~/.phone-harness/agent-workspace`, unless
+ `~/.phone-harness` is a git checkout (the clone above), in which case
+ it is `~/.local/share/phone-harness/agent-workspace` (`XDG_DATA_HOME`
+ if that is set). The same paths are used on every OS. A checkout of
+ this repo keeps using its own `agent-workspace/`. `PH_AGENT_WORKSPACE`
+ overrides all of these. The first run copies the packaged defaults
+ when that directory does not exist. An existing workspace is left
+ untouched, including a custom `agent_helpers.py`. To get a fresh
+ default, delete the workspace folder; it is recreated on the next run.
- The default phone is `phone-harness config set platform ios|android`;
`phone-harness config` shows every setting and where it came from;
`PHONE_HARNESS_PLATFORM=android phone-harness …` overrides for one call.
diff --git a/pyproject.toml b/pyproject.toml
index da94e33..f03c35a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -40,10 +40,13 @@ build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["src/phone_harness"]
-# The skill text ships inside the package so `phone-harness skill` works
-# from an installed wheel, not only from a checkout.
+# Shipped inside the package so an install works without a checkout.
+# agent-workspace/ stays the only copy in the repo; the wheel maps its
+# default file to phone_harness/agent_workspace/. Only that file is
+# packed: a .env or scratch file beside it must never ride along.
[tool.hatch.build.targets.wheel.force-include]
"SKILL.md" = "phone_harness/SKILL.md"
+"agent-workspace/agent_helpers.py" = "phone_harness/agent_workspace/agent_helpers.py"
[tool.hatch.build.targets.sdist]
-include = ["src/phone_harness", "SKILL.md", "onboarding.md", "README.md", "LICENSE", "install.md"]
+include = ["src/phone_harness", "SKILL.md", "onboarding.md", "README.md", "LICENSE", "install.md", "agent-workspace/agent_helpers.py"]
diff --git a/src/phone_harness/config.py b/src/phone_harness/config.py
index fb0f240..cc22903 100644
--- a/src/phone_harness/config.py
+++ b/src/phone_harness/config.py
@@ -22,9 +22,13 @@ One rule for every setting: explicit argument, else environment variable,
else config file, else built-in default. A `.env` file at the repo root or
in the agent workspace is read once at import and fills in environment
variables that are not already set (the same as browser-harness): a place
-for per-machine overrides such as PHONE_HARNESS_CLOUD_API, never committed. `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.
+for per-machine overrides such as PHONE_HARNESS_CLOUD_API, never committed.
+Resolving that workspace creates it from the packaged defaults when the
+directory does not exist; an existing directory is not modified. An
+install keeps it under the home directory, not the install prefix.
+`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
@@ -44,8 +48,12 @@ _REPO_ROOT = Path(__file__).resolve().parent.parent.parent
def _load_env_files():
"""KEY=value lines from <repo>/.env and <agent-workspace>/.env into the
environment, without overriding what is already set. No dependency; a
- `#` line is a comment, quotes around a value are stripped."""
- workspace = Path(os.environ.get("PH_AGENT_WORKSPACE", _REPO_ROOT / "agent-workspace"))
+ `#` line is a comment, quotes around a value are stripped.
+
+ The workspace path is the same one the helpers use, so a missing
+ directory is seeded before its `.env` is read."""
+ from .workspace import agent_workspace
+ workspace = agent_workspace()
for path in (_REPO_ROOT / ".env", workspace / ".env"):
try:
text = path.read_text(encoding="utf-8-sig")
diff --git a/src/phone_harness/helpers.py b/src/phone_harness/helpers.py
index 641d45f..65f2b90 100644
--- a/src/phone_harness/helpers.py
+++ b/src/phone_harness/helpers.py
@@ -1,7 +1,12 @@
"""Phone control — one flat API over any device.
Core helpers live here. Agent-editable helpers live in
-PH_AGENT_WORKSPACE/agent_helpers.py (defaults to <repo>/agent-workspace).
+PH_AGENT_WORKSPACE/agent_helpers.py. A checkout uses
+<repo>/agent-workspace. A pip or uv install uses
+~/.phone-harness/agent-workspace, or
+~/.local/share/phone-harness/agent-workspace when ~/.phone-harness is
+itself a git checkout. That directory is created from the packaged
+defaults when it is missing; an existing one is left alone.
Everything below is a thin wrapper over send(), which is defined first on
purpose: the helpers are conveniences, not a wall. Drop to send() for anything
@@ -13,16 +18,16 @@ live inside one backend each, behind the ops documented in transport.py, so
`nav.home` and `screen.text` mean the same thing everywhere even though an
iPhone answers them with a Cmd+1 keystroke and Vision OCR.
"""
-import hashlib, importlib.util, os, time
+import hashlib, importlib.util, time
from pathlib import Path
from . import transport
from .transport import Unsupported # re-exported for agent scripts
+from .workspace import agent_workspace, repo_root
CORE_DIR = Path(__file__).resolve().parent
-REPO_ROOT = CORE_DIR.parent.parent
-AGENT_WORKSPACE = Path(
- os.environ.get("PH_AGENT_WORKSPACE", REPO_ROOT / "agent-workspace"))
+REPO_ROOT = repo_root()
+AGENT_WORKSPACE = agent_workspace()
# The default device. connect() returns a fresh backend, so a script needing
# two phones at once can hold them side by side instead of being limited to
diff --git a/src/phone_harness/workspace.py b/src/phone_harness/workspace.py
new file mode 100644
index 0000000..b1a5f01
--- /dev/null
+++ b/src/phone_harness/workspace.py
@@ -0,0 +1,179 @@
+"""Default helpers an agent can edit, and how an install gets them.
+
+The repo's ``agent-workspace/agent_helpers.py`` is the only copy of the
+default helper. The wheel force-includes that file at
+``phone_harness/agent_workspace/agent_helpers.py``.
+
+Resolution:
+
+ PH_AGENT_WORKSPACE if set, else
+ <repo>/agent-workspace when this package sits in a git checkout
+ (that directory contains ``.git`` and ``agent-workspace/``), else
+ ~/.phone-harness/agent-workspace, unless ~/.phone-harness is itself a
+ git checkout, in which case
+ $XDG_DATA_HOME/phone-harness/agent-workspace, or
+ ~/.local/share/phone-harness/agent-workspace when XDG_DATA_HOME is unset.
+
+The last two are outside any install prefix, so a pip or uv upgrade does
+not wipe helpers an agent added. The same path is used on every OS.
+
+A missing directory is created from that default. An existing directory
+is never modified, even if it is only partly filled in. To get a fresh
+default, delete the workspace folder; it is recreated on the next run.
+"""
+import os
+import shutil
+import sys
+import tempfile
+from pathlib import Path
+
+_SKIPPED_NAMES = {".env", ".DS_Store", "__pycache__"}
+
+
+def repo_root():
+ """Two parents above this package.
+
+ In a checkout that is the repo root. In a pip or uv install it lands
+ inside the prefix (``lib/pythonX.Y``), which is not a place to store
+ helpers: that tree is replaced on upgrade.
+ """
+ return Path(__file__).resolve().parent.parent.parent
+
+
+def _is_git_checkout(path):
+ """True when ``path`` is a git work tree. ``.git`` may be a file."""
+ return (path / ".git").exists()
+
+
+def _user_agent_workspace():
+ """Per-user workspace, never inside an install prefix.
+
+ ``~/.phone-harness`` is the canonical clone (see install.md). When that
+ path is a checkout, its ``agent-workspace/`` belongs to the checkout;
+ an install uses the data directory instead of writing into the clone.
+ """
+ canonical = Path.home() / ".phone-harness"
+ if not _is_git_checkout(canonical):
+ return canonical / "agent-workspace"
+ base = os.environ.get("XDG_DATA_HOME")
+ root = Path(base) if base else Path.home() / ".local" / "share"
+ return root / "phone-harness" / "agent-workspace"
+
+
+def resolved_agent_workspace():
+ """Where agent helpers live.
+
+ ``PH_AGENT_WORKSPACE`` if set (an empty value is honoured; the default
+ applies only when the variable is unset). Otherwise the checkout's
+ ``agent-workspace/`` when this package is running from one, otherwise
+ the per-user directory from ``_user_agent_workspace``.
+ """
+ if "PH_AGENT_WORKSPACE" in os.environ:
+ return Path(os.environ["PH_AGENT_WORKSPACE"])
+ root = repo_root()
+ if _is_git_checkout(root) and (root / "agent-workspace").is_dir():
+ return root / "agent-workspace"
+ return _user_agent_workspace()
+
+
+def packaged_defaults():
+ """Default workspace files.
+
+ An installed wheel has them inside the package. A checkout does not;
+ the repo directory is that same source of truth, not a second copy.
+ """
+ from importlib import resources
+ try:
+ packaged = resources.files("phone_harness") / "agent_workspace"
+ if packaged.is_dir():
+ return packaged
+ except (ImportError, OSError, TypeError):
+ pass
+ fallback = repo_root() / "agent-workspace"
+ if fallback.is_dir():
+ return fallback
+ return None
+
+
+def _skipped(name):
+ """Secrets and bytecode are not defaults, even if they sit beside them."""
+ return name in _SKIPPED_NAMES or name.endswith((".pyc", ".pyo"))
+
+
+def _children(source):
+ items = [child for child in source.iterdir() if not _skipped(child.name)]
+ items.sort(key=lambda child: child.name)
+ return items
+
+
+def _same_dir(source, dest):
+ resolve = getattr(source, "resolve", None)
+ if resolve is None:
+ return False
+ try:
+ return Path(resolve()).resolve() == Path(dest).resolve()
+ except (OSError, TypeError, ValueError):
+ return False
+
+
+def _copy_into(source, dest):
+ """Copy ``source``'s children into the existing directory ``dest``."""
+ for child in _children(source):
+ target = dest / child.name
+ if child.is_dir():
+ target.mkdir()
+ _copy_into(child, target)
+ elif child.is_file():
+ target.write_bytes(child.read_bytes())
+
+
+def ensure_agent_workspace(dest):
+ """Create ``dest`` from the defaults when it is absent.
+
+ If ``dest`` already exists — a checkout, a partial directory, a file —
+ it is returned untouched.
+ """
+ dest = Path(dest)
+ if dest.exists():
+ return dest
+ source = packaged_defaults()
+ if source is None or _same_dir(source, dest):
+ return dest
+ parent = dest.parent
+ parent.mkdir(parents=True, exist_ok=True)
+ tmp = Path(tempfile.mkdtemp(prefix=f".{dest.name}.", dir=parent))
+ try:
+ _copy_into(source, tmp)
+ os.rename(tmp, dest)
+ except OSError:
+ shutil.rmtree(tmp, ignore_errors=True)
+ # Another process created it first. Keep that directory as it is.
+ if dest.is_dir():
+ return dest
+ raise
+ except Exception:
+ shutil.rmtree(tmp, ignore_errors=True)
+ raise
+ return dest
+
+
+_warned = False
+
+
+def _warn_once(dest, exc):
+ global _warned
+ if _warned:
+ return
+ _warned = True
+ print(f"phone-harness: could not create agent workspace {dest} ({exc})",
+ file=sys.stderr)
+
+
+def agent_workspace():
+ """The resolved workspace, seeded from the defaults when it is missing."""
+ dest = resolved_agent_workspace()
+ try:
+ return ensure_agent_workspace(dest)
+ except OSError as exc:
+ _warn_once(dest, exc)
+ return dest
diff --git a/tests/test_skill.py b/tests/test_skill.py
index ef38623..e08b4d0 100644
--- a/tests/test_skill.py
+++ b/tests/test_skill.py
@@ -12,7 +12,7 @@ sys.path.insert(0, str(SRC))
from phone_harness.run import _skill_text, _write_utf8 # noqa: E402
from phone_harness.android import CLI_USAGE as ANDROID_USAGE # noqa: E402
from phone_harness.cloud import CLI_USAGE as CLOUD_USAGE # noqa: E402
-from phone_harness.config import CLI_USAGE as CONFIG_USAGE # noqa: E402
+from phone_harness.config import CLI_USAGE as CONFIG_USAGE
from phone_harness.run import USAGE # noqa: E402
diff --git a/tests/test_workspace.py b/tests/test_workspace.py
new file mode 100644
index 0000000..d2b14fc
--- /dev/null
+++ b/tests/test_workspace.py
@@ -0,0 +1,309 @@
+"""Agent workspace seeding: first run copies defaults, an existing one is left alone.
+
+ python -m unittest discover tests
+"""
+import os
+import subprocess
+import sys
+import tempfile
+import unittest
+import zipfile
+from pathlib import Path
+from unittest import mock
+
+ROOT = Path(__file__).resolve().parents[1]
+SRC = ROOT / "src"
+DEFAULT_HELPERS = ROOT / "agent-workspace" / "agent_helpers.py"
+
+if str(SRC) not in sys.path:
+ sys.path.insert(0, str(SRC))
+
+from phone_harness.workspace import ( # noqa: E402
+ ensure_agent_workspace,
+ resolved_agent_workspace,
+)
+
+
+def _inside(child, parent):
+ try:
+ Path(child).resolve().relative_to(Path(parent).resolve())
+ except ValueError:
+ return False
+ return True
+
+
+def _run(code, workspace, home):
+ env = os.environ.copy()
+ env["PYTHONPATH"] = str(SRC)
+ env["PH_AGENT_WORKSPACE"] = str(workspace)
+ env["PHONE_HARNESS_HOME"] = str(home)
+ env["PHONE_HARNESS_PLATFORM"] = "android"
+ env["PHONE_HARNESS_TELEMETRY"] = "0"
+ env.pop("PHONE_HARNESS_SESSION", None)
+ return subprocess.run([sys.executable, "-c", code], capture_output=True,
+ text=True, env=env)
+
+
+class AgentWorkspace(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.home = Path(self.tmp.name) / "home"
+ self.ws = Path(self.tmp.name) / "workspace"
+
+ def test_a_missing_workspace_is_seeded_from_the_defaults(self):
+ r = _run("import phone_harness.config", self.ws, self.home)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ seeded = self.ws / "agent_helpers.py"
+ self.assertTrue(seeded.is_file(), r.stderr)
+ self.assertEqual(seeded.read_bytes(), DEFAULT_HELPERS.read_bytes())
+
+ r = _run(
+ "import phone_harness.helpers as h\n"
+ "assert callable(h.tap_icon)\n",
+ self.ws, self.home)
+ self.assertEqual(r.returncode, 0, r.stderr)
+
+ def test_an_existing_workspace_is_left_untouched(self):
+ self.ws.mkdir()
+ custom = self.ws / "agent_helpers.py"
+ custom.write_text("# agent edited this\nVALUE = 'custom'\n")
+ extra = self.ws / "my_helpers.py"
+ extra.write_text("mine = True\n")
+ before = {p.name: p.read_bytes() for p in self.ws.iterdir()}
+
+ r = _run("import phone_harness.config", self.ws, self.home)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ after = {p.name: p.read_bytes() for p in self.ws.iterdir()}
+ self.assertEqual(after, before)
+ self.assertNotIn(b"def tap_icon", custom.read_bytes())
+
+ def test_a_partial_workspace_is_not_filled_in(self):
+ self.ws.mkdir()
+ (self.ws / "my_helpers.py").write_text("mine = True\n")
+ self.assertEqual(ensure_agent_workspace(self.ws), self.ws)
+ self.assertFalse((self.ws / "agent_helpers.py").exists())
+ self.assertEqual((self.ws / "my_helpers.py").read_text(), "mine = True\n")
+
+ def test_a_checkout_workspace_is_not_rewritten(self):
+ before = DEFAULT_HELPERS.read_bytes()
+ names = sorted(p.name for p in DEFAULT_HELPERS.parent.iterdir())
+ env = os.environ.copy()
+ env.pop("PH_AGENT_WORKSPACE", None)
+ env["PYTHONPATH"] = str(SRC)
+ env["PHONE_HARNESS_HOME"] = str(self.home)
+ env["PHONE_HARNESS_PLATFORM"] = "android"
+ env["PHONE_HARNESS_TELEMETRY"] = "0"
+ r = subprocess.run(
+ [sys.executable, "-c", "import phone_harness.config"],
+ capture_output=True, text=True, env=env)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertEqual(DEFAULT_HELPERS.read_bytes(), before)
+ self.assertEqual(sorted(p.name for p in DEFAULT_HELPERS.parent.iterdir()), names)
+
+ def test_a_git_checkout_uses_its_own_agent_workspace(self):
+ self.assertTrue((ROOT / ".git").exists())
+ with mock.patch.dict(os.environ, {}, clear=False):
+ os.environ.pop("PH_AGENT_WORKSPACE", None)
+ dest = resolved_agent_workspace()
+ self.assertEqual(dest, ROOT / "agent-workspace")
+
+ def test_a_prefix_without_git_resolves_outside_it(self):
+ prefix = Path(self.tmp.name) / "tool" / "lib" / "python3.12"
+ prefix.mkdir(parents=True)
+ self.home.mkdir()
+ with mock.patch.dict(os.environ, {}, clear=False):
+ os.environ.pop("PH_AGENT_WORKSPACE", None)
+ os.environ.pop("XDG_DATA_HOME", None)
+ with mock.patch("phone_harness.workspace.repo_root", return_value=prefix), \
+ mock.patch("phone_harness.workspace.Path.home", return_value=self.home):
+ dest = resolved_agent_workspace()
+ self.assertEqual(dest, self.home / ".phone-harness" / "agent-workspace")
+ self.assertFalse(_inside(dest, prefix))
+
+ (self.home / ".phone-harness" / ".git").mkdir(parents=True)
+ with mock.patch.dict(os.environ, {}, clear=False):
+ os.environ.pop("PH_AGENT_WORKSPACE", None)
+ os.environ.pop("XDG_DATA_HOME", None)
+ with mock.patch("phone_harness.workspace.repo_root", return_value=prefix), \
+ mock.patch("phone_harness.workspace.Path.home", return_value=self.home):
+ dest = resolved_agent_workspace()
+ data = self.home / ".local" / "share" / "phone-harness" / "agent-workspace"
+ self.assertEqual(dest, data)
+ self.assertFalse(_inside(dest, prefix))
+ self.assertFalse(_inside(dest, self.home / ".phone-harness"))
+
+ xdg = Path(self.tmp.name) / "xdg"
+ with mock.patch.dict(os.environ, {"XDG_DATA_HOME": str(xdg)}, clear=False):
+ os.environ.pop("PH_AGENT_WORKSPACE", None)
+ with mock.patch("phone_harness.workspace.repo_root", return_value=prefix), \
+ mock.patch("phone_harness.workspace.Path.home", return_value=self.home):
+ dest = resolved_agent_workspace()
+ self.assertEqual(dest, xdg / "phone-harness" / "agent-workspace")
+ self.assertFalse(_inside(dest, prefix))
+
+ def test_seed_skips_a_dotenv_beside_the_defaults(self):
+ source = Path(self.tmp.name) / "defaults"
+ source.mkdir()
+ (source / "agent_helpers.py").write_text("default helpers\n")
+ (source / ".env").write_text("SECRET=1\n")
+ with mock.patch("phone_harness.workspace.packaged_defaults", return_value=source):
+ ensure_agent_workspace(self.ws)
+ self.assertEqual((self.ws / "agent_helpers.py").read_text(), "default helpers\n")
+ self.assertFalse((self.ws / ".env").exists())
+
+
+def _build_wheel(directory):
+ """Build a wheel of this tree. Prefer the installed hatchling; CI may not
+ have it, and then pip's isolated build downloads the backend."""
+ cmd = [sys.executable, "-m", "pip", "wheel", "--no-deps",
+ "--wheel-dir", str(directory), str(ROOT)]
+ r = subprocess.run([*cmd, "--no-build-isolation"], capture_output=True, text=True)
+ if r.returncode != 0:
+ r = subprocess.run(cmd, capture_output=True, text=True)
+ return r
+
+
+class PackagedWorkspace(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls._tmp = tempfile.TemporaryDirectory()
+ cls.out = Path(cls._tmp.name)
+ # Build with a secret-shaped .env beside the defaults, the way a
+ # developer's checkout looks. The wheel must not pack it.
+ cls._stray_env = ROOT / "agent-workspace" / ".env"
+ cls._wrote_env = not cls._stray_env.exists()
+ if cls._wrote_env:
+ cls._stray_env.write_text("PHONE_HARNESS_TOKEN=do-not-ship\n")
+ r = _build_wheel(cls.out)
+ if r.returncode != 0:
+ cls._tmp.cleanup()
+ raise AssertionError(r.stderr or r.stdout)
+ wheels = list(cls.out.glob("*.whl"))
+ if len(wheels) != 1:
+ cls._tmp.cleanup()
+ raise AssertionError(f"expected one wheel, got {wheels}")
+ cls.wheel = wheels[0]
+
+ @classmethod
+ def tearDownClass(cls):
+ if cls._wrote_env:
+ cls._stray_env.unlink(missing_ok=True)
+ cls._tmp.cleanup()
+
+ def test_the_wheel_ships_agent_workspace(self):
+ with zipfile.ZipFile(self.wheel) as zf:
+ names = zf.namelist()
+ packaged = "phone_harness/agent_workspace/agent_helpers.py"
+ self.assertIn(packaged, names)
+ self.assertEqual(zf.read(packaged), DEFAULT_HELPERS.read_bytes())
+ self.assertTrue(any(name.endswith("phone_harness/SKILL.md") or
+ name == "phone_harness/SKILL.md" for name in names))
+
+ def test_the_wheel_packs_only_the_default_helper(self):
+ """A .env sat beside the defaults while this wheel was built."""
+ with zipfile.ZipFile(self.wheel) as zf:
+ under = [n for n in zf.namelist()
+ if n.startswith("phone_harness/agent_workspace/")]
+ self.assertEqual(under, ["phone_harness/agent_workspace/agent_helpers.py"])
+
+ def test_an_installed_wheel_seeds_without_clobbering_edits(self):
+ """Install the wheel with pip --target (no venv; CI images vary) and
+ import it with only that tree on PYTHONPATH, so the checkout cannot
+ supply agent-workspace/."""
+ target = self.out / "install"
+ r = subprocess.run(
+ [sys.executable, "-m", "pip", "install", "--no-deps",
+ "--target", str(target), str(self.wheel)],
+ capture_output=True, text=True)
+ self.assertEqual(r.returncode, 0, r.stderr or r.stdout)
+ self.assertTrue((target / "phone_harness" / "agent_workspace" /
+ "agent_helpers.py").is_file())
+
+ def installed(workspace, code):
+ env = os.environ.copy()
+ env["PYTHONPATH"] = str(target)
+ env["PH_AGENT_WORKSPACE"] = str(workspace)
+ env["PHONE_HARNESS_HOME"] = str(self.out / "home")
+ env["PHONE_HARNESS_PLATFORM"] = "android"
+ env["PHONE_HARNESS_TELEMETRY"] = "0"
+ env.pop("PHONE_HARNESS_SESSION", None)
+ return subprocess.run(
+ [sys.executable, "-c", code], capture_output=True, text=True,
+ env=env, cwd=self.out)
+
+ ws = self.out / "seeded"
+ r = installed(ws,
+ "import phone_harness.helpers as h\n"
+ "assert callable(h.tap_icon)\n")
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertEqual((ws / "agent_helpers.py").read_bytes(),
+ DEFAULT_HELPERS.read_bytes())
+
+ (ws / "agent_helpers.py").write_text("VALUE = 'custom'\n")
+ (ws / "my_helpers.py").write_text("mine = True\n")
+ r = installed(ws,
+ "import phone_harness.helpers as h\n"
+ "assert h.VALUE == 'custom'\n"
+ "assert not hasattr(h, 'tap_icon')\n")
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertEqual((ws / "agent_helpers.py").read_text(), "VALUE = 'custom'\n")
+ self.assertEqual((ws / "my_helpers.py").read_text(), "mine = True\n")
+
+ def test_an_install_resolves_outside_the_prefix(self):
+ """A wheel install must not park helpers under lib/pythonX.Y.
+
+ ``repo_root()`` there is inside the prefix and is replaced on
+ upgrade. ``HOME`` is a temp directory so this does not touch the
+ real ``~/.phone-harness``.
+ """
+ target = self.out / "prefix"
+ r = subprocess.run(
+ [sys.executable, "-m", "pip", "install", "--no-deps",
+ "--target", str(target), str(self.wheel)],
+ capture_output=True, text=True)
+ self.assertEqual(r.returncode, 0, r.stderr or r.stdout)
+ home_tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(home_tmp.cleanup)
+ home = Path(home_tmp.name)
+
+ def installed():
+ env = os.environ.copy()
+ env["PYTHONPATH"] = str(target)
+ env["HOME"] = str(home)
+ env.pop("PH_AGENT_WORKSPACE", None)
+ env.pop("XDG_DATA_HOME", None)
+ env["PHONE_HARNESS_HOME"] = str(home / "state")
+ env["PHONE_HARNESS_PLATFORM"] = "android"
+ env["PHONE_HARNESS_TELEMETRY"] = "0"
+ env.pop("PHONE_HARNESS_SESSION", None)
+ return subprocess.run(
+ [sys.executable, "-c",
+ "from phone_harness.workspace import agent_workspace, repo_root\n"
+ "print(repo_root())\n"
+ "print(agent_workspace())\n"],
+ capture_output=True, text=True, env=env, cwd=home)
+
+ r = installed()
+ self.assertEqual(r.returncode, 0, r.stderr)
+ prefix, ws = [Path(line) for line in r.stdout.splitlines()]
+ self.assertEqual(ws, home / ".phone-harness" / "agent-workspace")
+ self.assertFalse(_inside(ws, target))
+ self.assertFalse(_inside(ws, prefix))
+ self.assertEqual((ws / "agent_helpers.py").read_bytes(),
+ DEFAULT_HELPERS.read_bytes())
+ self.assertFalse((prefix / "agent-workspace").exists())
+
+ (ws / "agent_helpers.py").write_text("VALUE = 'kept'\n")
+ (home / ".phone-harness" / ".git").mkdir()
+ r = installed()
+ self.assertEqual(r.returncode, 0, r.stderr)
+ prefix, ws2 = [Path(line) for line in r.stdout.splitlines()]
+ data = home / ".local" / "share" / "phone-harness" / "agent-workspace"
+ self.assertEqual(ws2, data)
+ self.assertFalse(_inside(ws2, target))
+ self.assertFalse(_inside(ws2, prefix))
+ self.assertFalse(_inside(ws2, home / ".phone-harness"))
+ self.assertEqual((ws / "agent_helpers.py").read_text(), "VALUE = 'kept'\n")
+ self.assertEqual((ws2 / "agent_helpers.py").read_bytes(),
+ DEFAULT_HELPERS.read_bytes())