let your agent control your phone
fix: find the phone window on any Space, not just the active one
ShawnPana1935f3c67035
diff --git a/src/phone_harness/background.py b/src/phone_harness/background.pyindex 99959ae..8b3a8c5 100644--- a/src/phone_harness/background.py+++ b/src/phone_harness/background.py@@ -34,7 +34,7 @@ Keyboard (type_text/press) still briefly activates the window: the keyboardevent-record layout isn't implemented yet, so those fall back to the mirrorpath. Mouse actions are fully background."""-import ctypes, ctypes.util, struct, tempfile, time+import ctypes, ctypes.util, os, struct, subprocess, tempfile, timefrom pathlib import Pathimport Quartz@@ -69,7 +69,21 @@ _LMOUSE_DOWN, _LMOUSE_UP, _LMOUSE_DRAGGED = 1, 2, 6# --- window / app state (reused from mirror; none of these activate) ----find_window = mirror.find_window+def find_window():+ """The phone window, on the active Space or not.++ SkyLight event records are addressed to a process and a window id, so this+ backend reaches the window wherever it is. mirror.py keeps the on-screen+ default because it posts CGEvents at global screen coordinates, which land+ on whatever is actually in front.++ Inheriting mirror's default is why a terminal on a different Space from the+ phone made the harness report a disconnected phone (#8) — the window was+ there the whole time, just not on the Space being asked about.+ """+ return mirror.find_window(on_screen=False)++running_app = mirror.running_appwindow_ax_content = mirror.window_ax_content@@ -119,12 +133,29 @@ def capture(path=None, retries=2):if Quartz.CGImageDestinationFinalize(dest):return path, winlast = "could not encode PNG"+ elif _screencapture(win, path):+ # CGWindowListCreateImage renders nothing for a window that is not+ # on the active Space. `screencapture -l` still reaches it, with+ # live frames rather than a stale backing store. It costs a+ # subprocess, so it stays the fallback. Its image is Retina where+ # the fast path is point-resolution; ocr.recognize derives the+ # scale from the window, so both work.+ return path, winelse:- last = "CGWindowListCreateImage returned nothing"+ last = "CGWindowListCreateImage returned nothing, screencapture failed"time.sleep(0.3)raise RuntimeError(f"background capture failed: {last}")+def _screencapture(win, path):+ """Window capture via the screencapture binary. True if it wrote a PNG."""+ if os.path.exists(path):+ os.remove(path)+ subprocess.run(["screencapture", "-x", "-o", "-l", str(win["id"]), path],+ capture_output=True)+ return os.path.exists(path) and os.path.getsize(path) > 1000++# --- input (hands), no focus ---def _post(pid, wid, etype, gx, gy, lx, ly):diff --git a/src/phone_harness/mirror.py b/src/phone_harness/mirror.pyindex ef660cf..0aa9489 100644--- a/src/phone_harness/mirror.py+++ b/src/phone_harness/mirror.py@@ -23,9 +23,15 @@ TMP.mkdir(exist_ok=True)# --- window / app state ----def find_window():+def find_window(on_screen=True):"""{x, y, w, h, id} of the mirroring window in screen points, or None.+ on_screen=False also finds the window when it is on another Space, hidden,+ or minimized. Only backends that address the window by id can use that:+ SkyLight event records reach it wherever it is, while CGEvents are posted+ at global screen coordinates and would land on whatever is actually in+ front. This module posts CGEvents, so it keeps the on-screen default.+Windows are matched by the owner PID of the com.apple.ScreenContinuityprocess, never by kCGWindowOwnerName. The owner name is localized — macOSreports "iPhone镜像" on a Simplified Chinese system and "iPhone鏡像輸出" on@@ -38,24 +44,32 @@ def find_window():if app is None:return None # not running, so it owns no windowspid = app.processIdentifier()- wins = Quartz.CGWindowListCopyWindowInfo(- Quartz.kCGWindowListOptionOnScreenOnly, Quartz.kCGNullWindowID) or []- for w in wins:- if w.get("kCGWindowOwnerPID") == pid and w.get("kCGWindowLayer", 1) == 0:- b = w["kCGWindowBounds"]- # No size filter. The old `Width < 100` guard was there to skip- # panels and toolbars, but PID + on-screen + layer 0 already- # excludes those: the app's other windows (Settings, Welcome, and- # four unnamed 1512x33 strips) are never in the on-screen list, so- # this loop sees exactly one candidate. What the guard did hit was- # a real mirroring window that macOS had shrunk — with Stage- # Manager on, an inactive window is parked in the left rail at- # about 38x130, which is on-screen and genuinely the phone. The- # guard discarded it, so every time another app took the stage the- # harness reported a disconnected phone (#8). Window list order is- # front to back, so the first match is the frontmost.- return {"x": b["X"], "y": b["Y"], "w": b["Width"], "h": b["Height"],- "id": int(w["kCGWindowNumber"])}+ opts = (Quartz.kCGWindowListOptionOnScreenOnly if on_screen+ else Quartz.kCGWindowListOptionAll)+ wins = Quartz.CGWindowListCopyWindowInfo(opts, Quartz.kCGNullWindowID) or []+ cands = [w for w in wins if w.get("kCGWindowOwnerPID") == pid+ and w.get("kCGWindowLayer", 1) == 0]+ if not on_screen:+ # Off the active Space the list also carries the app's other windows:+ # a Settings sheet, a Welcome dialog, and four unnamed 1512x33 strips.+ # The phone window is the one whose title is the app's own name. Both+ # strings are localized together, so this still picks it out where a+ # comparison against the English constant would not.+ named = [w for w in cands+ if w.get("kCGWindowName") == w.get("kCGWindowOwnerName")]+ cands = named or cands+ # No size filter. The old `Width < 100` guard was there to skip panels and+ # toolbars, but PID + layer 0 already excludes those. What the guard did+ # hit was a real mirroring window that macOS had shrunk — with Stage+ # Manager on, an inactive window is parked in the left rail at about+ # 38x130, which is on-screen and genuinely the phone. The guard discarded+ # it, so every time another app took the stage the harness reported a+ # disconnected phone (#8). Window list order is front to back, so the+ # first candidate is the frontmost.+ for w in cands:+ b = w["kCGWindowBounds"]+ return {"x": b["X"], "y": b["Y"], "w": b["Width"], "h": b["Height"],+ "id": int(w["kCGWindowNumber"])}return None