Skip to content

Let an AI model use a real iPhone with a $7 ESP32: AirPlay eyes, USB HID hands, any OpenAI-compatible vision model. No Mac, no developer account, no jailbreak.

server: board heartbeat, safer keep-awake, no-cache UI, OpenAI token parameter

Henry099fd8dcd818
diff --git a/server/.env.example b/server/.env.example
index 7bcb1cb..ce46c78 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -6,6 +6,8 @@ LLM_BASE_URL=https://api.openai.com/v1
LLM_MODEL=gpt-4o-mini # any vision-capable chat model
LLM_API_KEY=
LLM_EXTRA_BODY='{}'
+# Newer OpenAI models want max_completion_tokens instead of max_tokens; "auto" (default) detects it.
+# LLM_TOKEN_PARAM=auto # auto | max_tokens | max_completion_tokens
# --- Local model (optional): vLLM, SGLang, llama.cpp server, Ollama, ... ---
# LLM_BASE_URL=http://localhost:8000/v1
diff --git a/server/hidagent/app.py b/server/hidagent/app.py
index a0cab93..54a80df 100644
--- a/server/hidagent/app.py
+++ b/server/hidagent/app.py
@@ -32,7 +32,7 @@ agent = Agent(phone, screen, LLM.from_env("ACTOR"), LLM.from_env("PLANNER"),
async def lifespan(_):
server = await device.serve("0.0.0.0", int(os.environ.get("DEVICE_PORT", 7300)))
screen.start()
- awake = asyncio.create_task(device.keep_awake())
+ awake = asyncio.create_task(device.keep_awake(screen=screen))
yield
awake.cancel()
screen.stop()
@@ -40,7 +40,16 @@ async def lifespan(_):
app = FastAPI(lifespan=lifespan)
-app.mount("/static", StaticFiles(directory=Path(__file__).parent / "static"), name="static")
+class Static(StaticFiles):
+ """Static files that browsers re-check on every load, so a new version shows up on refresh."""
+
+ async def get_response(self, path, scope):
+ response = await super().get_response(path, scope)
+ response.headers["Cache-Control"] = "no-cache"
+ return response
+
+
+app.mount("/static", Static(directory=Path(__file__).parent / "static"), name="static")
class Point(BaseModel):
@@ -143,7 +152,11 @@ async def raw(t: Text):
@app.post("/api/calibrate/start")
async def calibrate_start():
- return await act(phone.start_calibration())
+ """Calibrate the pointer. {"auto": true}: done by itself; otherwise the user clicks the pointer next."""
+ try:
+ return {"ok": True, "auto": await phone.start_calibration(), "span": phone.span}
+ except (DeviceError, RuntimeError) as e:
+ raise HTTPException(409, str(e)) from e
@app.post("/api/calibrate/finish")
diff --git a/server/hidagent/device.py b/server/hidagent/device.py
index c8376cb..e703138 100644
--- a/server/hidagent/device.py
+++ b/server/hidagent/device.py
@@ -17,7 +17,7 @@ class Device:
def __init__(self):
self._reader = self._writer = None
self._lock = asyncio.Lock()
- self._last = 0.0
+ self._last = self._beat = 0.0
self.links = 0 # bumped on every (re)connect, so gestures know to release and re-home
@property
@@ -28,11 +28,17 @@ class Device:
return await asyncio.start_server(self._accept, host, port)
async def _accept(self, reader, writer):
+ # newer firmware greets with "hello <last reset reason> <uptime ms>": read it before any command
+ try:
+ hello = (await asyncio.wait_for(reader.readline(), 1)).decode().strip()
+ except (OSError, asyncio.TimeoutError):
+ hello = ""
if self.connected:
self._writer.close()
self._reader, self._writer = reader, writer
self.links += 1
- log.info("board connected from %s", writer.get_extra_info("peername"))
+ self._last = self._beat = time.time() # fresh link: nothing to keep awake yet
+ log.info("board connected from %s %s", writer.get_extra_info("peername"), hello)
async def wait_connected(self, timeout: float) -> bool:
deadline = time.time() + timeout
@@ -49,6 +55,8 @@ class Device:
return 5 + max(abs(int(n)) for n in arg.split()) / 10 * 0.012
if name == "type":
return 5 + 0.1 * len(arg)
+ if name == "ping":
+ return 8 # an idle check: tolerate a Wi-Fi hiccup rather than drop a healthy board
return 5
async def send(self, command: str) -> None:
@@ -64,18 +72,27 @@ class Device:
except (OSError, asyncio.TimeoutError) as e:
self._writer.close() # the board reconnects on its own within a few seconds
raise DeviceError(f"board link lost during '{command[:30]}': {e!r}") from e
- self._last = time.time()
- log.debug("%s -> %s (%.0f ms)", command, reply, (time.time() - started) * 1000)
+ self._beat = time.time() # last reply of any kind
+ if command != "ping":
+ self._last = self._beat # last real command: the phone's idle time
+ log.debug("%s -> %s (%.0f ms)", command, reply, (time.time() - started) * 1000)
if reply != "ok":
raise DeviceError(reply or "board disconnected")
- async def keep_awake(self, idle: float = 25) -> None:
- """Nudge the pointer when idle so the phone does not auto-lock."""
+ async def keep_awake(self, idle: float = 25, heartbeat: float = 2, screen=None) -> None:
+ """While idle: ping every few seconds, so a board that was unplugged or hung shows as gone within
+ seconds (not at the next command), and nudge the pointer now and then so the phone does not auto-lock."""
while True:
- await asyncio.sleep(5)
- if self.connected and time.time() - self._last > idle:
- try:
+ await asyncio.sleep(heartbeat)
+ if not self.connected or time.time() - self._beat < heartbeat:
+ continue
+ try:
+ # nudge only a phone that is awake and mirroring: moving a sleeping phone's pointer can stall the
+ # board on its USB link, and there is nothing to keep awake anyway
+ if time.time() - self._last > idle and (screen is None or screen.live):
await self.send("move 1 0")
await self.send("move -1 0")
- except DeviceError as e:
- log.debug("keep-awake failed: %s", e)
+ else:
+ await self.send("ping")
+ except DeviceError as e:
+ log.info("board gone: %s", e)
diff --git a/server/hidagent/llm.py b/server/hidagent/llm.py
index 5756da2..195c2d2 100644
--- a/server/hidagent/llm.py
+++ b/server/hidagent/llm.py
@@ -6,10 +6,15 @@ import os
import httpx
+TOKEN_PARAMS = ("max_tokens", "max_completion_tokens")
+
class LLM:
- def __init__(self, base_url: str, model: str, api_key: str = "", extra: dict | None = None):
+ def __init__(self, base_url: str, model: str, api_key: str = "", extra: dict | None = None,
+ token_param: str = "auto"):
self.model, self.extra = model, extra or {}
+ # "auto": send max_tokens; switch for good if the server asks for max_completion_tokens (newer OpenAI models)
+ self.token_param, self._auto = (token_param, False) if token_param in TOKEN_PARAMS else ("max_tokens", True)
headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}
self._http = httpx.AsyncClient(base_url=base_url.rstrip("/"), headers=headers, timeout=120)
@@ -19,7 +24,7 @@ class LLM:
def env(key, default=""):
return os.environ.get(f"{role}_{key}") or os.environ.get(f"LLM_{key}", default)
return cls(env("BASE_URL", "http://localhost:8000/v1"), env("MODEL"),
- env("API_KEY"), json.loads(env("EXTRA_BODY", "{}")))
+ env("API_KEY"), json.loads(env("EXTRA_BODY", "{}")), env("TOKEN_PARAM", "auto"))
async def chat(self, system: str, text: str, image: bytes | None = None,
max_tokens: int = 600, temperature: float = 0) -> str:
@@ -27,8 +32,11 @@ class LLM:
if image:
url = "data:image/jpeg;base64," + base64.b64encode(image).decode()
content.insert(0, {"type": "image_url", "image_url": {"url": url}})
- body = {"model": self.model, "max_tokens": max_tokens, "temperature": temperature, **self.extra,
+ body = {"model": self.model, "temperature": temperature, **self.extra,
"messages": [{"role": "system", "content": system}, {"role": "user", "content": content}]}
- r = await self._http.post("/chat/completions", json=body)
+ r = await self._http.post("/chat/completions", json={self.token_param: max_tokens, **body})
+ if r.status_code == 400 and self._auto and "max_completion_tokens" in r.text:
+ self.token_param, self._auto = "max_completion_tokens", False
+ r = await self._http.post("/chat/completions", json={self.token_param: max_tokens, **body})
r.raise_for_status()
return r.json()["choices"][0]["message"]["content"] or ""
diff --git a/server/tests/test_llm.py b/server/tests/test_llm.py
new file mode 100644
index 0000000..b8e1691
--- /dev/null
+++ b/server/tests/test_llm.py
@@ -0,0 +1,53 @@
+import asyncio
+import json
+
+import httpx
+
+from hidagent.llm import LLM
+
+
+def fake_server(llm: LLM, wants: str) -> list[dict]:
+ """Point the client at an in-memory endpoint that only accepts the `wants` token parameter."""
+ seen = []
+
+ def handle(request: httpx.Request) -> httpx.Response:
+ body = json.loads(request.content)
+ seen.append(body)
+ if wants not in body:
+ return httpx.Response(400, json={"error": {"message": f"Unsupported parameter. Use '{wants}' instead."}})
+ return httpx.Response(200, json={"choices": [{"message": {"content": "DO: wait"}}]})
+
+ llm._http = httpx.AsyncClient(base_url="http://test/v1", transport=httpx.MockTransport(handle))
+ return seen
+
+
+def test_classic_servers_get_max_tokens_once():
+ llm = LLM("http://test/v1", "qwen")
+ seen = fake_server(llm, "max_tokens")
+ assert asyncio.run(llm.chat("sys", "hi")) == "DO: wait"
+ assert len(seen) == 1 and seen[0]["max_tokens"] == 600
+
+
+def test_auto_switches_to_max_completion_tokens_and_remembers():
+ llm = LLM("http://test/v1", "gpt")
+ seen = fake_server(llm, "max_completion_tokens")
+ asyncio.run(llm.chat("sys", "hi"))
+ asyncio.run(llm.chat("sys", "again"))
+ assert [("max_tokens" in b, "max_completion_tokens" in b) for b in seen] == [(True, False), (False, True),
+ (False, True)]
+
+
+def test_explicit_token_param_is_used_directly():
+ llm = LLM("http://test/v1", "gpt", token_param="max_completion_tokens")
+ seen = fake_server(llm, "max_completion_tokens")
+ asyncio.run(llm.chat("sys", "hi"))
+ assert len(seen) == 1
+
+
+def test_extra_body_and_image_are_sent():
+ llm = LLM("http://test/v1", "gpt", extra={"reasoning_effort": "none"})
+ seen = fake_server(llm, "max_tokens")
+ asyncio.run(llm.chat("sys", "hi", image=b"\xff\xd8jpeg"))
+ body = seen[0]
+ assert body["reasoning_effort"] == "none"
+ assert body["messages"][1]["content"][0]["image_url"]["url"].startswith("data:image/jpeg;base64,")