Skip to content

Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools

feat(cli): opt-in live viewer in the browser (#34)

TheSalaty8551a07781f9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bf5254f..b244a27 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,7 @@ All notable changes to this project are documented here. The format is based on
- English: `IPHONE_CONTROL_LANG=en` switches tool descriptions, tool results, CLI output and help, `status`/`doctor`, logs and notifications to English. The default stays Simplified Chinese, so nothing changes unless you set it.
- The MCP server and the CLI send their language with each request and the daemon answers in it; requests from older clients carry none and get Chinese as before, so mixed versions during an upgrade keep working. `mcp-config` includes the setting when English is on.
- Text responses carry an optional `outcome` (`tapped_nothing`, `alert_reported`), so the MCP server no longer reads result text to stop a batch after a missed tap or to skip the extra alert check. Responses without it (older daemons) are still recognised by their Chinese prefixes.
+- `iphone-control viewer [--port]`: watch and control the phone live in a browser (opt-in, 127.0.0.1:8200 by default). Taps, swipes, long presses, typing and buttons go through the daemon, so they queue with the agent's calls and unlock the phone first. It binds the loopback address only, checks `Host`, and also checks `Origin` on actions; other local users can reach the port, so stop it when done.
### Fixed
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index 57b2f69..82d6268 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -11,6 +11,7 @@
- 英文界面:设 `IPHONE_CONTROL_LANG=en` 后,工具说明和结果、命令行输出和帮助、`status`/`doctor`、日志、通知都改成英文。默认仍是简体中文,不设就没有任何变化。
- MCP 和命令行在每个请求里带上自己的语言,守护进程按它回答;旧版本客户端的请求不带语言,照旧用中文,升级过程中新旧版本混用也不受影响。开着英文时 `mcp-config` 会把这个设置带上。
- 文字响应带可选的 `outcome`(`tapped_nothing`、`alert_reported`),MCP 端据此在没点到时停下批量、跳过多余的弹窗检查,不再从结果文字里认;没有这个字段的响应(旧版本守护进程)照旧按中文开头认。
+- `iphone-control viewer [--port]`:在浏览器里看实时画面并操作手机(默认 127.0.0.1:8200,显式开启)。点击、滑动、长按、输入和按键都经守护进程,和 agent 的调用排队,并先自动解锁。只绑本机回环地址,检查 `Host`,操作还检查 `Origin`;本机其他用户能连上这个端口,用完就停。
### 修复
diff --git a/README.md b/README.md
index ce9166b..0c04e11 100644
--- a/README.md
+++ b/README.md
@@ -134,6 +134,7 @@ Run them as `docker exec -it iphone-control iphone-control <command>`, or direct
| `notify-test [event]` | Send test notifications |
| `mcp-config` | Print the command that registers the MCP server |
| `wda-bridge [--port]` | Expose WebDriverAgent on 127.0.0.1 for other tools; stop it when done |
+| `viewer [--port]` | Watch the screen live in a browser and tap, swipe and type on it, on 127.0.0.1:8200; stop it when done |
All commands and options: [CLI reference](https://derrors.github.io/iphone-control/en/guide/cli).
diff --git a/README.zh-CN.md b/README.zh-CN.md
index dd38a35..c798534 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -134,6 +134,7 @@ iphone-control mcp-config # 打印 `claude mcp add` 命令,复制运行
| `notify-test [事件]` | 发送测试通知 |
| `mcp-config` | 打印注册 MCP 的命令 |
| `wda-bridge [--port]` | 把 WebDriverAgent 桥接到 127.0.0.1 给别的工具用,用完就停 |
+| `viewer [--port]` | 在浏览器里看实时画面,并点击、滑动、输入,地址 127.0.0.1:8200;用完就停 |
全部命令和参数见[命令行](https://derrors.github.io/iphone-control/guide/cli)。
diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rs
index beaeeb8..6eed17a 100644
--- a/apps/iphone-control/src/main.rs
+++ b/apps/iphone-control/src/main.rs
@@ -14,6 +14,7 @@ use ictl_daemon::protocol::{self, Request, Response};
#[cfg(feature = "debug-cmds")]
mod debug;
+mod viewer;
#[derive(Parser)]
#[command(name = "iphone-control", version, about = ictl_l10n::tr!("在 Linux 或 macOS 上控制 iPhone,并提供 MCP 工具", "Control an iPhone from Linux or macOS, with MCP tools"))]
@@ -77,6 +78,11 @@ enum Command {
#[arg(long, default_value_t = 8100)]
port: u16,
},
+ #[command(about = ictl_l10n::tr!("在浏览器里看实时画面并操作手机:只开在 127.0.0.1,点击、滑动、输入和按键都经守护进程(默认不监听任何端口)", "Watch and control the phone live in a browser: serves 127.0.0.1 only, taps, swipes, typing and buttons go through the daemon (by default no port is opened)"))]
+ Viewer {
+ #[arg(long, default_value_t = 8200)]
+ port: u16,
+ },
#[command(about = ictl_l10n::tr!("真机诊断(开发用,要用 `--features debug-cmds` 编译)。`wda`/`e2e`/`hid` 会和守护进程抢 XCTest、HID,先停掉守护进程", "Real-device diagnostics (for development, build with `--features debug-cmds`). `wda`/`e2e`/`hid` compete with the daemon for XCTest and HID, so stop the daemon first"))]
#[cfg(feature = "debug-cmds")]
#[command(hide = true)]
@@ -145,6 +151,7 @@ async fn main() -> anyhow::Result<()> {
Command::Devices => print_text(&cli.socket, Request::ListDevices).await,
Command::Select { device } => print_text(&cli.socket, Request::SelectDevice { device }).await,
Command::WdaBridge { port } => wda_bridge(&cli.socket, port).await,
+ Command::Viewer { port } => viewer::run(&cli.socket, port).await,
#[cfg(feature = "debug-cmds")]
Command::Debug(args) => debug::run(env_nonempty("IPHONE_UDID").as_deref(), args).await,
Command::NotifyTest { event } => notify_test(&cli.data_dir, event.as_deref()).await,
diff --git a/apps/iphone-control/src/viewer.html b/apps/iphone-control/src/viewer.html
new file mode 100644
index 0000000..8bf2ef9
--- /dev/null
+++ b/apps/iphone-control/src/viewer.html
@@ -0,0 +1,129 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>iphone-control viewer</title>
+<style>
+ :root { color-scheme: light dark; --bg: #f4f4f5; --fg: #18181b; --muted: #71717a; --panel: #fff; --line: #d4d4d8; --err: #b91c1c; }
+ @media (prefers-color-scheme: dark) { :root { --bg: #18181b; --fg: #f4f4f5; --muted: #a1a1aa; --panel: #27272a; --line: #3f3f46; --err: #f87171; } }
+ * { box-sizing: border-box; }
+ body { margin: 0; background: var(--bg); color: var(--fg); font: 14px/1.4 system-ui, sans-serif; display: flex; flex-direction: column; align-items: center; gap: 12px; padding: 12px; min-height: 100vh; }
+ #screen { position: relative; height: min(80vh, 900px); aspect-ratio: 393 / 852; background: #000; border-radius: 28px; overflow: hidden; touch-action: none; user-select: none; }
+ #screen.landscape { height: auto; width: min(95vw, 1000px); }
+ #screen img { width: 100%; height: 100%; object-fit: contain; display: block; cursor: crosshair; -webkit-user-drag: none; }
+ #screen .msg { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; text-align: center; padding: 24px; color: #d4d4d8; }
+ #screen .msg[hidden] { display: none; }
+ .row { display: flex; gap: 8px; flex-wrap: wrap; justify-content: center; width: min(100%, 520px); }
+ button, input { font: inherit; color: inherit; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 6px 12px; }
+ button { cursor: pointer; }
+ button:disabled { opacity: .5; cursor: default; }
+ input { flex: 1; min-width: 0; }
+ #status { color: var(--muted); min-height: 1.4em; max-width: 520px; text-align: center; white-space: pre-wrap; }
+ #status.err { color: var(--err); }
+</style>
+</head>
+<body>
+<div id="screen">
+ <img id="img" src="/stream" alt="Live screen of the phone" draggable="false">
+ <div class="msg" id="msg">Connecting…</div>
+</div>
+<div class="row">
+ <button data-button="home">Home</button>
+ <button data-button="lock">Lock</button>
+ <button data-button="volume_down">Vol −</button>
+ <button data-button="volume_up">Vol +</button>
+</div>
+<form class="row" id="type">
+ <input id="text" placeholder="Text to type on the phone" autocomplete="off">
+ <button type="submit">Type</button>
+ <button type="button" id="submit">Type + Return</button>
+</form>
+<div id="status">Click to tap, drag to swipe, hold to long-press.</div>
+<script>
+const img = document.getElementById('img'), screenEl = document.getElementById('screen');
+const msg = document.getElementById('msg'), statusEl = document.getElementById('status');
+let size = null; // screen size in points, portrait
+
+function show(text, err) { statusEl.textContent = text; statusEl.classList.toggle('err', !!err); }
+
+async function post(action, body) {
+ try {
+ const r = await fetch('/api/' + action, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
+ const v = await r.json();
+ show(v.message || (v.ok ? 'OK' : 'Failed'), !v.ok);
+ return v.ok;
+ } catch (e) { show(String(e), true); return false; }
+}
+
+async function loadInfo() {
+ try {
+ const v = await (await fetch('/api/info')).json();
+ // a size recorded for another device would put taps in the wrong place: better none
+ size = v.width && v.height ? { w: v.width, h: v.height } : null;
+ if (v.warning) show(v.warning, true);
+ } catch (e) { /* retried with the stream */ }
+}
+
+function connect() {
+ msg.textContent = 'Connecting…'; msg.hidden = false;
+ img.src = '/stream?t=' + Date.now();
+}
+img.onload = () => {
+ msg.hidden = true;
+ // the frame's own shape: iPhone, iPad, portrait or landscape
+ screenEl.style.aspectRatio = img.naturalWidth + ' / ' + img.naturalHeight;
+ screenEl.classList.toggle('landscape', img.naturalWidth > img.naturalHeight);
+};
+img.onerror = () => {
+ msg.textContent = 'No picture: the stream comes from WebDriverAgent, which is not running right now. Retrying…';
+ msg.hidden = false;
+ setTimeout(() => { loadInfo(); connect(); }, 3000);
+};
+
+// Picture position → points on the phone, in the current orientation
+function toPoints(ev) {
+ if (!size || !img.naturalWidth) return null;
+ const r = img.getBoundingClientRect();
+ const scale = Math.min(r.width / img.naturalWidth, r.height / img.naturalHeight);
+ const w = img.naturalWidth * scale, h = img.naturalHeight * scale;
+ const fx = (ev.clientX - r.left - (r.width - w) / 2) / w, fy = (ev.clientY - r.top - (r.height - h) / 2) / h;
+ if (fx < 0 || fx > 1 || fy < 0 || fy > 1) return null;
+ const land = img.naturalWidth > img.naturalHeight;
+ const W = land ? size.h : size.w, H = land ? size.w : size.h;
+ return { x: Math.round(fx * W * 10) / 10, y: Math.round(fy * H * 10) / 10 };
+}
+
+let down = null;
+img.addEventListener('pointerdown', ev => { img.setPointerCapture(ev.pointerId); down = { p: toPoints(ev), t: performance.now(), cx: ev.clientX, cy: ev.clientY }; });
+img.addEventListener('pointerup', ev => {
+ if (!down) return;
+ const start = down; down = null;
+ const end = toPoints(ev), held = (performance.now() - start.t) / 1000;
+ if (!start.p) { show(size ? 'Outside the screen' : 'Screen size not known yet', true); return; }
+ if (Math.hypot(ev.clientX - start.cx, ev.clientY - start.cy) < 8) {
+ if (held < 0.5) post('tap', start.p); else post('long_press', { ...start.p, seconds: held });
+ } else if (end) {
+ post('swipe', { x1: start.p.x, y1: start.p.y, x2: end.x, y2: end.y, seconds: Math.max(held, 0.1) });
+ }
+});
+img.addEventListener('pointercancel', () => { down = null; });
+
+document.querySelectorAll('[data-button]').forEach(b => b.addEventListener('click', () => post('button', { button: b.dataset.button })));
+
+const text = document.getElementById('text');
+async function typeText(submit) {
+ if (!text.value && !submit) return;
+ if (await post('type', { text: text.value, submit })) text.value = '';
+}
+document.getElementById('type').addEventListener('submit', ev => { ev.preventDefault(); typeText(false); });
+document.getElementById('submit').addEventListener('click', () => typeText(true));
+
+loadInfo();
+// keep the size and the device check current (WDA may come up later, the daemon may switch devices)
+setInterval(loadInfo, 10000);
+// the stream may have failed before the handlers above were set
+if (img.complete && !img.naturalWidth) img.onerror();
+</script>
+</body>
+</html>
diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs
new file mode 100644
index 0000000..159d462
--- /dev/null
+++ b/apps/iphone-control/src/viewer.rs
@@ -0,0 +1,320 @@
+//! `iphone-control viewer`: a small page on 127.0.0.1 that shows the phone's screen live and acts on it.
+//!
+//! - `GET /` the page, `GET /stream` WDA's MJPEG stream (port 9100 on the phone, over usbmuxd, read-only),
+//! `GET /api/info` the screen size in points.
+//! - `POST /api/{tap,swipe,long_press,type,button}` turn into ordinary daemon requests, so they queue with
+//! the agent's calls, get auto-unlock and follow the controlled device, exactly like an MCP tool call.
+//!
+//! Protections, same model as `wda-bridge`: it binds to the loopback address only, every request needs a
+//! loopback `Host` (against DNS rebinding), and every action also needs an `Origin` of this very page and a
+//! JSON content type (against other web pages posting to it). Other local users can still reach the port,
+//! which the command says when it starts.
+//!
+//! The viewer belongs to one device, the one controlled when it starts: the picture always comes from it, and
+//! every action carries its UDID ([`ictl_daemon::protocol::EXPECT_UDID`]), so the daemon refuses an action once
+//! it controls another device (after `select`, or an unplug in automatic mode) instead of tapping a phone the
+//! user isn't looking at. The device handle is looked up again for each stream, so a replug (new usbmuxd id)
+//! doesn't break the picture.
+
+use std::path::Path;
+use std::time::Duration;
+
+use anyhow::bail;
+use ictl_daemon::protocol::{Request, Response};
+use serde_json::{Value, json};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::TcpStream;
+
+const PAGE: &str = include_str!("viewer.html");
+/// WDA's MJPEG server on the phone
+const MJPEG_PORT: u16 = 9100;
+const MAX_HEAD: usize = 16 * 1024;
+const MAX_BODY: usize = 16 * 1024;
+/// How long a client may take to send the request head or body
+const READ_TIMEOUT: Duration = Duration::from_secs(10);
+/// Connections served at once (a stream holds one for as long as the page is open)
+const MAX_CONNECTIONS: usize = 16;
+
+pub async fn run(socket: &Path, port: u16) -> anyhow::Result<()> {
+ let udid = crate::target_device(socket, None).await?.udid;
+ let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await?;
+ let port = listener.local_addr()?.port();
+ println!(
+ "{}",
+ ictl_l10n::trf!(
+ "实时画面:http://127.0.0.1:{port}/ (手机 {},Ctrl-C 停止)",
+ "Live viewer: http://127.0.0.1:{port}/ (phone {}, Ctrl-C to stop)",
+ udid
+ )
+ );
+ println!(
+ "{}",
+ ictl_l10n::tr!(
+ "注意:本机所有用户都能经这个端口看到屏幕、操作手机,用完就停掉。",
+ "Note: every user on this machine can watch and control the phone through this port; stop it when you are done."
+ )
+ );
+ let slots = std::sync::Arc::new(tokio::sync::Semaphore::new(MAX_CONNECTIONS));
+ loop {
+ let (client, _) = listener.accept().await?;
+ // too many open connections (for example many tabs): drop the new one
+ let Ok(slot) = slots.clone().try_acquire_owned() else { continue };
+ let (udid, socket) = (udid.clone(), socket.to_path_buf());
+ tokio::spawn(async move {
+ if let Err(e) = serve(client, &udid, &socket, port).await {
+ tracing::debug!("viewer connection: {e}");
+ }
+ drop(slot);
+ });
+ }
+}
+
+/// One request per connection (`Connection: close`), which keeps the parser small
+async fn serve(mut client: TcpStream, udid: &str, socket: &Path, port: u16) -> anyhow::Result<()> {
+ let (head, mut body) = read_head(&mut client).await?;
+ let Some(req) = Head::parse(&head) else {
+ return reply(&mut client, 400, "text/plain", b"bad request").await;
+ };
+ if !crate::host_is_loopback(&head) {
+ return reply(&mut client, 403, "text/plain", b"forbidden").await;
+ }
+ match (req.method.as_str(), req.path.as_str()) {
+ ("GET", "/") => reply(&mut client, 200, "text/html; charset=utf-8", PAGE.as_bytes()).await,
+ ("GET", "/stream") => {
+ // looked up again each time: after a replug usbmuxd gives the device a new id
+ let device = ictl_device::Device::find(Some(udid)).await;
+ let mut remote = match async { device?.connect_port(MJPEG_PORT).await }.await {
+ Ok(r) => r,
+ Err(e) => return reply(&mut client, 502, "text/plain", e.to_string().as_bytes()).await,
+ };
+ // WDA's MJPEG server answers any request with the multipart stream
+ remote.write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n").await?;
+ tokio::io::copy_bidirectional(&mut client, &mut remote).await?;
+ Ok(())
+ }
+ ("GET", "/api/info") => {
+ let v = info(socket, udid).await;
+ reply(&mut client, 200, "application/json", v.to_string().as_bytes()).await
+ }
+ ("POST", path) if path.starts_with("/api/") => {
+ if !action_allowed(&req, port) {
+ return reply(&mut client, 403, "text/plain", b"forbidden").await;
+ }
+ let len = req.content_length.unwrap_or(0);
+ if len > MAX_BODY {
+ return reply(&mut client, 413, "text/plain", b"too large").await;
+ }
+ while body.len() < len {
+ let mut buf = [0u8; 4096];
+ let n = tokio::time::timeout(READ_TIMEOUT, client.read(&mut buf)).await??;
+ if n == 0 {
+ bail!("body cut off");
+ }
+ body.extend_from_slice(&buf[..n]);
+ }
+ body.truncate(len);
+ let v = match serde_json::from_slice::<Value>(&body).ok().and_then(|b| action(&path[5..], &b)) {
+ Some(r) => run_action(socket, r, udid).await,
+ None => json!({"ok": false, "message": "bad action"}),
+ };
+ reply(&mut client, 200, "application/json", v.to_string().as_bytes()).await
+ }
+ _ => reply(&mut client, 404, "text/plain", b"not found").await,
+ }
+}
+
+/// Reads up to the end of the request head; returns the head and whatever of the body came with it
+async fn read_head(client: &mut TcpStream) -> anyhow::Result<(Vec<u8>, Vec<u8>)> {
+ let mut data = Vec::new();
+ let mut buf = [0u8; 4096];
+ loop {
+ if let Some(i) = data.windows(4).position(|w| w == b"\r\n\r\n") {
+ let body = data.split_off(i + 4);
+ return Ok((data, body));
+ }
+ if data.len() > MAX_HEAD {
+ bail!("request head too long");
+ }
+ let n = tokio::time::timeout(READ_TIMEOUT, client.read(&mut buf)).await??;
+ if n == 0 {
+ bail!("connection closed");
+ }
+ data.extend_from_slice(&buf[..n]);
+ }
+}
+
+async fn reply(client: &mut TcpStream, status: u16, kind: &str, body: &[u8]) -> anyhow::Result<()> {
+ let reason = match status {
+ 200 => "OK",
+ 400 => "Bad Request",
+ 403 => "Forbidden",
+ 404 => "Not Found",
+ 413 => "Payload Too Large",
+ _ => "Bad Gateway",
+ };
+ let head = format!(
+ "HTTP/1.1 {status} {reason}\r\nContent-Type: {kind}\r\nContent-Length: {}\r\nCache-Control: no-store\r\n\
+ X-Content-Type-Options: nosniff\r\nX-Frame-Options: DENY\r\nConnection: close\r\n\r\n",
+ body.len()
+ );
+ client.write_all(head.as_bytes()).await?;
+ client.write_all(body).await?;
+ Ok(())
+}
+
+struct Head {
+ method: String,
+ path: String,
+ origin: Option<String>,
+ content_type: Option<String>,
+ content_length: Option<usize>,
+}
+
+impl Head {
+ fn parse(head: &[u8]) -> Option<Self> {
+ let text = std::str::from_utf8(head).ok()?;
+ let mut lines = text.split("\r\n");
+ let mut first = lines.next()?.split(' ');
+ let method = first.next()?.to_owned();
+ let path = first.next()?.split('?').next()?.to_owned();
+ let mut h = Self { method, path, origin: None, content_type: None, content_length: None };
+ for l in lines {
+ let Some((k, v)) = l.split_once(':') else { continue };
+ let v = v.trim();
+ match k.trim().to_ascii_lowercase().as_str() {
+ "origin" => h.origin = Some(v.to_owned()),
+ "content-type" => h.content_type = Some(v.to_ascii_lowercase()),
+ "content-length" => h.content_length = Some(v.parse().ok()?),
+ _ => {}
+ }
+ }
+ Some(h)
+ }
+}
+
+/// An action must come from this page: `Origin` is the viewer's own address, and the body is JSON, which a
+/// cross-origin page can't send without a preflight that this server never answers
+fn action_allowed(req: &Head, port: u16) -> bool {
+ let json = req.content_type.as_deref().is_some_and(|c| c.split(';').next() == Some("application/json"));
+ let origin = req.origin.as_deref().is_some_and(|o| {
+ ["127.0.0.1", "localhost", "[::1]"].iter().any(|h| o.eq_ignore_ascii_case(&format!("http://{h}:{port}")))
+ });
+ json && origin
+}
+
+/// Maps a page action to the daemon request it stands for
+fn action(name: &str, b: &Value) -> Option<Request> {
+ let num = |k: &str| b.get(k).and_then(Value::as_f64).filter(|v| v.is_finite());
+ Some(match name {
+ "tap" => Request::Tap { x: num("x")?, y: num("y")? },
+ "long_press" => Request::LongPress { x: num("x")?, y: num("y")?, seconds: num("seconds")?.clamp(0.3, 5.0) },
+ "swipe" => Request::Swipe {
+ from: (num("x1")?, num("y1")?),
+ to: (num("x2")?, num("y2")?),
+ seconds: num("seconds")?.clamp(0.05, 3.0),
+ },
+ "type" => Request::TypeText {
+ text: b.get("text")?.as_str()?.to_owned(),
+ submit: b.get("submit").and_then(Value::as_bool).unwrap_or(false),
+ },
+ "button" => Request::PressButton { button: b.get("button")?.as_str()?.to_owned() },
+ _ => return None,
+ })
+}
+
+/// Sends one action to the daemon, only for the viewer's device (see the module docs)
+async fn run_action(socket: &Path, req: Request, udid: &str) -> Value {
+ match ictl_daemon::protocol::call_expecting(socket, &req, Some(Duration::from_secs(120)), Some(udid)).await {
+ Ok(Response::Text { text, .. }) => json!({"ok": true, "message": text}),
+ Ok(Response::Image { caption, .. }) => json!({"ok": true, "message": caption}),
+ Ok(Response::Error { message }) => json!({"ok": false, "message": message}),
+ Err(e) => json!({"ok": false, "message": e.to_string()}),
+ }
+}
+
+/// Screen size in points (portrait) for turning a click on the picture into a tap, and whether the daemon
+/// still controls the viewer's device
+async fn info(socket: &Path, udid: &str) -> Value {
+ match crate::snapshot(socket).await {
+ Ok(s) => {
+ let screen = screen_of(&s.persisted, udid);
+ let controlled = s.device.as_ref().is_some_and(|d| d.udid.eq_ignore_ascii_case(udid));
+ json!({
+ "width": screen.map(|s| s.width),
+ "height": screen.map(|s| s.height),
+ "state": s.state,
+ "device": s.device.map(|d| d.name),
+ "warning": (!controlled).then(|| ictl_l10n::trf!(
+ "守护进程现在控制的不是这台({udid}),操作会被拒绝;要看另一台,重新运行 iphone-control viewer",
+ "The daemon no longer controls this device ({udid}), so actions are refused; to view another device, run iphone-control viewer again"
+ )),
+ })
+ }
+ Err(e) => json!({"error": e.to_string()}),
+ }
+}
+
+/// The recorded screen size, only if it belongs to `udid` (a size recorded by an older version, without
+/// a device, is used as is, like the daemon does)
+fn screen_of(p: &ictl_daemon::core::Persisted, udid: &str) -> Option<ictl_device::ScreenSize> {
+ let same = p.screen_udid.as_deref().is_none_or(|u| u.eq_ignore_ascii_case(udid));
+ p.screen.filter(|_| same).map(|s| s.portrait())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn head(s: &str) -> Head {
+ Head::parse(s.as_bytes()).unwrap()
+ }
+
+ #[test]
+ fn actions_need_own_origin_and_json() {
+ let ok = "POST /api/tap HTTP/1.1\r\nHost: 127.0.0.1:8200\r\nOrigin: http://127.0.0.1:8200\r\nContent-Type: application/json\r\nContent-Length: 2\r\n\r\n";
+ assert!(action_allowed(&head(ok), 8200));
+ assert!(action_allowed(&head(&ok.replace("http://127.0.0.1:8200", "http://localhost:8200")), 8200));
+ // another page, another port, no origin, a form post
+ assert!(!action_allowed(&head(&ok.replace("http://127.0.0.1:8200", "http://evil.example")), 8200));
+ assert!(!action_allowed(&head(&ok.replace("http://127.0.0.1:8200", "http://127.0.0.1:3000")), 8200));
+ assert!(!action_allowed(&head(&ok.replace("Origin: http://127.0.0.1:8200\r\n", "")), 8200));
+ assert!(!action_allowed(&head(&ok.replace("application/json", "text/plain")), 8200));
+ assert!(!action_allowed(&head(&ok.replace("Origin: http://127.0.0.1:8200", "Origin: null")), 8200));
+ }
+
+ #[test]
+ fn page_actions_map_to_daemon_requests() {
+ assert_eq!(action("tap", &json!({"x": 10.0, "y": 20.5})), Some(Request::Tap { x: 10.0, y: 20.5 }));
+ assert_eq!(
+ action("swipe", &json!({"x1": 1, "y1": 2, "x2": 3, "y2": 4, "seconds": 9})),
+ Some(Request::Swipe { from: (1.0, 2.0), to: (3.0, 4.0), seconds: 3.0 })
+ );
+ assert_eq!(
+ action("type", &json!({"text": "hi"})),
+ Some(Request::TypeText { text: "hi".into(), submit: false })
+ );
+ assert_eq!(action("button", &json!({"button": "home"})), Some(Request::PressButton { button: "home".into() }));
+ assert_eq!(action("tap", &json!({"x": 1})), None);
+ assert_eq!(action("launch", &json!({})), None);
+ }
+
+ #[test]
+ fn screen_size_only_for_the_viewers_device() {
+ let mut p = ictl_daemon::core::Persisted {
+ screen: Some(ictl_device::ScreenSize { width: 932.0, height: 430.0 }),
+ screen_udid: Some("AAA".into()),
+ ..Default::default()
+ };
+ assert_eq!(screen_of(&p, "aaa").map(|s| (s.width, s.height)), Some((430.0, 932.0)), "portrait");
+ assert!(screen_of(&p, "BBB").is_none(), "another device's size would put taps in the wrong place");
+ p.screen_udid = None;
+ assert!(screen_of(&p, "BBB").is_some(), "older state without a device");
+ }
+
+ #[test]
+ fn parses_request_head() {
+ let h = head("GET /stream?t=1 HTTP/1.1\r\nHost: localhost:8200\r\n\r\n");
+ assert_eq!((h.method.as_str(), h.path.as_str()), ("GET", "/stream"));
+ assert!(Head::parse(b"POST / HTTP/1.1\r\nContent-Length: x\r\n\r\n").is_none());
+ }
+}
diff --git a/docs/architecture.md b/docs/architecture.md
index 5e2d3b5..3e2726e 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -44,6 +44,7 @@
- MCP 进程由 `docker exec -i`(从源码运行时直接调用二进制)拉起,短命且可能同时有多个;设备连接(尤其是 HID 需要的显示媒体流、WDA 的 XCTest 会话)只能有一个持有者。
- 不开 TCP 端口,避免重蹈 `ios forward` 监听所有网卡的覆辙。WDA 本身也通过 idevice 的 provider 直连设备端口,**本机不再监听 8100**。如需给外部工具用,`iphone-control wda-bridge` 显式开启,只绑 127.0.0.1,且只转发 Host 头是 `localhost`/`127.0.0.1`/`[::1]` 的请求(挡住 DNS rebinding)。注意容器用 host 网络,**本机的任何用户都能连上 bridge**,而 WDA 没有认证,用完就停。
+- `iphone-control viewer` 同样显式开启、只绑 127.0.0.1、检查 Host 头:页面看 WDA 的 MJPEG 流(手机上的 9100 端口,经 usbmuxd,只读);点击、滑动、输入、按键是 POST,还要检查 `Origin` 是页面本身、内容类型是 JSON,然后作为普通请求发给守护进程,和 agent 的调用排队、自动解锁。
### 并发模型
@@ -107,7 +108,7 @@
| `ictl-unlock` | 锁屏密码键盘定位、逐位输入并核对密码栏、从第 2 位起先写停用标记 | `ictl-wda` |
| `ictl-daemon` | `core`(共享状态、请求分发、快照)、`supervise`(巡检、usbmuxd 看护、后台启动 WDA、重签、会话检查)、`tools`(工具的实现、HID 后备)、`devices`(列出、选择设备)、`doctor`;通知(Bark/Telegram)、截图缩放/裁剪、控制接口服务端 | 以上全部、`tokio`、`reqwest`、`image` |
| `ictl-mcp` | MCP stdio 服务,17 个 `iphone_*` 工具:toolkit 的 13 个 + `iphone_wait_for`、`iphone_batch`、`iphone_list_devices`、`iphone_select_device`;操作类工具可带 `then` 顺带返回操作后的界面;经控制接口调用守护进程 | `ictl-protocol`、`rmcp`(`server`、`transport-io`) |
-| `apps/iphone-control` | CLI 入口:`daemon`、`mcp`、`mcp-config`、`status`、`doctor`、`setup`、`login`、`sign`、`resign`、`passcode`、`unlock-reset`、`devices`、`select`、`wda-bridge`、`notify-test`;隐藏的 `debug <ddi\|hid\|screenshot\|soak\|wda\|e2e>` 真机诊断(原第 0 步 spike,不经守护进程;feature `debug-cmds`,默认不编译) | `clap` |
+| `apps/iphone-control` | CLI 入口:`daemon`、`mcp`、`mcp-config`、`status`、`doctor`、`setup`、`login`、`sign`、`resign`、`passcode`、`unlock-reset`、`devices`、`select`、`wda-bridge`、`viewer`、`notify-test`;隐藏的 `debug <ddi\|hid\|screenshot\|soak\|wda\|e2e>` 真机诊断(原第 0 步 spike,不经守护进程;feature `debug-cmds`,默认不编译) | `clap` |
依赖方向:`apps` → `ictl-daemon` / `ictl-mcp`;`ictl-daemon` → `ictl-unlock` → `ictl-wda` → `ictl-device`;`ictl-daemon` 还依赖 `ictl-sign` 和 `ictl-protocol`。`ictl-mcp` 只依赖 `ictl-protocol`,不依赖守护进程和设备层。`apps` 的 `debug`(feature `debug-cmds`)直接调用 `ictl-device`、`ictl-wda`。
diff --git a/website/en/guide/cli.md b/website/en/guide/cli.md
index bce1376..ddd0dca 100644
--- a/website/en/guide/cli.md
+++ b/website/en/guide/cli.md
@@ -61,6 +61,7 @@ See [Auto-unlock](./auto-unlock). `--device` takes a UDID or name, and the devic
|---|---|
| `notify-test [event]` | Send test notifications: one per event type, or one type (`resign`, `session`, `pin`, `pin-recovered`, `unlock`, `offline`, `online`) |
| `wda-bridge [--port <port>]` | Expose WDA on `127.0.0.1` (default port 8100) for other tools. WDA has no authentication and every local user can reach it, so stop it when done |
+| `viewer [--port <port>]` | Live screen in the browser at `http://127.0.0.1:8200/` (default port): click to tap, drag to swipe, hold to long-press, plus a text field and the hardware buttons. Taps and typing go through the daemon like an MCP call, so they queue with the agent and unlock the phone first. Every local user can reach the port, so stop it when done |
The `debug` subcommand for diagnostics isn't compiled by default; see the [contributing guide](https://github.com/Derrors/iphone-control/blob/main/CONTRIBUTING.md#testing-on-a-real-phone).
diff --git a/website/en/guide/security.md b/website/en/guide/security.md
index e773b1a..c3d2cea 100644
--- a/website/en/guide/security.md
+++ b/website/en/guide/security.md
@@ -15,6 +15,7 @@ iphone-control is a remote control for a phone: whoever can reach it can do anyt
## Built-in protections
- **No network ports.** WDA is reached through usbmuxd. `wda-bridge` is an explicit opt-in that binds 127.0.0.1 only — but WDA has no authentication, so every local user can use it; stop it when done.
+- **The viewer is opt-in too.** `iphone-control viewer` binds 127.0.0.1 only and checks the `Host` header like `wda-bridge`. Actions also need an `Origin` of the viewer page itself and a JSON body, so other web pages in your browser can't act through it. It has no login, though: every local user can watch the screen and control the phone through the port, so stop it when done.
- **Not privileged**: the container only gets USB character devices.
- **Auto-unlock is off by default** and disables itself after one wrong attempt.
- Exact dependency versions, base images pinned by digest, and the WebDriverAgent download is sha256-checked.
diff --git a/website/guide/cli.md b/website/guide/cli.md
index e301d75..e44bef3 100644
--- a/website/guide/cli.md
+++ b/website/guide/cli.md
@@ -61,6 +61,7 @@
|---|---|
| `notify-test [事件]` | 发测试通知:每类事件各一条,或只发一类(`resign`、`session`、`pin`、`pin-recovered`、`unlock`、`offline`、`online`) |
| `wda-bridge [--port <端口>]` | 把 WDA 桥接到 `127.0.0.1`,端口默认 8100,给别的工具用。WDA 没有认证,本机任何用户都能连上,用完就停 |
+| `viewer [--port <端口>]` | 在浏览器里看实时画面,地址 `http://127.0.0.1:8200/`(默认端口):点一下是点击,拖动是滑动,按住是长按,另有输入框和硬件键。点击、输入和 MCP 调用一样经守护进程,和 agent 的操作排队,并先自动解锁。本机任何用户都能连上这个端口,用完就停 |
调试用的 `debug` 子命令默认不编译,见[贡献指南](https://github.com/Derrors/iphone-control/blob/main/CONTRIBUTING.md#testing-on-a-real-phone)。
diff --git a/website/guide/security.md b/website/guide/security.md
index ab80348..41b2a5c 100644
--- a/website/guide/security.md
+++ b/website/guide/security.md
@@ -15,6 +15,7 @@ iphone-control 本质上是一个手机遥控器:能访问它的人,就能
## 默认的保护
- **不开网络端口。** WDA 经 usbmuxd 直连手机。`wda-bridge` 是显式开启的桥接,只绑 127.0.0.1,但 WDA 没有认证,本机任何用户都能连上,用完就停。
+- **实时画面也是显式开启的。** `iphone-control viewer` 只绑 127.0.0.1,和 `wda-bridge` 一样检查 `Host` 头;操作还要求 `Origin` 是这个页面本身、请求体是 JSON,所以浏览器里的其他网页借不了它操作手机。但它没有登录:本机任何用户都能经这个端口看屏幕、操作手机,用完就停。
- **容器不用 privileged**,只开放 USB 字符设备。
- **自动解锁默认关闭**,输错一次即停用。
- 依赖锁定精确版本,基础镜像锁 digest,下载的 WebDriverAgent 核对 sha256。