let your agent control your phone
Let agents see a blocked iPhone Mirroring window (#119)
shawn panad394a8e8504f
diff --git a/SKILL.md b/SKILL.mdindex 97b76cc..54ab46d 100644--- a/SKILL.md+++ b/SKILL.md@@ -115,7 +115,7 @@ PYpassword or a 2FA code; on a cloud phone, hand the controls over instead(`phone-harness cloud open`, below).- **The harness reconnects what it can; the rest is the user's.** On a- personal iPhone, start the task with `ensure_mirroring()`: it opens iPhone+ personal iPhone, start the task with `ensure_device()`: it opens iPhoneMirroring if it is closed, presses the window's Connect once, and bringsthe window to the front so the user can watch. Pairing, unlocking, tapping Allow,locking an iPhone that says "iPhone in Use" or "Timed Out", approving a@@ -388,7 +388,8 @@ The Mac's iPhone Mirroring app renders the phone as a window; the harnesscaptures that window and OCRs it with Vision for eyes, and posts HID-levelevents into it for hands. All coordinates are global macOS screen points.-- **Start every task with `ensure_mirroring()`.** It opens iPhone Mirroring+- **Start every task with `ensure_device()`.** It is the first call on every+ phone, including iPhone Mirroring. It opens iPhone Mirroringif it is not running, brings the window to the front so the user sees whatyou see, presses the interstitial's Connect once through accessibility,and waits for the live stream. A phone that is in use shows up within@@ -427,18 +428,26 @@ events into it for hands. All coordinates are global macOS screen points.`press("tab")` moves between fields.- **What the harness cannot clear is physical.** Connect only works whilethe iPhone is locked; "iPhone in Use" and "Timed Out ... due to iPhone use"- mean it was not. `ensure_mirroring()` presses Connect once and then raises+ mean it was not. `ensure_device()` presses Connect once and then raisesquoting the screen (`connection_state()` is `ready` / `blocked` /- `no-window` / `not-running`). **STOP and relay it**, ask the user to lock- the phone, and retry once when they say so. The app reconnects by itself- the moment the phone is locked, so the retry usually finds it live; if- not, it presses Connect again. Do not press it yourself in a loop and do+ `no-window` / `not-running`). `connection_detail()` returns the labels and+ button titles in the window, with no screenshot, so you can see why it is+ blocked. **STOP and relay the error.** It names the next step: lock the+ iPhone when the window says in use, timed out, or lock your iPhone; approve+ or cancel when the Mac asks for Touch ID or a password (never type one);+ otherwise clear the window on the Mac. Retry once when the user says it is+ done. When the phone was in use, the app reconnects by itself the moment+ the phone is locked, so that retry usually finds it live; if not, it+ presses Connect again. Do not press it yourself in a loop and donot tap the window (an interstitial is a Mac view; taps meant for thephone go nowhere). **Unlocking the physical phone pauses the session**("iPhone in Use") - the same rule applies mid-task. Taps, scrolls, swipes,- typing, key presses, `open_app`, `home`, and `screenshot` raise that same- message and do not press Connect. Ask the user to lock the phone, then- call `ensure_mirroring()` and continue from the step that raised.+ typing, key presses, `open_app`, and `home` raise that same+ message and do not press Connect. `screenshot()` and `screen_info()` still+ work while the mirroring window is open, including when the state is+ blocked. Call `screenshot()` to see what the window shows. Ask the user+ to do what the error says, then call `ensure_device()` and continue from+ the step that raised.The Mac login prompt thatsometimes appears in the window is never typed into.- **Unfocused input is swallowed silently - for events you post yourself.**diff --git a/integrations/hermes/README.md b/integrations/hermes/README.mdindex a68bb5a..96caaf1 100644--- a/integrations/hermes/README.md+++ b/integrations/hermes/README.md@@ -28,6 +28,7 @@ hermes plugins install ShawnPana/phone-harness/integrations/hermesHermes installs the `phone-harness` package into its own environment and askswhether to enable the plugin. Tools load per session, so start a new chat.+Restart the Hermes desktop app after installing or updating the plugin.Each script runs as `python -m phone_harness.run` on Hermes's interpreter: thecopy Hermes installed, kept apart from a `phone-harness` command on `PATH`.@@ -47,7 +48,9 @@ This plugin has no settings of its own.- `PHONE_HARNESS_PLATFORM`, when you have exported it, is passed through.- The agent workspace is one folder, `agent-workspace`, in Hermes's plugindata directory. If `PH_AGENT_WORKSPACE` is already set, that path is used- instead. Each script receives it as `PH_AGENT_WORKSPACE`.+ instead. Each script receives it as `PH_AGENT_WORKSPACE`. If+ `agent_helpers.py` is missing, the packaged default is copied in; a file+ that is already there is left as it is.## How it worksdiff --git a/integrations/hermes/__init__.py b/integrations/hermes/__init__.pyindex bd7941a..705e310 100644--- a/integrations/hermes/__init__.py+++ b/integrations/hermes/__init__.py@@ -17,6 +17,7 @@ import astimport contextlibimport importlib.utilimport json+import loggingimport osimport reimport signal@@ -26,6 +27,8 @@ import threadingfrom pathlib import Pathfrom typing import Any+log = logging.getLogger("phone_harness.hermes")+PLUGIN = "phone-harness"DEFAULT_TIMEOUT_S, MIN_TIMEOUT_S, MAX_TIMEOUT_S = 300, 5, 1800LOCK_WAIT_S = 120@@ -37,7 +40,8 @@ DESCRIPTION = ("Drive the user's real phone with phone-harness: their iPhone through the Mac's iPhone Mirroring ""window, an Android over adb, or a Phone Harness Cloud phone. `code` runs as Python with the phone ""helpers pre-imported; print() whatever you need back. Each call is a fresh interpreter (variables "- "do not persist); the phone keeps its state. Start with ensure_device(). Ask the user before "+ "do not persist); the phone keeps its state. Start with ensure_device(); it covers iPhone "+ "Mirroring, Android, and a cloud phone. Ask the user before ""anything outward-facing or hard to undo (sending, posting, buying, deleting, changing settings). ""Never type passwords, PINs or 2FA codes. Read the skill phone-harness:phone-harness for the helpers.")@@ -157,6 +161,24 @@ def _workspace() -> Path:return _data_dir() / "agent-workspace"+def _seed_workspace(workspace: Path) -> None:+ """Copy the packaged agent_helpers.py in when that file is missing.++ Hermes's plugin-data folder is created up front. An empty directory+ makes phone-harness skip its first-run seed, so the workspace can end+ up with no helpers. Existing files are never overwritten.+ """+ try:+ from phone_harness.workspace import seed_missing_files+ except ImportError as exc:+ log.warning("phone-harness: could not seed the agent workspace: %s", exc)+ workspace.mkdir(parents=True, exist_ok=True)+ return+ seed_missing_files(workspace)+ if not workspace.is_dir():+ workspace.mkdir(parents=True, exist_ok=True)++def _env(workspace: Path) -> dict:"""The script inherits Hermes's environment. Platform and telemetry stay phone-harness's ownconfig: an exported PHONE_HARNESS_PLATFORM is left as it is, and this plugin does not set one."""@@ -224,7 +246,7 @@ def phone_exec(args: dict, **kwargs) -> str:group: dict[str, Any] = ({"creationflags": getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)}if os.name == "nt" else {"start_new_session": True})try:- workspace.mkdir(parents=True, exist_ok=True)+ _seed_workspace(workspace)with _phone_lock(LOCK_WAIT_S):proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,@@ -307,5 +329,7 @@ def register(ctx) -> None:ctx.register_tool(name="phone_exec", toolset=PLUGIN, schema=SCHEMA, handler=phone_exec,check_fn=_available, emoji="π±")ctx.register_hook("pre_tool_call", _on_pre_tool_call)- with contextlib.suppress(Exception):+ try:_register_skill(ctx)+ except Exception as exc:+ log.warning("phone-harness: could not register the skill: %s", exc)diff --git a/src/phone_harness/helpers.py b/src/phone_harness/helpers.pyindex 0ff7b24..71f38c3 100644--- a/src/phone_harness/helpers.py+++ b/src/phone_harness/helpers.py@@ -63,10 +63,25 @@ def connection_state():On iPhone Mirroring: 'ready' | 'blocked' | 'no-window' | 'not-running',where 'blocked' means an interstitial is up and nothing should be tappedor typed until it is cleared β ensure_device() tries that once.+ screenshot() and screen_info() still work while blocked if the mirroring+ window is open.++ connection_detail() is the reason, as text already in the window. It+ does not take a screenshot."""return send("session.state")+def connection_detail():+ """Why connection_state() is not 'ready', without a screenshot.++ On iPhone Mirroring this is the labels and button titles in the+ mirroring window. Empty when the phone is live, because that image+ has no such text. On Android it is the adb device list.+ """+ return send("session.detail")++def ensure_device():"""Screen bounds once the device is usable, else raise telling the userwhat they physically need to do.@@ -91,7 +106,10 @@ def find_window():def screen_info():- """{window, frontmost, img_px} β bounds, focus state, capture size."""+ """{window, frontmost, img_px} β bounds, focus state, capture size.++ On iPhone Mirroring this still works when the session is blocked, as+ long as the mirroring window exists."""from . import ocr as _visionpath, win = send("screen.capture")w, h = _vision.image_size(path)@@ -101,7 +119,11 @@ def screen_info():def screenshot(path=None):"""Capture the screen to a PNG and return its path. View it to see the- phone; combine with ocr() for coordinates."""+ phone; combine with ocr() for coordinates.++ On iPhone Mirroring this still works when connection_state() is not+ 'ready', as long as the mirroring window exists. Looking does not+ press Connect."""p, _ = send("screen.capture", path=path)return pdiff --git a/src/phone_harness/ios.py b/src/phone_harness/ios.pyindex f145181..41a1b58 100644--- a/src/phone_harness/ios.py+++ b/src/phone_harness/ios.py@@ -27,14 +27,6 @@ import osfrom . import ocr as _visionfrom .transport import Backend-# Fallback only. The primary check is structural (see _session_state), and a-# phrase list cannot be complete: it missed "Connection Paused" and the Mac-# login screen in English, and misses every interstitial on a non-English-# system.-_BLOCKED_MARKERS = ("iphone in use", "lock your iphone", "mirroring ended",- "to connect", "connection paused", "connection interrupted",- "is locked", "enter the mac login", "try again")-def _load_transport():"""background drives iPhone Mirroring without ever taking the window to the@@ -63,9 +55,10 @@ class IPhone(Backend):self._note_seen = Falsedef send(self, op, **kw):- """Run `op`. Actions and captures check the stream first and again- after, and raise if it is no longer live. They do not press Connect:- a takeover means the user has the phone."""+ """Run `op`. Actions check the stream first and again after, and+ raise if it is no longer live. They do not press Connect: a takeover+ means the user has the phone. A screenshot is not an action: looking+ at the window stays available while an interstitial is up."""watch = op in _ACTION_OPSif watch:self._raise_if_not_live()@@ -148,34 +141,40 @@ class IPhone(Backend):'blocked' means an interstitial is up β iPhone in Use, paused, ended,connect, or the Mac login screen β and nothing should be tapped or- typed until the user clears it.-- Detected structurally: the live phone image is a video stream that- accessibility cannot see into, so a working session exposes no UI- inside the window, while every interstitial is an ordinary Mac view- with labels and a button. That holds in any language and for screens- Apple has not shipped yet, where matching known phrases does neither β- the old list missed both "Connection Paused" and the Mac login prompt,- and reported 'ready' for a password field.+ typed until the user clears it. screenshot() still works.++ Accessibility decides, and nothing else may override a structural+ 'ready'. The live phone image is a video stream that accessibility+ cannot see into, so a working session exposes no UI inside the+ window, while every interstitial is an ordinary Mac view with labels+ and a button. That holds in any language and for screens Apple has+ not shipped yet. OCR is not used: it reads the phone's own screen+ and cannot tell that text from a Mac interstitial."""- if self.mirror.running_app() is None:- return "not-running"- if self.mirror.find_window() is None:- return "no-window"- if self.mirror.window_ax_content():- return "blocked"- path, win = self.mirror.capture() # window exists, launches nothing- texts = " ".join(o["text"] for o in _vision.recognize(path, win)).lower()- return "blocked" if any(m in texts for m in _BLOCKED_MARKERS) else "ready"+ return self._structural_state()def _session_detail(self):- """What the interstitial says, quoted rather than guessed at.+ """Labels and button titles accessibility can read in the window.- Button titles are not used: the same screen reported 'Connect' once and- an empty title a minute later.+ Empty when the phone image is live. An empty button title is+ skipped: the same screen has reported 'Connect' and then nothing."""- return " ".join(t for role, t in self.mirror.window_ax_content()- if role == "AXStaticText" and t)+ texts, buttons = [], []+ for role, text in self.mirror.window_ax_content():+ label = " ".join((text or "").split())+ if not label:+ continue+ if role == "AXButton":+ buttons.append(label)+ elif role == "AXStaticText":+ texts.append(label)+ parts = []+ if texts:+ parts.append(" ".join(texts))+ if buttons:+ quoted = ", ".join(f"'{b}'" for b in buttons)+ parts.append(f"buttons: {quoted}")+ return " ".join(parts)def _session_require(self):"""Bounds once the phone is connected and ready.@@ -232,8 +231,8 @@ class IPhone(Backend):Two structural reads bracket each guarded action (before and after).Each read is one ax_session_hint(): the running app, the phonewindow, and whether that window has any accessibility children. A- live stream has none. There is no screen capture and no Vision OCR,- which is what a full session.state costs.+ live stream has none. There is no screen capture and no Vision OCR.+ session.state is this same read.When the observer is up, a zero-timeout run-loop turn delivers anotification that arrived since the last action, and that@@ -275,7 +274,11 @@ class IPhone(Backend):self._session_watch_off = Truedef _structural_state(self):- """ready | blocked | no-window | not-running, without capture or OCR."""+ """ready | blocked | no-window | not-running, without capture or OCR.++ Accessibility content in the window is 'blocked'. None is 'ready'.+ Text recognised on the phone's own screen must not change that.+ """hint = getattr(self.mirror, "ax_session_hint", None)if hint is not None:return hint()@@ -288,7 +291,7 @@ class IPhone(Backend):return "ready"def _raise_not_live(self, state, pressed=None):- """The error ensure_mirroring raises, without pressing anything."""+ """The error ensure_device raises, without pressing anything."""if state == "not-running":raise RuntimeError("iPhone Mirroring would not launch. Please open the iPhone "@@ -298,14 +301,16 @@ class IPhone(Backend):"iPhone Mirroring is open but shows no phone window. Pair ""the phone in the app (it has to be nearby, locked, and ""signed in to the same Apple Account), then retry.")- said = self._session_detail() or "an interstitial with no text"+ said = (self._session_detail() or "an interstitial with no text").strip()did = (f"I pressed {pressed} and it came back with"if pressed else "It says")+ # The quote often already ends with a period ("...to connect.").+ # Adding another one produced "connect.. This needs you".+ stop = "" if said.endswith((".", "!", "?")) else "."raise RuntimeError(- f"iPhone Mirroring is not connected. {did}: {said}. This needs "- "you: if it mentions the iPhone being in use or timing out, LOCK "- "your iPhone, then tell me and I will try once more. I never "- "type a passcode.")+ f"iPhone Mirroring is not connected. {did}: {said}{stop} "+ f"{_blocked_guidance(said)} "+ "Call screenshot() to see what the window shows.")def _show(self):"""Bring the mirroring window to the front so the user can watch.@@ -497,6 +502,31 @@ class IPhone(Backend):return self.mirror.interruption(before, after)+def _blocked_guidance(said):+ """What to tell the user, from the words already quoted.++ Lock the iPhone only when the window says it is in use, timed out, or+ to lock the iPhone. A Mac Touch ID or password sheet is the user's to+ approve or cancel. Anything else is cleared on the Mac.+ """+ low = said.lower()+ if any(p in low for p in ("in use", "timed out", "lock your iphone")):+ return ("This needs you: LOCK your iPhone, then tell me and I will "+ "try once more. I never type a passcode.")+ if "touch id" in low or _has_word(low, "password"):+ return ("This needs you: the Mac is asking for Touch ID or a password. "+ "Approve it or cancel it. I never type a password.")+ return "This needs you: clear this on the Mac."+++def _has_word(text, word):+ """True when `word` is its own word. 'password' does not match 'Passwords'."""+ padded = text.lower()+ for ch in ".,:;!?\"'":+ padded = padded.replace(ch, " ")+ return f" {word} " in f" {padded} "++# Buttons an interstitial offers that mean "try to connect"; pressed once# per session.require. Lower-case; matched case-insensitively._CONNECT_BUTTONS = ("connect", "try again", "retry", "continue", "reconnect")@@ -674,11 +704,13 @@ def _ax_watch_open(mirror, on_notify):return _AxWatch(remove_note, remove_source, added, callback)-# Ops that drive the phone or read its screen. Each one refuses to run-# against a paused window. session.require is not here: that is the one-# call allowed to press Connect, and only when the user asks to resume.+# Ops that drive the phone or read it as phone content. Each one refuses+# to run against a paused window. session.require is not here: that is the+# one call allowed to press Connect, and only when the user asks to resume.+# screen.capture is not here either. Looking at the window is read-only and+# works while the session is blocked, as long as the window exists._ACTION_OPS = frozenset({- "screen.capture", "screen.text", "screen.text_pixels",+ "screen.text", "screen.text_pixels","input.tap", "input.press", "input.drag", "input.scroll","input.keys", "input.text","nav.home", "nav.recents",diff --git a/src/phone_harness/workspace.py b/src/phone_harness/workspace.pyindex b1a5f01..bc0de4e 100644--- a/src/phone_harness/workspace.py+++ b/src/phone_harness/workspace.py@@ -127,6 +127,48 @@ def _copy_into(source, dest):target.write_bytes(child.read_bytes())+def _copy_missing(source, dest):+ """Copy children of ``source`` that ``dest`` does not already have.++ A file that exists is left as it is, even when the default differs.+ """+ dest.mkdir(parents=True, exist_ok=True)+ for child in _children(source):+ target = dest / child.name+ if child.is_dir():+ if target.exists() and not target.is_dir():+ continue+ if not target.exists():+ target.mkdir()+ _copy_into(child, target)+ else:+ _copy_missing(child, target)+ elif child.is_file() and not target.exists():+ target.write_bytes(child.read_bytes())+++def seed_missing_files(dest):+ """Copy packaged defaults that ``dest`` does not already contain.++ A missing directory is created from the defaults, the same way as+ ``ensure_agent_workspace``. An existing directory keeps every file it+ already has; only names that are absent are filled in. A destination+ that is not a directory is left alone.+ """+ dest = Path(dest)+ if not dest.exists():+ ensure_agent_workspace(dest)+ if dest.is_dir():+ source = packaged_defaults()+ if source is not None and not _same_dir(source, dest):+ _copy_missing(source, dest)+ return dest+ if dest.exists():+ return dest+ dest.mkdir(parents=True, exist_ok=True)+ return dest++def ensure_agent_workspace(dest):"""Create ``dest`` from the defaults when it is absent.diff --git a/tests/test_hermes_plugin.py b/tests/test_hermes_plugin.pyindex 79fb8bd..5ec8592 100644--- a/tests/test_hermes_plugin.py+++ b/tests/test_hermes_plugin.py@@ -218,6 +218,52 @@ class Skill(unittest.TestCase):"description": "Drive the phone.",})+ def test_a_failing_skill_registration_is_logged(self):+ path = self.root / "SKILL.md"+ path.write_text(+ '---\nname: phone-harness\ndescription: "Drive the phone."\n---\n\n# phone-harness\n',+ encoding="utf-8",+ )+ self.plugin._package_dir = lambda: self.root+ self.plugin._command = lambda: [sys.executable, "-c", ""]++ class Boom(FakeCtx):+ def register_skill(self, name, path, description="", frontmatter=None):+ raise RuntimeError("skill store down")++ ctx = Boom()+ with self.assertLogs("phone_harness.hermes", level="WARNING") as caught:+ self.plugin.register(ctx)+ self.assertIn("phone_exec", ctx.tools)+ self.assertTrue(any("skill store down" in line for line in caught.output))+++class WorkspaceSeed(unittest.TestCase):+ def test_an_empty_workspace_is_seeded_and_an_edit_is_kept(self):+ src = Path(__file__).resolve().parents[1] / "src"+ sys.path.insert(0, str(src))+ self.addCleanup(sys.path.remove, str(src))+ plugin = load_plugin()+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ data = Path(tmp.name)+ plugin._data_dir = lambda: data+ plugin._workspace = lambda: data / "agent-workspace"+ plugin._command = lambda: [sys.executable, "-c", "import sys; exec(sys.stdin.read())"]+ plugin._packaged_skill = lambda: None++ first = json.loads(plugin.phone_exec({"code": "print('seeded')"}))+ self.assertTrue(first["success"], first)+ helper = data / "agent-workspace" / "agent_helpers.py"+ self.assertTrue(helper.is_file())+ helper.write_text("# keep\n")+ (data / "agent-workspace" / "notes.txt").write_text("mine\n")++ again = json.loads(plugin.phone_exec({"code": "print('again')"}))+ self.assertTrue(again["success"], again)+ self.assertEqual(helper.read_text(), "# keep\n")+ self.assertEqual((data / "agent-workspace" / "notes.txt").read_text(), "mine\n")+class Running(Base):def test_prints_come_back_as_output(self):diff --git a/tests/test_ios_session.py b/tests/test_ios_session.pyindex 7633794..86b7eca 100644--- a/tests/test_ios_session.py+++ b/tests/test_ios_session.py@@ -63,6 +63,13 @@ IN_USE_RETRYING = [("AXStaticText", "iPhone in Use"),("AXStaticText", "Lock your iPhone to connect.")]LOGIN = [("AXStaticText", "Enter the Mac login password"),("AXSecureTextField", ""), ("AXButton", "Unlock")]+# macOS draws this sheet over the mirroring window. Blocked is correct.+# The words are a Mac password prompt, not "lock your iPhone".+TOUCH_ID = [("AXStaticText", "Passwords"),+ ("AXStaticText", "Authenticate to access Passwords. Touch ID or "+ "enter your password to continue."),+ ("AXButton", "Home Screen"), ("AXButton", "App Switcher"),+ ("AXButton", "Cancel")]LIVE = []@@ -262,7 +269,10 @@ class SessionRequire(unittest.TestCase):IN_USE_RETRYING)with self.assertRaises(RuntimeError) as cm:p._session_require()- self.assertIn("iPhone in Use", str(cm.exception))+ msg = str(cm.exception)+ self.assertIn("iPhone in Use", msg)+ self.assertIn("LOCK your iPhone", msg)+ self.assertNotIn("..", msg)self.assertLess(self.clock[0], 5.0, "gave up within a few seconds")self.assertEqual(p.mirror.shown, 1, "the window was raised even so")@@ -271,7 +281,10 @@ class SessionRequire(unittest.TestCase):with self.assertRaises(RuntimeError) as cm:p._session_require()self.assertEqual(p.mirror.pressed, [])- self.assertIn("Connecting to", str(cm.exception))+ msg = str(cm.exception)+ self.assertIn("Connecting to", msg)+ self.assertIn("clear this on the Mac", msg)+ self.assertNotIn("LOCK your iPhone", msg)self.assertGreaterEqual(self.clock[0], ios._CONNECT_WAIT,"a Connecting screen is waited out to the cap")@@ -291,7 +304,10 @@ class SessionRequire(unittest.TestCase):p = self.phone(None, None, BLANK)with self.assertRaises(RuntimeError) as cm:p._session_require()- self.assertIn("an interstitial with no text", str(cm.exception))+ msg = str(cm.exception)+ self.assertIn("an interstitial with no text", msg)+ self.assertIn("clear this on the Mac", msg)+ self.assertNotIn("..", msg)self.assertEqual(p.mirror.launched, 1)self.assertEqual(p.mirror.pressed, [])self.assertGreaterEqual(self.clock[0], ios._CONNECT_WAIT)@@ -312,8 +328,25 @@ class SessionRequire(unittest.TestCase):p = self.phone(LOGIN)with self.assertRaises(RuntimeError) as cm:p._session_require()+ msg = str(cm.exception)self.assertEqual(p.mirror.pressed, [])- self.assertIn("login password", str(cm.exception))+ self.assertIn("login password", msg)+ self.assertIn("Touch ID or a password", msg)+ self.assertIn("never type a password", msg)+ self.assertNotIn("LOCK your iPhone", msg)++ def test_touch_id_sheet_asks_the_user_to_approve_or_cancel(self):+ p = self.phone(TOUCH_ID)+ with self.assertRaises(RuntimeError) as cm:+ p._session_require()+ msg = str(cm.exception)+ self.assertEqual(p.mirror.pressed, [])+ self.assertIn("Touch ID", msg)+ self.assertIn("Approve it or cancel it", msg)+ self.assertIn("never type a password", msg)+ self.assertIn("screenshot()", msg)+ self.assertNotIn("LOCK your iPhone", msg)+ self.assertNotIn("..", msg)def test_launch_without_a_window_raises(self):p = self.phone(None, None, "no-window")@@ -364,8 +397,10 @@ class SessionRequire(unittest.TestCase):p.send("input.scroll", x=1, y=1, dy=-10, dx=0)msg = str(cm.exception)self.assertIn("iPhone in Use", msg)+ self.assertIn("Try Again", msg)self.assertIn("LOCK your iPhone", msg)self.assertIn("passcode", msg)+ self.assertIn("screenshot()", msg)self.assertEqual(p.mirror.pressed, [])self.assertNotIn("scroll", p.mirror.actions)@@ -427,12 +462,18 @@ class SessionRequire(unittest.TestCase):self.assertNotIn("scroll", p.mirror.actions)self.assertEqual(p.mirror.pressed, [])- def test_screenshot_raises_when_the_phone_is_in_use(self):+ def test_screenshot_works_when_the_window_is_blocked(self):p = self.phone(IN_USE)+ path, win = p.send("screen.capture")+ self.assertEqual(path, "/dev/null")+ self.assertEqual(win, WIN)+ self.assertEqual(p.mirror.actions, ["capture"])+ self.assertEqual(p.mirror.pressed, [])with self.assertRaises(RuntimeError) as cm:- p.send("screen.capture")+ p.send("screen.text")self.assertIn("iPhone in Use", str(cm.exception))- self.assertNotIn("capture", p.mirror.actions)+ self.assertIn("screenshot()", str(cm.exception))+ self.assertEqual(p.mirror.actions, ["capture"])if __name__ == "__main__":diff --git a/tests/test_workspace.py b/tests/test_workspace.pyindex d2b14fc..be6fd3f 100644--- a/tests/test_workspace.py+++ b/tests/test_workspace.py@@ -21,6 +21,7 @@ if str(SRC) not in sys.path:from phone_harness.workspace import ( # noqa: E402ensure_agent_workspace,resolved_agent_workspace,+ seed_missing_files,)@@ -78,6 +79,21 @@ class AgentWorkspace(unittest.TestCase):self.assertEqual(after, before)self.assertNotIn(b"def tap_icon", custom.read_bytes())+ def test_seed_missing_files_fills_gaps_and_keeps_existing_files(self):+ missing = Path(self.tmp.name) / "fresh"+ self.assertEqual(seed_missing_files(missing), missing)+ self.assertEqual((missing / "agent_helpers.py").read_bytes(),+ DEFAULT_HELPERS.read_bytes())++ self.ws.mkdir()+ self.assertTrue((seed_missing_files(self.ws) / "agent_helpers.py").is_file())+ custom = self.ws / "agent_helpers.py"+ custom.write_text("# agent edited this\nVALUE = 'custom'\n")+ (self.ws / "notes.txt").write_text("keep\n")+ seed_missing_files(self.ws)+ self.assertEqual(custom.read_text(), "# agent edited this\nVALUE = 'custom'\n")+ self.assertEqual((self.ws / "notes.txt").read_text(), "keep\n")+def test_a_partial_workspace_is_not_filled_in(self):self.ws.mkdir()(self.ws / "my_helpers.py").write_text("mine = True\n")