Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools
Rust ai-agentautomationclaudeclaude-codedockeriosiphonelinuxmcpmcp-servermodel-context-protocolrustwebdriveragent
"""Real-device scenarios for AI tasks kept by the daemon (docs/task-control.md; regression cases #65–67, #106–110, and an agent controlling itself).
pip install -r tests/device/requirements.txt
python tests/device/tasks.py # every scenario except `restart`
python tests/device/tasks.py pause scope # only these
python tests/device/tasks.py restart --restart 'systemctl --user restart iphone-control'
It plays an agent platform: opens tasks on the daemon's control socket (holding the lease the way `task run` does),
starts one MCP server with the task's token (the agent) and one without (anyone else), steers the task with the
`iphone-control task …` commands and checks what the daemon lets through. Every check prints a PASS / FAIL line with
what came back; the last line sums up, and the exit code is 1 if anything failed. Paste the output into the pull
request (CONTRIBUTING.md, "Required tests", part 4).
Harmless by design: it presses Home, opens Settings and Clock, takes screenshots, and refuses the two links it tries
to open (one of them a scheme no app handles). Nothing is sent, bought, deleted or changed.
Environment: ICTL_BIN (default `iphone-control`; your branch's build for a pull request), MCP_CMD (default
`$ICTL_BIN mcp`; or MCP_URL for MCP over HTTP, see mcp_http.py), ICTL_SOCKET (default `$XDG_RUNTIME_DIR/iphone-control/ctl.sock`), ICTL_VIEWER (the control page of
the same build, such as `http://127.0.0.1:8202`; the `self` scenario then also tries the page's API from inside a
task), ICTL_VIEWER_TOKEN (its login token, `iphone-control viewer token`; also sent to MCP_URL).
"""
import argparse
import asyncio
import json
import os
import shlex
import sys
import tempfile
import traceback
import time
from contextlib import AsyncExitStack
from mcp import ClientSession
from mcp.client.stdio import StdioServerParameters, stdio_client
import mcp_http
BIN = shlex.split(os.environ.get("ICTL_BIN", "iphone-control"))
MCP_CMD = shlex.split(os.environ.get("MCP_CMD", "")) or [*BIN, "mcp"]
SOCKET = os.environ.get("ICTL_SOCKET") or os.path.join(
os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}"), "iphone-control", "ctl.sock"
)
TOKEN_ENV = "IPHONE_CONTROL_TASK_TOKEN"
OWNER = "device-test"
HERE = os.path.dirname(os.path.abspath(__file__))
VIEWER = os.environ.get("ICTL_VIEWER", "").rstrip("/")
# Run under `task run`: asks the control page to pause the task it runs in, prints the answer
PAGE_PAUSE = """
import json, os, sys, urllib.error, urllib.request
v, task = sys.argv[1], os.environ["IPHONE_CONTROL_TASK_ID"]
headers = {"Content-Type": "application/json", "Origin": v}
if os.environ.get("ICTL_VIEWER_TOKEN"):
headers["Authorization"] = "Bearer " + os.environ["ICTL_VIEWER_TOKEN"]
req = urllib.request.Request(f"{v}/api/agent/tasks/{task}/pause", data=b"{}", method="POST", headers=headers)
try:
r = urllib.request.urlopen(req, timeout=15)
print(r.status, r.read().decode())
except urllib.error.HTTPError as e:
print(e.code, e.read().decode())
"""
results: list[bool] = []
def short(text: str, n: int = 160) -> str:
one = " ".join(text.split())
return one if len(one) <= n else one[: n - 1] + "…"
def check(case: str, what: str, ok: bool, got: str = "") -> bool:
results.append(ok)
print(f"{'PASS' if ok else 'FAIL'} [{case}] {what}" + (f" ← {short(got)}" if got else ""), flush=True)
return ok
# ---------------------------------------------------------------- the daemon's control socket
async def ask(req: dict, timeout: float = 15) -> dict:
r, w = await asyncio.open_unix_connection(SOCKET)
try:
w.write((json.dumps(req, ensure_ascii=False) + "\n").encode())
await w.drain()
return json.loads(await asyncio.wait_for(r.readline(), timeout))
finally:
w.close()
async def events(task_id: str, timeout: float = 10) -> list[dict]:
"""A task's events so far (it has ended, so the stream closes)"""
r, w = await asyncio.open_unix_connection(SOCKET)
try:
w.write((json.dumps({"op": "task_events", "id": task_id}) + "\n").encode())
await w.drain()
await asyncio.wait_for(r.readline(), timeout)
out = []
while line := await asyncio.wait_for(r.readline(), timeout):
out.append(json.loads(line))
return out
finally:
w.close()
async def tasks() -> list[dict]:
r = await ask({"op": "task_list"})
if r.get("kind") != "text":
raise RuntimeError(f"task_list: {r}")
return json.loads(r["text"])
async def info(task_id: str) -> dict:
return next((t for t in await tasks() if t["id"] == task_id), {})
async def wait_for(cond, timeout: float = 15, every: float = 0.2):
"""Polls the async `cond()` until it returns something truthy; returns that, or None on timeout"""
end = time.time() + timeout
while time.time() < end:
v = await cond()
if v:
return v
await asyncio.sleep(every)
return None
async def state_is(task_id: str, state: str, timeout: float = 15) -> bool:
async def ok():
return (await info(task_id)).get("state") == state
return bool(await wait_for(ok, timeout))
class Lease:
"""An opened task: the connection is its lease, and its events are collected as they come"""
def __init__(self):
self.id = self.token = ""
self.events: list[dict] = []
self._w = None
self._reader = None
@classmethod
async def open(cls, title: str, apps=()):
self = cls()
r, self._w = await asyncio.open_unix_connection(SOCKET)
req = {"op": "task_open", "title": title, "owner": OWNER, "apps": list(apps)}
self._w.write((json.dumps(req, ensure_ascii=False) + "\n").encode())
await self._w.drain()
first = json.loads(await asyncio.wait_for(r.readline(), 60))
if first.get("kind") != "text":
self._w.close()
raise RuntimeError(first.get("message", first))
opened = json.loads(first["text"])
self.id, self.token = opened["id"], opened["token"]
self._reader = asyncio.create_task(self._read(r))
return self
async def _read(self, r):
while line := await r.readline():
try:
self.events.append(json.loads(line))
except ValueError:
pass
def of(self, kind: str) -> list[dict]:
return [e["data"] for e in self.events if e["event"] == kind]
def done(self):
return next(iter(self.of("done")), None)
async def finish(self, ok: bool = True, summary: str = "device test"):
return await ask({"op": "task_finish", "ok": ok, "summary": summary, "task": self.token})
def close(self):
if self._w:
self._w.close()
self._w = None
# ---------------------------------------------------------------- MCP servers and the CLI
async def mcp(stack: AsyncExitStack, token: str | None) -> ClientSession:
env = dict(os.environ)
env.pop(TOKEN_ENV, None)
if token:
env[TOKEN_ENV] = token
params = StdioServerParameters(command=MCP_CMD[0], args=MCP_CMD[1:], env=env)
if mcp_http.URL:
r, w = await mcp_http.streams(stack, token)
else:
r, w = await stack.enter_async_context(stdio_client(params))
s = await stack.enter_async_context(ClientSession(r, w))
await s.initialize()
return s
async def call(s: ClientSession, name: str, args: dict | None = None, timeout: float = 90):
"""(is_error, text, seconds)"""
t = time.time()
res = await asyncio.wait_for(s.call_tool(name, args or {}), timeout)
text = "\n".join(c.text for c in res.content if c.type == "text")
return bool(res.is_error), text, time.time() - t
async def cli(*args: str, timeout: float = 30, token: str | None = None):
"""`iphone-control task …`: (exit code, output). `token`: run it inside that task (the agent's environment)"""
env = dict(os.environ)
env.pop(TOKEN_ENV, None)
if token:
env[TOKEN_ENV] = token
p = await asyncio.create_subprocess_exec(
*BIN, "task", *args, env=env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT
)
out, _ = await asyncio.wait_for(p.communicate(), timeout)
return p.returncode, out.decode(errors="replace").strip()
async def confirm_asked(lease: Lease, before: int, timeout: float = 30):
"""Waits until the task waits for a confirmation it didn't have before; returns the confirmation"""
async def asked():
c = lease.of("confirm")
return c[-1] if len(c) > before and (await info(lease.id)).get("state") == "waiting" else None
return await wait_for(asked, timeout)
# ---------------------------------------------------------------- scenarios
async def others(stack):
"""#106: while a task runs, anyone else may look but not act; the task's agent may"""
c = "others"
lease = await Lease.open("真机回归:任务进行中别人只能看")
stack.callback(lease.close)
agent, other = await mcp(stack, lease.token), await mcp(stack, None)
names = lambda r: {t.name for t in r.tools} # noqa: E731
check(c, "the agent's MCP server lists iphone_confirm", "iphone_confirm" in names(await agent.list_tools()))
check(c, "a plain MCP server doesn't", "iphone_confirm" not in names(await other.list_tools()))
err, text, dt = await call(other, "iphone_screenshot")
check(c, f"another caller may take a screenshot ({dt:.2f}s)", not err, text)
err, text, dt = await call(other, "iphone_press_button", {"button": "home"})
check(c, f"another caller's Home is refused, naming the task ({dt:.2f}s)", err and lease.id in text, text)
# the device it already controls: harmless even if it went through (`auto` would undo a pinned choice)
udid = (await info(lease.id)).get("udid", "")
err, text, _ = await call(other, "iphone_select_device", {"device": udid})
check(c, "selecting a device is refused", err, text)
err, text, dt = await call(agent, "iphone_press_button", {"button": "home"})
check(c, f"the agent's Home goes through ({dt:.2f}s)", not err, text)
steps = [s for s in lease.of("step") if s.get("tool") == "iphone_press_button"]
check(c, "the agent's call is a step of the task", bool(steps), json.dumps(steps[:1], ensure_ascii=False))
await lease.finish()
check(c, "finished as completed", await state_is(lease.id, "completed"))
err, text, dt = await call(other, "iphone_press_button", {"button": "home"})
check(c, f"after the task, anyone may act again ({dt:.2f}s)", not err, text)
async def pause(stack):
"""#66: a paused task's calls wait in the daemon, also between the steps of iphone_batch"""
c = "pause"
lease = await Lease.open("真机回归:暂停")
stack.callback(lease.close)
agent = await mcp(stack, lease.token)
code, out = await cli("pause", lease.id)
check(c, "`task pause` works", code == 0, out)
began = lambda: len([s for s in lease.of("step") if "tool" in s]) # noqa: E731
n = began()
held = asyncio.create_task(call(agent, "iphone_screenshot"))
await asyncio.sleep(5)
check(c, "a call while paused is held (5 s, no result)", not held.done())
check(c, "and no new step shows up", began() == n)
code, out = await cli("resume", lease.id)
check(c, "`task resume` works", code == 0, out)
err, text, dt = await asyncio.wait_for(held, 60)
check(c, f"after resuming it runs ({dt:.1f}s in all)", not err and dt >= 5, text)
steps = [{"tool": "iphone_press_button", "button": "home"}, {"tool": "wait", "seconds": 3}, {"tool": "iphone_press_button", "button": "home"}]
batch = asyncio.create_task(call(agent, "iphone_batch", {"steps": steps}))
await asyncio.sleep(1.5)
await cli("pause", lease.id)
await asyncio.sleep(5)
check(c, "a batch paused in its wait doesn't take its next step (held 5 s after a 3 s wait)", not batch.done())
await cli("resume", lease.id)
err, text, dt = await asyncio.wait_for(batch, 60)
check(c, f"after resuming the batch finishes ({dt:.1f}s in all)", not err and dt >= 6, text)
await lease.finish()
async def handback(stack):
"""#67: the user may act while the task is taken over; after handing back, the agent looks before acting"""
c = "handback"
lease = await Lease.open("真机回归:接管和交还")
stack.callback(lease.close)
agent, other = await mcp(stack, lease.token), await mcp(stack, None)
code, out = await cli("takeover", lease.id)
check(c, "`task takeover` works", code == 0 and await state_is(lease.id, "takeover"), out)
err, text, dt = await call(other, "iphone_press_button", {"button": "home"})
check(c, f"while taken over, the user's Home goes through ({dt:.2f}s)", not err, text)
code, out = await cli("handback", lease.id)
check(c, "`task handback` works", code == 0 and await state_is(lease.id, "running"), out)
err, text, _ = await call(agent, "iphone_press_button", {"button": "home"})
check(c, "the agent's first action is refused: look first", err and "iphone_screenshot" in text, text)
err, text, _ = await call(agent, "iphone_press_button", {"button": "home"})
check(c, "and the next one too, until it has looked", err, text)
err, text, _ = await call(agent, "iphone_screenshot")
check(c, "a screenshot goes through", not err, text)
err, text, _ = await call(agent, "iphone_press_button", {"button": "home"})
check(c, "after it, the agent acts again", not err, text)
await lease.finish()
async def confirm(stack):
"""iphone_confirm waits for `task approve` / `task reject`; a rejection ends the task as rejected"""
c = "confirm"
lease = await Lease.open("真机回归:确认")
stack.callback(lease.close)
agent = await mcp(stack, lease.token)
code, out = await cli("approve", lease.id)
check(c, "`task approve` with nothing waiting fails", code != 0, out)
args = {"action": "真机回归:测试确认", "detail": "只是测试,同意或拒绝都不会在手机上做任何事"}
for approve in (True, False):
before = len(lease.of("confirm"))
asking = asyncio.create_task(call(agent, "iphone_confirm", args))
shown = await confirm_asked(lease, before)
check(c, "the task waits, with the confirmation shown", bool(shown), json.dumps(shown, ensure_ascii=False))
code, out = await cli("approve" if approve else "reject", lease.id)
err, text, dt = await asyncio.wait_for(asking, 30)
what = "approved: a normal result" if approve else "rejected: an error the agent must stop on"
check(c, f"{what} ({dt:.1f}s)", code == 0 and err != approve, text)
await lease.finish(ok=True)
check(c, "the task ends as rejected though the agent said ok", await state_is(lease.id, "rejected"))
async def self_control(stack):
"""An agent can't answer its own confirmation or pause itself: not with the task's token, nor from a process
`task run` started without it; the user can, and the log says who"""
c = "self"
lease = await Lease.open("真机回归:Agent 不能自己确认")
stack.callback(lease.close)
agent = await mcp(stack, lease.token)
args = {"action": "真机回归:Agent 自己确认", "detail": "只是测试,不会在手机上做任何事"}
asking = asyncio.create_task(call(agent, "iphone_confirm", args))
shown = await confirm_asked(lease, 0)
check(c, "the task waits for a confirmation", bool(shown), json.dumps(shown, ensure_ascii=False))
code, out = await cli("approve", lease.id, token=lease.token)
check(c, "`task approve` with the task's token is refused", code != 0, out)
check(c, "and the task still waits", (await info(lease.id)).get("state") == "waiting")
code, out = await cli("reject", lease.id)
err, text, _ = await asyncio.wait_for(asking, 30)
check(c, "the user's `task reject` answers it", code == 0 and err, text)
by = [d.get("by") for d in lease.of("control")]
check(c, "the log says it was the command line", by == ["cli"], json.dumps(by))
await lease.finish(ok=False)
# under `task run`, the command drops the token and tries anyway: it was started by the task, so no
title = f"真机回归:task run 里自己暂停 {int(time.time())}"
script = 'env -u IPHONE_CONTROL_TASK_TOKEN "$@" task pause "$IPHONE_CONTROL_TASK_ID"'
p = await asyncio.create_subprocess_exec(
*BIN, "task", "run", "--title", title, "--owner", OWNER, "--", "sh", "-c", script, "sh", *BIN,
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT,
)
out, _ = await asyncio.wait_for(p.communicate(), 60)
out = out.decode(errors="replace")
t = next((t for t in reversed(await tasks()) if t["title"] == title), {})
check(c, "a process `task run` started can't pause its task, even without the token",
p.returncode != 0 and t.get("state") == "failed", f"exit {p.returncode}, {t.get('state')}: {out}")
if not VIEWER:
print(f"SKIP [{c}] the page's API from inside a task: set ICTL_VIEWER", flush=True)
return
title = f"真机回归:task run 里调控制台暂停 {int(time.time())}"
p = await asyncio.create_subprocess_exec(
*BIN, "task", "run", "--title", title, "--owner", OWNER, "--", sys.executable, "-c", PAGE_PAUSE, VIEWER,
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT,
)
out, _ = await asyncio.wait_for(p.communicate(), 60)
out = out.decode(errors="replace")
t = next((t for t in reversed(await tasks()) if t["title"] == title), {})
paused = any(e["event"] == "control" for e in await events(t["id"])) if t else True
check(c, "nor through the control page's API (Linux)", '"ok":false' in out.replace(" ", "") and not paused,
f"{t.get('state')}: {out}")
async def stop(stack):
"""#65: once stopped, the task's token is refused for everything"""
c = "stop"
lease = await Lease.open("真机回归:停止")
stack.callback(lease.close)
agent = await mcp(stack, lease.token)
err, text, _ = await call(agent, "iphone_press_button", {"button": "home"})
check(c, "the agent acts", not err, text)
code, out = await cli("stop", lease.id)
check(c, "`task stop` works", code == 0, out)
done = await wait_for(lambda: asyncio.sleep(0, lease.done()), 10)
check(c, "the opener hears it ended (cancelled)", bool(done) and done.get("outcome") == "cancelled", json.dumps(done, ensure_ascii=False))
for tool in ("iphone_press_button", "iphone_screenshot"):
err, text, _ = await call(agent, tool, {"button": "home"} if tool == "iphone_press_button" else {})
check(c, f"afterwards the agent's {tool} is refused", err, text)
async def lease(stack):
"""#65: the opener going away ends the task as abandoned; the agent stops, others may act again"""
c = "lease"
t = await Lease.open("真机回归:发起方断开")
agent, other = await mcp(stack, t.token), await mcp(stack, None)
t.close()
check(c, "closing the lease ends the task as abandoned", await state_is(t.id, "abandoned", 10))
err, text, _ = await call(agent, "iphone_screenshot")
check(c, "the agent is refused", err, text)
err, text, _ = await call(other, "iphone_press_button", {"button": "home"})
check(c, "others may act again", not err, text)
async def run_cmd(stack):
"""`task run`: the integration for agent platforms (#50), end to end and when stopped from elsewhere"""
c = "run"
title = f"真机回归:task run {int(time.time())}"
steps = [
["iphone_status", {}],
["iphone_press_button", {"button": "home"}],
["iphone_launch_app", {"app": "时钟"}],
["iphone_list_elements", {"limit": 5}],
["iphone_press_button", {"button": "home"}],
]
env = {**os.environ, "MCP_CMD": shlex.join(MCP_CMD), "SHOTS_DIR": tempfile.mkdtemp(prefix="ictl-shots-")}
env.pop(TOKEN_ENV, None)
p = await asyncio.create_subprocess_exec(
*BIN, "task", "run", "--title", title, "--owner", OWNER, "--",
sys.executable, os.path.join(HERE, "run.py"), json.dumps(steps, ensure_ascii=False),
env=env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT,
)
out, _ = await asyncio.wait_for(p.communicate(), 300)
out = out.decode(errors="replace")
last = [line for line in out.splitlines() if line.startswith("---")]
check(c, "run.py under `task run` passes (exit 0)", p.returncode == 0, last[-1] if last else out[-300:])
t = next((t for t in reversed(await tasks()) if t["title"] == title), {})
check(c, "its task completed with every call as a step", t.get("state") == "completed" and t.get("steps", 0) >= len(steps), json.dumps(t, ensure_ascii=False))
title = f"真机回归:task run 被停止 {int(time.time())}"
p = await asyncio.create_subprocess_exec(
*BIN, "task", "run", "--title", title, "--owner", OWNER, "--", "sleep", "600",
stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL,
)
async def running():
return next((t for t in await tasks() if t["title"] == title and t["state"] == "running"), None)
t = await wait_for(running, 20)
check(c, "`task run -- sleep 600` opens a task", bool(t))
if t:
t0 = time.time()
await cli("stop", t["id"])
code = await asyncio.wait_for(p.wait(), 15)
check(c, f"`task stop` ends the command too ({time.time() - t0:.1f}s, exit {code})", code != 0)
check(c, "and the task is cancelled", await state_is(t["id"], "cancelled"))
elif p.returncode is None:
p.kill()
# the command ends the task itself (`task finish`): its own exit code, not 1 from being stopped while leaving
for title_tail, script, want, max_s in (
("finish 后退出", '"$@" task finish 完成; sleep 1', 0, 4),
("finish 后不退出", '"$@" task finish 完成; sleep 600', 0, 12),
("finish 失败后退出", '"$@" task finish --failed 没做成; exit 3', 3, 4),
):
title = f"真机回归:task run {title_tail} {int(time.time())}"
t0 = time.time()
p = await asyncio.create_subprocess_exec(
*BIN, "task", "run", "--title", title, "--owner", OWNER, "--", "sh", "-c", script, "sh", *BIN,
stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL,
)
code = await asyncio.wait_for(p.wait(), 30)
dt = time.time() - t0
state = (next((t for t in reversed(await tasks()) if t["title"] == title), {})).get("state")
check(c, f"`task finish` then {title_tail}: exit {code} ({dt:.1f}s), task {state}",
code == want and dt < max_s and state == ("failed" if want else "completed"))
async def remote(stack):
"""docs/task-control.md 7.6: a platform on another machine opens a task over HTTP and keeps the login; its agent
has only the task's token, works through /mcp and can't control the task; closing the response abandons it.
Then `task run --url`, the same from the command line"""
c = "remote"
login = os.environ.get("ICTL_VIEWER_TOKEN")
if not (VIEWER and login and mcp_http.URL):
print(f"SKIP [{c}] needs ICTL_VIEWER, ICTL_VIEWER_TOKEN and MCP_URL (the branch's viewer)", flush=True)
return
import ssl
import httpx2
ca = os.environ.get("MCP_CA")
verify = ssl.create_default_context(cafile=ca) if ca else True
timeout = httpx2.Timeout(30, read=300)
platform = httpx2.AsyncClient(base_url=VIEWER, headers={"Authorization": f"Bearer {login}"}, verify=verify,
trust_env=False, timeout=timeout)
nobody = httpx2.AsyncClient(base_url=VIEWER, verify=verify, trust_env=False, timeout=timeout)
await stack.enter_async_context(platform)
await stack.enter_async_context(nobody)
# the platform opens the task; the response is the lease
opening = platform.stream("POST", "/api/agent/tasks/open", json={"title": "真机回归:远端开任务", "owner": OWNER})
resp = await opening.__aenter__()
closed = False
async def close_lease():
nonlocal closed
if not closed:
closed = True
await opening.__aexit__(None, None, None)
stack.push_async_callback(close_lease)
lines = resp.aiter_lines()
async def next_event():
name, data = None, []
async for line in lines:
if not line:
if name:
return name, json.loads("\n".join(data))
continue
if line.startswith("event:"):
name = line[6:].strip()
elif line.startswith("data:"):
data.append(line[5:].lstrip())
return None, None
url = ["--url", VIEWER] + (["--ca", ca] if ca else [])
# the platform's command line (the login) and the agent's shell (the task's token and the address, no login)
platform_env = {k: v for k, v in os.environ.items() if k not in (TOKEN_ENV, "ICTL_VIEWER_TOKEN")}
platform_env["IPHONE_CONTROL_VIEWER_TOKEN"] = login
async def rcli(*args, env=None):
p = await asyncio.create_subprocess_exec(*BIN, "task", *args, *url, env=env or platform_env,
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT)
out, _ = await asyncio.wait_for(p.communicate(), 30)
return p.returncode, out.decode(errors="replace").strip()
name, opened = await asyncio.wait_for(next_event(), 30)
check(c, "the platform opens a task over HTTP (server-sent events)", resp.status_code == 200 and name == "opened",
f"{resp.status_code} {name}")
task_id, token = opened["id"], opened["token"]
seen: list[tuple[str, dict]] = []
async def follow():
while True:
n, d = await next_event()
if n is None:
return
seen.append((n, d))
follower = asyncio.create_task(follow())
stack.callback(follower.cancel)
# the agent: the task's token and the address, no login
saved = os.environ.pop("ICTL_VIEWER_TOKEN")
try:
agent = await mcp(stack, token)
finally:
os.environ["ICTL_VIEWER_TOKEN"] = saved
err, text, _ = await call(agent, "iphone_press_button", {"button": "home"})
check(c, "the agent acts through /mcp with the task's token alone", not err, text)
hdr = {"Iphone-Control-Task-Token": token}
for action, body in (("resume", {}), ("confirm", {"approve": True}), ("stop", {})):
r = await nobody.post(f"/api/agent/tasks/{task_id}/{action}", json=body, headers=hdr)
check(c, f"the agent can't {action} its task with that token", r.status_code == 401, f"{r.status_code} {r.text[:80]}")
r = await nobody.get("/api/info", headers=hdr)
check(c, "nor see the page's API", r.status_code == 401, str(r.status_code))
# the platform's command line, through the viewer
code, out = await rcli("list")
check(c, "`task list --url` shows the task", code == 0 and task_id in out and "running" in out, out[-200:])
code, out = await rcli("pause", task_id)
check(c, "`task pause --url` pauses it", code == 0 and await state_is(task_id, "paused"), out)
code, out = await rcli("resume", task_id)
check(c, "`task resume --url` resumes it", code == 0 and await state_is(task_id, "running"), out)
agent_env = {k: v for k, v in os.environ.items() if k not in ("ICTL_VIEWER_TOKEN", "IPHONE_CONTROL_VIEWER_TOKEN")}
agent_env.update({TOKEN_ENV: token, "IPHONE_CONTROL_URL": VIEWER, **({"IPHONE_CONTROL_CA": ca} if ca else {})})
code, out = await rcli("pause", task_id, env=agent_env)
check(c, "in the agent's shell (no login) `task pause` is refused",
code != 0 and await state_is(task_id, "running"), out)
# the platform pauses: the agent's next call waits until it resumes
r = await platform.post(f"/api/agent/tasks/{task_id}/pause", json={})
check(c, "the platform pauses it over HTTP", r.status_code == 200 and await state_is(task_id, "paused"), r.text)
t0 = time.time()
held = asyncio.create_task(call(agent, "iphone_screenshot"))
await asyncio.sleep(3)
still = not held.done()
await platform.post(f"/api/agent/tasks/{task_id}/resume", json={})
err, text, _ = await asyncio.wait_for(held, 60)
check(c, f"the agent's call waited while paused ({time.time() - t0:.1f}s)", still and not err, text)
# a confirmation: only the platform answers it
args = {"action": "真机回归:远端确认", "detail": "只是测试,不会在手机上做任何事"}
asking = asyncio.create_task(call(agent, "iphone_confirm", args))
waiting = await state_is(task_id, "waiting", 30)
r = await nobody.post(f"/api/agent/tasks/{task_id}/confirm", json={"approve": True}, headers=hdr)
check(c, "the agent waits for a confirmation it can't give itself", waiting and r.status_code == 401, str(r.status_code))
code, out = await rcli("approve", task_id, env=agent_env)
check(c, "nor with `task approve` in its shell", code != 0 and await state_is(task_id, "waiting", 2), out)
code, out = await rcli("approve", task_id)
err, text, _ = await asyncio.wait_for(asking, 30)
check(c, "the platform's `task approve --url` answers it", code == 0 and not err, f"{out} / {text}")
by = [d.get("by") for n, d in seen if n == "control"]
check(c, "the log names the login token", bool(by) and all(str(b).startswith("viewer:") for b in by), json.dumps(by))
# the platform goes away: the task is abandoned and the agent stops
await close_lease()
check(c, "closing the response abandons the task", await state_is(task_id, "abandoned", 15))
# with only the task's token, /mcp itself refuses it (401), which the client reports as an error
try:
err, text, _ = await call(agent, "iphone_screenshot")
except Exception as e: # noqa: BLE001 - any refusal will do
err, text = True, f"{type(e).__name__}: {e}"
check(c, "after that the agent is refused", err, text)
code, out = await rcli("events", task_id)
lines = [json.loads(line) for line in out.splitlines() if line.startswith("{")]
check(c, "`task events --url` replays the task to its end",
code == 0 and bool(lines) and lines[0]["event"] == "task" and lines[-1]["event"] == "done",
f"{len(lines)} events, last {lines[-1]['event'] if lines else None}")
# `task run --url`: run.py under it, through the viewer only (no daemon socket here)
env = {k: v for k, v in os.environ.items() if k not in (TOKEN_ENV, "MCP_URL", "MCP_CA", "ICTL_VIEWER_TOKEN")}
env.update({"IPHONE_CONTROL_VIEWER_TOKEN": login, "ICTL_SOCKET": "/nonexistent/ctl.sock",
"SHOTS_DIR": tempfile.mkdtemp(prefix="ictl-shots-")})
steps = [["iphone_status", {}], ["iphone_press_button", {"button": "home"}], ["iphone_list_elements", {"limit": 3}]]
title = f"真机回归:task run --url {int(time.time())}"
p = await asyncio.create_subprocess_exec(
*BIN, "task", "run", *url, "--title", title, "--owner", OWNER, "--",
sys.executable, os.path.join(HERE, "run.py"), json.dumps(steps), env=env,
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT,
)
out, _ = await asyncio.wait_for(p.communicate(), 300)
out = out.decode(errors="replace")
last = [line for line in out.splitlines() if line.startswith("---")]
t = next((t for t in reversed(await tasks()) if t["title"] == title), {})
check(c, "`task run --url` runs run.py through the viewer (exit 0)", p.returncode == 0, last[-1] if last else out[-300:])
check(c, "its task completed with every call as a step",
t.get("state") == "completed" and t.get("steps", 0) >= len(steps), json.dumps(t, ensure_ascii=False))
# an agent that only starts a command: plain `iphone-control mcp`, which bridges to the viewer by itself
title = f"真机回归:task run --url,stdio 转接 {int(time.time())}"
stdio_env = {**env, "MCP_CMD": shlex.join([*BIN, "mcp"])}
p = await asyncio.create_subprocess_exec(
*BIN, "task", "run", *url, "--title", title, "--owner", OWNER, "--",
"env", "-u", "IPHONE_CONTROL_MCP_URL", sys.executable, os.path.join(HERE, "run.py"), json.dumps(steps),
env=stdio_env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT,
)
out, _ = await asyncio.wait_for(p.communicate(), 300)
out = out.decode(errors="replace")
last = [line for line in out.splitlines() if line.startswith("---")]
t = next((t for t in reversed(await tasks()) if t["title"] == title), {})
check(c, "a stdio MCP client under `task run --url` works through `iphone-control mcp` (the bridge)",
p.returncode == 0 and t.get("state") == "completed" and t.get("steps", 0) >= len(steps),
(last[-1] if last else out[-300:]) + f" / {t.get('state')}, {t.get('steps')} steps")
title = f"真机回归:task run --url finish {int(time.time())}"
script = '[ -z "$IPHONE_CONTROL_VIEWER_TOKEN" ] || exit 9; "$@" task finish 远端完成'
p = await asyncio.create_subprocess_exec(
*BIN, "task", "run", *url, "--title", title, "--owner", OWNER, "--", "sh", "-c", script, "sh", *BIN, env=env,
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT,
)
out, _ = await asyncio.wait_for(p.communicate(), 60)
t = next((t for t in reversed(await tasks()) if t["title"] == title), {})
check(c, "the command doesn't get the login, and `task finish` ends its task remotely",
p.returncode == 0 and t.get("state") == "completed", f"exit {p.returncode}, {t.get('state')}: {out.decode(errors='replace')[-200:]}")
async def scope(stack):
"""#110: a task limited to Settings asks before going elsewhere; approving lets it in, rejecting refuses one step"""
c = "scope"
lease = await Lease.open("真机回归:只在设置里", apps=["设置"])
stack.callback(lease.close)
apps = (await info(lease.id)).get("apps", [])
if not apps:
print(f"SKIP [{c}] this daemon has no app scope (feat/task-scope)", flush=True)
await lease.finish()
return
check(c, "「设置」 resolved to its bundle ID", "com.apple.Preferences" in apps, ", ".join(apps))
agent = await mcp(stack, lease.token)
asked = lambda: len(lease.of("confirm")) # noqa: E731
n = asked()
err, text, _ = await call(agent, "iphone_launch_app", {"app": "设置"})
check(c, "launching Settings doesn't ask", not err and asked() == n, text)
async def outside(name, args, approve):
n = asked()
doing = asyncio.create_task(call(agent, name, args))
shown = await confirm_asked(lease, n)
check(c, f"{name} {json.dumps(args, ensure_ascii=False)} waits for the user", bool(shown), json.dumps(shown, ensure_ascii=False))
await cli("approve" if approve else "reject", lease.id)
err, text, dt = await asyncio.wait_for(doing, 60)
check(c, f"…{'approved: done' if approve else 'rejected: refused, the task goes on'} ({dt:.1f}s)", err != approve, text)
if not approve:
# the tool call the user kept out of scope shows as rejected on the page, not as failed
done = [e for e in lease.of("step") if "ms" in e and e.get("status") in ("rejected", "error")]
check(c, "…and its step is shown as rejected, not failed", bool(done) and done[-1]["status"] == "rejected", json.dumps(done[-1:], ensure_ascii=False))
return shown
shown = await outside("iphone_launch_app", {"app": "时钟"}, False)
check(c, "the question names the app", bool(shown) and "mobiletimer" in json.dumps(shown))
check(c, "the task is still running", (await info(lease.id)).get("state") == "running")
err, text, _ = await call(agent, "iphone_press_button", {"button": "home"})
check(c, "Home (the way back) isn't checked", not err, text)
await outside("iphone_launch_app", {"app": "时钟"}, True)
check(c, "Clock joined the scope", "com.apple.mobiletimer" in (await info(lease.id)).get("apps", []))
n = asked()
err, text, _ = await call(agent, "iphone_tap_element", {"text": "不存在的按钮xyz"})
check(c, "acting in Clock no longer asks (and taps nothing)", asked() == n, text)
await outside("iphone_open_url", {"url": "ictl-device-test://nothing"}, False)
await outside("iphone_open_url", {"url": "https://example.com"}, False)
err, text, _ = await call(agent, "iphone_press_button", {"button": "home"})
await lease.finish()
check(c, "the task completes (refusals don't make it rejected)", await state_is(lease.id, "completed"))
async def restart(stack, cmd: str):
"""#108: the daemon restarting interrupts the task; its old token means nothing afterwards"""
c = "restart"
lease = await Lease.open("真机回归:守护进程重启")
agent = await mcp(stack, lease.token)
err, text, _ = await call(agent, "iphone_press_button", {"button": "home"})
check(c, "the agent acts", not err, text)
p = await asyncio.create_subprocess_shell(cmd)
check(c, f"restart command `{cmd}`", await p.wait() == 0)
async def answers():
try:
return await info(lease.id)
except OSError:
return None
t = await wait_for(answers, 120, 1)
check(c, "after the restart the task is interrupted", (t or {}).get("state") == "interrupted", json.dumps(t, ensure_ascii=False))
err, text, _ = await call(agent, "iphone_screenshot", timeout=180)
check(c, "the old token is refused", err, text)
lease.close()
SCENARIOS = {
"others": others,
"pause": pause,
"handback": handback,
"confirm": confirm,
"self": self_control,
"stop": stop,
"lease": lease,
"run": run_cmd,
"scope": scope,
"remote": remote,
}
async def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("only", nargs="*", help=f"scenarios ({', '.join([*SCENARIOS, 'restart'])}); all but restart if none")
ap.add_argument("--restart", metavar="CMD", help="shell command that restarts the daemon, for `restart`")
a = ap.parse_args()
names = a.only or list(SCENARIOS)
unknown = [n for n in names if n not in SCENARIOS and n != "restart"]
if unknown or ("restart" in names and not a.restart):
ap.error(f"unknown {unknown}" if unknown else "restart needs --restart CMD")
print(f"=== {shlex.join(BIN)} ({SOCKET}), MCP: {shlex.join(MCP_CMD)}", flush=True)
t0 = time.time()
for name in names:
busy = [t for t in await tasks() if t["state"] in ("running", "paused", "takeover", "waiting")]
if busy:
print(f"FAIL [{name}] another task is active ({busy[0]['id']}, {busy[0]['title']}); not run", flush=True)
results.append(False)
continue
print(f"--- {name}", flush=True)
t = time.time()
async with AsyncExitStack() as stack:
try:
await (restart(stack, a.restart) if name == "restart" else SCENARIOS[name](stack))
except Exception as e: # noqa: BLE001 - a scenario that blew up is a failure, the next one still runs
traceback.print_exc()
check(name, f"scenario raised {type(e).__name__}", False, str(e))
finally:
# never leave a task holding the phone
for t_ in await tasks():
if t_["state"] in ("running", "paused", "takeover", "waiting") and t_["owner"] == OWNER:
await ask({"op": "task_control", "id": t_["id"], "action": "stop"})
print(f" ({time.time() - t:.1f}s)", flush=True)
failed = results.count(False)
print(f"--- {len(results)} checks, {failed} failed, {time.time() - t0:.1f}s in all", flush=True)
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(asyncio.run(main()))